[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ninsert_final_newline = true\nindent_style = space\nindent_size = 2\ntrim_trailing_whitespace = true\n\n[*.md]\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: ciderapp\nko_fi: cryptofyre\nopen_collective: ciderapp\ncustom: \"https://opencollective.com/ciderapp/donate/10/month/Support%20Development?redirect=https://cidercollective.dev/thanks\"\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yaml",
    "content": "name: Bug Report\ndescription: If you encounter an issue whilst using our app, please use this template to help improve the app.\ntitle: \"[Bug]: \"\nlabels: [\"bug\", \"needs-triage\"]\nassignees: []\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thanks for taking the time to fill out this bug report!\n  - type: checkboxes\n    attributes:\n      label: Preflight Checklist\n      description: Please ensure you've completed all of the following.\n      options:\n        - label: I have read the [Support Disclaimer](https://docs.cider.sh/support/disclaimer) for this project.\n          required: true\n        - label: I agree to follow the [Code of Conduct](https://github.com/ciderapp/Cider/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.\n          required: true\n        - label: I have searched the [issue tracker](https://www.github.com/ciderapp/Cider/issues) for a bug report that matches the one I want to file, without success.\n          required: true\n        - label: I have read the [troublshooting FAQs](https://cider.gitbook.io/welcome-to-gitbook/support/faqs#why-is-my-discordrpc-status-not-appearing) and none solved my issue.\n          required: true\n  - type: input\n    attributes:\n      label: Cider Version\n      description: |\n        What version of Cider are you using?\n        \n        Note: Please only report issues for [currently supported versions of Cider](hhttps://cider.gitbook.io/welcome-to-gitbook/support/version-information). You can find your version on the About Page.\n      placeholder: 1.6.0\n    validations:\n      required: true\n  - type: dropdown\n    attributes:\n      label: What operating system are you using?\n      options:\n        - Windows\n        - macOS\n        - Ubuntu\n        - Other Linux\n        - Other (specify below)\n    validations:\n      required: true\n  - type: input\n    attributes:\n      label: Operating System Version\n      description: What operating system version are you using? On Windows, click Start button > Settings > System > About. On macOS, click the Apple Menu > About This Mac. On Linux, use lsb_release or uname -a.\n      placeholder: \"e.g. Windows 10 version 1909, macOS Catalina 10.15.7, or Ubuntu 20.04\"\n    validations:\n      required: true\n  - type: dropdown\n    id: download\n    attributes:\n      label: Where did you download Cider from?\n      options:\n        - Microsoft Store\n        - GitHub\n        - Winget\n        - Winget (Nightly)\n        - Chocolatey\n        - Flathub\n        - AUR\n    validations:\n      required: true\n  - type: textarea\n    id: description\n    attributes:\n      label: Describe the Bug\n      description: A clear and concise description of the bug you encountered. Tell us what did you expect to happen?\n      placeholder: Tell us what you see!\n    validations:\n      required: true\n  - type: textarea\n    id: replication\n    attributes:\n      label: Steps to Reproduce\n      description: How did you produce this bug, tell us how you did it so we can do it ourselves.\n      placeholder: 1. Clicked on...\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Anything else?\n      description: |\n        Links? References? Anything that will give us more context about the issue you are encountering!\n\n        Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Support Disclaimer\n    url: https://docs.cider.sh/support/disclaimer\n    about: Please read this before creating any issue.\n  - name: Feature Request\n    url: https://github.com/ciderapp/Cider/discussions/new?category=feature-request\n    about: Have a feature you would like to have in the app? Make a request.\n  - name: Discord Support\n    url: https://discord.com/invite/AppleMusic\n    about: For quick support, make a ticket or ask for community support here.\n  - name: Cider Documentation\n    url: https://docs.cider.sh/support/faqs\n    about: In most cases, these troubleshooting tips can resolve basic issues. Try them out before opening an issue.\n  - name: GitHub Issues\n    url: https://github.com/ciderapp/Cider/issues\n    about: Check to make sure there is not an issues already open that is related to your issue.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/translation.yaml",
    "content": "name: Translation Report/Request\ndescription: Request a language or report an issue with one.\ntitle: \"[Translation]: \"\nlabels: [\"🌐 Translations\"]\nassignees: []\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thanks for taking the time to fill out this report!\n  - type: input\n    id: language\n    attributes:\n      label: Relevant Language\n      description: The language you would like to request for or have an issue with.\n      placeholder: en_US\n    validations:\n      required: true\n  - type: dropdown\n    id: requestType\n    attributes:\n      label: Change or Addition or Both\n      multiple: true\n      options:\n        - Change a Language\n        - Add a Language\n    validations:\n      required: true\n  - type: textarea\n    id: description\n    attributes:\n      label: Change Requested / Any Additional Information\n      description: If you are requesting a change, place all the information here, or you can provide additional information to additions if you want.\n      placeholder: I would like ... changed to ...\n    validations:\n      required: false\n  - type: checkboxes\n    id: terms\n    attributes:\n      label: Code of Conduct\n      description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/ciderapp/Cider/blob/main/CODE_OF_CONDUCT.md)\n      options:\n        - label: I agree to follow this project's Code of Conduct\n          required: true\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE/translations.md",
    "content": "---\nname: Translations\nabout: Improvement to our tranlations\ntitle: \"\"\nlabels: 🌐 Translations\nassignees: ''\n---\n\n\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where the package manifests are located.\n# Please see the documentation for all configuration options:\n# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file\n\nversion: 2\nupdates:\n  - package-ecosystem: \"npm\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"monthly\"\n"
  },
  {
    "path": ".github/workflows/auto-project.yml",
    "content": "name: Add bugs to bugs project\n\non:\n  issues:\n    types:\n      - opened\n\njobs:\n  add-to-project:\n    name: Add issue to project\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/add-to-project@main\n        with:\n          project-url: https://github.com/orgs/ciderapp/projects/5\n          github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}\n          labeled: bug, needs-triage\n          label-operator: OR\n"
  },
  {
    "path": ".github/workflows/cider-chores.yml",
    "content": "name: Cider Chores\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  compile-and-post:\n    runs-on: ubuntu-latest\n\n    container:\n      image: electronuserland/builder:wine\n\n\n    steps:\n      - name: Checkout 🛎\n        uses: actions/checkout@v4\n\n      - uses: pnpm/action-setup@v4\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v4\n        with:\n          node-version-file: '.nvmrc'\n\n      - name: Install Dependencies 📦\n        run: pnpm install\n\n      - name: Build 🏗\n        run: pnpm dist:all\n\n      - name: Upload Release 🚀\n        uses: softprops/action-gh-release@v2.0.5\n        with:\n          files: |\n            ./dist/*.exe\n            ./dist/*.deb\n            ./dist/*.AppImage\n            ./dist/*.rpm\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/dev-chores.yml",
    "content": "name: Developer Chores\n\non: [pull_request]\n\njobs:\n    linter-check:\n      runs-on: ${{ matrix.os }}\n\n      strategy:\n        matrix:\n          os: [ubuntu-latest]\n          node: [18]\n\n      steps:\n        - name: Checkout 🛎\n          uses: actions/checkout@v3\n\n        - name: Setup node env 🏗\n          uses: actions/setup-node@v3\n          with:\n            node-version: ${{ matrix.node }}\n            check-latest: true\n\n        - name: Install dependencies 👨🏻‍💻\n          run: npm run bootstrap\n\n        - name: Run linter 👀\n          run: npm run format:write\n\n        - name: Comment Suggestions 🗒️\n          uses: getsentry/action-git-diff-suggestions@main\n          with:\n            message: Prettier Suggestion\n"
  },
  {
    "path": ".github/workflows/stale-issues.yml",
    "content": "name: 'Close stale issues and PRs'\non:\n  schedule:\n    - cron: '30 1 * * *'\n\npermissions:\n  issues: write\n  pull-requests: write\n\njobs:\n  stale:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/stale@v4\n        with:\n          stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.'\n          days-before-stale: 30\n          days-before-close: 7\n          stale-issue-label: \"stale\"\n          stale-pr-label: \"stale\"\n          exempt-all-assignees: true\n          exempt-issue-labels: 'more-info,work-in-progress,accessibility-feature,help-wanted,persist/priority'\n"
  },
  {
    "path": ".github/workflows/support-notice.yml",
    "content": "name: Support Notice\n\non:\n  issues:\n    types: [opened]\n\njobs:\n  post-notice:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: derekprior/add-autoresponse@master\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          respondableId: ${{ github.event.issue.node_id }}\n          response: \"Cider 1.x is no longer actively maintained. We highly suggest moving to the newer version versions of the app available at https://cider.sh through official storefronts ex. Itch.io, or the Microsoft Store.\"\n          author: ${{ github.event.issue.user.login }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Building\ndist\nbuild\n.flatpak*\nyarn-cache\nsrc/renderer/style.css\n.pnpm-store\n\n# Misc\n.idea\n.vscode\nauth.json\nmusickit.js\n\n# Microsoft Store Package Configs\nmsft-package.json\n\n## Node GitIgnore ##\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n.pnpm-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.development.local\n.env.test.local\n.env.production.local\n.env.local\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# vuepress v2.x temp and cache directory\n.temp\n.cache\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# yarn v2\n.pnp.*\n.yarn/*\n.yarn/cache\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n\n## JetBrains GitIgnore ##\n\n# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider\n# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839\n\n# User-specific stuff\n.idea/**/workspace.xml\n.idea/**/tasks.xml\n.idea/**/usage.statistics.xml\n.idea/**/dictionaries\n.idea/**/shelf\n\n# AWS User-specific\n.idea/**/aws.xml\n\n# Generated files\n.idea/**/contentModel.xml\n\n# Sensitive or high-churn files\n.idea/**/dataSources/\n.idea/**/dataSources.ids\n.idea/**/dataSources.local.xml\n.idea/**/sqlDataSources.xml\n.idea/**/dynamic.xml\n.idea/**/uiDesigner.xml\n.idea/**/dbnavigator.xml\n\n# Gradle\n.idea/**/gradle.xml\n.idea/**/libraries\n\n# Gradle and Maven with auto-import\n# When using Gradle or Maven with auto-import, you should exclude module files,\n# since they will be recreated, and may cause churn.  Uncomment if using\n# auto-import.\n# .idea/artifacts\n# .idea/compiler.xml\n# .idea/jarRepositories.xml\n# .idea/modules.xml\n# .idea/*.iml\n# .idea/modules\n# *.iml\n# *.ipr\n\n# CMake\ncmake-build-*/\n\n# Mongo Explorer plugin\n.idea/**/mongoSettings.xml\n\n# File-based project format\n*.iws\n\n# IntelliJ\nout/\n\n# mpeltonen/sbt-idea plugin\n.idea_modules/\n\n# JIRA plugin\natlassian-ide-plugin.xml\n\n# Cursive Clojure plugin\n.idea/replstate.xml\n\n# SonarLint plugin\n.idea/sonarlint/\n\n# Crashlytics plugin (for Android Studio and IntelliJ)\ncom_crashlytics_export_strings.xml\ncrashlytics.properties\ncrashlytics-build.properties\nfabric.properties\n\n# Editor-based Rest Client\n.idea/httpRequests\n\n# Android studio 3.1+ serialized cache file\n.idea/caches/build_file_checksums.ser\n\n\n## macOS GitIgnore ##\n\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n\n## VSCode GitIgnore ##\n\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n!.vscode/*.code-snippets\n\n# Local History for Visual Studio Code\n.history/\n\n# Built Visual Studio Code Extensions\n*.vsix\n\n## Sublime Text GitIgnore ##\n\n# Cache files for Sublime Text\n*.tmlanguage.cache\n*.tmPreferences.cache\n*.stTheme.cache\n\n# Workspace files are user-specific\n*.sublime-workspace\n\n# Project files should be checked into the repository, unless a significant\n# proportion of contributors will probably not be using Sublime Text\n# *.sublime-project\n\n# SFTP configuration file\nsftp-config.json\nsftp-config-alt*.json\n\n# Package control specific files\nPackage Control.last-run\nPackage Control.ca-list\nPackage Control.ca-bundle\nPackage Control.system-ca-bundle\nPackage Control.cache/\nPackage Control.ca-certs/\nPackage Control.merged-ca-bundle\nPackage Control.user-ca-bundle\noscrypto-ca-bundle.crt\nbh_unicode_properties.cache\n\n# Sublime-github package stores a github token in this file\n# https://packagecontrol.io/packages/sublime-github\nGitHub.sublime-settings\n\n#Service Worker mappings\nsrc/renderer/sw.js.map\nsrc/renderer/workbox-962786f2.js.map\n/src/renderer/musickit-dev.js\n\n#Mac certs\n*.p12\nkeys.sh\n\npackage-lock.json\nresources/b64.txt\n\n\nsavedconfig/cider-config.json\nsavedconfig/config.json\nsavedconfig/session.json\nsavedconfig/window-state.json\nsrc/main/base/sample.json\n\n# yeet circleci ci for now\n.circleci/\n"
  },
  {
    "path": ".npmrc",
    "content": "node-linker=hoisted\npublic-hoist-pattern=*\nshamefully-hoist=true\n"
  },
  {
    "path": ".nvmrc",
    "content": "20.2.0\n"
  },
  {
    "path": ".prettierignore",
    "content": "src/renderer/*hls*.js\nbuild/*\ndist/*\nsrc/renderer/lib/*\n*.min.*\n.pnpm-store\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"printWidth\": 600,\n  \"singleAttributePerLine\": true,\n  \"bracketSameLine\": true,\n  \"overrides\": [\n    {\n      \"files\": \"src/renderer/main/**/*.js\",\n      \"options\": {\n        \"singleAttributePerLine\": false\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": ".yarnrc.yml",
    "content": "compressionLevel: mixed\n\nenableGlobalCache: false\n\nnodeLinker: node-modules\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n> Threats made to someone's wellbeing, especially towards self-harm or sucide, will be automatically be dealt with as a maximum level offense, no matter the reasoning.\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\ncryptofyre@cider.sh.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n<picture>\n    <img src=\"resources/icons/icon.png\" width=\"128px\">\n</picture>\n</div>\n<h1 align=\"center\">\nCider 1\n</h1>\n\n> [!WARNING]  \n>This project has been archived, and no further updates or support will be provided under any circumstances. We highly recommend switching to [Cider v2](https://cider.sh/downloads/client) for the latest features, improvements, and continued support.  \n\nThis repository contains the source code for **Cider v1.x**, a cross-platform Apple Music client built from the ground up by the development team.  \n\nCider v1 was developed using [Electron.js](https://electronjs.org), [Vue.js 2](https://vuejs.org), and [Webpack](https://webpack.js.org).  \n\n**Note:** While distributions may still be available through various third-party sources, first-party builds are no longer provided due to the high volume of support requests for v1. You can compile it following the [insructions outlined in our legacy documentation](https://cider.sh/docs) from our website. Support will not be provided for compiling.\n"
  },
  {
    "path": "docs/plugins/example/examplePlugin.ts",
    "content": "let i = 1,\n  k = 1;\nclass ExamplePlugin {\n  /**\n   * Private variables for interaction in plugins\n   */\n  private _win: any;\n  private _app: any;\n  private _store: any;\n\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"examplePlugin\";\n  public description: string = \"Example plugin\";\n  public version: string = \"1.0.0\";\n  public author: string = \"Example author\";\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(app: any, store: any) {\n    this._app = app;\n    this._store = store;\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n  }\n\n  /**\n   * Runs on app ready\n   */\n  onReady(win: any): void {\n    this._win = win;\n    console.debug(`[Plugin][${this.name}] Ready.`);\n  }\n\n  /**\n   * Runs on app stop\n   */\n  onBeforeQuit(): void {\n    console.debug(`[Plugin][${this.name}] Stopped.`);\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  onPlaybackStateDidChange(attributes: object): void {\n    console.log(\"onPlaybackStateDidChange has been called \" + i + \" times\");\n    i++;\n  }\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  onNowPlayingItemDidChange(attributes: object): void {\n    console.log(\"onNowPlayingDidChange has been called \" + k + \" times\");\n    k++;\n  }\n}\n\nmodule.exports = ExamplePlugin;\n"
  },
  {
    "path": "docs/plugins/sendSongToTitlebar.ts",
    "content": "class sendSongToTitlebar {\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"sendSongToTitlebar\";\n  public description: string = \"Sets the app's titlebar to the Song title\";\n  public version: string = \"0.0.1\";\n  public author: string = \"Cider Collective (credit to 8times9 via #147)\";\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  private _win: any;\n  private _app: any;\n  constructor() {}\n  /**\n   * Runs on app ready\n   */\n  onReady(win: any): void {\n    this._win = win;\n  }\n  /**\n   * Runs on app stop\n   */\n  onBeforeQuit(): void {}\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  onPlaybackStateDidChange(attributes: any): void {\n    this._win.setTitle(`${attributes != null && attributes.name != null && attributes.name.length > 0 ? attributes.name + \" - \" : \"\"}Cider`);\n  }\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  onNowPlayingItemDidChange(attributes: object): void {}\n}\n\nmodule.exports = sendSongToTitlebar;\n"
  },
  {
    "path": "flatpak/cider-wrapper",
    "content": "#!/bin/sh\n\nfor i in {0..9}; do\n    test -S $XDG_RUNTIME_DIR/discord-ipc-$i || ln -sf {app/com.discordapp.Discord,$XDG_RUNTIME_DIR}/discord-ipc-$i;\ndone\n\ncider \"$@\""
  },
  {
    "path": "flatpak/flathub.json",
    "content": "{\n  \"only-arches\": [\"x86_64\"],\n  \"publish-delay-hours\": 2\n}\n"
  },
  {
    "path": "flatpak/org.cidercollective.cider.yml",
    "content": "app-id: org.cidercollective.cider\nruntime: org.freedesktop.Platform\nruntime-version: '21.08'\nsdk: org.freedesktop.Sdk\nbase: org.electronjs.Electron2.BaseApp\nbase-version: '21.08'\ncommand: cider\nrename-desktop-file: cider.desktop\nrename-icon: cider\nfinish-args:\n  - --device=dri\n  - --filesystem=xdg-music\n  - --own-name=org.mpris.MediaPlayer2.Cider\n  - --share=ipc\n  - --share=network\n  - --socket=pulseaudio\n  # needs electron v11 (chromium v87) or newer with ozone enabled\n  # https://github.com/electron/electron/issues/10915\n  # - --socket=wayland\n  - --socket=x11\n  - --system-talk-name=org.freedesktop.UPower\n  - --talk-name=com.canonical.AppMenu.Registrar\n  - --talk-name=com.canonical.dbusmenu\n  - --talk-name=org.freedesktop.Notifications\n  - --talk-name=org.kde.StatusNotifierWatcher\nmodules:\n  - name: cider\n    buildsystem: simple\n    build-commands:\n      - install -dm755 ${FLATPAK_DEST}/cider\n      - |\n        bsdtar -Oxf cider.deb 'data.tar*' |\n        bsdtar -xf - \\\n        -C ${FLATPAK_DEST}/cider \\\n        --strip-components=3 \\\n        ./opt/Cider\n      - |\n        bsdtar -Oxf cider.deb 'data.tar*' |\n        bsdtar -xf - \\\n        -C ${FLATPAK_DEST} \\\n        --strip-components=2 \\\n        --exclude=./usr/share/doc \\\n        ./usr/share\n      - desktop-file-edit --set-key=Exec --set-value=cider ${FLATPAK_DEST}/share/applications/cider.desktop\n      - install -Dm755 stub_sandbox ${FLATPAK_DEST}/cider/chrome-sandbox\n      - install -Dm755 cider -t ${FLATPAK_DEST}/bin/\n    sources:\n      - type: file\n        dest-filename: cider.deb\n        url: https://1308-429851205-gh.circle-artifacts.com/0/~/Cider/dist/artifacts/cider_1.3.1308_amd64.deb\n        sha256: 342abde96bac9668e7238860ba435171edd72077ed9f4b385a3546c4d8f96995\n        x-checker-data:\n          type: html\n          url: https://circleci.com/api/v1.1/project/gh/ciderapp/Cider/latest/artifacts?branch=main&filter=successful\n          pattern: (https://.*circle-artifacts.com/.+/cider_([\\d\\.]+)_amd64.deb)\n      - type: script\n        dest-filename: cider\n        commands:\n          # share chromium singleton between multiple session, needed for flatpak<1.11.1\n          - export TMPDIR=$XDG_RUNTIME_DIR/app/$FLATPAK_ID\n          - exec zypak-wrapper /app/cider/cider \"$@\"\n      - type: script\n        dest-filename: stub_sandbox\n        commands:\n          - |\n            echo Stub sandbox ignoring command: $@\n            exit 1\n"
  },
  {
    "path": "flatpak/sh.cider.Cider.metainfo.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<component type=\"desktop-application\">\n  <content_rating type=\"oars-1.0\"/>\n  <id>sh.cider.Cider</id>\n  \n  <name>Cider</name>\n  <summary>An open source and community oriented Apple Music client</summary>\n  \n  <metadata_license>CC0-1.0</metadata_license>\n  <project_license>AGPL-1.0-or-later</project_license>\n  <developer_name>Cider Collective</developer_name>\n\n  <url type=\"homepage\">https://cider.sh/?utm_source=flathub%26utm_medium=link%26utm_campaign=product-page</url>\n  <url type=\"bugtracker\">https://github.com/ciderapp/Cider/issues</url>\n  <url type=\"donation\">https://ko-fi.com/cryptofyre</url>\n  \n  <description>\n    <p>\n      Project Cider. A new look into listening and enjoying Apple Music in style and performance with Features such as Discord and Last.fm integration, spatial audio support, equalizers, and remote controllable using companion app\n    </p>\n  </description>\n  \n  <launchable type=\"desktop-id\">cider.desktop</launchable>\n\n  <screenshots>\n    <screenshot type=\"default\">\n      <image>https://github.com/ciderapp/cider.sh/blob/main/assets/img/frontpage-scn.png?raw=true</image>\n    </screenshot>\n  </screenshots>\n\n  <releases>\n    <release version=\"v1.3.0.1555\" date=\"2022-03-24\"/>\n    <release version=\"v1.3.0.1548\" date=\"2022-03-24\"/>\n    <release version=\"v1.3.0.1541\" date=\"2022-03-23\"/>\n    <release version=\"v1.3.0.1540\" date=\"2022-03-23\"/>\n    <release version=\"v1.3.0.1531\" date=\"2022-03-22\"/>\n  </releases>\n</component>\n"
  },
  {
    "path": "flatpak/sh.cider.Cider.yml",
    "content": "app-id: sh.cider.Cider\nruntime: org.freedesktop.Platform\nruntime-version: '21.08'\nsdk: org.freedesktop.Sdk\nbase: org.electronjs.Electron2.BaseApp\nbase-version: '21.08'\ncommand: cider-wrapper\nrename-desktop-file: cider.desktop\nrename-icon: cider\nfinish-args:\n  - --device=dri\n  - --filesystem=xdg-music\n  - --filesystem=xdg-run/app/com.discordapp.Discord:create\n  - --own-name=org.mpris.MediaPlayer2.cider\n  - --share=ipc\n  - --share=network\n  - --socket=pulseaudio\n  # needs electron v11 (chromium v87) or newer with ozone enabled\n  # https://github.com/electron/electron/issues/10915\n  #- --socket=wayland\n  - --socket=x11\n  - --system-talk-name=org.freedesktop.UPower\n  - --talk-name=com.canonical.AppMenu.Registrar\n  - --talk-name=com.canonical.dbusmenu\n  - --talk-name=org.freedesktop.Notifications\n  - --talk-name=org.kde.StatusNotifierWatcher\nmodules:\n  - name: cider\n    buildsystem: simple\n    build-commands:\n      - install -dm755 ${FLATPAK_DEST}/cider\n      - |\n        bsdtar -Oxf cider.deb 'data.tar*' |\n        bsdtar -xf - \\\n        -C ${FLATPAK_DEST}/cider \\\n        --strip-components=3 \\\n        ./opt/Cider\n      - |\n        bsdtar -Oxf cider.deb 'data.tar*' |\n        bsdtar -xf - \\\n        -C ${FLATPAK_DEST} \\\n        --strip-components=2 \\\n        --exclude=./usr/share/doc \\\n        ./usr/share\n      - install -Dm755 cider-wrapper /app/bin/cider-wrapper\n      - desktop-file-edit --set-key=Exec --set-value=cider-wrapper ${FLATPAK_DEST}/share/applications/cider.desktop\n      - install -Dm755 stub_sandbox ${FLATPAK_DEST}/cider/chrome-sandbox\n      - install -Dm755 cider -t ${FLATPAK_DEST}/bin/\n      - install -Dm644 -t /app/share/metainfo ${FLATPAK_ID}.metainfo.xml\n    sources:\n      - type: file\n        dest-filename: cider.deb\n        url: https://github.com/ciderapp/cider-releases/releases/download/v1.3.0.1555/cider_1.3.0-alpha.1555_amd64.deb\n        sha256: 8a582ca2758d556cc2d5fad73e05ed3e2f27076e13bf377d1d83d9494aaef9c2\n        x-checker-data:\n          type: json\n          url: https://api.github.com/repos/ciderapp/cider-releases/releases/latest\n          version-query: .tag_name\n          url-query: .assets[] | select(.name | match(\"(amd64.deb)\")) | .browser_download_url\n      - type: script\n        dest-filename: cider\n        commands:\n          # share chromium singleton between multiple session, needed for flatpak<1.11.1\n          - export TMPDIR=$XDG_RUNTIME_DIR/app/$FLATPAK_ID\n          - exec zypak-wrapper /app/cider/cider \"$@\"\n      - type: script\n        dest-filename: stub_sandbox\n        commands:\n          - |\n            echo Stub sandbox ignoring command: $@\n            exit 1\n      - type: file\n        path: cider-wrapper\n      - type: file\n        path: sh.cider.Cider.metainfo.xml\n"
  },
  {
    "path": "msft-test.json",
    "content": "{\n  \"electronVersion\": \"16.2.8\",\n  \"electronDownload\": {\n    \"version\": \"16.2.8+wvcus\",\n    \"mirror\": \"https://github.com/castlabs/electron-releases/releases/download/v\"\n  },\n  \"appId\": \"cider\",\n  \"protocols\": [\n    {\n      \"name\": \"Cider\",\n      \"schemes\": [\"ame\", \"cider\", \"itms\", \"itmss\", \"musics\", \"music\"]\n    }\n  ],\n  \"extends\": null,\n  \"files\": [\"**/*\", \"./src/**/*\", \"./resources/icons/icon.*\"],\n  \"linux\": {\n    \"target\": [\"AppImage\", \"deb\", \"snap\", \"rpm\"],\n    \"synopsis\": \"A new look into listening and enjoying music in style and performance. \",\n    \"category\": \"AudioVideo\",\n    \"icon\": \"cider\",\n    \"executableName\": \"cider\"\n  },\n  \"appx\": {\n    \"applicationId\": \"CiderAlpha\",\n    \"publisher\": \"CN=CiderCollective, OID.2.25.311729368913984317654407730594956997722=1\",\n    \"displayName\": \"Cider\",\n    \"identityName\": \"CiderCollective.CiderAlpha\",\n    \"backgroundColor\": \"transparent\",\n    \"setBuildNumber\": true\n  },\n  \"win\": {\n    \"target\": [\"appx\"],\n    \"icon\": \"resources/icons/icon.ico\"\n  },\n  \"directories\": {\n    \"buildResources\": \".\",\n    \"output\": \"dist\"\n  },\n  \"mac\": {\n    \"icon\": \"./resources/icons/icon.icns\",\n    \"category\": \"public.app-category.music\",\n    \"entitlements\": \"resources/entitlements.mac.plist\",\n    \"darkModeSupport\": true\n  }\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"cider\",\n  \"applicationId\": \"Cider\",\n  \"productName\": \"Cider\",\n  \"version\": \"1.6.4\",\n  \"description\": \"A new cross-platform Apple Music experience based on Electron and Vue.js written from scratch with performance in mind.\",\n  \"license\": \"AGPL-3.0\",\n  \"exports\": \"./build/index.js\",\n  \"main\": \"./build/index.js\",\n  \"author\": \"Cider Collective <development@cider.sh> (https://cider.sh)\",\n  \"repository\": \"github:ciderapp/Cider\",\n  \"type\": \"module\",\n  \"bugs\": {\n    \"url\": \"https://github.com/ciderapp/Cider/issues?q=is%3Aopen+is%3Aissue+label%3Abug\"\n  },\n  \"homepage\": \"https://cider.sh/\",\n  \"buildResources\": \"resources\",\n  \"scripts\": {\n    \"bootstrap\": \"npx -y check-engine && pnpm i\",\n    \"build\": \"tsc && lessc ./src/renderer/style.less ./src/renderer/style.css\",\n    \"start\": \"npm run build && electron ./build/index.js\",\n    \"dist\": \"npm run build && electron-builder --publish=never\",\n    \"dist:win\": \"npm run build && electron-builder --win --publish=never\",\n    \"dist:linux\": \"npm run build && electron-builder --linux --publish=never\",\n    \"dist:all\": \"npm run build && electron-builder -wl --publish=never\",\n    \"dist:universalNotWorking\": \"npm run build && electron-builder --mac --universal --publish:never\",\n    \"winget\": \"npm run build && electron-builder --win -c winget.json\",\n    \"msft\": \"npm run build && electron-builder -c msft-package.json\",\n    \"mstest\": \"npm run build && electron-builder -c msft-test.json\",\n    \"steamdeck\": \"npm run build && electron-builder --linux -c steam-deck.json\",\n    \"format:check\": \"npx prettier --check \\\"src/**/*.{js,json,ts,less}\\\"\",\n    \"format:write\": \"npx prettier --write \\\"src/**/*.{js,json,ts,less}\\\"\"\n  },\n  \"dependencies\": {\n    \"@achingbrain/ssdp\": \"^4.2.1\",\n    \"@crowdin/ota-client\": \"^1.1.3\",\n    \"adm-zip\": \"^0.5.16\",\n    \"airtunes2\": \"github:ciderapp/node_airtunes2\",\n    \"castv2-client\": \"github:ciderapp/node-castv2-client\",\n    \"chokidar\": \"^3.6.0\",\n    \"discord-auto-rpc\": \"^1.0.17\",\n    \"ejs\": \"^3.1.10\",\n    \"electron-log\": \"^5.2.4\",\n    \"electron-notarize\": \"^1.2.2\",\n    \"electron-store\": \"^9.0.0\",\n    \"electron-updater\": \"6.2.1\",\n    \"electron-window-state\": \"^5.0.3\",\n    \"express\": \"^4.21.2\",\n    \"get-port\": \"7.1.0\",\n    \"jimp\": \"^0.22.12\",\n    \"lastfmapi\": \"^0.1.1\",\n    \"mdns-js\": \"github:ciderapp/node-mdns-js\",\n    \"mpris-service\": \"github:ciderapp/mpris-service\",\n    \"music-metadata\": \"7.14.0\",\n    \"node-fetch\": \"^3.3.2\",\n    \"node-ssdp\": \"^4.0.1\",\n    \"node-ssdp-js\": \"^0.9.6\",\n    \"qrcode\": \"^1.5.4\",\n    \"request\": \"^2.88.2\",\n    \"simple-ssdp\": \"^1.0.2\",\n    \"source-map-support\": \"^0.5.21\",\n    \"ssdp-js\": \"^1.0.1\",\n    \"ts-md5\": \"1.3.1\",\n    \"upnp-mediarenderer-client\": \"github:vapormusic/node-upnp-mediarenderer-client\",\n    \"v8-compile-cache\": \"^2.4.0\",\n    \"wallpaper\": \"7.2.1\",\n    \"ws\": \"^8.18.0\",\n    \"xml2js\": \"^0.6.2\",\n    \"youtube-search-without-api-key\": \"^2.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/adm-zip\": \"^0.5.7\",\n    \"@types/discord-rpc\": \"4.0.8\",\n    \"@types/express\": \"^4.17.21\",\n    \"@types/musickit\": \"github:ciderapp/musickit-types\",\n    \"@types/node\": \"^20.17.9\",\n    \"@types/node-ssdp\": \"^4.0.4\",\n    \"@types/qrcode-terminal\": \"^0.12.2\",\n    \"@types/request\": \"^2.48.12\",\n    \"@types/upnp-mediarenderer-client\": \"^1.4.3\",\n    \"@types/ws\": \"^8.5.13\",\n    \"@types/xml2js\": \"^0.4.14\",\n    \"electron\": \"github:castlabs/electron-releases#v32.2.6+wvcus\",\n    \"electron-builder\": \"^24.13.3\",\n    \"electron-builder-notarize-pkg\": \"^1.2.0\",\n    \"electron-webpack\": \"^2.8.2\",\n    \"less\": \"^4.2.1\",\n    \"node-gyp\": \"^10.3.1\",\n    \"prettier\": \"3.2.5\",\n    \"typescript\": \"^5.7.2\",\n    \"vue-devtools\": \"^5.1.4\",\n    \"webpack\": \"~5.91.0\"\n  },\n  \"fileAssociations\": [\n    {\n      \"name\": \"Cider\",\n      \"mimeType\": \"x-scheme-handler/ame;x-scheme-handler/itms;x-scheme-handler/itmss;x-scheme-handler/musics;x-scheme-handler/music;\",\n      \"schemes\": [\n        \"ame\",\n        \"cider\",\n        \"itms\",\n        \"itmss\",\n        \"musics\",\n        \"music\"\n      ],\n      \"protocols\": [\n        \"ame\",\n        \"cider\",\n        \"itms\",\n        \"itmss\",\n        \"musics\",\n        \"music\"\n      ]\n    }\n  ],\n  \"build\": {\n    \"electronDownload\": {\n      \"mirror\": \"https://github.com/castlabs/electron-releases/releases/download/v\"\n    },\n    \"appId\": \"cider\",\n    \"afterPack\": \"./resources/afterPack.cjs\",\n    \"afterSign\": \"./resources/notarize.cjs\",\n    \"protocols\": [\n      {\n        \"name\": \"Cider\",\n        \"schemes\": [\n          \"ame\",\n          \"cider\",\n          \"itms\",\n          \"itmss\",\n          \"musics\",\n          \"music\"\n        ]\n      }\n    ],\n    \"extends\": null,\n    \"files\": [\n      \"./build/**/*\",\n      \"./src/**/*\",\n      \"./resources/icons/**/*\"\n    ],\n    \"linux\": {\n      \"target\": [\n        \"AppImage\",\n        \"deb\",\n        \"rpm\"\n      ],\n      \"synopsis\": \"A new look into listening and enjoying music in style and performance. \",\n      \"category\": \"AudioVideo\",\n      \"icon\": \"cider\",\n      \"executableName\": \"cider\"\n    },\n    \"appx\": {\n      \"applicationId\": \"Cider\",\n      \"displayName\": \"Cider\",\n      \"identityName\": \"Cider\",\n      \"publisherDisplayName\": \"Cider Collective\",\n      \"backgroundColor\": \"transparent\",\n      \"setBuildNumber\": true\n    },\n    \"nsis\": {\n      \"oneClick\": false,\n      \"perMachine\": false,\n      \"allowToChangeInstallationDirectory\": true,\n      \"license\": \"LICENSE\",\n      \"deleteAppDataOnUninstall\": true,\n      \"artifactName\": \"${productName}-Setup-${version}.${ext}\"\n    },\n    \"pkg\": {\n      \"installLocation\": \"/Applications\",\n      \"background\": {\n        \"file\": \"./resources/bg.png\",\n        \"alignment\": \"bottomleft\"\n      },\n      \"allowAnywhere\": true,\n      \"allowCurrentUserHome\": true,\n      \"allowRootDirectory\": true,\n      \"license\": \"./LICENSE\",\n      \"isVersionChecked\": false,\n      \"isRelocatable\": false,\n      \"overwriteAction\": \"upgrade\"\n    },\n    \"snap\": {\n      \"slots\": [\n        {\n          \"mpris\": {\n            \"interface\": \"mpris\"\n          }\n        }\n      ]\n    },\n    \"dmg\": {\n      \"background\": \"./resources/bg.tiff\",\n      \"icon\": \"resources/icons/icon.ico\"\n    },\n    \"mas\": {\n      \"entitlements\": \"./resources/entitlements.mac.plist\",\n      \"entitlementsInherit\": \"./resources/entitlements.mac.plist\"\n    },\n    \"win\": {\n      \"target\": [\n        \"nsis\"\n      ],\n      \"icon\": \"resources/icons/icon.ico\"\n    },\n    \"directories\": {\n      \"buildResources\": \".\",\n      \"output\": \"dist\"\n    },\n    \"mac\": {\n      \"hardenedRuntime\": true,\n      \"gatekeeperAssess\": false,\n      \"icon\": \"./resources/icons/icon.icns\",\n      \"category\": \"public.app-category.music\",\n      \"entitlements\": \"./resources/entitlements.mac.plist\",\n      \"entitlementsInherit\": \"./resources/entitlements.mac.plist\",\n      \"darkModeSupport\": true,\n      \"target\": [\n        \"dmg\"\n      ],\n      \"extendInfo\": {\n        \"NSUserNotificationAlertStyle\": \"alert\"\n      }\n    }\n  },\n  \"electronWebpack\": {\n    \"devtool\": \"source-map\"\n  },\n  \"packageManager\": \"pnpm@9.15.0\"\n}\n"
  },
  {
    "path": "resources/afterPack.cjs",
    "content": "exports.default = function (context) {\n  const { execSync } = require(\"child_process\");\n  const fs = require(\"fs\");\n\n  if (process.platform !== \"darwin\") return;\n\n  if (fs.existsSync(\"dist/mac-universal--x64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/Electron Framework.sig\"))\n    fs.unlinkSync(\"dist/mac-universal--x64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/Electron Framework.sig\");\n  if (fs.existsSync(\"dist/mac-universal--arm64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/Electron Framework.sig\"))\n    fs.unlinkSync(\"dist/mac-universal--arm64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/Electron Framework.sig\");\n  console.log('Castlabs-evs update start')\n  execSync('python3 -m pip install --upgrade castlabs-evs')\n  console.log('Castlabs-evs update complete')\n\n  // xcode 13\n  if (\n    fs.existsSync(\"dist/mac-universal--x64\") &&\n    fs.existsSync(\"dist/mac-universal--arm64\") &&\n    fs.existsSync(\"dist/mac-universal--x64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/MainMenu.nib/keyedobjects-101300.nib\")\n  )\n    execSync(\n      \"cp 'dist/mac-universal--x64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/MainMenu.nib/keyedobjects-101300.nib' 'dist/mac-universal--arm64/Cider.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/MainMenu.nib/keyedobjects-101300.nib'\",\n      { stdio: \"inherit\" }\n    );\n\n  console.log('VMP signing start')\n  if (fs.existsSync('dist/mac-universal'))\n  execSync('python3 -m castlabs_evs.vmp -n sign-pkg dist/mac-universal',{stdio: 'inherit'})\n  if (fs.existsSync('dist/mac'))\n  execSync('python3 -m castlabs_evs.vmp -n sign-pkg dist/mac',{stdio: 'inherit'})\n  if (fs.existsSync('dist/mac-arm64'))\n  execSync('python3 -m castlabs_evs.vmp -n sign-pkg dist/mac-arm64 -z',{stdio: 'inherit'})\n\n  console.log('VMP signing complete')\n};\n"
  },
  {
    "path": "resources/entitlements.mac.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n  <dict>\n    <!-- https://github.com/electron/electron-notarize#prerequisites -->\n    <key>com.apple.security.cs.allow-jit</key>\n    <true/>\n    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>\n    <true/>\n    <!-- https://github.cm/electron-userland/electron-builder/issues/3940 -->\n    <key>com.apple.security.cs.disable-library-validation</key>\n    <true/>\n  </dict>\n</plist>"
  },
  {
    "path": "resources/license.json",
    "content": "{\n  \"$schema\": \"https://github.com/argv-minus-one/dmg-license/raw/master/schema.json\",\n  \"body\": [\n    {\n      \"file\": \"license.txt\",\n      \"lang\": [\"en-US\"]\n    }\n  ]\n}\n"
  },
  {
    "path": "resources/license.txt",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "resources/macPackager.cjs",
    "content": "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst bluebird_lst_1 = require(\"bluebird-lst\");\nconst builder_util_1 = require(\"builder-util\");\nconst electron_osx_sign_1 = require(\"electron-osx-sign\");\nconst promises_1 = require(\"fs/promises\");\nconst lazy_val_1 = require(\"lazy-val\");\nconst path = require(\"path\");\nconst fs_1 = require(\"builder-util/out/fs\");\nconst promise_1 = require(\"builder-util/out/promise\");\nconst appInfo_1 = require(\"./appInfo\");\nconst macCodeSign_1 = require(\"./codeSign/macCodeSign\");\nconst core_1 = require(\"./core\");\nconst platformPackager_1 = require(\"./platformPackager\");\nconst ArchiveTarget_1 = require(\"./targets/ArchiveTarget\");\nconst pkg_1 = require(\"./targets/pkg\");\nconst targetFactory_1 = require(\"./targets/targetFactory\");\nconst macosVersion_1 = require(\"./util/macosVersion\");\nconst pathManager_1 = require(\"./util/pathManager\");\nconst fs = require(\"fs/promises\");\nclass MacPackager extends platformPackager_1.PlatformPackager {\n  constructor(info) {\n    super(info, core_1.Platform.MAC);\n    this.codeSigningInfo = new lazy_val_1.Lazy(() => {\n      const cscLink = this.getCscLink();\n      if (cscLink == null || process.platform !== \"darwin\") {\n        return Promise.resolve({\n          keychainFile: process.env.CSC_KEYCHAIN || null,\n        });\n      }\n      return macCodeSign_1\n        .createKeychain({\n          tmpDir: this.info.tempDirManager,\n          cscLink,\n          cscKeyPassword: this.getCscPassword(),\n          cscILink: platformPackager_1.chooseNotNull(this.platformSpecificBuildOptions.cscInstallerLink, process.env.CSC_INSTALLER_LINK),\n          cscIKeyPassword: platformPackager_1.chooseNotNull(this.platformSpecificBuildOptions.cscInstallerKeyPassword, process.env.CSC_INSTALLER_KEY_PASSWORD),\n          currentDir: this.projectDir,\n        })\n        .then((result) => {\n          const keychainFile = result.keychainFile;\n          if (keychainFile != null) {\n            this.info.disposeOnBuildFinish(() => macCodeSign_1.removeKeychain(keychainFile));\n          }\n          return result;\n        });\n    });\n    this._iconPath = new lazy_val_1.Lazy(() => this.getOrConvertIcon(\"icns\"));\n  }\n  get defaultTarget() {\n    return this.info.framework.macOsDefaultTargets;\n  }\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  prepareAppInfo(appInfo) {\n    return new appInfo_1.AppInfo(this.info, this.platformSpecificBuildOptions.bundleVersion, this.platformSpecificBuildOptions);\n  }\n  async getIconPath() {\n    return this._iconPath.value;\n  }\n  createTargets(targets, mapper) {\n    for (const name of targets) {\n      switch (name) {\n        case core_1.DIR_TARGET:\n          break;\n        case \"dmg\": {\n          // eslint-disable-next-line @typescript-eslint/no-var-requires\n          const { DmgTarget } = require(\"dmg-builder\");\n          mapper(name, (outDir) => new DmgTarget(this, outDir));\n          break;\n        }\n        case \"zip\":\n          // https://github.com/electron-userland/electron-builder/issues/2313\n          mapper(name, (outDir) => new ArchiveTarget_1.ArchiveTarget(name, outDir, this, true));\n          break;\n        case \"pkg\":\n          mapper(name, (outDir) => new pkg_1.PkgTarget(this, outDir));\n          break;\n        default:\n          mapper(name, (outDir) => (name === \"mas\" || name === \"mas-dev\" ? new targetFactory_1.NoOpTarget(name) : targetFactory_1.createCommonTarget(name, outDir, this)));\n          break;\n      }\n    }\n  }\n  async doPack(outDir, appOutDir, platformName, arch, platformSpecificBuildOptions, targets) {\n    switch (arch) {\n      default: {\n        return super.doPack(outDir, appOutDir, platformName, arch, platformSpecificBuildOptions, targets);\n      }\n      case builder_util_1.Arch.universal: {\n        const x64Arch = builder_util_1.Arch.x64;\n        const x64AppOutDir = appOutDir + \"--\" + builder_util_1.Arch[x64Arch];\n        await super.doPack(outDir, x64AppOutDir, platformName, x64Arch, platformSpecificBuildOptions, targets, false, true);\n        const arm64Arch = builder_util_1.Arch.arm64;\n        const arm64AppOutPath = appOutDir + \"--\" + builder_util_1.Arch[arm64Arch];\n        await super.doPack(outDir, arm64AppOutPath, platformName, arm64Arch, platformSpecificBuildOptions, targets, false, true);\n        const framework = this.info.framework;\n        builder_util_1.log.info(\n          {\n            platform: platformName,\n            arch: builder_util_1.Arch[arch],\n            [`${framework.name}`]: framework.version,\n            appOutDir: builder_util_1.log.filePath(appOutDir),\n          },\n          `packaging`\n        );\n        const appFile = `${this.appInfo.productFilename}.app`;\n        const { makeUniversalApp } = require(\"@electron/universal\");\n        await makeUniversalApp({\n          x64AppPath: path.join(x64AppOutDir, appFile),\n          arm64AppPath: path.join(arm64AppOutPath, appFile),\n          outAppPath: path.join(appOutDir, appFile),\n          force: true,\n        });\n        await fs.rm(x64AppOutDir, { recursive: true, force: true });\n        await fs.rm(arm64AppOutPath, { recursive: true, force: true });\n        const packContext = {\n          appOutDir,\n          outDir,\n          arch,\n          targets,\n          packager: this,\n          electronPlatformName: platformName,\n        };\n        await this.info.afterPack(packContext);\n        if (framework.afterPack != null) {\n          await framework.afterPack(packContext);\n        }\n        await this.doSignAfterPack(outDir, appOutDir, platformName, arch, platformSpecificBuildOptions, targets);\n        break;\n      }\n    }\n  }\n  async pack(outDir, arch, targets, taskManager) {\n    let nonMasPromise = null;\n    const hasMas = targets.length !== 0 && targets.some((it) => it.name === \"mas\" || it.name === \"mas-dev\");\n    const prepackaged = this.packagerOptions.prepackaged;\n    if (!hasMas || targets.length > 1) {\n      const appPath = prepackaged == null ? path.join(this.computeAppOutDir(outDir, arch), `${this.appInfo.productFilename}.app`) : prepackaged;\n      nonMasPromise = (prepackaged ? Promise.resolve() : this.doPack(outDir, path.dirname(appPath), this.platform.nodeName, arch, this.platformSpecificBuildOptions, targets)).then(() =>\n        this.packageInDistributableFormat(appPath, arch, targets, taskManager)\n      );\n    }\n    for (const target of targets) {\n      const targetName = target.name;\n      if (!(targetName === \"mas\" || targetName === \"mas-dev\")) {\n        continue;\n      }\n      const masBuildOptions = builder_util_1.deepAssign({}, this.platformSpecificBuildOptions, this.config.mas);\n      if (targetName === \"mas-dev\") {\n        builder_util_1.deepAssign(masBuildOptions, this.config.masDev, {\n          type: \"development\",\n        });\n      }\n      const targetOutDir = path.join(outDir, `${targetName}${builder_util_1.getArchSuffix(arch)}`);\n      if (prepackaged == null) {\n        await this.doPack(outDir, targetOutDir, \"mas\", arch, masBuildOptions, [target]);\n        await this.sign(path.join(targetOutDir, `${this.appInfo.productFilename}.app`), targetOutDir, masBuildOptions, arch);\n      } else {\n        await this.sign(prepackaged, targetOutDir, masBuildOptions, arch);\n      }\n    }\n    if (nonMasPromise != null) {\n      await nonMasPromise;\n    }\n  }\n  async sign(appPath, outDir, masOptions, arch) {\n    if (!macCodeSign_1.isSignAllowed()) {\n      return;\n    }\n    const isMas = masOptions != null;\n    const options = masOptions == null ? this.platformSpecificBuildOptions : masOptions;\n    const qualifier = options.identity;\n    if (!isMas && qualifier === null) {\n      if (this.forceCodeSigning) {\n        throw new builder_util_1.InvalidConfigurationError(\"identity explicitly is set to null, but forceCodeSigning is set to true\");\n      }\n      builder_util_1.log.info({ reason: \"identity explicitly is set to null\" }, \"skipped macOS code signing\");\n      return;\n    }\n    const keychainFile = (await this.codeSigningInfo.value).keychainFile;\n    const explicitType = options.type;\n    const type = explicitType || \"distribution\";\n    const isDevelopment = type === \"development\";\n    const certificateTypes = getCertificateTypes(isMas, isDevelopment);\n    let identity = null;\n    for (const certificateType of certificateTypes) {\n      identity = await macCodeSign_1.findIdentity(certificateType, qualifier, keychainFile);\n      if (identity != null) {\n        break;\n      }\n    }\n    if (identity == null) {\n      if (!isMas && !isDevelopment && explicitType !== \"distribution\") {\n        identity = await macCodeSign_1.findIdentity(\"Mac Developer\", qualifier, keychainFile);\n        if (identity != null) {\n          builder_util_1.log.warn(\"Mac Developer is used to sign app — it is only for development and testing, not for production\");\n        }\n      }\n      if (identity == null) {\n        await macCodeSign_1.reportError(isMas, certificateTypes, qualifier, keychainFile, this.forceCodeSigning);\n        return;\n      }\n    }\n    if (!macosVersion_1.isMacOsHighSierra()) {\n      throw new builder_util_1.InvalidConfigurationError(\"macOS High Sierra 10.13.6 is required to sign\");\n    }\n    let filter = options.signIgnore;\n    if (Array.isArray(filter)) {\n      if (filter.length == 0) {\n        filter = null;\n      }\n    } else if (filter != null) {\n      filter = filter.length === 0 ? null : [filter];\n    }\n    const filterRe = filter == null ? null : filter.map((it) => new RegExp(it));\n    let binaries = options.binaries || undefined;\n    if (binaries) {\n      // Accept absolute paths for external binaries, else resolve relative paths from the artifact's app Contents path.\n      const userDefinedBinaries = await Promise.all(\n        binaries.map(async (destination) => {\n          if (await fs_1.statOrNull(destination)) {\n            return destination;\n          }\n          return path.resolve(appPath, destination);\n        })\n      );\n      // Insert at front to prioritize signing. We still sort by depth next\n      binaries = userDefinedBinaries.concat(binaries);\n      builder_util_1.log.info(\"Signing addtional user-defined binaries: \" + JSON.stringify(userDefinedBinaries, null, 1));\n    }\n    const signOptions = {\n      \"identity-validation\": false,\n      // https://github.com/electron-userland/electron-builder/issues/1699\n      // kext are signed by the chipset manufacturers. You need a special certificate (only available on request) from Apple to be able to sign kext.\n      ignore: (file) => {\n        if (filterRe != null) {\n          for (const regExp of filterRe) {\n            if (regExp.test(file)) {\n              return true;\n            }\n          }\n        }\n        return (\n          file.endsWith(\".kext\") ||\n          file.startsWith(\"/Contents/PlugIns\", appPath.length) ||\n          file.includes(\"/node_modules/puppeteer/.local-chromium\") ||\n          file.includes(\"/node_modules/playwright-firefox/.local-browsers\") ||\n          file.includes(\"/node_modules/playwright/.local-browsers\")\n        );\n        /* Those are browser automating modules, browser (chromium, nightly) cannot be signed\n                  https://github.com/electron-userland/electron-builder/issues/2010\n                  https://github.com/electron-userland/electron-builder/issues/5383\n                  */\n      },\n      identity: identity,\n      type,\n      platform: isMas ? \"mas\" : \"darwin\",\n      version: this.config.electronVersion,\n      app: appPath,\n      keychain: keychainFile || undefined,\n      binaries,\n      timestamp: isMas ? (masOptions === null || masOptions === void 0 ? void 0 : masOptions.timestamp) : options.timestamp,\n      requirements: isMas || this.platformSpecificBuildOptions.requirements == null ? undefined : await this.getResource(this.platformSpecificBuildOptions.requirements),\n      // https://github.com/electron-userland/electron-osx-sign/issues/196\n      // will fail on 10.14.5+ because a signed but unnotarized app is also rejected.\n      \"gatekeeper-assess\": options.gatekeeperAssess === true,\n      // https://github.com/electron-userland/electron-builder/issues/1480\n      \"strict-verify\": options.strictVerify,\n      hardenedRuntime: isMas ? masOptions && masOptions.hardenedRuntime === true : options.hardenedRuntime !== false,\n    };\n    await this.adjustSignOptions(signOptions, masOptions);\n    builder_util_1.log.info(\n      {\n        file: builder_util_1.log.filePath(appPath),\n        identityName: identity.name,\n        identityHash: identity.hash,\n        provisioningProfile: signOptions[\"provisioning-profile\"] || \"none\",\n      },\n      \"signing\"\n    );\n    await this.doSign(signOptions);\n    // https://github.com/electron-userland/electron-builder/issues/1196#issuecomment-312310209\n    if (masOptions != null && !isDevelopment) {\n      const certType = isDevelopment ? \"Mac Developer\" : \"3rd Party Mac Developer Installer\";\n      const masInstallerIdentity = await macCodeSign_1.findIdentity(certType, masOptions.identity, keychainFile);\n      if (masInstallerIdentity == null) {\n        throw new builder_util_1.InvalidConfigurationError(`Cannot find valid \"${certType}\" identity to sign MAS installer, please see https://electron.build/code-signing`);\n      }\n      // mas uploaded to AppStore, so, use \"-\" instead of space for name\n      const artifactName = this.expandArtifactNamePattern(masOptions, \"pkg\", arch);\n      const artifactPath = path.join(outDir, artifactName);\n      await this.doFlat(appPath, artifactPath, masInstallerIdentity, keychainFile);\n      await this.dispatchArtifactCreated(artifactPath, null, builder_util_1.Arch.x64, this.computeSafeArtifactName(artifactName, \"pkg\", arch, true, this.platformSpecificBuildOptions.defaultArch));\n    }\n  }\n  async adjustSignOptions(signOptions, masOptions) {\n    const resourceList = await this.resourceList;\n    const customSignOptions = masOptions || this.platformSpecificBuildOptions;\n    const entitlementsSuffix = masOptions == null ? \"mac\" : \"mas\";\n    let entitlements = customSignOptions.entitlements;\n    if (entitlements == null) {\n      const p = `entitlements.${entitlementsSuffix}.plist`;\n      if (resourceList.includes(p)) {\n        entitlements = path.join(this.info.buildResourcesDir, p);\n      } else {\n        entitlements = pathManager_1.getTemplatePath(\"entitlements.mac.plist\");\n      }\n    }\n    signOptions.entitlements = entitlements;\n    let entitlementsInherit = customSignOptions.entitlementsInherit;\n    if (entitlementsInherit == null) {\n      const p = `entitlements.${entitlementsSuffix}.inherit.plist`;\n      if (resourceList.includes(p)) {\n        entitlementsInherit = path.join(this.info.buildResourcesDir, p);\n      } else {\n        entitlementsInherit = pathManager_1.getTemplatePath(\"entitlements.mac.plist\");\n      }\n    }\n    signOptions[\"entitlements-inherit\"] = entitlementsInherit;\n    if (customSignOptions.provisioningProfile != null) {\n      signOptions[\"provisioning-profile\"] = customSignOptions.provisioningProfile;\n    }\n    signOptions[\"entitlements-loginhelper\"] = customSignOptions.entitlementsLoginHelper;\n  }\n  //noinspection JSMethodCanBeStatic\n  async doSign(opts) {\n    return electron_osx_sign_1.signAsync(opts);\n  }\n  //noinspection JSMethodCanBeStatic\n  async doFlat(appPath, outFile, identity, keychain) {\n    // productbuild doesn't created directory for out file\n    await promises_1.mkdir(path.dirname(outFile), { recursive: true });\n    const args = pkg_1.prepareProductBuildArgs(identity, keychain);\n    args.push(\"--component\", appPath, \"/Applications\");\n    args.push(outFile);\n    return await builder_util_1.exec(\"productbuild\", args);\n  }\n  getElectronSrcDir(dist) {\n    return path.resolve(this.projectDir, dist, this.info.framework.distMacOsAppName);\n  }\n  getElectronDestinationDir(appOutDir) {\n    return path.join(appOutDir, this.info.framework.distMacOsAppName);\n  }\n  // todo fileAssociations\n  async applyCommonInfo(appPlist, contentsPath) {\n    const appInfo = this.appInfo;\n    const appFilename = appInfo.productFilename;\n    // https://github.com/electron-userland/electron-builder/issues/1278\n    appPlist.CFBundleExecutable = appFilename.endsWith(\" Helper\") ? appFilename.substring(0, appFilename.length - \" Helper\".length) : appFilename;\n    const icon = await this.getIconPath();\n    if (icon != null) {\n      const oldIcon = appPlist.CFBundleIconFile;\n      const resourcesPath = path.join(contentsPath, \"Resources\");\n      if (oldIcon != null) {\n        await fs_1.unlinkIfExists(path.join(resourcesPath, oldIcon));\n      }\n      const iconFileName = \"icon.icns\";\n      appPlist.CFBundleIconFile = iconFileName;\n      await fs_1.copyFile(icon, path.join(resourcesPath, iconFileName));\n    }\n    appPlist.CFBundleName = appInfo.productName;\n    appPlist.CFBundleDisplayName = appInfo.productName;\n    const minimumSystemVersion = this.platformSpecificBuildOptions.minimumSystemVersion;\n    if (minimumSystemVersion != null) {\n      appPlist.LSMinimumSystemVersion = minimumSystemVersion;\n    }\n    appPlist.CFBundleIdentifier = appInfo.macBundleIdentifier;\n    appPlist.CFBundleShortVersionString = this.platformSpecificBuildOptions.bundleShortVersion || appInfo.version;\n    appPlist.CFBundleVersion = appInfo.buildVersion;\n    builder_util_1.use(this.platformSpecificBuildOptions.category || this.config.category, (it) => (appPlist.LSApplicationCategoryType = it));\n    appPlist.NSHumanReadableCopyright = appInfo.copyright;\n    if (this.platformSpecificBuildOptions.darkModeSupport) {\n      appPlist.NSRequiresAquaSystemAppearance = false;\n    }\n    const extendInfo = this.platformSpecificBuildOptions.extendInfo;\n    if (extendInfo != null) {\n      Object.assign(appPlist, extendInfo);\n    }\n  }\n  async signApp(packContext, isAsar) {\n    const appFileName = `${this.appInfo.productFilename}.app`;\n    await bluebird_lst_1.default.map(promises_1.readdir(packContext.appOutDir), (file) => {\n      if (file === appFileName) {\n        return this.sign(path.join(packContext.appOutDir, file), null, null, null);\n      }\n      return null;\n    });\n    if (!isAsar) {\n      return;\n    }\n    const outResourcesDir = path.join(packContext.appOutDir, \"resources\", \"app.asar.unpacked\");\n    await bluebird_lst_1.default.map(promise_1.orIfFileNotExist(promises_1.readdir(outResourcesDir), []), (file) => {\n      if (file.endsWith(\".app\")) {\n        return this.sign(path.join(outResourcesDir, file), null, null, null);\n      } else {\n        return null;\n      }\n    });\n  }\n}\nexports.default = MacPackager;\nfunction getCertificateTypes(isMas, isDevelopment) {\n  if (isDevelopment) {\n    return isMas ? [\"Mac Developer\", \"Apple Development\"] : [\"Developer ID Application\"];\n  }\n  return isMas ? [\"Apple Distribution\"] : [\"Developer ID Application\"];\n}\n//# sourceMappingURL=macPackager.js.map\n"
  },
  {
    "path": "resources/notarize.cjs",
    "content": "require(\"dotenv\").config();\nconst { notarize } = require(\"electron-notarize\");\n\nexports.default = async function notarizing(context) {\n  const { electronPlatformName, appOutDir } = context;\n  if (electronPlatformName !== \"darwin\") {\n    return;\n  }\n\n  const appName = context.packager.appInfo.productFilename;\n\n  return await notarize({\n    appBundleId: \"com.ciderapp.cider\",\n    appPath: `${appOutDir}/${appName}.app`,\n    appleId: process.env.APPLEID,\n    appleIdPassword: process.env.APPLEIDPASS,\n  });\n};\n"
  },
  {
    "path": "resources/verror-types",
    "content": "// Type definitions for verror 1.10\n// Project: https://github.com/davepacheco/node-verror\n// Definitions by: Sven Reglitzki <https://github.com/svi3c>, Maxime Toumi-M <https://github.com/max4t>\n// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n\n/*\n * VError([cause], fmt[, arg...]): Like JavaScript's built-in Error class, but\n * supports a \"cause\" argument (another error) and a printf-style message.  The\n * cause argument can be null or omitted entirely.\n *\n * Examples:\n *\n * CODE                                    MESSAGE\n * new VError('something bad happened')    \"something bad happened\"\n * new VError('missing file: \"%s\"', file)  \"missing file: \"/etc/passwd\"\n *   with file = '/etc/passwd'\n * new VError(err, 'open failed')          \"open failed: file not found\"\n *   with err.message = 'file not found'\n */\ndeclare class VError extends Error {\n    static VError: typeof VError;\n\n    static cause(err: Error): Error | null;\n    static info(err: Error): VError.Info;\n    static fullStack(err: Error): string;\n    static findCauseByName(err: Error, name: string): Error | null;\n    static hasCauseWithName(err: Error, name: string): boolean;\n    static errorFromList<T extends Error>(errors: T[]): null | T | VError.MultiError;\n    static errorForEach(err: Error, func: (err: Error) => void): void;\n\n    //@ts-ignore\n    cause(): Error | undefined;\n    constructor(options: VError.Options | Error, message: string, ...params: any[]);\n    constructor(message?: string, ...params: any[]);\n}\n\ndeclare namespace VError {\n    interface Info {\n        [key: string]: any;\n    }\n\n    interface Options {\n        cause?: Error | null | undefined;\n        name?: string | undefined;\n        strict?: boolean | undefined;\n        constructorOpt?(...args: any[]): void;\n        info?: Info | undefined;\n    }\n\n    /*\n    * SError is like VError, but stricter about types.  You cannot pass \"null\" or\n    * \"undefined\" as string arguments to the formatter.  Since SError is only a\n    * different function, not really a different class, we don't set\n    * SError.prototype.name.\n    */\n    class SError extends VError {}\n\n    /*\n    * Represents a collection of errors for the purpose of consumers that generally\n    * only deal with one error.  Callers can extract the individual errors\n    * contained in this object, but may also just treat it as a normal single\n    * error, in which case a summary message will be printed.\n    */\n    class MultiError extends VError {\n        constructor(errors: Error[]);\n        errors(): Error[];\n    }\n\n    /*\n    * Like JavaScript's built-in Error class, but supports a \"cause\" argument which\n    * is wrapped, not \"folded in\" as with VError.    Accepts a printf-style message.\n    * The cause argument can be null.\n    */\n    class WError extends VError {}\n}\n\nexport = VError;"
  },
  {
    "path": "resources/version.sh",
    "content": "#!/bin/bash\n\n# Setup the variables needed\nif [[ $GH_REQUEST_TOKEN != \"\" ]]; then\n\tSTABLE_SHA=$(curl -H \"Authorization: token ${GH_REQUEST_TOKEN}\" -s https://api.github.com/repos/ciderapp/Cider/branches/stable | grep '\"sha\"' | head -1 | cut -d '\"' -f 4)\nelif [[ $GITHUB_TOKEN != \"\" ]]; then\n\tSTABLE_SHA=$(curl -H \"Authorization: token ${GITHUB_TOKEN}\" -s https://api.github.com/repos/ciderapp/Cider/branches/stable | grep '\"sha\"' | head -1 | cut -d '\"' -f 4)\nelse\n\tSTABLE_SHA=$(curl -s https://api.github.com/repos/ciderapp/Cider/branches/stable | grep '\"sha\"' | head -1 | cut -d '\"' -f 4)\nfi\n\nSHA_DATE=$(git show -s --format=%ci $STABLE_SHA)\nVERSION_POSTFIX=$(git rev-list $STABLE_SHA..HEAD --count --since=\"$SHA_DATE\")\nCURRENT_VERSION=$(node -p -e \"require('./package.json').version\" | cut -d '-' -f 1)\n\n# Set the version number for commits on main branch\nif [[ ($CIRCLE_BRANCH == \"main\" || $GITHUB_REF_NAME == \"main\") && $VERSION_POSTFIX -gt 0 ]]; then\n  NEW_VERSION_NUMBERED=\"$CURRENT_VERSION-beta.$(printf \"%03d\\n\" $VERSION_POSTFIX)\"\n\tNEW_VERSION=\"${CURRENT_VERSION}-beta.${VERSION_POSTFIX}\"\n\n\t# Update the version in package.json\n  if [[ $NO_WRITE_VER == \"\" && $(node -p -e \"require('./package.json').version\" | cut -d '.' -f 4) != $VERSION_POSTFIX ]]; then\n    if [[ $RUNNER_OS == \"macOS\" ]]; then\n      sed -i \"\" -e \"s/$CURRENT_VERSION/$NEW_VERSION/\" package.json\n    else\n      sed -i \"0,/$CURRENT_VERSION/s//$NEW_VERSION/\" package.json\n    fi\n  fi\nelse\n  NEW_VERSION_NUMBERED=$CURRENT_VERSION\n\tNEW_VERSION=$CURRENT_VERSION\nfi\n\necho $NEW_VERSION\n\n\n# Add the version to the environment for CI usage\nif [[ $GITHUB_REF_NAME != \"\" ]] && [[ \"$GITHUB_ENV\" ]]; then\n  echo \"APP_VERSION=$NEW_VERSION\" >>$GITHUB_ENV\n  echo \"RELEASE_VERSION=$NEW_VERSION_NUMBERED\" >>$GITHUB_ENV\nelif [[ $CIRCLE_BRANCH != \"\" ]] && [[ \"$BASH_ENV\" ]]; then\n  echo \"export APP_VERSION=$NEW_VERSION\" >>$BASH_ENV\n  echo \"export RELEASE_VERSION=$NEW_VERSION_NUMBERED\" >>$BASH_ENV\nfi\n"
  },
  {
    "path": "src/ciderkit/public.js",
    "content": "const CiderKit = {\n  v1: {\n    musickit: {\n      async mkv3(route, body, options) {\n        let opts = {\n          method: \"POST\",\n          cache: \"no-cache\",\n          credentials: \"same-origin\",\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n          redirect: \"follow\",\n          referrerPolicy: \"no-referrer\",\n          body: {},\n        };\n        opts.body = JSON.stringify({\n          route: route,\n          body: body,\n          options: options,\n        });\n        let response = await fetch(\"./api/musickit/v3\", opts);\n        return response.json();\n      },\n    },\n  },\n};\n"
  },
  {
    "path": "src/main/base/app.ts",
    "content": "import { Menu, Tray, app, clipboard, ipcMain, nativeImage, shell } from \"electron\";\nimport log from \"electron-log\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport os from \"os\";\nimport { utils } from \"../base/utils.js\";\n\n/**\n * @file Creates App instance\n * @author CiderCollective\n */\n\n/** @namespace */\nexport class AppEvents {\n  private protocols: string[] = [\"ame\", \"cider\", \"itms\", \"itmss\", \"musics\", \"music\"];\n  private plugin: any = undefined;\n  private tray: any = undefined;\n  private i18n: any = undefined;\n\n  /** @constructor */\n  constructor() {\n    this.start();\n  }\n\n  /**\n   * Handles all actions that occur for the app on start (Mainly commandline arguments)\n   * @returns {void}\n   */\n  private start(): void {\n    AppEvents.initLogging();\n    console.info(\"[AppEvents] App started\");\n\n    /**********************************************************************************************************************\n     * Startup arguments handling\n     **********************************************************************************************************************/\n    if (app.commandLine.hasSwitch(\"version\") || app.commandLine.hasSwitch(\"v\")) {\n      console.log(app.getVersion());\n      app.exit();\n    }\n\n    // Verbose Check\n    if (app.commandLine.hasSwitch(\"verbose\")) {\n      console.log(\"[Cider] User has launched the application with --verbose\");\n    }\n\n    // Log File Location\n    if (app.commandLine.hasSwitch(\"log\") || app.commandLine.hasSwitch(\"l\")) {\n      console.log(join(app.getPath(\"userData\"), \"logs\"));\n      app.exit();\n    }\n\n    // Try limiting JS memory to 350MB.\n    app.commandLine.appendSwitch(\"js-flags\", \"--max-old-space-size=350\");\n\n    // Expose GC\n    app.commandLine.appendSwitch(\"js-flags\", \"--expose_gc\");\n\n    if (process.platform === \"win32\") {\n      app.setAppUserModelId(app.getName()); // For notification name\n    }\n\n    /***********************************************************************************************************************\n     * Commandline arguments\n     **********************************************************************************************************************/\n    switch (utils.getStoreValue(\"visual.hw_acceleration\") as string) {\n      default:\n      case \"default\":\n        app.commandLine.appendSwitch(\"enable-accelerated-mjpeg-decode\");\n        app.commandLine.appendSwitch(\"enable-accelerated-video\");\n        app.commandLine.appendSwitch(\"disable-gpu-driver-bug-workarounds\");\n        app.commandLine.appendSwitch(\"ignore-gpu-blacklist\");\n        app.commandLine.appendSwitch(\"enable-native-gpu-memory-buffers\");\n        app.commandLine.appendSwitch(\"enable-accelerated-video-decode\");\n        app.commandLine.appendSwitch(\"enable-gpu-rasterization\");\n        app.commandLine.appendSwitch(\"enable-native-gpu-memory-buffers\");\n        app.commandLine.appendSwitch(\"enable-oop-rasterization\");\n        break;\n\n      case \"webgpu\":\n        console.info(\"[AppEvents] WebGPU is enabled.\");\n        app.commandLine.appendSwitch(\"enable-unsafe-webgpu\");\n        if (process.platform === \"linux\") {\n          app.commandLine.appendSwitch(\"enable-features\", \"Vulkan\");\n        }\n        break;\n\n      case \"disabled\":\n        console.info(\"[AppEvents] Hardware acceleration is disabled.\");\n        app.commandLine.appendSwitch(\"disable-gpu\");\n        app.disableHardwareAcceleration();\n        break;\n    }\n\n    if (process.platform === \"linux\") {\n      app.commandLine.appendSwitch(\"disable-features\", \"MediaSessionService\");\n\n      if (os.version().includes(\"SteamOS\")) {\n        app.commandLine.appendSwitch(\"enable-features\", \"UseOzonePlatform\");\n        app.commandLine.appendSwitch(\"ozone-platform\", \"x11\");\n      }\n    }\n\n    /***********************************************************************************************************************\n     * Protocols\n     **********************************************************************************************************************/\n    /**  */\n    if (process.defaultApp) {\n      if (process.argv.length >= 2) {\n        this.protocols.forEach((protocol: string) => {\n          app.setAsDefaultProtocolClient(protocol, process.execPath, [resolve(process.argv[1])]);\n        });\n      }\n    } else {\n      this.protocols.forEach((protocol: string) => {\n        app.setAsDefaultProtocolClient(protocol);\n      });\n    }\n  }\n\n  public quit() {\n    console.log(\"[AppEvents] App quit\");\n  }\n\n  public ready(plug: any) {\n    this.plugin = plug;\n    console.log(\"[AppEvents] App ready\");\n\n    AppEvents.setLoginSettings();\n  }\n\n  public bwCreated() {\n    app.on(\"open-url\", (event, url) => {\n      event.preventDefault();\n      if (this.protocols.some((protocol: string) => url.includes(protocol))) {\n        this.LinkHandler(url);\n        console.log(url);\n      }\n    });\n\n    if (process.platform === \"darwin\") {\n      app.setUserActivity(\n        \"8R23J2835D.com.ciderapp.webremote.play\",\n        {\n          title: \"Web Remote\",\n          description: \"Connect to your Web Remote\",\n        },\n        \"https://webremote.cider.sh\",\n      );\n    }\n\n    this.InstanceHandler();\n    if (process.platform !== \"darwin\") {\n      this.InitTray();\n    }\n  }\n\n  /***********************************************************************************************************************\n   * Private methods\n   **********************************************************************************************************************/\n\n  /**\n   * Handles links (URI) and protocols for the application\n   * @param arg\n   */\n  private LinkHandler(arg: string) {\n    if (!arg) return;\n\n    // LastFM Auth URL\n    if (arg.includes(\"auth\")) {\n      const authURI = arg.split(\"/auth/\")[1];\n      if (authURI.startsWith(\"lastfm\")) {\n        // If we wanted more auth options\n        console.log(\"token: \", authURI.split(\"lastfm?token=\")[1]);\n        utils\n          .getWindow()\n          .webContents.executeJavaScript(`ipcRenderer.send('lastfm:auth', ${JSON.stringify(authURI.split(\"lastfm?token=\")[1])})`)\n          .catch(console.error);\n      }\n    } else if (arg.includes(\"playpause\")) {\n      //language=JS\n      utils.getWindow().webContents.executeJavaScript(\"MusicKitInterop.playPause()\");\n    } else if (arg.includes(\"nextitem\")) {\n      //language=JS\n      utils.getWindow().webContents.executeJavaScript(\"app.mk.skipToNextItem()\");\n    }\n    // Play\n    else if (arg.includes(\"/play/\")) {\n      //Steer away from protocol:// specific conditionals\n      const playParam = arg.split(\"/play/\")[1];\n\n      const mediaType = {\n        \"s/\": \"song\",\n        \"a/\": \"album\",\n        \"p/\": \"playlist\",\n      };\n\n      for (const [key, value] of Object.entries(mediaType)) {\n        if (playParam.includes(key)) {\n          const id = playParam.split(key)[1];\n          utils.getWindow().webContents.send(\"play\", value, id);\n          console.debug(`[LinkHandler] Attempting to load ${value} by id: ${id}`);\n        }\n      }\n    } else if (arg.includes(\"music.apple.com\")) {\n      // URL (used with itms/itmss/music/musics uris)\n      console.log(arg);\n      let url = arg.split(\"//\")[1];\n      console.warn(`[LinkHandler] Attempting to load url: ${url}`);\n      utils.getWindow().webContents.send(\"play\", \"url\", url);\n    } else if (arg.includes(\"/debug/appdata\")) {\n      shell.openPath(app.getPath(\"userData\"));\n    } else if (arg.includes(\"/debug/logs\")) {\n      shell.openPath(app.getPath(\"logs\"));\n    } else if (arg.includes(\"/discord\")) {\n      shell.openExternal(\"https://discord.gg/applemusic\");\n    } else if (arg.includes(\"/github\")) {\n      shell.openExternal(\"https://github.com/ciderapp/cider\");\n    } else if (arg.includes(\"/donate\")) {\n      shell.openExternal(\"https://opencollective.com/ciderapp\");\n    } else if (arg.includes(\"/beep\")) {\n      shell.beep();\n    } else {\n      utils.getWindow().webContents.executeJavaScript(`app.appRoute(${JSON.stringify(arg.split(\"//\")[1])})`);\n    }\n  }\n\n  /**\n   * Handles the creation of a new instance of the app\n   */\n  private InstanceHandler() {\n    // Detects of an existing instance is running (So if the lock has been achieved, no existing instance has been found)\n    const gotTheLock = app.requestSingleInstanceLock();\n\n    if (!gotTheLock) {\n      // Runs on the new instance if another instance has been found\n      console.log(\"[Cider] Another instance has been found, quitting.\");\n      app.quit();\n    } else {\n      // Runs on the first instance if no other instance has been found\n      app.on(\"second-instance\", (_event, startArgs) => {\n        console.log(\"[InstanceHandler] (second-instance) Instance started with \" + startArgs.toString());\n\n        startArgs.forEach((arg) => {\n          console.log(arg);\n          if (arg.includes(\"cider://\") || arg.includes(\"itms://\") || arg.includes(\"itmss://\") || arg.includes(\"music://\") || arg.includes(\"musics://\")) {\n            console.debug(\"[InstanceHandler] (second-instance) Link detected with \" + arg);\n            this.LinkHandler(arg);\n          } else if (arg.includes(\"--force-quit\")) {\n            console.warn(\"[InstanceHandler] (second-instance) Force Quit found. Quitting App.\");\n            app.quit();\n          } else if (utils.getWindow()) {\n            if (utils.getWindow().isMinimized()) utils.getWindow().restore();\n            utils.getWindow().show();\n            utils.getWindow().focus();\n          }\n        });\n      });\n    }\n  }\n\n  /**\n   * Initializes the applications tray\n   */\n  private InitTray() {\n    const icons = {\n      win32: nativeImage.createFromPath(join(dirname(fileURLToPath(import.meta.url)), `../../resources/icons/icon.ico`)).resize({\n        width: 32,\n        height: 32,\n      }),\n      linux: nativeImage.createFromPath(join(dirname(fileURLToPath(import.meta.url)), `../../resources/icons/icon.png`)).resize({\n        width: 32,\n        height: 32,\n      }),\n      darwin: nativeImage.createFromPath(join(dirname(fileURLToPath(import.meta.url)), `../../resources/icons/icon.png`)).resize({\n        width: 20,\n        height: 20,\n      }),\n    };\n    this.tray = new Tray(process.platform === \"win32\" ? icons.win32 : process.platform === \"darwin\" ? icons.darwin : icons.linux);\n    this.tray.setToolTip(app.getName());\n    this.setTray(false);\n\n    this.tray.on(\"double-click\", () => {  // supports windows and mac only\n      if (utils.getWindow()) {\n        if (utils.getWindow().isVisible()) {\n          utils.getWindow().focus();\n        } else {\n          utils.getWindow().show();\n        }\n      }\n    });\n\n    this.tray.on(\"click\", () => {\n      if (utils.getWindow() && process.platform === \"linux\") {  // use single click to open when double doesn't work\n        if (utils.getWindow().isVisible()) {\n          utils.getWindow().focus();\n        } else {\n          utils.getWindow().show();\n        }\n      }\n    });\n\n    utils.getWindow().on(\"show\", () => {\n      this.setTray(true);\n    });\n\n    utils.getWindow().on(\"restore\", () => {\n      this.setTray(true);\n    });\n\n    utils.getWindow().on(\"hide\", () => {\n      this.setTray(false);\n    });\n\n    utils.getWindow().on(\"minimize\", () => {\n      this.setTray(false);\n    });\n  }\n\n  /**\n   * Sets the tray context menu to a given state\n   * @param visible - BrowserWindow Visibility\n   */\n  private setTray(visible: boolean = utils.getWindow().isVisible()) {\n    this.i18n = utils.getLocale(utils.getStoreValue(\"general.language\"));\n\n    const ciderIcon = nativeImage.createFromPath(join(dirname(fileURLToPath(import.meta.url)), `../../resources/icons/icon.png`)).resize({\n      width: 24,\n      height: 24,\n    });\n\n    const menu = Menu.buildFromTemplate([\n      {\n        label: app.getName(),\n        enabled: false,\n        icon: ciderIcon,\n      },\n\n      { type: \"separator\" },\n\n      /* For now only idea i dont know if posible to implement\n\n            this could be implemented in a plugin if you would like track info, it would be impractical to put listeners in this file. -Core\n            {\n                label: this.i18n['action.tray.listento'],\n                enabled: false,\n            },\n\n            {\n                visible: visible,\n                label: 'track info',\n                enabled: false,\n            },\n\n            {type: 'separator'},\n            */\n\n      {\n        visible: !visible,\n        label: this.i18n[\"term.playpause\"],\n        click: () => {\n          utils.getWindow().webContents.executeJavaScript(\"MusicKitInterop.playPause()\");\n        },\n      },\n\n      {\n        visible: !visible,\n        label: this.i18n[\"term.next\"],\n        click: () => {\n          utils.getWindow().webContents.executeJavaScript(`MusicKitInterop.next()`);\n        },\n      },\n\n      {\n        visible: !visible,\n        label: this.i18n[\"term.previous\"],\n        click: () => {\n          utils.getWindow().webContents.executeJavaScript(`MusicKitInterop.previous()`);\n        },\n      },\n\n      { type: \"separator\", visible: !visible },\n\n      {\n        label: visible ? this.i18n[\"action.tray.minimize\"] : `${this.i18n[\"action.tray.show\"]}`,\n        click: () => {\n          if (utils.getWindow()) {\n            if (visible) {\n              utils.getWindow().hide();\n            } else {\n              utils.getWindow().show();\n            }\n          }\n        },\n      },\n      {\n        label: this.i18n[\"term.quit\"],\n        click: () => {\n          app.quit();\n        },\n      },\n    ]);\n    this.tray.setContextMenu(menu);\n  }\n\n  /**\n   * Initializes logging in the application\n   * @private\n   */\n  private static initLogging() {\n    log.transports.console.format = \"[{h}:{i}:{s}.{ms}] [{level}] {text}\";\n    Object.assign(console, log.functions);\n    console.debug = function (...args: any[]) {\n      if (!app.isPackaged) {\n        log.debug(...args);\n      }\n    };\n\n    ipcMain.on(\"fetch-log\", (_event) => {\n      const data = readFileSync(log.transports.file.getFile().path, {\n        encoding: \"utf8\",\n        flag: \"r\",\n      });\n      clipboard.writeText(data);\n    });\n  }\n\n  /**\n   * Set login settings\n   * @private\n   */\n  private static setLoginSettings() {\n    if (utils.getStoreValue(\"general.onStartup.enabled\")) {\n      app.setLoginItemSettings({\n        openAtLogin: true,\n        path: app.getPath(\"exe\"),\n        args: [`${utils.getStoreValue(\"general.onStartup.hidden\") ? \"--hidden\" : \"\"}`],\n      });\n    } else {\n      app.setLoginItemSettings({\n        openAtLogin: false,\n        path: app.getPath(\"exe\"),\n      });\n    }\n  }\n}\n"
  },
  {
    "path": "src/main/base/browserwindow.ts",
    "content": "import AdmZip from \"adm-zip\";\nimport { watch } from \"chokidar\";\nimport { ShareMenu, app, BrowserWindow as bw, dialog, ipcMain, nativeTheme, screen, shell } from \"electron\";\nimport windowStateKeeper from \"electron-window-state\";\nimport express from \"express\";\nimport { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from \"fs\";\nimport getPort from \"get-port\";\nimport { LocalFiles } from \"../providers/local/index.js\";\nimport mm from \"music-metadata\";\nimport fetch from \"node-fetch\";\nimport os, { networkInterfaces } from \"os\";\nimport { join } from \"path\";\nimport { Stream } from \"stream\";\nimport { getWallpaper } from \"wallpaper\";\nimport { search } from \"youtube-search-without-api-key\";\nimport { Plugins } from \"./plugins.js\";\nimport { utils } from \"./utils.js\";\nimport { wsapi } from \"./wsapi.js\";\n\n/**\n * @file Creates the BrowserWindow\n * @author CiderCollective\n */\n\n/** @namespace */\nexport class BrowserWindow {\n  public static win: any | undefined = null;\n  private devMode: boolean = !app.isPackaged;\n  public static express: any | undefined = null;\n\n  private audioStream: any = new Stream.PassThrough();\n  private headerSent: any = false;\n  private chromecastIP: any = [];\n  private clientPort: number = 0;\n  private remotePort: number = 6942;\n  private EnvironmentVariables: object = {\n    env: {\n      platform: process.platform,\n      dev: app.isPackaged,\n      osRelease: os.release(),\n      updatable: !process.windowsStore || !process.mas,\n      useV3: utils.getStoreValue(\"advanced.experiments\").includes(\"ampv3\"),\n      components: [\n        \"pages/podcasts\",\n        \"pages/apple-account-settings\",\n        \"pages/library-songs\",\n        \"pages/library-albums\",\n        \"pages/library-artists\",\n        \"pages/library-recentlyadded\",\n        \"pages/browse\",\n        \"pages/groupings\",\n        \"pages/charts\",\n        //\"pages/installed-themes\",\n        \"pages/listen_now\",\n        \"pages/radio\",\n        \"pages/home\",\n        \"pages/artist-feed\",\n        \"pages/cider-playlist\",\n        \"pages/playlist-inline\",\n        \"pages/recordLabel\",\n        \"pages/cider-multiroom\",\n        \"pages/collection-list\",\n        \"pages/apple-curator\",\n        \"pages/artist\",\n        \"pages/search\",\n        \"pages/about\",\n        \"pages/library-videos\",\n        \"pages/remote-pair\",\n        //\"pages/themes-github\",\n        //\"pages/plugins-github\",\n        \"pages/replay\",\n        \"pages/audiolabs\",\n        \"pages/zoo\",\n        \"pages/plugin-renderer\",\n        \"pages/oobe\",\n        \"pages/cider-profile\",\n        \"components/c2-upgrade\",\n        \"components/app-content\",\n        \"components/sidebar\",\n        \"components/mediaitem-artwork\",\n        \"components/artwork-material\",\n        \"components/menu-panel\",\n        \"components/sidebar-playlist\",\n        \"components/audio-settings\",\n        \"components/plugin-menu\",\n        \"components/audio-controls\",\n        \"components/audio-playbackrate\",\n        \"components/qrcode-modal\",\n        \"components/moreinfo-modal\",\n        \"components/equalizer\",\n        \"components/add-to-playlist\",\n        \"components/queue\",\n        \"components/smarthints\",\n        \"components/mediaitem-scroller-horizontal\",\n        \"components/mediaitem-scroller-horizontal-large\",\n        \"components/mediaitem-scroller-horizontal-sp\",\n        \"components/mediaitem-scroller-horizontal-mvview\",\n        \"components/mediaitem-list-item\",\n        \"components/mediaitem-hrect\",\n        \"components/mediaitem-square\",\n        \"components/mediaitem-mvview\",\n        // \"components/libraryartist-item\",\n        \"components/listennow-child\",\n        \"components/mediaitem-mvview-sp\",\n        \"components/animatedartwork-view\",\n        \"components/listitem-horizontal\",\n        \"components/lyrics-view\",\n        \"components/fullscreen\",\n        \"components/miniplayer\",\n        \"components/castmenu\",\n        \"components/pathmenu\",\n        \"components/airplay-modal\",\n        \"components/artist-chip\",\n        \"components/hello-world\",\n        \"components/inline-collection-list\",\n        \"components/settings-window\",\n        \"components/pagination\",\n        \"components/settings-keybinds\",\n        \"components/settings-themes\",\n        \"components/settings-themes-github\",\n        \"components/settings-plugins-github\",\n      ],\n      appRoutes: [\n        {\n          page: \"lzedit\",\n          component: `<i18n-editor></i18n-editor>`,\n          condition: \"$root.page == 'lzedit'\",\n        },\n        {\n          page: \"library-recentlyadded\",\n          component: `<cider-recentlyadded></cider-recentlyadded>`,\n          condition: \"$root.page == 'library-recentlyadded'\",\n        },\n        {\n          page: \"plugin-renderer\",\n          component: `<plugin-renderer></plugin-renderer>`,\n          condition: \"$root.page == 'plugin-renderer'\",\n        },\n        {\n          page: \"zoo\",\n          component: \"<cider-zoo></cider-zoo>\",\n          condition: \"$root.page == 'zoo'\",\n        },\n        {\n          page: \"podcasts\",\n          component: `<apple-podcasts></apple-podcasts>`,\n          condition: `$root.page == 'podcasts'`,\n        },\n        {\n          page: \"library-videos\",\n          component: `<cider-library-videos></cider-library-videos>`,\n          condition: `$root.page == 'library-videos'`,\n        },\n        {\n          page: \"apple-account-settings\",\n          component: `<apple-account-settings></apple-account-settings>`,\n          condition: `$root.page == 'apple-account-settings'`,\n        },\n        {\n          page: \"about\",\n          component: `<about-page></about-page>`,\n          condition: `$root.page == 'about'`,\n        },\n        {\n          page: \"cider-artist\",\n          component: `<cider-artist :data=\"$root.artistPage.data\"></cider-artist>`,\n          condition: `$root.page == 'artist-page' && $root.artistPage.data.attributes`,\n        },\n        {\n          page: \"collection-list\",\n          component: `<cider-collection-list :data=\"$root.collectionList.response\" :type=\"$root.collectionList.type\" :title=\"$root.collectionList.title\"></cider-collection-list>`,\n          condition: `$root.page == 'collection-list'`,\n        },\n        {\n          page: \"home\",\n          component: `<cider-home></cider-home>`,\n          condition: `$root.page == 'home'`,\n        },\n        {\n          page: \"artist-feed\",\n          component: `<cider-artist-feed></cider-artist-feed>`,\n          condition: `$root.page == 'artist-feed'`,\n        },\n        {\n          page: \"playlist-inline\",\n          component: `<playlist-inline :data=\"$root.showingPlaylist\"></playlist-inline>`,\n          condition: `$root.modals.showPlaylist`,\n        },\n        {\n          page: \"playlist_\",\n          component: `<cider-playlist :data=\"$root.showingPlaylist\"></cider-playlist>`,\n          condition: `$root.page.includes('playlist_')`,\n        },\n        {\n          page: \"album_\",\n          component: `<cider-playlist :data=\"$root.showingPlaylist\"></cider-playlist>`,\n          condition: `$root.page.includes('album_')`,\n        },\n        {\n          page: \"recordLabel_\",\n          component: `<cider-recordlabel :data=\"$root.showingPlaylist\"></cider-recordlabel>`,\n          condition: `$root.page.includes('recordLabel_')`,\n        },\n        {\n          page: \"social-profiles_\",\n          component: `<cider-socialprofile :data=\"$root.showingPlaylist\"></cider-socialprofile>`,\n          condition: `$root.page.includes('social-profiles_')`,\n        },\n        {\n          page: \"multiroom\",\n          component: `<cider-multiroom :data=\"$root.multiroom\"></cider-multiroom>`,\n          condition: `$root.page.includes('multiroom')`,\n        },\n        {\n          page: \"curator_\",\n          component: `<cider-recordlabel :data=\"$root.showingPlaylist\"></cider-recordlabel>`,\n          condition: `$root.page.includes('curator_')`,\n        },\n        {\n          page: \"browsepage\",\n          component: `<cider-browse :data=\"$root.browsepage\"></cider-browse>`,\n          condition: `$root.page == 'browse'`,\n          onEnter: ``,\n        },\n        {\n          page: \"groupings\",\n          component: `<cider-groupings :data=\"$root.browsepage\"></cider-groupings>`,\n          condition: `$root.page == 'groupings'`,\n          onEnter: ``,\n        },\n        {\n          page: \"charts\",\n          component: `<cider-charts :data=\"$root.browsepage\"></cider-charts>`,\n          condition: `$root.page == 'charts'`,\n          onEnter: ``,\n        },\n        {\n          page: \"listen_now\",\n          component: `<cider-listen-now :data=\"$root.listennow\"></cider-listen-now>`,\n          condition: `$root.page == 'listen_now'`,\n          onEnter: ``,\n        },\n        {\n          page: \"radio\",\n          component: `<cider-radio :data=\"$root.radio\"></cider-radio>`,\n          condition: `$root.page == 'radio'`,\n          onEnter: ``,\n        },\n        {\n          page: \"settings\",\n          component: `<cider-settings></cider-settings>`,\n          condition: `$root.page == 'settings'`,\n        },\n        {\n          page: \"installed-themes\",\n          component: `<installed-themes></installed-themes>`,\n          condition: `$root.page == 'installed-themes'`,\n        },\n        {\n          page: \"search\",\n          component: `<cider-search :search=\"$root.search\"></cider-search>`,\n          condition: `$root.page == 'search'`,\n        },\n        {\n          page: \"library-songs\",\n          component: `<cider-library-songs :data=\"$root.library.songs\"></cider-library-songs>`,\n          condition: `$root.page == 'library-songs'`,\n          onEnter: ``,\n        },\n        {\n          page: \"library-albums\",\n          component: `<cider-library-albums :data=\"$root.library.songs\"></cider-library-albums>`,\n          condition: `$root.page == 'library-albums'`,\n          onEnter: ``,\n        },\n        {\n          page: \"library-artists\",\n          component: `<cider-library-artists></cider-library-artists>`,\n          condition: `$root.page == 'library-artists'`,\n          onEnter: ``,\n        },\n        {\n          page: \"appleCurator\",\n          component: `<cider-applecurator :data=\"$root.appleCurator\"></cider-applecurator>`,\n          condition: `$root.page.includes('appleCurator')`,\n        },\n        {\n          page: \"themes-github\",\n          component: `<themes-github></themes-github>`,\n          condition: `$root.page == 'themes-github'`,\n        },\n        {\n          page: \"plugins-github\",\n          component: `<plugins-github></plugins-github>`,\n          condition: `$root.page == 'plugins-github'`,\n        },\n        {\n          page: \"remote-pair\",\n          component: `<remote-pair></remote-pair>`,\n          condition: `$root.page == 'remote-pair'`,\n        },\n        {\n          page: \"audiolabs\",\n          component: `<audiolabs-page></audiolabs-page>`,\n          condition: `$root.page == 'audiolabs'`,\n        },\n        {\n          page: \"replay\",\n          component: `<replay-page></replay-page>`,\n          condition: `$root.page == 'replay'`,\n        },\n        {\n          page: \"keydinds\",\n          component: `<keybinds-settings></keybinds-settings>`,\n          condition: `$root.page == 'keybinds-settings'`,\n        },\n      ],\n    },\n  };\n  private options: any = {\n    icon: join(utils.getPath(\"resourcePath\"), `icons/icon.` + (process.platform === \"win32\" ? \"ico\" : \"png\")),\n    width: 1024,\n    height: 600,\n    x: undefined,\n    y: undefined,\n    minWidth: 900,\n    minHeight: 390,\n    frame: false,\n    title: \"Cider\",\n    show: false,\n    // backgroundColor: \"#1E1E1E\",\n    titleBarStyle: \"hidden\",\n    trafficLightPosition: { x: 15, y: 20 },\n    webPreferences: {\n      experimentalFeatures: true,\n      nodeIntegration: true,\n      sandbox: true,\n      allowRunningInsecureContent: true,\n      contextIsolation: false,\n      webviewTag: true,\n      plugins: true,\n      nodeIntegrationInWorker: true,\n      webSecurity: false,\n      preload: join(utils.getPath(\"srcPath\"), \"./preload/cider-preload.js\"),\n    },\n  };\n\n  public static watcher: any;\n\n  StartWatcher(path: string) {\n    BrowserWindow.watcher = watch(path, {\n      ignored: /[\\/\\\\]\\./,\n      persistent: true,\n    });\n\n    function onWatcherReady() {\n      console.info(\"From here can you check for real changes, the initial scan has been completed.\");\n    }\n\n    // Declare the listeners of the watcher\n    BrowserWindow.watcher\n      .on(\"add\", function (path: string) {\n        // console.log('File', path, 'has been added');\n      })\n      .on(\"addDir\", function (path: string) {\n        // console.log('Directory', path, 'has been added');\n      })\n      .on(\"change\", function (path: string) {\n        console.log(\"File\", path, \"has been changed\");\n        BrowserWindow.win.webContents.send(\"theme-update\", \"\");\n      })\n      .on(\"unlink\", function (path: string) {\n        // console.log('File', path, 'has been removed');\n      })\n      .on(\"unlinkDir\", function (path: string) {\n        // console.log('Directory', path, 'has been removed');\n      })\n      .on(\"error\", function (error: string) {\n        // console.log('Error happened', error);\n      })\n      .on(\"ready\", onWatcherReady)\n      .on(\"raw\", function (event: any, path: any, details: any) {\n        // This event should be triggered everytime something happens.\n        // console.log('Raw event info:', event, path, details);\n      });\n  }\n\n  async StopWatcher() {\n    await BrowserWindow.watcher.close();\n  }\n\n  /**\n   * Creates the browser window\n   * @generator\n   * @function createWindow\n   * @yields {object} Electron browser window\n   */\n  async createWindow(): Promise<Electron.BrowserWindow> {\n    const envPort = process.env?.CIDER_PORT || \"9000\";\n    this.clientPort = await getPort({ port: parseInt(envPort, 10) || 9000 });\n    BrowserWindow.verifyFiles();\n    this.StartWatcher(utils.getPath(\"themes\"));\n\n    // Load the previous state with fallback to defaults\n    const windowState = windowStateKeeper({\n      defaultWidth: 1024,\n      defaultHeight: 600,\n      fullScreen: false,\n    });\n    this.options.width = windowState.width;\n    this.options.height = windowState.height;\n    this.options.x = windowState.x;\n    this.options.y = windowState.y;\n\n    switch (process.platform) {\n      default:\n        break;\n      case \"win32\":\n        if (!(utils.getStoreValue(\"visual.transparent\") ?? false)) {\n          this.options.backgroundColor = \"#1E1E1E\";\n        } else {\n          this.options.transparent = true;\n        }\n        this.options.autoHideMenuBar = true;\n        if (utils.getStoreValue(\"visual.nativeTitleBar\")) {\n          this.options.titleBarStyle = \"visible\";\n          this.options.frame = true;\n        }\n        break;\n      case \"linux\":\n        this.options.autoHideMenuBar = true;\n        if (!(utils.getStoreValue(\"visual.transparent\") ?? false)) {\n          this.options.backgroundColor = \"#1E1E1E\";\n        } else {\n          this.options.transparent = true;\n        }\n        if (utils.getStoreValue(\"visual.nativeTitleBar\")) {\n          this.options.titleBarStyle = \"visible\";\n          this.options.frame = true;\n        }\n        break;\n      case \"darwin\":\n        this.options.transparent = true;\n        this.options.vibrancy = \"dark\";\n        this.options.hasShadow = true;\n        break;\n    }\n\n    nativeTheme.themeSource = utils.getStoreValue(\"visual.overrideDisplayTheme\");\n\n    // Start the webserver for the browser window to load\n    // LocalFiles.DB.init()\n    this.startWebServer();\n\n    BrowserWindow.win = new bw(this.options);\n    // cant be built in CI\n    // if (process.platform === \"win32\" && (utils.getStoreValue('visual.transparent') ?? false)) {\n    //     var electronVibrancy = require('electron-vibrancy-updated');\n    //     electronVibrancy.SetVibrancy(BrowserWindow.win, 0);\n\n    // }\n    const ws = new wsapi(BrowserWindow.win);\n    ws.InitWebSockets();\n    // and load the renderer.\n    this.startSession();\n    this.startHandlers();\n\n    // Register listeners on Window to track size and position of the Window.\n    windowState.manage(BrowserWindow.win);\n\n    return BrowserWindow.win;\n  }\n\n  /**\n   * Verifies the files for the renderer to use (Cache, library info, etc.)\n   */\n  private static verifyFiles(): void {\n    const expectedDirectories = [\"CiderCache\"];\n    const expectedFiles = [\"library-songs.json\", \"library-artists.json\", \"library-albums.json\", \"library-playlists.json\", \"library-recentlyAdded.json\"];\n    for (let i = 0; i < expectedDirectories.length; i++) {\n      if (!existsSync(join(app.getPath(\"userData\"), expectedDirectories[i]))) {\n        mkdirSync(join(app.getPath(\"userData\"), expectedDirectories[i]));\n      }\n    }\n    for (let i = 0; i < expectedFiles.length; i++) {\n      const file = join(join(app.getPath(\"userData\"), \"CiderCache\"), expectedFiles[i]);\n      if (!existsSync(file)) {\n        writeFileSync(file, JSON.stringify([]));\n      }\n    }\n  }\n\n  /**\n   * Starts the webserver for the renderer process.\n   */\n  private startWebServer(): void {\n    const app = express();\n    BrowserWindow.express = app;\n    app.use(express.static(join(utils.getPath(\"srcPath\"), \"./renderer/\")));\n    app.set(\"views\", join(utils.getPath(\"srcPath\"), \"./renderer/views\"));\n    app.set(\"view engine\", \"ejs\");\n    let firstRequest = true;\n    app.use((req, res, next) => {\n      if (!req || !req.headers || !req.headers.host || !req.headers[\"user-agent\"]) {\n        console.error(\"Req not defined\");\n        return;\n      }\n      if (req.url.includes(\"api\") || req.url.includes(\"audio.wav\") || (req.headers.host.includes(\"localhost\") && (this.devMode || req.headers[\"user-agent\"].includes(\"Electron\"))) || req.url.includes(\"/connect\")) {\n        next();\n      } else {\n        res.redirect(\"https://discord.gg/applemusic\");\n      }\n    });\n\n    app.get(\"/\", (_req, res) => {\n      res.render(\"main\", this.EnvironmentVariables);\n    });\n\n    app.get(\"/audio/cideraudio.js\", (_req, res) => {\n      if (existsSync(join(utils.getPath(\"externals\"), \"/audio.js\"))) {\n        if (utils.getStoreValue(\"audio.maikiwiAudio.cloud\") == true) {\n          res.sendFile(join(utils.getPath(\"externals\"), \"/cloud/audio.js\"));\n        } else {\n          res.sendFile(join(utils.getPath(\"externals\"), \"/audio.js\"));\n        }\n      } else {\n        res.sendFile(join(utils.getPath(\"srcPath\"), \"./renderer/audio/audio.js\"));\n      }\n    });\n\n    app.get(\"/cideraudio/impulses/:file\", (req, res) => {\n      const impulseExternals = join(utils.getPath(\"externals\"), \"/impulses/\");\n      const impulseFile = join(impulseExternals, req.params.file);\n      if (existsSync(impulseFile)) {\n        res.sendFile(impulseFile);\n      } else {\n        res.sendFile(join(utils.getPath(\"srcPath\"), \"./renderer/audio/impulses/\" + req.params.file));\n      }\n    });\n\n    app.get(\"/api/playback/:action\", (req, res) => {\n      const action = req.params.action;\n      switch (action) {\n        case \"playpause\":\n          BrowserWindow.win.webContents.executeJavaScript(\"wsapi.togglePlayPause()\");\n          res.send(\"Play/Pause toggle\");\n          break;\n        case \"play\":\n          BrowserWindow.win.webContents.executeJavaScript(\"MusicKit.getInstance().play()\");\n          res.send(\"Playing\");\n          break;\n        case \"pause\":\n          BrowserWindow.win.webContents.executeJavaScript(\"MusicKit.getInstance().pause()\");\n          res.send(\"Paused\");\n          break;\n        case \"stop\":\n          BrowserWindow.win.webContents.executeJavaScript(\"MusicKit.getInstance().stop()\");\n          res.send(\"Stopped\");\n          break;\n        case \"next\":\n          BrowserWindow.win.webContents.executeJavaScript(\"if (MusicKit.getInstance().queue.nextPlayableItemIndex != -1 && MusicKit.getInstance().queue.nextPlayableItemIndex != null) {MusicKit.getInstance().changeToMediaAtIndex(MusicKit.getInstance().queue.nextPlayableItemIndex);}\");\n          res.send(\"Next\");\n          break;\n        case \"previous\":\n          BrowserWindow.win.webContents.executeJavaScript(\"if (MusicKit.getInstance().queue.previousPlayableItemIndex != -1 && MusicKit.getInstance().queue.previousPlayableItemIndex != null) {MusicKit.getInstance().changeToMediaAtIndex(MusicKit.getInstance().queue.previousPlayableItemIndex);}\");\n          res.send(\"Previous\");\n          break;\n        default: {\n          res.send(\"Invalid action\");\n        }\n      }\n    });\n\n    app.get(\"/themes/:theme\", (req, res) => {\n      const theme = req.params.theme;\n      const themePath = join(utils.getPath(\"srcPath\"), \"./renderer/themes/\", theme);\n      const userThemePath = join(utils.getPath(\"themes\"), theme);\n      if (existsSync(userThemePath)) {\n        res.sendFile(userThemePath);\n      } else if (existsSync(themePath)) {\n        res.sendFile(themePath);\n      } else {\n        res.send(`// Theme not found - ${userThemePath}`);\n      }\n    });\n\n    app.get(\"/themes/:theme/*\", (req: { params: { theme: string; 0: string } }, res) => {\n      const theme = req.params.theme;\n      const file = req.params[0];\n      const themePath = join(utils.getPath(\"srcPath\"), \"./renderer/themes/\", theme);\n      const userThemePath = join(utils.getPath(\"themes\"), theme);\n      if (existsSync(userThemePath)) {\n        res.sendFile(join(userThemePath, file));\n      } else if (existsSync(themePath)) {\n        res.sendFile(join(themePath, file));\n      } else {\n        res.send(`// File not found - ${userThemePath}`);\n      }\n    });\n\n    app.get(\"/plugins/:plugin/*\", (req: { params: { plugin: string; 0: string } }, res) => {\n      let plugin = req.params.plugin;\n      if (Plugins.getPluginFromMap(plugin)) {\n        plugin = Plugins.getPluginFromMap(plugin);\n      }\n      const file = req.params[0];\n      const pluginPath = join(utils.getPath(\"plugins\"), plugin);\n      console.log(pluginPath);\n      if (existsSync(pluginPath)) {\n        res.sendFile(join(pluginPath, file));\n      } else {\n        res.send(`// Plugin not found - ${pluginPath}`);\n      }\n    });\n\n    app.get(\"/audio.wav\", (req, res) => {\n      try {\n        const ip = req.headers[\"x-forwarded-for\"] || req.connection.remoteAddress;\n        if (!this.chromecastIP.includes(ip)) {\n          this.headerSent = false;\n          this.audioStream._readableState.buffer.clear();\n          this.audioStream._readableState.length = 0;\n          this.chromecastIP.push(ip);\n        }\n        req.socket.setTimeout(Number.MAX_SAFE_INTEGER);\n        // CiderBase.requests.push({req: req, res: res});\n        // var pos = CiderBase.requests.length - 1;\n        req.on(\"close\", () => {\n          console.log(\"disconnected\");\n          this.headerSent = false;\n          this.chromecastIP = this.chromecastIP.filter((item: any) => item !== ip);\n        });\n\n        this.audioStream.on(\"data\", (data: any) => {\n          try {\n            res.write(data);\n          } catch (ex) {\n            console.log(ex);\n          }\n        });\n      } catch (ex) {\n        console.log(ex);\n      }\n    });\n    //region Connect Integration\n    app.get(\"/connect/set-cc-user/:data\", (req, res) => {\n      //utils.getStoreValue('connectUser', JSON.parse()) // [Connect] Save user in store\n      utils.getWindow().webContents.send(\"setStoreValue\", \"connectUser\", JSON.parse(req.params.data));\n      res.redirect(`https://connect.cidercollective.dev/linked.html`);\n    });\n\n    LocalFiles.setupHandlers();\n\n    // [Connect] Set auth URL in store for `shell.openExternal`\n    utils.setStoreValue(\"cc_authURL\", `https://connect.cidercollective.dev/callback/discord?app=cider&appPort=${this.clientPort}`);\n    console.log(`[Connect] Auth URL: ${utils.getStoreValue(\"cc_authURL\")}`);\n    //endregion\n\n    app.listen(this.clientPort, () => {\n      console.log(`Cider client port: ${this.clientPort}`);\n    });\n\n    /*\n     * Remote Client -@quacksire\n     * https://github.com/ciderapp/Apple-Music-Electron/blob/818189ed40ff600d76eb59d22016723a75885cd5/resources/functions/handler.js#L1173\n     */\n    const remote = express();\n    remote.use(express.static(join(utils.getPath(\"srcPath\"), \"./web-remote/\")));\n    remote.set(\"views\", join(utils.getPath(\"srcPath\"), \"./web-remote/views\"));\n    remote.set(\"view engine\", \"ejs\");\n    getPort({ port: 6942 }).then((port: number) => {\n      this.remotePort = port;\n      // Start Remote Discovery\n      this.broadcastRemote();\n      remote.listen(this.remotePort, () => {\n        console.log(`Cider remote port: ${this.remotePort}`);\n        firstRequest = false;\n      });\n      remote.get(\"/\", (_req, res) => {\n        res.render(\"index\", this.EnvironmentVariables);\n      });\n    });\n  }\n\n  /**\n   * Starts the session for the renderer process.\n   */\n  private startSession(): void {\n    // intercept \"https://js-cdn.music.apple.com/hls.js/2.141.1/hls.js/hls.js\" and redirect to local file \"./apple-hls.js\" instead\n    BrowserWindow.win.webContents.session.webRequest.onBeforeRequest(\n      {\n        urls: [\"https://*/*\"],\n      },\n      (details: { url: string | string[] }, callback: (arg0: { redirectURL?: string; cancel?: boolean }) => void) => {\n        if (details.url.includes(\"hls.js\")) {\n          callback({\n            redirectURL: `http://localhost:${this.clientPort}/apple-hls.js`,\n          });\n        } else if (details.url.includes(\"ciderlocal\") && !details.url.includes(\"https://apic-desktop.musixmatch.com\")) {\n          let text = details.url.toString().includes(\"ids=\") ? decodeURIComponent(details.url.toString()).split(\"?ids=\")[1] : decodeURIComponent(details.url.toString().substring(details.url.toString().lastIndexOf(\"/\") + 1));\n          //console.log('localurl',text)\n          callback({\n            redirectURL: `http://localhost:${this.clientPort}/ciderlocal/${Buffer.from(text).toString(\"base64url\")}`,\n          });\n        } else {\n          callback({\n            cancel: false,\n          });\n        }\n      },\n    );\n\n    BrowserWindow.win.webContents.session.webRequest.onBeforeSendHeaders(async (details: { url: string; requestHeaders: { [x: string]: string } }, callback: (arg0: { requestHeaders: any }) => void) => {\n      if (details.url === \"https://buy.itunes.apple.com/account/web/info\") {\n        details.requestHeaders[\"sec-fetch-site\"] = \"same-site\";\n        details.requestHeaders[\"DNT\"] = \"1\";\n        let itspod = await BrowserWindow.win.webContents.executeJavaScript(`window.localStorage.getItem(\"music.ampwebplay.itspod\")`);\n        if (itspod != null) details.requestHeaders[\"Cookie\"] = `itspod=${itspod}`;\n      }\n      if (details.url.includes(\"apple.com\")) {\n        details.requestHeaders[\"DNT\"] = \"1\";\n        details.requestHeaders[\"authority\"] = \"amp-api.music.apple.com\";\n        details.requestHeaders[\"origin\"] = \"https://beta.music.apple.com\";\n        details.requestHeaders[\"referer\"] = \"https://beta.music.apple.com\";\n        details.requestHeaders[\"sec-fetch-dest\"] = \"empty\";\n        details.requestHeaders[\"sec-fetch-mode\"] = \"cors\";\n        details.requestHeaders[\"sec-fetch-site\"] = \"same-site\";\n      }\n      if (details.url.startsWith(\"https://music.163.com\")) {\n        details.requestHeaders[\"Referer\"] = \"https://music.163.com/\";\n        details.requestHeaders[\"user-agent\"] = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Cider/1.0.0 Chrome/96.0.4664.45 Electron/16.0.0 Safari/537.36\";\n      }\n      if (details.url.includes(\"https://qq.com\")) {\n        (details.requestHeaders[\"Accept\"] = \"*/*\"), (details.requestHeaders[\"Accept-Encoding\"] = \"gzip, deflate, br\"), (details.requestHeaders[\"Accept-Language\"] = \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\"), (details.requestHeaders[\"Referer\"] = \"https://y.qq.com/\"), (details.requestHeaders[\"User-Agent\"] = \"Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (\");\n        (\"KHTML, like Gecko) Mobile/17D50 UCBrowser/12.8.2.1268 Mobile AliApp(TUnionSDK/0.1.20.3) \");\n      }\n      if (details.url.includes(\"https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg\")) {\n        (details.requestHeaders[\"Accept\"] = \"*/*\"), (details.requestHeaders[\"Accept-Encoding\"] = \"gzip, deflate, br\"), (details.requestHeaders[\"Accept-Language\"] = \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\"), (details.requestHeaders[\"User-Agent\"] = \"Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (\");\n        (\"KHTML, like Gecko) Mobile/17D50 UCBrowser/12.8.2.1268 Mobile AliApp(TUnionSDK/0.1.20.3) \");\n        details.requestHeaders[\"Referer\"] = \"https://y.qq.com/portal/player.html\";\n      }\n      callback({ requestHeaders: details.requestHeaders });\n    });\n\n    let location = `http://localhost:${this.clientPort}/`;\n\n    if (app.isPackaged) {\n      BrowserWindow.win.loadURL(location);\n    } else {\n      BrowserWindow.win.loadURL(location, {\n        userAgent: \"Cider Development Environment\",\n      });\n    }\n  }\n\n  /**\n   * Initializes the window handlers\n   */\n  private startHandlers(): void {\n    /**********************************************************************************************************************\n     * ipcMain Events\n     ****************************************************************************************************************** */\n\n    ipcMain.handle(\"mkv3\", async (event, args) => {\n      const options = {\n        route: \"\",\n        token: \"\",\n        mediaToken: \"\",\n        GETBody: {},\n      };\n      Object.assign(options, args);\n\n      let res = await fetch(\n        `https://amp-api.music.apple.com/${options.route}?${new URLSearchParams({\n          ...options.GETBody,\n        }).toString()}`,\n        {\n          method: \"GET\",\n          headers: {\n            \"Content-Type\": \"application/json\",\n            authorization: `Bearer ${options.token}`,\n            path: options.route,\n            authority: \"amp-api.music.apple.com\",\n            \"media-user-token\": options.mediaToken,\n            \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Cider/1.4.2 Chrome/100.0.4896.75 Electron/18.0.3 Safari/537.36\",\n          },\n        },\n      );\n      let json = await res.json();\n      return json;\n    });\n\n    ipcMain.on(\"get-wallpaper\", async (event, args) => {\n      const wpPath: string = await getWallpaper();\n      const Jimp = (await import(\"jimp\")).default;\n      const img = await Jimp.read(wpPath);\n      const blurAmount = args.blurAmount ?? 256;\n      if (blurAmount) {\n        img.blur(blurAmount);\n      }\n      const screens = await screen.getAllDisplays();\n      const width = screens.reduce((a, b) => a + b.size.width, 0);\n      const height = screens.reduce((a, b) => a + b.size.height, 0);\n\n      img.cover(width, height, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_MIDDLE);\n      const result = await img.getBase64Async(Jimp.MIME_PNG);\n\n      event.returnValue = {\n        path: wpPath,\n        data: result,\n        res: {\n          width: width,\n          height: height,\n        },\n      };\n    });\n\n    ipcMain.handle(\"uninstall-theme\", async (event, path) => {\n      await this.StopWatcher();\n      const themesDir = utils.getPath(\"themes\");\n      // validate the path is in the themes directory\n      try {\n        if (path.startsWith(themesDir)) {\n          // get last dir in path, can be either / or \\ and may have a trailing slash\n          const themeName = path.split(/[\\\\\\/]/).pop();\n          if (themeName == \"Themes\" || themeName == \"themes\") {\n            BrowserWindow.win.webContents.send(\"theme-uninstalled\", {\n              path: path,\n              status: 3,\n            });\n            return;\n          }\n          // if path is directory, delete it\n          if (lstatSync(path).isDirectory()) {\n            await rmdirSync(path, { recursive: true });\n          } else {\n            // if path is file, delete it\n            await unlinkSync(path);\n          }\n          // return the path\n          BrowserWindow.win.webContents.send(\"theme-uninstalled\", {\n            path: path,\n            status: 0,\n          });\n        } else {\n          BrowserWindow.win.webContents.send(\"theme-uninstalled\", {\n            path: path,\n            status: 1,\n          });\n        }\n      } catch (e: any) {\n        BrowserWindow.win.webContents.send(\"theme-uninstalled\", {\n          path: path,\n          message: e.message,\n          status: 2,\n        });\n      }\n\n      this.StartWatcher(utils.getPath(\"themes\"));\n    });\n\n    ipcMain.handle(\"reinstall-widevine-cdm\", () => {\n      // remove WidevineCDM from appdata folder\n      const widevineCdmPath = join(app.getPath(\"userData\"), \"./WidevineCdm\");\n      if (existsSync(widevineCdmPath)) {\n        rmSync(widevineCdmPath, { recursive: true, force: true });\n      }\n      // reinstall WidevineCDM\n      app.relaunch();\n      app.exit();\n    });\n\n    ipcMain.handle(\"get-github-plugin\", async (event, url) => {\n      await this.StopWatcher();\n      const returnVal = {\n        success: true,\n        theme: null,\n        message: \"\",\n      };\n      try {\n        if (!existsSync(utils.getPath(\"plugins\"))) {\n          mkdirSync(utils.getPath(\"plugins\"));\n        }\n        if (url.endsWith(\"/\")) url = url.slice(0, -1);\n        let response = await utils.fetch(`${url}/archive/refs/heads/main.zip`);\n        let repo = url.split(\"/\").slice(-2).join(\"/\");\n        let apiRepo = await utils.fetch(`https://api.github.com/repos/${repo}`).then((res) => res.json()) as { id: number };\n        console.debug(`REPO ID: ${apiRepo.id}`);\n        // extract the files from the first folder in the zip response\n        let zip = new AdmZip(await response.buffer());\n        let entry = zip.getEntries()[0];\n        if (!existsSync(join(utils.getPath(\"plugins\"), \"gh_\" + apiRepo.id))) {\n          mkdirSync(join(utils.getPath(\"plugins\"), \"gh_\" + apiRepo.id));\n        }\n        console.log(join(utils.getPath(\"plugins\"), \"gh_\" + apiRepo.id));\n        zip.extractEntryTo(entry, join(utils.getPath(\"plugins\"), \"gh_\" + apiRepo.id), false, true);\n        let commit = await utils.fetch(`https://api.github.com/repos/${repo}/commits`).then((res) => res.json()) as { sha: string }[];\n        console.debug(`COMMIT SHA: ${commit[0].sha}`);\n        let theme = JSON.parse(readFileSync(join(utils.getPath(\"plugins\"), \"gh_\" + apiRepo.id, \"package.json\"), \"utf8\"));\n        theme.id = apiRepo.id;\n        theme.commit = commit[0].sha;\n        writeFileSync(join(utils.getPath(\"plugins\"), \"gh_\" + apiRepo.id, \"package.json\"), JSON.stringify(theme, null, 4), \"utf8\");\n      } catch (e) {\n        returnVal.success = false;\n      }\n      BrowserWindow.win.webContents.send(\"plugin-installed\", returnVal);\n      this.StartWatcher(utils.getPath(\"themes\"));\n    });\n\n    ipcMain.handle(\"get-github-theme\", async (event, url) => {\n      await this.StopWatcher();\n      const returnVal = {\n        success: true,\n        theme: null,\n        message: \"\",\n      };\n      try {\n        if (!existsSync(utils.getPath(\"themes\"))) {\n          mkdirSync(utils.getPath(\"themes\"));\n        }\n        if (url.endsWith(\"/\")) url = url.slice(0, -1);\n        let response = await utils.fetch(`${url}/archive/refs/heads/main.zip`);\n        let repo = url.split(\"/\").slice(-2).join(\"/\");\n        let apiRepo = await utils\n          .fetch(`https://api.github.com/repos/${repo}`, {\n            headers: {\n              \"User-Agent\": utils.getWindow().webContents.getUserAgent(),\n            },\n          })\n          .then((res) => res.json()) as { id: number }\n        console.error(apiRepo);\n        console.debug(`REPO ID: ${apiRepo.id}`);\n        // extract the files from the first folder in the zip response\n        let zip = new AdmZip(await response.buffer());\n        if (!existsSync(join(utils.getPath(\"themes\"), \"gh_\" + apiRepo.id))) {\n          mkdirSync(join(utils.getPath(\"themes\"), \"gh_\" + apiRepo.id));\n        }\n        console.log(join(utils.getPath(\"themes\"), \"gh_\" + apiRepo.id));\n        zip.getEntries().forEach((entry) => {\n          if (entry.entryName.endsWith(\"/\")) return;\n          let subFolder = entry.entryName.split(\"/\").slice(1, -1).join(\"/\");\n          zip.extractEntryTo(entry, join(utils.getPath(\"themes\"), \"gh_\" + apiRepo.id, \"/\", subFolder), false, true);\n        });\n        let commit = await utils.fetch(`https://api.github.com/repos/${repo}/commits`).then((res) => res.json()) as { sha: string }[];\n        console.debug(`COMMIT SHA: ${commit[0].sha}`);\n        let theme = JSON.parse(readFileSync(join(utils.getPath(\"themes\"), \"gh_\" + apiRepo.id, \"theme.json\"), \"utf8\"));\n        theme.id = apiRepo.id;\n        theme.commit = commit[0].sha;\n        writeFileSync(join(utils.getPath(\"themes\"), \"gh_\" + apiRepo.id, \"theme.json\"), JSON.stringify(theme, null, 4), \"utf8\");\n      } catch (e) {\n        console.error(e);\n        returnVal.success = false;\n      }\n      BrowserWindow.win.webContents.send(\"theme-installed\", returnVal);\n      this.StartWatcher(utils.getPath(\"themes\"));\n      BrowserWindow.win.webContents.send(\"theme-update\", \"\");\n    });\n\n    ipcMain.on(\"get-themes\", (event, _key) => {\n      if (existsSync(utils.getPath(\"themes\"))) {\n        let files = readdirSync(utils.getPath(\"themes\"));\n        let themes = [];\n        for (let file of files) {\n          if (file.endsWith(\".less\")) {\n            themes.push(file);\n          } else if (statSync(join(utils.getPath(\"themes\"), file)).isDirectory()) {\n            let subFiles = readdirSync(join(utils.getPath(\"themes\"), file));\n            for (let subFile of subFiles) {\n              if (subFile.endsWith(\"index.less\")) {\n                themes.push(join(file, subFile));\n              }\n            }\n          }\n        }\n        let themeObjects = [];\n        for (let theme of themes) {\n          let themePath = join(utils.getPath(\"themes\"), theme);\n          let themeName = theme;\n          let themeDescription = \"\";\n          if (theme.includes(\"/\")) {\n            themeName = theme.split(\"/\")[1];\n            themeDescription = theme.split(\"/\")[0];\n          }\n          if (themePath.endsWith(\"index.less\")) {\n            themePath = themePath.slice(0, -10);\n          }\n          if (existsSync(join(themePath, \"theme.json\"))) {\n            try {\n              let themeJson = JSON.parse(readFileSync(join(themePath, \"theme.json\"), \"utf8\"));\n              themeObjects.push({\n                name: themeJson.name || themeName,\n                description: themeJson.description || themeDescription,\n                path: themePath,\n                file: theme,\n                github_repo: themeJson.github_repo || \"\",\n                commit: themeJson.commit || \"\",\n                pack: themeJson.pack || false,\n              });\n            } catch (e) {\n              console.error(e);\n            }\n          } else {\n            themeObjects.push({\n              name: themeName,\n              description: themeDescription,\n              path: themePath,\n              file: theme,\n              github_repo: \"\",\n              commit: \"\",\n              pack: false,\n            });\n          }\n        }\n        event.returnValue = themeObjects;\n      } else {\n        event.returnValue = [];\n      }\n    });\n\n    ipcMain.handle(\"open-path\", async (event, path) => {\n      switch (path) {\n        default:\n        case \"plugins\":\n          if (existsSync(utils.getPath(\"plugins\"))) {\n            shell.openPath(utils.getPath(\"plugins\"));\n          } else {\n            mkdirSync(utils.getPath(\"plugins\"));\n            shell.openPath(utils.getPath(\"plugins\"));\n          }\n          break;\n        case \"userdata\":\n          shell.openPath(app.getPath(\"userData\"));\n          break;\n        case \"themes\":\n          if (existsSync(utils.getPath(\"themes\"))) {\n            shell.openPath(utils.getPath(\"themes\"));\n          } else {\n            mkdirSync(utils.getPath(\"themes\"));\n            shell.openPath(utils.getPath(\"themes\"));\n          }\n          break;\n      }\n    });\n\n    ipcMain.on(\"get-i18n\", (event, key) => {\n      event.returnValue = utils.getLocale(key);\n    });\n\n    ipcMain.on(\"get-i18n-listing\", (event) => {\n      const translations = utils.i18n;\n      const i18nListing: any = [];\n\n      for (const lang in translations) {\n        i18nListing.push({\n          code: lang,\n          nameNative: translations[lang][0].content[\"i18n.languageName\"] ?? lang,\n          nameEnglish: translations[lang][0].content[\"i18n.languageNameEnglish\"] ?? lang,\n          category: translations[lang][0].content[\"i18n.category\"] ?? \"\",\n          authors: translations[lang][0].content[\"i18n.authors\"] ?? \"\",\n        });\n      }\n\n      event.returnValue = i18nListing;\n    });\n\n    ipcMain.on(\"get-gpu-mode\", (event) => {\n      event.returnValue = process.platform;\n    });\n\n    ipcMain.on(\"get-port\", (event) => {\n      event.returnValue = this.clientPort;\n    });\n\n    ipcMain.on(\"is-dev\", (event) => {\n      event.returnValue = this.devMode;\n    });\n\n    ipcMain.handle(\"put-cache\", (_event, arg) => {\n      writeFileSync(join(join(app.getPath(\"userData\"), \"CiderCache\"), `${arg.file}.json`), arg.data);\n    });\n\n    ipcMain.on(\"get-cache\", (event, arg) => {\n      let read = \"\";\n      if (existsSync(join(join(app.getPath(\"userData\"), \"CiderCache\"), `${arg}.json`))) {\n        read = readFileSync(join(join(app.getPath(\"userData\"), \"CiderCache\"), `${arg}.json`), \"utf8\");\n      }\n      event.returnValue = read;\n    });\n\n    ipcMain.handle(\"getYTLyrics\", async (_event, track, artist) => {\n      const u = track + \" \" + artist + \" official video\";\n      return await search(u);\n    });\n\n    ipcMain.on(\"close\", (_event) => {\n      BrowserWindow.win.close();\n    });\n\n    ipcMain.on(\"maximize\", (_event) => {\n      // listen for maximize event\n      if (BrowserWindow.win.isMaximized()) {\n        BrowserWindow.win.unmaximize();\n      } else {\n        BrowserWindow.win.maximize();\n      }\n    });\n    ipcMain.on(\"unmaximize\", () => {\n      // listen for maximize event\n      BrowserWindow.win.unmaximize();\n    });\n\n    ipcMain.on(\"minimize\", () => {\n      // listen for minimize event\n      BrowserWindow.win.minimize();\n    });\n\n    // Set scale\n    ipcMain.on(\"setScreenScale\", (_event, scale) => {\n      BrowserWindow.win.webContents.setZoomFactor(parseFloat(scale));\n    });\n\n    ipcMain.on(\"windowmin\", (_event, width, height) => {\n      BrowserWindow.win.setMinimumSize(width, height);\n    });\n\n    ipcMain.on(\"windowontop\", (_event, ontop) => {\n      BrowserWindow.win.setAlwaysOnTop(ontop);\n    });\n\n    // Set scale\n    ipcMain.on(\"windowresize\", (_event, width, height, lock = false) => {\n      BrowserWindow.win.setContentSize(width, height);\n      BrowserWindow.win.setResizable(!lock);\n    });\n\n    // Move window\n    ipcMain.on(\"windowmove\", (_event, x, y) => {\n      BrowserWindow.win.setBounds({ x, y });\n    });\n\n    // Override light, dark\n    ipcMain.on(\"changeDisplayTheme\", (event, theme) => {\n      nativeTheme.themeSource = theme;\n    });\n\n    //Fullscreen\n    ipcMain.on(\"setFullScreen\", (_event, flag) => {\n      BrowserWindow.win.setFullScreen(flag);\n    });\n\n    //Fullscreen\n    ipcMain.on(\"getFullScreen\", (event, flag) => {\n      event.returnValue = BrowserWindow.win.isFullScreen();\n    });\n\n    //Fullscreen\n    ipcMain.on(\"detachDT\", (_event, _) => {\n      BrowserWindow.win.webContents.openDevTools({ mode: \"detach\" });\n    });\n\n    ipcMain.handle(\"relaunchApp\", (_event, _) => {\n      const opt: Electron.RelaunchOptions = {};\n      opt.args = process.argv.slice(1).concat([\"--relaunch\"]);\n      opt.execPath = process.execPath;\n      if (app.isPackaged && process.env.PORTABLE_EXECUTABLE_FILE != undefined) {\n        opt.execPath = process.env.PORTABLE_EXECUTABLE_FILE;\n      } else if (app.isPackaged && process.env.APPIMAGE != undefined) {\n        opt.execPath = process.env.APPIMAGE;\n        opt.args.unshift(\"--appimage-extract-and-run\");\n      } else if (app.isPackaged && process.env.CHROME_DESKTOP != undefined && process.env.PLATFORM == \"Linux\") {\n        opt.execPath = \"cider\";\n      }\n      app.relaunch(opt);\n      app.quit();\n    });\n\n    ipcMain.handle(\"quit-app\", (_event, _) => {\n      app.quit();\n    });\n\n    ipcMain.on(\"play\", (_event, type, id) => {\n      BrowserWindow.win.webContents.executeJavaScript(`\n\t\t\t    MusicKit.getInstance().setQueue({ ${type}: '${id}', parameters : {l : app.mklang}}).then(function(queue) {\n\t\t\t\t    MusicKit.getInstance().play();\n\t\t\t    });\n\t\t    `);\n    });\n\n    // ipcMain.handle(\"scanLibrary\", async (event, folders) => {\n    //   // const oldmetadatalist = await LocalFiles.sendOldLibrary();\n    //   // BrowserWindow.win.webContents.send(\"getUpdatedLocalList\", oldmetadatalist);\n    //   const metadatalist = await LocalFiles.scanLibrary();\n    //   BrowserWindow.win.webContents.send(\"getUpdatedLocalList\", metadatalist);\n    //   LocalFiles.localSongs = metadatalist;\n    //   // LocalFiles.cleanUpDB();\n    // });\n\n    LocalFiles.eventEmitter.on(\"newtracks\", (data) => {\n      BrowserWindow.win.webContents.send(\"getUpdatedLocalList\", data);\n    });\n\n    ipcMain.on(\"writeWAV\", (event, leftpcm, rightpcm, bufferlength) => {\n      function interleave16(leftChannel: any, rightChannel: any) {\n        var length = leftChannel.length + rightChannel.length;\n        var result = new Int16Array(length);\n\n        var inputIndex = 0;\n\n        for (var index = 0; index < length;) {\n          result[index++] = leftChannel[inputIndex];\n          result[index++] = rightChannel[inputIndex];\n          inputIndex++;\n        }\n        return result;\n      }\n\n      //https://github.com/HSU-ANT/jsdafx\n\n      function quantization(audiobufferleft: any, audiobufferright: any) {\n        let h = Float32Array.from([1]);\n        let nsState = new Array(0);\n        let ditherstate = new Float32Array(0);\n        let qt = Math.pow(2, 1 - 16);\n\n        //noise shifting order 3\n        h = Float32Array.from([1.623, -0.982, 0.109]);\n        for (let i = 0; i < nsState.length; i++) {\n          nsState[i] = new Float32Array(h.length);\n        }\n\n        function setChannelCount(nc: any) {\n          if (ditherstate.length !== nc) {\n            ditherstate = new Float32Array(nc);\n          }\n          if (nsState.length !== nc) {\n            nsState = new Array(nc);\n            for (let i = 0; i < nsState.length; i++) {\n              nsState[i] = new Float32Array(h.length);\n            }\n          }\n        }\n\n        function hpDither(channel: any) {\n          const rnd = Math.random() - 0.5;\n          const d = rnd - ditherstate[channel];\n          ditherstate[channel] = rnd;\n          return d;\n        }\n\n        setChannelCount(2);\n        const inputs = [audiobufferleft, audiobufferright];\n        const outputs = [audiobufferleft, audiobufferright];\n\n        for (let channel = 0; channel < inputs.length; channel++) {\n          const inputData = inputs[channel];\n          const outputData = outputs[channel];\n          for (let sample = 0; sample < bufferlength; sample++) {\n            let input = inputData[sample];\n            // console.log('a2',inputData.length);\n            for (let i = 0; i < h.length; i++) {\n              input -= h[i] * nsState[channel][i];\n            }\n            // console.log('a3',input);\n            let d_rand = 0.0;\n            // ditherstate = new Float32Array(h.length);\n            // d_rand = hpDither(channel);\n            const tmpOutput = qt * Math.round(input / qt + d_rand);\n            for (let i = h.length - 1; i >= 0; i--) {\n              nsState[channel][i] = nsState[channel][i - 1];\n            }\n            nsState[channel][0] = tmpOutput - input;\n            outputData[sample] = tmpOutput;\n          }\n        }\n        return outputs;\n      }\n\n      function convert(n: any) {\n        var v = n < 0 ? n * 32768 : n * 32767; // convert in range [-32768, 32767]\n        return Math.max(-32768, Math.min(32768, v)); // clamp\n      }\n\n      function bitratechange(e: any) {\n        var t = e.length;\n        let sampleRate = 96.0;\n        let outputSampleRate = 48.0;\n        var s = 0,\n          o = sampleRate / outputSampleRate,\n          u = Math.ceil((t * outputSampleRate) / sampleRate),\n          a = new Int16Array(u);\n        for (let i = 0; i < u; i++) {\n          a[i] = e[Math.floor(s)];\n          s += o;\n        }\n\n        return a;\n      }\n\n      let newaudio = quantization(leftpcm, rightpcm);\n      //let newaudio = [leftpcm, rightpcm];\n      // console.log(newaudio.length);\n\n      const pcmData = Buffer.from(new Uint8Array(interleave16(\n        bitratechange(Int16Array.from(newaudio[0], (x) => convert(x))),\n        bitratechange(Int16Array.from(newaudio[1], (x) => convert(x)))\n      ).buffer));\n\n      if (!this.headerSent) {\n        console.log(\"new header\");\n        const header = Buffer.alloc(44);\n        header.write(\"RIFF\", 0);\n        header.writeUInt32LE(2147483600, 4);\n        header.write(\"WAVE\", 8);\n        header.write(\"fmt \", 12);\n        header.writeUInt8(16, 16);\n        header.writeUInt8(1, 20);\n        header.writeUInt8(2, 22);\n        header.writeUInt32LE(48000, 24);\n        header.writeUInt32LE(16, 28);\n        header.writeUInt8(4, 32);\n        header.writeUInt8(16, 34);\n        header.write(\"data\", 36);\n        header.writeUInt32LE(2147483600 + 44 - 8, 40);\n        this.audioStream.write(Buffer.concat([header, pcmData]));\n        this.headerSent = true;\n      } else {\n        this.audioStream.write(pcmData);\n      }\n    });\n\n    //QR Code\n    ipcMain.handle(\"showQR\", async (_event, _) => {\n      //macOS\n      let url = `http://${BrowserWindow.getIP()}:${this.remotePort}`;\n      BrowserWindow.win.webContents.send(\"send-remote-pair-url\", `https://cider.sh/remote/pair?url=${Buffer.from(encodeURI(url)).toString(\"base64\")}`.toString());\n    });\n\n    ipcMain.on(\"get-remote-pair-url\", (_event, _) => {\n      // Linux and Windows\n      let url = `http://${BrowserWindow.getIP()}:${this.remotePort}`;\n      //if (app.isPackaged) {\n      BrowserWindow.win.webContents.send(\"send-remote-pair-url\", `https://cider.sh/remote/pair?url=${Buffer.from(encodeURI(url)).toString(\"base64\")}`.toString());\n      //} else {\n      //    BrowserWindow.win.webContents.send('send-remote-pair-url', (`http://127.0.0.1:5500/pair-remote.html?url=${Buffer.from(encodeURI(url)).toString('base64')}`).toString());\n      //}\n    });\n\n    if (process.platform === \"darwin\") {\n      //macOS\n      app.setUserActivity(\n        \"com.CiderCollective.remote.pair\",\n        {\n          ip: `${BrowserWindow.getIP()}`,\n        },\n        `http://${BrowserWindow.getIP()}:${this.remotePort}`,\n      );\n    }\n    // Get previews for normalization\n    ipcMain.on(\"getPreviewURL\", (_event, url) => {\n\n      fetch(url)\n        .then((res) => res.buffer())\n        .then(async (buffer) => {\n          const metadata = await mm.parseBuffer(buffer, \"audio/x-m4a\");\n          let SoundCheckTag = metadata.native.iTunes[1].value;\n          console.debug(\"sc\", SoundCheckTag);\n          BrowserWindow.win.webContents.send(\"SoundCheckTag\", SoundCheckTag);\n        })\n        .catch((err) => {\n          console.log(err);\n        });\n    });\n\n    ipcMain.on(\"share-menu\", async (_event, url) => {\n      if (process.platform !== \"darwin\") return;\n      //https://www.electronjs.org/docs/latest/api/share-menu\n      console.log(\"[Share Sheet - App.ts]\", url);\n      const options = {\n        title: \"Share\",\n        urls: [url],\n      };\n      const shareMenu = new ShareMenu(options);\n      shareMenu.popup();\n    });\n\n    ipcMain.on(\"get-version\", (_event) => {\n      if (app.isPackaged) {\n        _event.returnValue = app.getVersion();\n      } else {\n        _event.returnValue = `Experimental running on Electron ${app.getVersion()}`;\n      }\n    });\n\n    ipcMain.on(\"open-appdata\", (_event) => {\n      shell.openPath(app.getPath(\"userData\"));\n    });\n\n    ipcMain.handle(\"folderSelector\", async (_event) => {\n      let u = await dialog.showOpenDialog({\n        properties: [\"openDirectory\", \"multiSelections\"],\n      });\n      return u.filePaths;\n    });\n\n    //#region Cider Connect\n    ipcMain.on(\"cc-auth\", (_event) => {\n      shell.openExternal(String(utils.getStoreValue(\"cc_authURL\")));\n    });\n\n    ipcMain.on(\"auth-window\", (_event) => {\n      AuthWindow(BrowserWindow.win);\n    });\n\n    function AuthWindow(win: bw) {\n      // create a BrowserWindow\n      const authWindow = new bw({\n        width: 500,\n        height: 600,\n        show: false,\n        titleBarOverlay: {\n          color: \"#1d1d1f\",\n          symbolColor: \"#ffffff\",\n        },\n        titleBarStyle: \"hidden\",\n        darkTheme: true,\n        resizable: false,\n        webPreferences: {\n          contextIsolation: false,\n          nodeIntegration: true,\n          sandbox: true,\n          allowRunningInsecureContent: true,\n          webSecurity: false,\n          preload: join(utils.getPath(\"srcPath\"), \"./preload/cider-preload.js\"),\n          nodeIntegrationInWorker: false,\n          experimentalFeatures: true,\n        },\n      });\n      // authWindow.webContents.openDevTools();\n      // remove all local storage data\n      authWindow.webContents.session.clearStorageData();\n\n      // set user agent\n      authWindow.webContents.setUserAgent(`Mozilla/5.0 (Macintosh; Intel Mac OS X 13_3_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15`);\n\n      // show the window\n      authWindow.loadURL(\"https://beta.music.apple.com/\");\n      const cookieKeys = [\"itspod\", \"pltvcid\", \"pldfltcid\", \"itua\", \"media-user-token\", \"acn1\", \"dslang\"];\n\n      ipcMain.on(\"auth-window-ready\", async (_event) => {\n        authWindow.show();\n      });\n\n      ipcMain.on(\"auth-completed\", async (_event) => {\n        const cookies = await getCookies();\n        console.log(\"cookies\", cookies);\n        win.webContents.send(\"recv-cookies\", cookies);\n        authWindow.close();\n      });\n\n      const overlayStyling = `\n    .hehehe {\n      position: fixed;\n      top:0;\n      left:0;\n      width: 100px;\n      height: 100px;\n      background: #1d1d1f;\n      z-index: 99999;\n    }\n    .titlebar {\n      height: 30px;\n      position: fixed;\n      top:0;\n      left:0;\n      right:0;\n      -webkit-app-region: drag;\n      z-index: 99999;\n    }`;\n\n      // on content loaded\n      authWindow.webContents.on(\"did-finish-load\", () => {\n        authWindow.webContents.executeJavaScript(`\n      let tOut = setInterval(async ()=>{\n        try {\n          if(typeof MusicKit === 'undefined') return;\n          MusicKit.getInstance().addEventListener(MusicKit.Events.authorizationStatusDidChange, ()=>{\n            if(MusicKit.getInstance().isAuthorized) {\n              ipcRenderer.send('auth-completed')\n            }\n          })\n          clearInterval(tOut)\n        }catch(e) {}\n      }, 500)\n      let tOut2 = setInterval(()=>{\n        try {\n          const el = document.querySelector('.signin')\n          if(el) {\n            el.click()\n            ipcRenderer.send('auth-window-ready')\n            clearInterval(tOut2)\n          }\n        }catch(e) {}\n      }, 500)\n      let styling = \\`${overlayStyling}\\`;\n      (()=>{\n        const titleBarEl = document.createElement('div')\n        const overlayEl = document.createElement('div')\n        titleBarEl.classList.add('titlebar')\n        overlayEl.classList.add('hehehe')\n        const styleTag = document.createElement('style')\n        styleTag.innerHTML = styling\n        document.head.appendChild(styleTag)\n        document.body.appendChild(overlayEl)\n        document.body.appendChild(titleBarEl)\n      })()\n    `);\n      });\n\n      async function getCookies(): Promise<{ [key: string]: string }> {\n        return new Promise((res, rej) => {\n          authWindow.webContents.session.cookies\n            .get({})\n            .then((cookies) => {\n              // for each cookie\n              const toRenderer: {\n                [key: string]: string;\n              } = {};\n              for (let i = 0; i < cookieKeys.length; i++) {\n                const key = cookieKeys[i];\n                // find the cookie\n                const cookie = cookies.find((cookie) => cookie.name === key);\n                // if cookie exists\n                if (cookie) {\n                  toRenderer[`music.ampwebplay.${cookie.name}`] = cookie.value;\n                }\n              }\n              res(toRenderer);\n            })\n            .catch((error) => {\n              console.log(error);\n              rej();\n            });\n        });\n      }\n    }\n\n    ipcMain.on(\"cc-logout\", (_event) => {\n      //Make sure to update the default store\n      utils.setStoreValue(\"connectUser\", {\n        auth: null,\n        sync: {\n          themes: false,\n          plugins: false,\n          settings: false,\n        },\n      });\n      utils.getWindow().reload();\n    });\n\n    ipcMain.on(\"cc-push\", (_event) => {\n      utils.pushStoreToConnect();\n    });\n    /* *********************************************************************************************\n     * Window Events\n     * **********************************************************************************************/\n    let WND_STATE = {\n      MINIMIZED: 0,\n      NORMAL: 1,\n      MAXIMIZED: 2,\n      FULL_SCREEN: 3,\n    };\n    let wndState = WND_STATE.NORMAL;\n    const win = BrowserWindow.win;\n    let isQuitting = false;\n\n    win.on(\"resize\", (_: any) => {\n      const isMaximized = win.isMaximized();\n      const isMinimized = win.isMinimized();\n      const isFullScreen = win.isFullScreen();\n      const state = wndState;\n      if (isMinimized && state !== WND_STATE.MINIMIZED) {\n        wndState = WND_STATE.MINIMIZED;\n        win.webContents.send(\"window-state-changed\", \"minimized\");\n      } else if (isFullScreen && state !== WND_STATE.FULL_SCREEN) {\n        wndState = WND_STATE.FULL_SCREEN;\n        win.webContents.send(\"window-state-changed\", \"fullscreen\");\n      } else if (isMaximized && state !== WND_STATE.MAXIMIZED) {\n        wndState = WND_STATE.MAXIMIZED;\n        win.webContents.send(\"window-state-changed\", \"maximized\");\n        win.webContents.executeJavaScript(`app.chrome.maximized = true`);\n      } else if (state !== WND_STATE.NORMAL) {\n        wndState = WND_STATE.NORMAL;\n        win.webContents.send(\"window-state-changed\", \"normal\");\n        win.webContents.executeJavaScript(`app.chrome.maximized = false`);\n      }\n    });\n\n    win.on(\"close\", async (e: any) => {\n      if ((process.platform === \"darwin\" || utils.getStoreValue(\"general.close_button_hide\")) && !isQuitting) {\n        e.preventDefault();\n        win.hide();\n      } else {\n        await win.webContents.executeJavaScript(`\n            window.localStorage.setItem(\"currentTrack\", JSON.stringify(app.mk.nowPlayingItem));\n            window.localStorage.setItem(\"currentTime\", JSON.stringify(app.mk.currentPlaybackTime));\n            window.localStorage.setItem(\"currentQueue\", JSON.stringify(app.mk.queue._unplayedQueueItems));\n            ipcRenderer.send('stopGCast','');\n            MusicKit.getInstance().stop();\n        `);\n      }\n    });\n\n    app.on(\"before-quit\", () => {\n      isQuitting = true;\n    });\n\n    app.on(\"activate\", function () {\n      win.show();\n    });\n\n    // Quit when all windows are closed.\n    app.on(\"window-all-closed\", () => {\n      if (process.platform !== \"darwin\") {\n        app.quit();\n      }\n    });\n\n    // Set window Handler\n    BrowserWindow.win.webContents.setWindowOpenHandler((x: any) => {\n      if (x.url.includes(\"apple.com\") || x.url.includes(\"localhost\")) {\n        return { action: \"allow\" };\n      }\n      shell.openExternal(x.url).catch(console.error);\n      return { action: \"deny\" };\n    });\n  }\n\n  /**\n   * Gets ip\n   * @private\n   */\n  private static getIP(): string {\n    let ip: string = \"\";\n    let ip2: any = [];\n    let alias = 0;\n    const ifaces: any = networkInterfaces();\n    for (let dev in ifaces) {\n      ifaces[dev].forEach((details: any) => {\n        if (details.family === \"IPv4\" && !details.internal) {\n          if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? \":\" + alias : \"\"))) {\n            if (details.address.substring(0, 8) === \"192.168.\" || details.address.substring(0, 7) === \"172.16.\" || details.address.substring(0, 3) === \"10.\") {\n              if (!ip.startsWith(\"192.168.\") || (String(ip2).startsWith(\"192.168.\") && !ip.startsWith(\"192.168.\") && String(ip2).startsWith(\"172.16.\") && !ip.startsWith(\"192.168.\") && !ip.startsWith(\"172.16.\")) || (String(ip2).startsWith(\"10.\") && !ip.startsWith(\"192.168.\") && !ip.startsWith(\"172.16.\") && !ip.startsWith(\"10.\"))) {\n                ip = details.address;\n              }\n              ++alias;\n            }\n          }\n        }\n      });\n    }\n    return ip;\n  }\n\n  /**\n   * Broadcast the remote to the IP\n   * @private\n   */\n  private async broadcastRemote() {\n    const myString = `http://${BrowserWindow.getIP()}:${this.remotePort}`;\n    const mdns = (await import(\"mdns-js\")).default;\n    const encoded = Buffer.from(myString).toString(\"base64\");\n    const x = mdns.tcp(\"cider-remote\");\n    const txt_record = {\n      Ver: \"131077\",\n      DvSv: \"3689\",\n      DbId: \"D41D8CD98F00B205\",\n      DvTy: \"Cider\",\n      OSsi: \"0x212F0\",\n      txtvers: \"1\",\n      CtlN: \"Cider\",\n      iV: \"196623\",\n    };\n    let server2 = mdns.createAdvertisement(x, `${await getPort({ port: 3839 })}`, {\n      name: encoded,\n      txt: txt_record,\n    });\n    server2.start();\n    console.log(\"remote broadcasted\");\n  }\n}\n"
  },
  {
    "path": "src/main/base/castcontroller.ts",
    "content": "// @ts-nocheck\nimport castv2Cli from \"castv2-client\";\nconst RequestResponseController = castv2Cli.RequestResponseController;\n\n\n\nexport class CiderCastController extends RequestResponseController {\n  constructor(client: string, sourceId: string, destinationId: string) {\n    super(client, sourceId, destinationId, \"urn:x-cast:com.ciderapp.customdata\");\n    this.once(\"close\", onclose);\n    var self = this;\n    function onclose() {\n      self.stop();\n    }\n  }\n\n  sendIp(ip: string) {\n    // TODO: Implement Callback\n    let data = {\n      ip: ip,\n    };\n    this.request(data);\n  }\n\n  kill() {\n    // TODO: Implement Callback\n    let data = {\n      action: \"stop\",\n    };\n    this.request(data);\n  }\n}\n"
  },
  {
    "path": "src/main/base/castreceiver.ts",
    "content": "// @ts-nocheck\nimport castv2Cli from \"castv2-client\";\nimport { CiderCastController } from \"./castcontroller.js\";\n\nconst Application = castv2Cli.Application;\nconst MediaController = castv2Cli.MediaController;\n\nexport class CiderReceiver extends Application {\n  // FE96A351\n  // 27E1334F\n  public APP_ID = \"FE96A351\";\n\n  constructor(_client: unknown, _session: unknown) {\n    super();\n    super.apply(this, arguments);\n\n    this.media = this.createController(MediaController);\n    this.mediaReceiver = this.createController(CiderCastController);\n\n    this.media.on(\"status\", onstatus);\n\n    var self = this;\n\n    function onstatus(status: string) {\n      self.emit(\"status\", status);\n    }\n  }\n\n  getStatus(callback: unknown) {\n    this.media.getStatus.apply(this.media, arguments);\n  }\n\n  load(media: unknown, options: unknown, callback: unknown) {\n    this.media.load.apply(this.media, arguments);\n  }\n\n  play(callback: unknown) {\n    this.media.play.apply(this.media, arguments);\n  }\n\n  pause(callback: unknown) {\n    this.media.pause.apply(this.media, arguments);\n  }\n\n  stop(callback: unknown) {\n    this.media.stop.apply(this.media, arguments);\n  }\n\n  seek(currentTime: unknown, callback: unknown) {\n    this.media.seek.apply(this.media, arguments);\n  }\n\n  queueLoad(items: unknown, options: unknown, callback: unknown) {\n    this.media.queueLoad.apply(this.media, arguments);\n  }\n\n  queueInsert(items: unknown, options: unknown, callback: unknown) {\n    this.media.queueInsert.apply(this.media, arguments);\n  }\n\n  queueRemove(itemIds: unknown, options: unknown, callback: unknown) {\n    this.media.queueRemove.apply(this.media, arguments);\n  }\n\n  queueReorder(itemIds: unknown, options: unknown, callback: unknown) {\n    this.media.queueReorder.apply(this.media, arguments);\n  }\n\n  queueUpdate(items: unknown, callback: unknown) {\n    this.media.queueUpdate.apply(this.media, arguments);\n  }\n\n  sendIp(opts: unknown) {\n    this.mediaReceiver.sendIp.apply(this.mediaReceiver, arguments);\n  }\n\n  kill(opts: unknown) {\n    this.mediaReceiver.kill.apply(this.mediaReceiver, arguments);\n  }\n}\n"
  },
  {
    "path": "src/main/base/plugins.ts",
    "content": "import {app} from \"electron\";\nimport { existsSync, lstatSync, readdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { utils } from \"./utils.js\";\n\n//\n// Hello, this is our loader for the various plugins that the Cider Development Team built for our\n// numerous plugins internally and ones made by the community\n//\n// To learn how to make your own, visit https://github.com/ciderapp/Cider/wiki/Plugins\n//\n/**\n * @class\n * Plugin Loading\n * @author booploops#7139\n * @see {@link https://github.com/ciderapp/Cider/wiki/Plugins|Documentation}\n */\nexport class Plugins {\n  private static PluginMap: any = {};\n  private basePluginsPath = join(dirname(fileURLToPath(import.meta.url)), \"../plugins\");\n  private userPluginsPath = join(app.getPath(\"userData\"), \"Plugins\");\n  private readonly pluginsList: any = {};\n\n  constructor() {\n    this.pluginsList = this.getPlugins();\n  }\n\n  public static getPluginFromMap(plugin: string): any {\n    if (Plugins.PluginMap[plugin]) {\n      return Plugins.PluginMap[plugin];\n    } else {\n      return plugin;\n    }\n  }\n\n  public getPlugins(): any {\n    let plugins: any = {};\n\n    if (existsSync(this.basePluginsPath)) {\n      readdirSync(this.basePluginsPath).forEach(async (file) => {\n        if (file.endsWith(\".ts\") || file.endsWith(\".js\")) {\n          const plugin = (await import(join(this.basePluginsPath, file))).default;\n          if (plugins[file] || plugin.name in plugins) {\n            console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`);\n          } else {\n            plugins[file] = new plugin(utils);\n          }\n        }\n      });\n    }\n\n    if (existsSync(this.userPluginsPath)) {\n      readdirSync(this.userPluginsPath).forEach(async (file) => {\n        // Plugins V1\n        if (file.endsWith(\".ts\") || file.endsWith(\".js\")) {\n          if (!app.isPackaged) {\n            const plugin = (await import(join(this.userPluginsPath, file))).default;\n            file = file.replace(\".ts\", \"\").replace(\".js\", \"\");\n            if (plugins[file] || plugin in plugins) {\n              console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`);\n            } else {\n              plugins[file] = new plugin(utils);\n            }\n          } else {\n            const plugin = await import(join(this.userPluginsPath, file));\n            file = file.replace(\".ts\", \"\").replace(\".js\", \"\");\n            if (plugins[file] || plugin in plugins) {\n              console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`);\n            } else {\n              plugins[file] = new plugin(utils);\n            }\n          }\n        }\n        // Plugins V2\n        else if (lstatSync(join(this.userPluginsPath, file)).isDirectory()) {\n          const pluginPath = join(this.userPluginsPath, file);\n          if (existsSync(join(pluginPath, \"package.json\"))) {\n            const pluginPackage = await import(join(pluginPath, \"package.json\"));\n            const plugin = await import(join(pluginPath, pluginPackage.main));\n            if (plugins[plugin.name] || plugin.name in plugins) {\n              console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`);\n            } else {\n              Plugins.PluginMap[pluginPackage.name] = file;\n              const pluginEnv = {\n                app: app,\n                store: utils.getStore(),\n                utils: utils,\n                win: utils.getWindow(),\n                dir: pluginPath,\n                dirName: file,\n                express: utils.getExpress(),\n              };\n              plugins[plugin.name] = new plugin(pluginEnv);\n            }\n          }\n        }\n      });\n    }\n    console.log(\"[PluginHandler] Loaded plugins:\", Object.keys(plugins));\n    return plugins;\n  }\n\n  public callPlugins(event: string, ...args: any[]) {\n    for (const plugin in this.pluginsList) {\n      if (this.pluginsList[plugin][event]) {\n        try {\n          this.pluginsList[plugin][event](...args);\n        } catch (e) {\n          console.error(`[${plugin}] An error was encountered: ${e}`);\n          console.error(e);\n        }\n      }\n    }\n  }\n\n  public callPlugin(plugin: string, event: string, ...args: any[]) {\n    if (this.pluginsList[plugin][event]) {\n      this.pluginsList[plugin][event](...args);\n    }\n  }\n}\n"
  },
  {
    "path": "src/main/base/store.ts",
    "content": "import ElectronStore from \"electron-store\";\nimport { app, ipcMain } from \"electron\";\nimport fetch from \"node-fetch\";\n\nexport class Store {\n  static cfg: ElectronStore<any>;\n\n  private defaults = {\n    main: {\n      PLATFORM: process.platform,\n      UPDATABLE: app.isPackaged && (!process.mas || !process.windowsStore || !process.env.FLATPAK_ID),\n    },\n    general: {\n      close_button_hide: false,\n      language: \"en_US\",\n      playbackNotifications: true,\n      resumeOnStartupBehavior: \"local\",\n      privateEnabled: false,\n      themeUpdateNotification: true,\n      sidebarItems: {\n        recentlyAdded: true,\n        songs: true,\n        albums: true,\n        artists: true,\n        videos: true,\n        podcasts: true,\n      },\n      sidebarCollapsed: {\n        cider: false,\n        applemusic: false,\n        library: false,\n        amplaylists: false,\n        playlists: false,\n        localLibrary: false,\n      },\n      onStartup: {\n        enabled: false,\n        hidden: false,\n      },\n      resumeTabs: {\n        tab: \"home\",\n        dynamicData: \"\",\n      },\n      keybindings: {\n        search: [\"CommandOrControl\", \"F\"],\n        listnow: [\"CommandOrControl\", \"L\"],\n        browse: [\"CommandOrControl\", \"B\"],\n        recentAdd: [\"CommandOrControl\", \"G\"],\n        songs: [\"CommandOrControl\", \"J\"],\n        albums: [\"CommandOrControl\", process.platform == \"darwin\" ? \"Option\" : process.platform == \"linux\" ? \"Shift\" : \"Alt\", \"A\"],\n        artists: [\"CommandOrControl\", \"D\"],\n        togglePrivateSession: [\"CommandOrControl\", \"P\"],\n        webRemote: [\"CommandOrControl\", process.platform == \"darwin\" ? \"Option\" : process.platform == \"linux\" ? \"Shift\" : \"Alt\", \"W\"],\n        audioSettings: [\"CommandOrControl\", process.platform == \"darwin\" ? \"Option\" : process.platform == \"linux\" ? \"Shift\" : \"Alt\", \"A\"],\n        pluginMenu: [\"CommandOrControl\", process.platform == \"darwin\" ? \"Option\" : process.platform == \"linux\" ? \"Shift\" : \"Alt\", \"P\"],\n        castToDevices: [\"CommandOrControl\", process.platform == \"darwin\" ? \"Option\" : process.platform == \"linux\" ? \"Shift\" : \"Alt\", \"C\"],\n        settings: [\n          \"CommandOrControl\", // Who the hell uses a different key for this? Fucking Option?\n          \",\",\n        ],\n        zoomn: [\"Control\", \"numadd\"],\n        zoomt: [\"Control\", \"numsub\"],\n        zoomrst: [\"Control\", \"num0\"],\n        openDeveloperTools: [\"CommandOrControl\", \"Shift\", \"I\"],\n      },\n      showLovedTracksInline: true,\n    },\n    connectivity: {\n      discord_rpc: {\n        enabled: true,\n        client: \"Cider\",\n        activity: {\n          state_format: \"by {artist}\",\n          details_format: \"{title}\",\n          hide_timestamp: false,\n          buttons: {\n            enabled: true,\n            first: \"listenOnCider\",\n            second: \"viewOnAppleMusic\",\n            options: [\"listenOnCider\", \"viewOnAppleMusic\", \"viewOnOtherMusicServices\"],\n          },\n        },\n        clear_on_pause: true,\n      },\n      lastfm: {\n        enabled: false,\n        scrobble_after: 50,\n        filter_loop: false,\n        filter_types: {},\n        remove_featured: true,\n        secrets: {\n          username: \"\",\n          key: \"\",\n        },\n      },\n    },\n    home: {\n      followedArtists: [],\n      favoriteItems: [],\n    },\n    libraryPrefs: {\n      songs: {\n        scroll: \"paged\",\n        sort: \"name\",\n        sortOrder: \"asc\",\n        size: \"normal\",\n      },\n      albums: {\n        scroll: \"paged\",\n        sort: \"name\",\n        sortOrder: \"asc\",\n        viewAs: \"covers\",\n      },\n      playlists: {\n        scroll: \"infinite\",\n      },\n      localPaths: [],\n      pageSize: 250,\n    },\n    audio: {\n      volume: 1,\n      volumeStep: 0.01,\n      maxVolume: 1,\n      lastVolume: 1,\n      muted: false,\n      playbackRate: 1,\n      quality: \"HIGH\",\n      seamless_audio: true,\n      normalization: true,\n      dBSPL: false,\n      dBSPLcalibration: 90,\n      maikiwiAudio: {\n        ciderPPE: true,\n        ciderPPE_value: \"MAIKIWI\",\n        staticOptimizer: {\n          state: false,\n          lock: false,\n        },\n        opportunisticCorrection_state: \"OFF\",\n        atmosphereRealizer1: false,\n        atmosphereRealizer1_value: \"NATURAL_STANDARD\",\n        atmosphereRealizer2: false,\n        atmosphereRealizer2_value: \"NATURAL_STANDARD\",\n        spatial: false,\n        spatialProfile: \"BPLK\",\n        vibrantBass: {\n          // Hard coded into the app. Don't include any of this config into exporting presets in store.ts\n          frequencies: [17.182, 42.169, 53.763, 112.69, 119.65, 264.59, 336.57, 400.65, 505.48, 612.7, 838.7, 1155.3, 1175.6, 3406.8, 5158.6, 5968.1, 6999.9, 7468.6, 8862.9, 9666, 10109],\n          Q: [2.5, 0.388, 5, 5, 2.5, 7.071, 14.14, 10, 7.071, 14.14, 8.409, 0.372, 7.071, 10, 16.82, 7.071, 28.28, 20, 8.409, 40, 40],\n          gain: [-0.34, 2.49, 0.23, -0.49, 0.23, -0.12, 0.32, -0.29, 0.33, 0.19, -0.18, -1.27, -0.11, 0.25, -0.18, -0.53, 0.34, 1.32, 1.78, 0.41, -0.28],\n        },\n        cloud: false,\n      },\n      spatial: false,\n      spatial_properties: {\n        presets: [],\n        gain: 0.8,\n        listener_position: [0, 0, 0],\n        audio_position: [0, 0, 0],\n        room_dimensions: {\n          width: 32,\n          height: 12,\n          depth: 32,\n        },\n        room_materials: {\n          left: \"metal\",\n          right: \"metal\",\n          front: \"brick-bare\",\n          back: \"brick-bare\",\n          down: \"acoustic-ceiling-tiles\",\n          up: \"acoustic-ceiling-tiles\",\n        },\n      },\n      equalizer: {\n        preset: \"default\",\n        frequencies: [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000],\n        gain: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n        Q: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n        mix: 1,\n        vibrantBass: 0,\n        presets: [],\n        userGenerated: false,\n      },\n    },\n    visual: {\n      theme: \"\",\n      styles: [],\n      scrollbars: 0, // 0 = show on hover, 2 = always hide, 3 = always show\n      refresh_rate: 0,\n      window_background_style: \"none\", // \"none\", \"artwork\", \"color\"\n      animated_artwork: \"limited\", // 0 = always, 1 = limited, 2 = never\n      animated_artwork_qualityLevel: 1,\n      bg_artwork_rotation: false,\n      hw_acceleration: \"default\", // default, webgpu, disabled\n      showuserinfo: true,\n      transparent: false,\n      miniplayer_top_toggle: true,\n      directives: {\n        windowLayout: \"twopanel\",\n      },\n      windowControlPosition: 0, // 0 default right\n      nativeTitleBar: false,\n      windowColor: \"#000000\",\n      customAccentColor: false,\n      accentColor: \"#fc3c44\",\n      purplePodcastPlaybackBar: false,\n      maxElementScale: -1, // -1 default, anything else is a custom scale\n      overrideDisplayTheme: \"system\", // system , dark, light\n      artworkDisplayLayout: \"default\",\n    },\n    lyrics: {\n      enable_mxm: true,\n      mxm_karaoke: false,\n      mxm_language: \"disabled\",\n      enable_qq: false,\n      enable_yt: false,\n    },\n    advanced: {\n      AudioContext: true,\n      experiments: [],\n      playlistTrackMapping: true,\n      ffmpegLocation: \"\",\n      disableLogging: true,\n    },\n    connectUser: {\n      auth: null,\n      sync: {\n        themes: false,\n        plugins: false,\n        settings: false,\n      },\n    },\n    musickit: {\n      \"stored-attributes\": {\n        autoplayEnabled: \"\",\n      },\n    },\n  };\n  private migrations = {};\n\n\n  constructor() {\n    Store.cfg = new ElectronStore({\n      name: \"cider-config\",\n      defaults: this.defaults,\n      migrations: this.migrations,\n      clearInvalidConfig: false, //disabled for now\n    });\n\n    Store.cfg.set(this.mergeStore(this.defaults, Store.cfg.store));\n    this.ipcHandler();\n  }\n\n  static pushToCloud(): void {\n    if (Store.cfg.get(\"connectUser.auth\") === null) return;\n    var syncData = Object();\n    if (Store.cfg.get(\"connectUser.sync.themes\")) {\n      syncData.push({\n        themes: Store.cfg.store.themes,\n      });\n    }\n    if (Store.cfg.get(\"connectUser.sync.plugins\")) {\n      syncData.push({\n        plugins: Store.cfg.store.plugins,\n      });\n    }\n\n    if (Store.cfg.get(\"connectUser.sync.settings\")) {\n      syncData.push({\n        general: Store.cfg.get(\"general\"),\n        home: Store.cfg.get(\"home\"),\n        libraryPrefs: Store.cfg.get(\"libraryPrefs\"),\n        advanced: Store.cfg.get(\"advanced\"),\n      });\n    }\n    let postBody = {\n      id: Store.cfg.get(\"connectUser.id\"),\n      app: app.getName(),\n      version: app.isPackaged ? app.getVersion() : \"dev\",\n      syncData: syncData,\n    };\n\n    fetch(\"https://connect.cidercollective.dev/api/v1/setttings/set\", {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify(postBody),\n    });\n  }\n\n  /**\n   * Merge Configurations\n   * @param target The target configuration\n   * @param source The source configuration\n   */\n  private mergeStore = (target: { [x: string]: any }, source: { [x: string]: any }) => {\n    // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties\n    for (const key of Object.keys(source)) {\n      if (key.includes(\"migrations\")) {\n        continue;\n      }\n      if (source[key] instanceof Array) {\n        continue;\n      }\n      if (source[key] instanceof Object) Object.assign(source[key], this.mergeStore(target[key], source[key]));\n    }\n    // Join `target` and modified `source`\n    Object.assign(target || {}, source);\n    return target;\n  };\n\n  /**\n   * IPC Handler\n   */\n  private ipcHandler(): void {\n    ipcMain.handle(\"getStoreValue\", (_event, key, defaultValue) => {\n      return defaultValue ? Store.cfg.get(key, true) : Store.cfg.get(key);\n    });\n\n    ipcMain.handle(\"setStoreValue\", (_event, key, value) => {\n      Store.cfg.set(key, value);\n    });\n\n    ipcMain.on(\"getStore\", (event) => {\n      event.returnValue = Store.cfg.store;\n    });\n\n    ipcMain.on(\"setStore\", (_event, store) => {\n      Store.cfg.store = store;\n    });\n  }\n}\n"
  },
  {
    "path": "src/main/base/utils.ts",
    "content": "import { BrowserWindow, app, ipcMain } from \"electron\";\nimport ElectronStore from \"electron-store\";\nimport fetch from \"node-fetch\";\nimport { readFileSync } from \"node:fs\";\nimport { join, resolve,dirname } from \"node:path\";\nimport { BrowserWindow as bw } from \"./browserwindow.js\";\nimport { Store } from \"./store.js\";\nimport { fileURLToPath } from \"node:url\";\n\nexport class utils {\n  static hash = \"fda9a6528649ea90dee35390wog\"\n  static i18n: any = {};\n\n  /**\n   * Playback Functions\n   */\n  static playback = {\n    pause: () => {\n      bw.win.webContents.executeJavaScript(\"MusicKitInterop.pause()\");\n    },\n    play: () => {\n      bw.win.webContents.executeJavaScript(\"MusicKitInterop.play()\");\n    },\n    playPause: () => {\n      bw.win.webContents.executeJavaScript(\"MusicKitInterop.playPause()\");\n    },\n    next: () => {\n      bw.win.webContents.executeJavaScript(\"MusicKitInterop.next()\");\n    },\n    previous: () => {\n      bw.win.webContents.executeJavaScript(\"MusicKitInterop.previous()\");\n    },\n    seek: (seconds: number) => {\n      bw.win.webContents.executeJavaScript(`MusicKit.getInstance().seekToTime(${seconds})`);\n    },\n  };\n  /**\n   * Paths for the application to use\n   */\n  static paths: any = {\n    srcPath: join(dirname(fileURLToPath(import.meta.url)), \"../../src\"),\n    rendererPath: join(dirname(fileURLToPath(import.meta.url)), \"../../src/renderer\"),\n    mainPath: join(dirname(fileURLToPath(import.meta.url)), \"../../src/main\"),\n    resourcePath: join(dirname(fileURLToPath(import.meta.url)), \"../../resources\"),\n    ciderCache: resolve(app.getPath(\"userData\"), \"CiderCache\"),\n    themes: resolve(app.getPath(\"userData\"), \"Themes\"),\n    plugins: resolve(app.getPath(\"userData\"), \"Plugins\"),\n    externals: resolve(app.getPath(\"userData\"), \"externals\"),\n  };\n\n  /**\n   * Get the path\n   * @returns {string}\n   * @param name\n   */\n  static getPath(name: string): string {\n    return this.paths[name];\n  }\n\n  /**\n   * Get the app\n   * @returns {Electron.App}\n   */\n  static getApp(): Electron.App {\n    return app;\n  }\n\n  /**\n   * Get the IPCMain\n   */\n  static getIPCMain(): Electron.IpcMain {\n    return ipcMain;\n  }\n\n  /*\n   * Get the Express instance\n   * @returns {any}\n   */\n  static getExpress(): any {\n    return bw.express;\n  }\n\n  /**\n   * MitM the electron fetch for a function that proxies github.\n   * Written in TS so Maikiwi doesn't fuck up\n   */\n  static async fetch(url: string, opts: object = {}) {\n    Object.assign(opts, {\n      headers: {\n        \"User-Agent\": utils.getWindow().webContents.getUserAgent(),\n      },\n    });\n    if (this.getStoreValue(\"advanced.experiments\").includes(\"cider_mirror\") === true) {\n      if (url.includes(\"api.github.com/\")) {\n        return await fetch(url.replace(\"api.github.com/\", \"mirror.api.cider.sh/v2/api/\"), opts);\n      } else if (url.includes(\"raw.githubusercontent.com/\")) {\n        return await fetch(url.replace(\"raw.githubusercontent.com/\", \"mirror.api.cider.sh/v2/raw/\"), opts);\n      } else {\n        return await fetch(url, opts);\n      }\n    } else {\n      return await fetch(url, opts);\n    }\n  }\n\n  static async initializeTranslations() {\n    const otaClient = (await import('@crowdin/ota-client')).default.default;\n    const crowdin = new otaClient(this.hash)\n\n    this.i18n = await crowdin.getTranslations();\n  }\n\n  /**\n   * Fetches the i18n locale for the given language.\n   * @param language {string} The language to fetch the locale for.\n   * @param key {string} The key to search for.\n   * @returns {string | Object} The locale value.\n   */\n  static getLocale(language: string, key?: string): string | object {\n    let i18n: any = {};\n\n    if (!this.i18n[language]) {\n      i18n = this.i18n[\"en-US\"][0].content;\n    } else {\n      i18n = this.i18n[language ?? \"en-US\"][0].content;\n    }\n\n    if (key) {\n      return i18n[key];\n    } else {\n      return i18n;\n    }\n  }\n\n  /**\n   * Gets a store value\n   * @param key\n   * @returns store value\n   */\n  static getStoreValue(key: string): any {\n    return Store.cfg.get(key);\n  }\n\n  /**\n   * Sets a store\n   * @returns store\n   */\n  static getStore(): Object {\n    return Store.cfg.store;\n  }\n\n  /**\n   * Get the store instance\n   * @returns {Store}\n   */\n  static getStoreInstance(): ElectronStore {\n    return Store.cfg;\n  }\n\n  /**\n   * Sets a store value\n   * @param key\n   * @param value\n   */\n  static setStoreValue(key: string, value: any): void {\n    Store.cfg.set(key, value);\n  }\n\n  /**\n   * Pushes Store to Connect\n   * @return Function\n   */\n  static pushStoreToConnect(): Function {\n    return Store.pushToCloud;\n  }\n\n  /**\n   * Gets the browser window\n   */\n  static getWindow(): Electron.BrowserWindow {\n    if (bw.win) {\n      return bw.win;\n    } else {\n      return BrowserWindow.getAllWindows()[0];\n    }\n  }\n\n  static loadPluginFrontend(path: string): void {}\n\n  static loadJSFrontend(path: string): void {\n    bw.win.webContents.executeJavaScript(readFileSync(path, \"utf8\"));\n  }\n}\n"
  },
  {
    "path": "src/main/base/vcomponents.json",
    "content": "[\n  \"pages/podcasts\",\n  \"pages/apple-account-settings\",\n  \"pages/library-songs\",\n  \"pages/library-albums\",\n  \"pages/library-artists\",\n  \"pages/browse\",\n  \"pages/groupings\",\n  \"pages/installed-themes\",\n  \"pages/listen_now\",\n  \"pages/radio\",\n  \"pages/home\",\n  \"pages/artist-feed\",\n  \"pages/cider-playlist\",\n  \"pages/playlist-inline\",\n  \"pages/recordLabel\",\n  \"pages/cider-multiroom\",\n  \"pages/collection-list\",\n  \"pages/apple-curator\",\n  \"pages/artist\",\n  \"pages/search\",\n  \"pages/about\",\n  \"pages/library-videos\",\n  \"pages/remote-pair\",\n  \"pages/themes-github\",\n  \"pages/plugins-github\",\n  \"pages/replay\",\n  \"pages/audiolabs\",\n  \"pages/zoo\",\n  \"pages/plugin-renderer\",\n  \"pages/keybinds\",\n  \"pages/oobe\",\n  \"components/mediaitem-artwork\",\n  \"components/artwork-material\",\n  \"components/menu-panel\",\n  \"components/sidebar-playlist\",\n  \"components/audio-settings\",\n  \"components/plugin-menu\",\n  \"components/audio-controls\",\n  \"components/audio-playbackrate\",\n  \"components/qrcode-modal\",\n  \"components/moreinfo-modal\",\n  \"components/equalizer\",\n  \"components/add-to-playlist\",\n  \"components/smarthints\",\n  \"components/queue\",\n  \"components/mediaitem-scroller-horizontal\",\n  \"components/mediaitem-scroller-horizontal-large\",\n  \"components/mediaitem-scroller-horizontal-sp\",\n  \"components/mediaitem-scroller-horizontal-mvview\",\n  \"components/mediaitem-list-item\",\n  \"components/mediaitem-hrect\",\n  \"components/mediaitem-square\",\n  \"components/mediaitem-mvview\",\n  \"components/listennow-child\",\n  \"components/mediaitem-mvview-sp\",\n  \"components/animatedartwork-view\",\n  \"components/listitem-horizontal\",\n  \"components/lyrics-view\",\n  \"components/fullscreen\",\n  \"components/miniplayer\",\n  \"components/castmenu\",\n  \"components/pathmenu\",\n  \"components/airplay-modal\",\n  \"components/artist-chip\",\n  \"components/hello-world\",\n  \"components/inline-collection-list\"\n]\n"
  },
  {
    "path": "src/main/base/vrouting.json",
    "content": "[\n  {\n    \"page\": \"plugin-renderer\",\n    \"component\": \"<plugin-renderer></plugin-renderer>\",\n    \"condition\": \"page == 'plugin-renderer'\"\n  },\n  {\n    \"page\": \"zoo\",\n    \"component\": \"<cider-zoo></cider-zoo>\",\n    \"condition\": \"page == 'zoo'\"\n  },\n  {\n    \"page\": \"podcasts\",\n    \"component\": \"<apple-podcasts></apple-podcasts>\",\n    \"condition\": \"page == 'podcasts'\"\n  },\n  {\n    \"page\": \"library-videos\",\n    \"component\": \"<cider-library-videos></cider-library-videos>\",\n    \"condition\": \"page == 'library-videos'\"\n  },\n  {\n    \"page\": \"apple-account-settings\",\n    \"component\": \"<apple-account-settings></apple-account-settings>\",\n    \"condition\": \"page == 'apple-account-settings'\"\n  },\n  {\n    \"page\": \"about\",\n    \"component\": \"<about-page></about-page>\",\n    \"condition\": \"page == 'about'\"\n  },\n  {\n    \"page\": \"cider-artist\",\n    \"component\": \"<cider-artist :data=\\\"artistPage.data\\\"></cider-artist>\",\n    \"condition\": \"page == 'artist-page' && artistPage.data.attributes\"\n  },\n  {\n    \"page\": \"collection-list\",\n    \"component\": \"<cider-collection-list :data=\\\"collectionList.response\\\" :type=\\\"collectionList.type\\\" :title=\\\"collectionList.title\\\"></cider-collection-list>\",\n    \"condition\": \"page == 'collection-list'\"\n  },\n  {\n    \"page\": \"home\",\n    \"component\": \"<cider-home></cider-home>\",\n    \"condition\": \"page == 'home'\"\n  },\n  {\n    \"page\": \"artist-feed\",\n    \"component\": \"<cider-artist-feed></cider-artist-feed>\",\n    \"condition\": \"page == 'artist-feed'\"\n  },\n  {\n    \"page\": \"playlist-inline\",\n    \"component\": \"<playlist-inline :data=\\\"showingPlaylist\\\"></playlist-inline>\",\n    \"condition\": \"modals.showPlaylist\"\n  },\n  {\n    \"page\": \"playlist_\",\n    \"component\": \"<cider-playlist :data=\\\"showingPlaylist\\\"></cider-playlist>\",\n    \"condition\": \"page.includes('playlist_')\"\n  },\n  {\n    \"page\": \"oobe\",\n    \"component\": \"<cider-oobe/>\",\n    \"condition\": \"page == 'oobe'\"\n  },\n  {\n    \"page\": \"album_\",\n    \"component\": \"<cider-playlist :data=\\\"showingPlaylist\\\"></cider-playlist>\",\n    \"condition\": \"page.includes('album_')\"\n  },\n  {\n    \"page\": \"social-profiles_\",\n    \"component\": \"<cider-socialprofile :data=\\\"showingPlaylist\\\"></cider-socialprofile>\",\n    \"condition\": \"$root.page.includes('social-profiles_')\"\n  },\n  {\n    \"page\": \"recordLabel_\",\n    \"component\": \"<cider-recordlabel :data=\\\"showingPlaylist\\\"></cider-recordlabel>\",\n    \"condition\": \"page.includes('recordLabel_')\"\n  },\n  {\n    \"page\": \"multiroom\",\n    \"component\": \"<cider-multiroom :data=\\\"multiroom\\\"></cider-multiroom>\",\n    \"condition\": \"page.includes('multiroom')\"\n  },\n  {\n    \"page\": \"curator_\",\n    \"component\": \"<cider-recordlabel :data=\\\"showingPlaylist\\\"></cider-recordlabel>\",\n    \"condition\": \"page.includes('curator_')\"\n  },\n  {\n    \"page\": \"browsepage\",\n    \"component\": \"<cider-browse :data=\\\"browsepage\\\"></cider-browse>\",\n    \"condition\": \"page == 'browse'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"groupings\",\n    \"component\": \"<cider-groupings :data=\\\"browsepage\\\"></cider-groupings>\",\n    \"condition\": \"page == 'groupings'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"charts\",\n    \"component\": \"<cider-charts :data=\\\"browsepage\\\"></cider-charts>\",\n    \"condition\": \"page == 'charts'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"listen_now\",\n    \"component\": \"<cider-listen-now :data=\\\"listennow\\\"></cider-listen-now>\",\n    \"condition\": \"page == 'listen_now'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"radio\",\n    \"component\": \"<cider-radio :data=\\\"radio\\\"></cider-radio>\",\n    \"condition\": \"page == 'radio'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"settings\",\n    \"component\": \"<cider-settings></cider-settings>\",\n    \"condition\": \"page == 'settings'\"\n  },\n  {\n    \"page\": \"installed-themes\",\n    \"component\": \"<installed-themes></installed-themes>\",\n    \"condition\": \"page == 'installed-themes'\"\n  },\n  {\n    \"page\": \"search\",\n    \"component\": \"<cider-search :search=\\\"search\\\"></cider-search>\",\n    \"condition\": \"page == 'search'\"\n  },\n  {\n    \"page\": \"library-songs\",\n    \"component\": \"<cider-library-songs :data=\\\"library.songs\\\"></cider-library-songs>\",\n    \"condition\": \"page == 'library-songs'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"library-albums\",\n    \"component\": \"<cider-library-albums :data=\\\"library.songs\\\"></cider-library-albums>\",\n    \"condition\": \"page == 'library-albums'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"library-artists\",\n    \"component\": \"<cider-library-artists></cider-library-artists>\",\n    \"condition\": \"page == 'library-artists'\",\n    \"onEnter\": \"\"\n  },\n  {\n    \"page\": \"appleCurator\",\n    \"component\": \"<cider-applecurator :data=\\\"appleCurator\\\"></cider-applecurator>\",\n    \"condition\": \"page.includes('appleCurator')\"\n  },\n  {\n    \"page\": \"themes-github\",\n    \"component\": \"<themes-github></themes-github>\",\n    \"condition\": \"page == 'themes-github'\"\n  },\n  {\n    \"page\": \"plugins-github\",\n    \"component\": \"<plugins-github></plugins-github>\",\n    \"condition\": \"page == 'plugins-github'\"\n  },\n  {\n    \"page\": \"remote-pair\",\n    \"component\": \"<remote-pair></remote-pair>\",\n    \"condition\": \"page == 'remote-pair'\"\n  },\n  {\n    \"page\": \"audiolabs\",\n    \"component\": \"<audiolabs-page></audiolabs-page>\",\n    \"condition\": \"page == 'audiolabs'\"\n  },\n  {\n    \"page\": \"replay\",\n    \"component\": \"<replay-page></replay-page>\",\n    \"condition\": \"page == 'replay'\"\n  }\n]\n"
  },
  {
    "path": "src/main/base/wsapi.ts",
    "content": "import WebSocket, { WebSocketServer } from 'ws';\nimport electron from \"electron\";\n\ninterface standardResponse {\n  status?: Number;\n  message?: String;\n  data?: any;\n  type?: string;\n}\n\nexport class wsapi {\n  static clients: any;\n  port: any = 26369;\n  wss: any = null;\n  clients: any = [];\n  private _win: any;\n\n  constructor(win: any) {\n    this._win = win;\n  }\n\n  createId() {\n    // create random guid\n    return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function (c) {\n      var r = (Math.random() * 16) | 0,\n        v = c == \"x\" ? r : (r & 0x3) | 0x8;\n      return v.toString(16);\n    });\n  }\n\n  public async InitWebSockets() {\n    electron.ipcMain.on(\"wsapi-updatePlaybackState\", (_event: any, arg: any) => {\n      this.updatePlaybackState(arg);\n    });\n\n    electron.ipcMain.on(\"wsapi-returnQueue\", (_event: any, arg: any) => {\n      this.returnQueue(JSON.parse(arg));\n    });\n\n    electron.ipcMain.on(\"wsapi-returnSearch\", (_event: any, arg: any) => {\n      console.log(\"SEARCH\");\n      this.returnSearch(JSON.parse(arg));\n    });\n\n    electron.ipcMain.on(\"wsapi-returnSearchLibrary\", (_event: any, arg: any) => {\n      this.returnSearchLibrary(JSON.parse(arg));\n    });\n\n    electron.ipcMain.on(\"wsapi-returnDynamic\", (_event: any, arg: any, type: any) => {\n      this.returnDynamic(JSON.parse(arg), type);\n    });\n\n    electron.ipcMain.on(\"wsapi-returnMusicKitApi\", (_event: any, arg: any, method: any) => {\n      this.returnMusicKitApi(JSON.parse(arg), method);\n    });\n\n    electron.ipcMain.on(\"wsapi-returnLyrics\", (_event: any, arg: any) => {\n      this.returnLyrics(JSON.parse(arg));\n    });\n    electron.ipcMain.on(\"wsapi-returnvolumeMax\", (_event: any, arg: any) => {\n      this.returnmaxVolume(JSON.parse(arg));\n    });\n    electron.ipcMain.on(\"wsapi-libraryStatus\", (_event: any, inLibrary: boolean, rating: number) => {\n      this.returnLibraryStatus(inLibrary, rating);\n    });\n    electron.ipcMain.on(\"wsapi-rate\", (_event: any, kind: string, id: string, rating: number) => {\n      this.returnRatingStatus(kind, id, rating);\n    });\n    electron.ipcMain.on(\"wsapi-change-library\", (_event: any, kind: string, id: string, shouldAdd: boolean) => {\n      this.returnLibraryChange(kind, id, shouldAdd);\n    });\n    this.wss = new WebSocketServer({\n      port: this.port,\n      perMessageDeflate: {\n        zlibDeflateOptions: {\n          // See zlib defaults.\n          chunkSize: 1024,\n          memLevel: 7,\n          level: 3,\n        },\n        zlibInflateOptions: {\n          chunkSize: 10 * 1024,\n        },\n        // Other options settable:\n        clientNoContextTakeover: true, // Defaults to negotiated value.\n        serverNoContextTakeover: true, // Defaults to negotiated value.\n        serverMaxWindowBits: 10, // Defaults to negotiated value.\n        // Below options specified as default values.\n        concurrencyLimit: 10, // Limits zlib concurrency for perf.\n        threshold: 1024, // Size (in bytes) below which messages\n        // should not be compressed if context takeover is disabled.\n      },\n    });\n    console.log(`WebSocketServer started on port: ${this.port}`);\n\n    const defaultResponse: standardResponse = {\n      status: 0,\n      data: {},\n      message: \"OK\",\n      type: \"generic\",\n    };\n\n    this.wss.on(\"connection\", (ws: any) => {\n      ws.id = this.createId();\n      console.log(`Client ${ws.id} connected`);\n      this.clients.push(ws);\n      ws.on(\"message\", function incoming(_message: any) {});\n      // ws on message\n      ws.on(\"message\", (message: any) => {\n        let data = JSON.parse(message);\n        let response: standardResponse = {\n          status: 0,\n          data: {},\n          message: \"OK\",\n          type: \"generic\",\n        };\n        if (data.action) {\n          data.action.toLowerCase();\n        }\n        switch (data.action) {\n          default:\n            response.message = \"Action not found\";\n            break;\n          case \"identify\":\n            response.message = \"Thanks for identifying!\";\n            response.data = {\n              id: ws.id,\n            };\n            ws.identity = {\n              name: data.name,\n              author: data.author,\n              description: data.description,\n              version: data.version,\n            };\n            break;\n          case \"play-next\":\n            this._win.webContents.executeJavaScript(`wsapi.playNext(\\`${data.type}\\`,\\`${data.id}\\`)`);\n            response.message = \"Play Next\";\n            break;\n          case \"play-later\":\n            this._win.webContents.executeJavaScript(`wsapi.playLater(\\`${data.type}\\`,\\`${data.id}\\`)`);\n            response.message = \"Play Later\";\n            break;\n          case \"quick-play\":\n            this._win.webContents.executeJavaScript(`wsapi.quickPlay(\\`${data.term}\\`)`);\n            response.message = \"Quick Play\";\n            break;\n          case \"get-lyrics\":\n            this._win.webContents.executeJavaScript(`wsapi.getLyrics()`);\n            break;\n          case \"shuffle\":\n            this._win.webContents.executeJavaScript(`wsapi.toggleShuffle()`);\n            break;\n          case \"set-shuffle\":\n            if (data.shuffle == true) {\n              this._win.webContents.executeJavaScript(`MusicKit.getInstance().shuffleMode = 1`);\n            } else {\n              this._win.webContents.executeJavaScript(`MusicKit.getInstance().shuffleMode = 0`);\n            }\n            break;\n          case \"repeat\":\n            this._win.webContents.executeJavaScript(`wsapi.toggleRepeat()`);\n            break;\n          case \"set-repeat\":\n            if (data.repeat === 0 || data.repeat === 1 || data.repeat === 2) {\n              this._win.webContents.executeJavaScript(`MusicKit.getInstance().repeatMode = ${data.repeat}`);\n              response.message = \"Repeat \" + data.repeat;\n            } else {\n              this._win.webContents.executeJavaScript(`wsapi.toggleRepeat()`);\n              response.message = \"Invalid Repeat, toggling\";\n            }\n            break;\n          case \"seek\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().seekToTime(${parseFloat(data.time)})`);\n            response.message = \"Seek\";\n            break;\n          case \"pause\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().pause()`);\n            response.message = \"Paused\";\n            break;\n          case \"playpause\":\n            this._win.webContents.executeJavaScript(`MusicKitInterop.playPause()`);\n            response.message = \"Play/Pause\";\n            break;\n          case \"play\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().play()`);\n            response.message = \"Playing\";\n            break;\n          case \"stop\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().stop()`);\n            response.message = \"Stopped\";\n            break;\n          case \"volumeMax\":\n            this._win.webContents.executeJavaScript(`wsapi.getmaxVolume()`);\n            response.message = \"maxVolume\";\n            break;\n          case \"volume\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().volume = ${parseFloat(data.volume)}`);\n            response.message = \"Volume\";\n            break;\n          case \"mute\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().mute()`);\n            response.message = \"Muted\";\n            break;\n          case \"unmute\":\n            this._win.webContents.executeJavaScript(`MusicKit.getInstance().unmute()`);\n            response.message = \"Unmuted\";\n            break;\n          case \"next\":\n            this._win.webContents.executeJavaScript(`MusicKitInterop.next()`);\n            response.message = \"Next\";\n            break;\n          case \"previous\":\n            this._win.webContents.executeJavaScript(`MusicKitInterop.previous()`);\n            response.message = \"Previous\";\n            break;\n          case \"musickit-api\":\n            this._win.webContents.executeJavaScript(`wsapi.musickitApi(\\`${data.method}\\`, \\`${data.id}\\`, ${JSON.stringify(data.params)} , ${data.library})`);\n            break;\n          case \"musickit-library-api\":\n            break;\n          case \"set-autoplay\":\n            this._win.webContents.executeJavaScript(`wsapi.setAutoplay(${data.autoplay})`);\n            break;\n          case \"queue-move\":\n            this._win.webContents.executeJavaScript(`wsapi.moveQueueItem(${data.from},${data.to})`);\n            break;\n          case \"get-queue\":\n            this._win.webContents.executeJavaScript(`wsapi.getQueue()`);\n            break;\n          case \"search\":\n            if (!data.limit) {\n              data.limit = 10;\n            }\n            this._win.webContents.executeJavaScript(`wsapi.search(\\`${data.term}\\`, \\`${data.limit}\\`)`);\n            break;\n          case \"library-search\":\n            if (!data.limit) {\n              data.limit = 10;\n            }\n            this._win.webContents.executeJavaScript(`wsapi.searchLibrary(\\`${data.term}\\`, \\`${data.limit}\\`)`);\n            break;\n          case \"show-window\":\n            this._win.show();\n            break;\n          case \"hide-window\":\n            this._win.hide();\n            break;\n          case \"play-mediaitem\":\n            this._win.webContents.executeJavaScript(`wsapi.playTrackById(\"${data.id}\", \\`${data.kind}\\`)`);\n            response.message = \"Playing track\";\n            break;\n          case \"get-status\":\n            response.data = {\n              isAuthorized: true,\n            };\n            response.message = \"Status\";\n            break;\n          case \"get-currentmediaitem\":\n            this._win.webContents.executeJavaScript(`wsapi.getPlaybackState()`);\n            break;\n          case \"library-status\":\n            this._win.webContents.executeJavaScript(`wsapi.getLibraryStatus(\"${data.type}\", \"${data.id}\")`);\n            break;\n          case \"rating\":\n            this._win.webContents.executeJavaScript(`wsapi.rate(\"${data.type}\", \"${data.id}\", ${data.rating})`);\n            break;\n          case \"change-library\":\n            this._win.webContents.executeJavaScript(`wsapi.changeLibrary(\"${data.type}\", \"${data.id}\", ${data.add})`);\n            break;\n          case \"quit\":\n            electron.app.quit();\n            break;\n        }\n        ws.send(JSON.stringify(response));\n      });\n\n      ws.on(\"close\", () => {\n        // remove client from list\n        this.clients.splice(wsapi.clients.indexOf(ws), 1);\n        console.log(`Client ${ws.id} disconnected`);\n      });\n      ws.send(JSON.stringify(defaultResponse));\n    });\n  }\n\n  sendToClient(_id: any) {\n    // replace the clients.forEach with a filter to find the client that requested\n  }\n\n  updatePlaybackState(attr: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: attr,\n      message: \"OK\",\n      type: \"playbackStateUpdate\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnMusicKitApi(results: any, method: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: results,\n      message: \"OK\",\n      type: `musickitapi.${method}`,\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnDynamic(results: any, type: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: results,\n      message: \"OK\",\n      type: type,\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnLyrics(results: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: results,\n      message: \"OK\",\n      type: \"lyrics\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnSearch(results: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: results,\n      message: \"OK\",\n      type: \"searchResults\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnSearchLibrary(results: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: results,\n      message: \"OK\",\n      type: \"searchResultsLibrary\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnQueue(queue: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: queue,\n      message: \"OK\",\n      type: \"queue\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnmaxVolume(vol: any) {\n    const response: standardResponse = {\n      status: 0,\n      data: vol,\n      message: \"OK\",\n      type: \"maxVolume\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnLibraryStatus(inLibrary: boolean, rating: number) {\n    const response: standardResponse = {\n      status: 0,\n      data: {\n        inLibrary,\n        rating,\n      },\n      message: \"OK\",\n      type: \"libraryStatus\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnRatingStatus(kind: string, id: string, rating: number) {\n    const response: standardResponse = {\n      status: 0,\n      data: { kind, id, rating },\n      message: \"OK\",\n      type: \"rate\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n\n  returnLibraryChange(kind: string, id: string, shouldAdd: boolean) {\n    const response: standardResponse = {\n      status: 0,\n      data: { kind, id, add: shouldAdd },\n      message: \"OK\",\n      type: \"change-library\",\n    };\n    this.clients.forEach(function each(client: any) {\n      client.send(JSON.stringify(response));\n    });\n  }\n}\n"
  },
  {
    "path": "src/main/index.ts",
    "content": "// @ts-ignore\nawait import(\"v8-compile-cache\");\n\nimport { app, components, ipcMain } from \"electron\";\nimport { join } from \"path\";\nimport { Store } from \"./base/store.js\";\nimport { AppEvents } from \"./base/app.js\";\nimport { Plugins } from \"./base/plugins.js\";\nimport { BrowserWindow } from \"./base/browserwindow.js\";\nimport { utils } from \"./base/utils.js\";\n\nconst appName = 'sh.cider.classic';\n\nif (!app.isPackaged) {\n  app.setPath('userData', join(app.getPath('appData'), `${appName}.dev`));\n} else {\n  app.setPath('userData', join(app.getPath('appData'), appName));\n}\n\nnew Store();\nconst Cider = new AppEvents();\nconst CiderPlug = new Plugins();\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n * App Event Handlers\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\napp.on(\"ready\", async () => {\n  await utils.initializeTranslations();\n  Cider.ready(CiderPlug);\n\n  console.log(\"[Cider] Application is Ready. Creating Window.\");\n  if (!app.isPackaged) {\n    console.info(\"[Cider] Running in development mode.\");\n    // @ts-ignore\n    (await import(\"vue-devtools\")).default.install();\n  }\n  components.whenReady().then(async () => {\n    const bw = new BrowserWindow();\n    console.log(\"[Cider] Creating Window.\");\n    const win = await bw.createWindow();\n\n    app.getGPUInfo(\"complete\").then((gpuInfo) => {\n      console.log(gpuInfo);\n    });\n\n    console.log(\"[Cider][Widevine] Status:\", components.status());\n    Cider.bwCreated();\n    win.on(\"ready-to-show\", () => {\n      console.debug(\"[Cider] Window is Ready.\");\n      CiderPlug.callPlugins(\"onReady\", win);\n      if (!app.commandLine.hasSwitch(\"hidden\")) {\n        win.show();\n      }\n    });\n  });\n});\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n * Renderer Event Handlers\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\nlet rendererInitialized = false;\nipcMain.handle(\"renderer-ready\", (event) => {\n  if (rendererInitialized) return;\n  CiderPlug.callPlugins(\"onRendererReady\", event);\n  rendererInitialized = true;\n});\n\nipcMain.on(\"playbackStateDidChange\", (_event, attributes) => {\n  CiderPlug.callPlugins(\"onPlaybackStateDidChange\", attributes);\n});\n\nipcMain.on(\"nowPlayingItemDidChange\", (_event, attributes) => {\n  CiderPlug.callPlugins(\"onNowPlayingItemDidChange\", attributes);\n});\n\nipcMain.on(\"playbackTimeDidChange\", (_event, attributes) => {\n  CiderPlug.callPlugins(\"playbackTimeDidChange\", attributes);\n});\n\napp.on(\"before-quit\", () => {\n  CiderPlug.callPlugins(\"onBeforeQuit\");\n  console.warn(`${app.getName()} exited.`);\n});\n"
  },
  {
    "path": "src/main/plugins/chromecast.ts",
    "content": "import electron from \"electron\";\nimport os from \"os\";\nimport { CiderReceiver } from \"../base/castreceiver.js\";\nimport MediaRendererClient from \"upnp-mediarenderer-client\";\nimport request from \"request\";\n// @ts-expect-error\nimport castv2 from \"castv2-client\";\nimport mdnsjs from \"mdns-js\";\n\nexport default class ChromecastPlugin {\n  /**\n   * Private variables for interaction in plugins\n   */\n  private _win: any;\n  private _app: any;\n  private _lastfm: any;\n  private _store: any;\n  private _timer: any;\n  private audioClient = castv2.Client;\n  private mdns = mdnsjs;\n\n  private devices: any = [];\n  private castDevices: any = [];\n\n  // private GCRunning = false;\n  // private GCBuffer: any;\n  // private expectedConnections = 0;\n  // private currentConnections = 0;\n  private activeConnections: any = [];\n  // private requests = [];\n  // private GCstream = new Stream.PassThrough(),\n  private connectedHosts: any = {};\n  private connectedPlayer: any;\n  private ciderPort: any = 9000;\n  private scanCount: any = 0;\n  // private server = false;\n  // private  bufcount = 0;\n  // private bufcount2 = 0;\n  // private headerSent = false;\n\n  private async searchForGCDevices() {\n    try {\n      let browser = this.mdns.createBrowser(this.mdns.tcp(\"googlecast\"));\n      browser.on(\"ready\", browser.discover);\n\n      browser.on(\"update\", (service: any) => {\n        if (service.addresses && service.fullname && service.fullname.includes(\"_googlecast._tcp\")) {\n          let a = service.txt.filter((u: any) => String(u).startsWith(\"fn=\"));\n          let name = (a[0] ?? \"\").substring(3) != \"\" ? (a[0] ?? \"\").substring(3) : service.fullname.substring(0, service.fullname.indexOf(\"._googlecast\"));\n          this.ondeviceup(service.addresses[0], name + \" (\" + (service.type[0]?.description ?? \"\") + \")\", \"\", \"googlecast\");\n        }\n      });\n      const Client = (await import(\"node-ssdp\")).Client;\n      // also do a SSDP/UPnP search\n      let ssdpBrowser = new Client();\n      ssdpBrowser.on(\"response\", (headers: any, statusCode: any, rinfo: any) => {\n        var location = getLocation(headers);\n        if (location != null) {\n          this.getServiceDescription(location, rinfo.address);\n        }\n      });\n\n      function getLocation(headers: any) {\n        let location = null;\n        if (headers[\"LOCATION\"] != null) {\n          location = headers[\"LOCATION\"];\n        } else if (headers[\"Location\"] != null) {\n          location = headers[\"Location\"];\n        }\n        return location;\n      }\n\n      ssdpBrowser.search(\"urn:dial-multiscreen-org:device:dial:1\");\n\n      // actual upnp devices\n      let ssdpBrowser2 = new Client();\n      ssdpBrowser2.on(\"response\", (headers: any, statusCode: any, rinfo: any) => {\n        var location = getLocation(headers);\n        if (location != null) {\n          this.getServiceDescription(location, rinfo.address);\n        }\n      });\n      ssdpBrowser2.search(\"urn:schemas-upnp-org:device:MediaRenderer:1\");\n    } catch (e) {\n      console.log(\"Search GC err\", e);\n    }\n  }\n\n  private getServiceDescription(url: any, address: any) {\n    request.get(url, (error: any, response: any, body: any) => {\n      if (!error && response.statusCode === 200) {\n        this.parseServiceDescription(body, address, url);\n      }\n    });\n  }\n\n  private ondeviceup(host: any, name: any, location: any, type: any) {\n    if (this.castDevices.findIndex((item: any) => item.host === host && item.name === name && item.location === location && item.type === type) === -1) {\n      this.castDevices.push({\n        name: name,\n        host: host,\n        location: location,\n        type: type,\n      });\n      if (this.devices.indexOf(host) === -1) {\n        this.devices.push(host);\n      }\n      if (name) {\n        this._win.webContents.executeJavaScript(`console.log('deviceFound','ip: ${host} name:${name}')`).catch((err: any) => console.error(err));\n        console.log(\"deviceFound\", host, name);\n      }\n    } else {\n      this._win.webContents.executeJavaScript(`console.log('deviceFound (added)','ip: ${host} name:${name}')`).catch((err: any) => console.error(err));\n      console.log(\"deviceFound (added)\", host, name);\n    }\n  }\n\n  private async parseServiceDescription(body: any, address: any, url: any) {\n    const parseString = (await import(\"xml2js\")).parseString;\n    parseString(body, (err: any, result: any) => {\n      if (!err && result && result.root && result.root.device) {\n        const device = result.root.device[0];\n        console.log(\"device\", device);\n        let devicetype = \"googlecast\";\n        console.log();\n        if (device.deviceType && device.deviceType.toString() === \"urn:schemas-upnp-org:device:MediaRenderer:1\") {\n          devicetype = \"upnp\";\n        }\n        this.ondeviceup(address, device.friendlyName.toString(), url, devicetype);\n      }\n    });\n  }\n\n  private loadMedia(client: any, song: any, artist: any, album: any, albumart: any, cb?: any) {\n    // const u = 'http://' + this.getIp() + ':' + server.address().port + '/';\n    //  const DefaultMediaReceiver : any = require('castv2-client').DefaultMediaReceiver;\n    client.launch(CiderReceiver, (err: any, player: any) => {\n      if (err) {\n        console.log(err);\n        return;\n      }\n      let media = {\n        // Here you can plug an URL to any mp4, webm, mp3 or jpg file with the proper contentType.\n        contentId: \"http://\" + this.getIp() + \":\" + this.ciderPort + \"/audio.wav\",\n        contentType: \"audio/wav\",\n        streamType: \"LIVE\", // or LIVE\n\n        // Title and cover displayed while buffering\n        metadata: {\n          type: 0,\n          metadataType: 3,\n          title: song ?? \"\",\n          albumName: album ?? \"\",\n          artist: artist ?? \"\",\n          images: [{ url: albumart ?? \"\" }],\n        },\n      };\n\n      player.on(\"status\", (status: any) => {\n        console.log(\"status broadcast playerState=%s\", status);\n      });\n\n      console.log('app \"%s\" launched, loading media %s ...', player, media);\n\n      player.load(\n        media,\n        {\n          autoplay: true,\n        },\n        (err: any, status: any) => {\n          console.log(\"media loaded playerState=%s\", status);\n        },\n      );\n\n      client.getStatus((x: any, status: any) => {\n        if (status && status.volume) {\n          client.volume = status.volume.level;\n          client.muted = status.volume.muted;\n          client.stepInterval = status.volume.stepInterval;\n        }\n      });\n\n      // send websocket ip\n\n      player.sendIp(\"ws://\" + this.getIp() + \":26369\");\n      electron.ipcMain.on(\"stopGCast\", (_event) => {\n        player.kill();\n      });\n      electron.app.on(\"before-quit\", (_event) => {\n        player.kill();\n      });\n    });\n  }\n\n  private getIp() {\n    let ip: string = \"\";\n    let ip2: any = [];\n    let alias = 0;\n    const ifaces: any = os.networkInterfaces();\n    for (let dev in ifaces) {\n      ifaces[dev].forEach((details: any) => {\n        if (details.family === \"IPv4\" && !details.internal) {\n          if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? \":\" + alias : \"\"))) {\n            if (details.address.substring(0, 8) === \"192.168.\" || details.address.substring(0, 7) === \"172.16.\" || details.address.substring(0, 3) === \"10.\") {\n              if (!ip.startsWith(\"192.168.\") || (ip2.startsWith(\"192.168.\") && !ip.startsWith(\"192.168.\") && ip2.startsWith(\"172.16.\") && !ip.startsWith(\"192.168.\") && !ip.startsWith(\"172.16.\")) || (ip2.startsWith(\"10.\") && !ip.startsWith(\"192.168.\") && !ip.startsWith(\"172.16.\") && !ip.startsWith(\"10.\"))) {\n                ip = details.address;\n              }\n              ++alias;\n            }\n          }\n        }\n      });\n    }\n    return ip;\n  }\n\n  private stream(device: any, song: any, artist: any, album: any, albumart: any) {\n    let castMode = \"googlecast\";\n    let UPNPDesc = \"\";\n    castMode = device.type;\n    UPNPDesc = device.location;\n\n    let client;\n    if (castMode === \"googlecast\") {\n      let client = new this.audioClient();\n      client.volume = 100;\n      client.stepInterval = 0.5;\n      client.muted = false;\n\n      client.connect(device.host, () => {\n        // console.log('connected, launching app ...', 'http://' + this.getIp() + ':' + server.address().port + '/');\n        if (!this.connectedHosts[device.host]) {\n          this.connectedHosts[device.host] = client;\n          this.activeConnections.push(client);\n        }\n        this.loadMedia(client, song, artist, album, albumart);\n      });\n\n      client.on(\"close\", () => {\n        console.info(\"Client Closed\");\n        for (let i = this.activeConnections.length - 1; i >= 0; i--) {\n          if (this.activeConnections[i] === client) {\n            this.activeConnections.splice(i, 1);\n            return;\n          }\n        }\n      });\n\n      client.on(\"error\", (err: any) => {\n        console.log(\"Error: %s\", err.message);\n        client.close();\n        delete this.connectedHosts[device.host];\n      });\n    } else {\n      // upnp devices\n      try {\n        let client = new MediaRendererClient(UPNPDesc);\n        const options = {\n          autoplay: true,\n          contentType: \"audio/x-wav\",\n          dlnaFeatures: \"DLNA.ORG_PN=-;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01700000000000000000000000000000\",\n          metadata: {\n            title: \"Cider\",\n            creator: \"Streaming ...\",\n            type: \"audio\", // can be 'video', 'audio' or 'image'\n            //  url: 'http://' + getIp() + ':' + server.address().port + '/',\n            //  protocolInfo: 'DLNA.ORG_PN=MP3;DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000;\n          },\n        };\n        client.load(\"http://\" + this.getIp() + \":\" + this.ciderPort + \"/audio.wav\", options, function (err: any, _result: any) {\n          if (err) throw err;\n          console.log(\"playing ...\");\n        });\n        if (!this.connectedHosts[device.host]) {\n          this.connectedHosts[device.host] = client;\n          this.activeConnections.push(client);\n        }\n      } catch (e) { }\n    }\n  }\n\n  private async setupGCServer() {\n    return \"\";\n  }\n\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"Chromecast\";\n  public description: string = \"LastFM plugin for Cider\";\n  public version: string = \"0.0.1\";\n  public author: string = \"vapormusic / Cider Collective\";\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(utils: { getApp: () => any; getStore: () => any }) {\n    this._app = utils.getApp();\n    this._store = utils.getStore();\n  }\n\n  /**\n   * Runs on app ready\n   */\n  onReady(win: any): void {\n    this._win = win;\n    electron.ipcMain.on(\"getKnownCastDevices\", (event) => {\n      event.returnValue = this.castDevices;\n    });\n\n    electron.ipcMain.on(\"performGCCast\", (event, device, song, artist, album, albumart) => {\n      // this.setupGCServer().then( () => {\n      this._win.webContents.setAudioMuted(true);\n      console.log(device);\n      this.stream(device, song, artist, album, albumart);\n      // })\n    });\n\n    electron.ipcMain.on(\"getChromeCastDevices\", (_event, _data) => {\n      if (this.scanCount++ == 2) {\n        this.scanCount = 0;\n        this.castDevices = [];\n      }\n      this.searchForGCDevices();\n    });\n\n    electron.ipcMain.on(\"stopGCast\", (_event) => {\n      this._win.webContents.setAudioMuted(false);\n      this.activeConnections.forEach((client: any) => {\n        try {\n          client.stop();\n        } catch (e) { }\n      });\n      this.activeConnections = [];\n      this.connectedHosts = {};\n    });\n  }\n\n  /**\n   * Runs on app stop\n   */\n  onBeforeQuit(): void { }\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  onNowPlayingItemDidChange(attributes: any): void { }\n\n  onRendererReady(): void {\n    this._win.webContents.executeJavaScript(`ipcRenderer.sendSync('get-port')`).then((result: any) => {\n      this.ciderPort = result;\n    });\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/discordrpc.ts",
    "content": "import { AutoClient } from \"discord-auto-rpc\";\nimport { ipcMain } from \"electron\";\nimport fetch from \"node-fetch\";\n\nexport default class DiscordRPC {\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"Discord Rich Presence\";\n  public description: string = \"Discord RPC plugin for Cider\";\n  public version: string = \"1.1.0\";\n  public author: string = \"vapormusic/Core/cryptofyre (Cider Collective)\";\n\n  /**\n   * Private variables for interaction in plugins\n   */\n  private _utils: any;\n  private _attributes: any;\n  private ready: boolean = false;\n\n  /**\n   * Plugin Initialization\n   */\n  private _client: any = null;\n  private _activityCache: any = {\n    details: \"\",\n    state: \"\",\n    largeImageKey: \"\",\n    largeImageText: \"\",\n    smallImageKey: \"\",\n    smallImageText: \"\",\n    instance: false,\n  };\n\n  /*******************************************************************************************\n   * Public Methods\n   * ****************************************************************************************/\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(utils: any) {\n    this._utils = utils;\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n  }\n\n  /**\n   * Runs on app ready\n   */\n  onReady(_win: any): void {\n    this.connect();\n    console.debug(`[Plugin][${this.name}] Ready.`);\n  }\n\n  /**\n   * Set up ipc listeners for the plugin\n   */\n  onRendererReady() {\n    const self = this;\n    ipcMain.on(\"discordrpc:updateImage\", async (_event, artworkUrl) => {\n      if (this._utils.getStoreValue(\"general.privateEnabled\")) return;\n\n      fetch(\"https://api.cider.sh/v1/images\", {\n        method: \"POST\",\n        headers: {\n          \"User-Agent\": this._utils.getWindow().webContents.getUserAgent(),\n          url: artworkUrl,\n        },\n      })\n        .then(async (res) => {\n          const json = await res.json() as { imageUrl: string };\n          self._activityCache.largeImageKey = \"https://images.weserv.nl/?url=\" + json.imageUrl + \"&w=1024&h=1024&output=jpg\";\n          self._client.setActivity(self._activityCache);\n        });\n    });\n    ipcMain.on(\"discordrpc:reload\", (_event, configUpdate = null) => {\n      console.log(`[DiscordRPC][reload] Reloading DiscordRPC.`);\n\n      if (this._client) {\n        this._client.destroy();\n      }\n\n      if (!this._utils.getStoreValue(\"connectivity.discord_rpc.enabled\")) return;\n      this._client\n        .endlessLogin({\n          clientId: this._utils.getStoreValue(\"connectivity.discord_rpc.client\") === \"Cider\" ? \"911790844204437504\" : \"886578863147192350\",\n        })\n        .then(() => {\n          console.log(`[DiscordRPC][reload] DiscordRPC Reloaded.`);\n          this.ready = true;\n          if (configUpdate == null) this._utils.getWindow().webContents.send(\"rpcReloaded\", this._client.user);\n          if (this._activityCache && this._activityCache.details && this._activityCache.state) {\n            console.info(`[DiscordRPC][reload] Restoring activity cache.`);\n            this._client.setActivity(this._activityCache);\n          }\n        })\n        .catch((e: any) => console.error(`[DiscordRPC][reload] ${e}`));\n      // this.connect(true)\n    });\n    ipcMain.on(\"onPrivacyModeChange\", (_event, enabled) => {\n      if (enabled && this._client) {\n        this._client.clearActivity();\n      } else if (!enabled && this._activityCache && this._activityCache.details && this._activityCache.state) {\n        this._client.setActivity(this._activityCache);\n      }\n    });\n  }\n\n  /**\n   * Runs on app stop\n   */\n  onBeforeQuit(): void {\n    console.debug(`[Plugin][${this.name}] Stopped.`);\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  onPlaybackStateDidChange(attributes: object): void {\n    this._attributes = attributes;\n    this.setActivity(attributes);\n  }\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  playbackTimeDidChange(attributes: object): void {\n    this._attributes = attributes;\n    this.setActivity(attributes);\n  }\n\n  /*******************************************************************************************\n   * Private Methods\n   * ****************************************************************************************/\n\n  /**\n   * Connect to Discord RPC\n   * @private\n   */\n  private connect() {\n    if (!this._utils.getStoreValue(\"connectivity.discord_rpc.enabled\")) {\n      return;\n    }\n\n    // Create the client\n    this._client = new AutoClient({ transport: \"ipc\" });\n\n    // Runs on Ready\n    this._client.once(\"ready\", () => {\n      console.info(`[DiscordRPC][connect] Successfully Connected to Discord. Authed for user: ${this._client.user.id}.`);\n\n      if (this._activityCache && this._activityCache.details && this._activityCache.state && !this._utils.getStoreValue(\"general.privateEnabled\")) {\n        console.info(`[DiscordRPC][connect] Restoring activity cache.`);\n        this._client.setActivity(this._activityCache);\n      }\n    });\n\n    // Login to Discord\n    this._client\n      .endlessLogin({\n        clientId: this._utils.getStoreValue(\"connectivity.discord_rpc.client\") === \"Cider\" ? \"911790844204437504\" : \"886578863147192350\",\n      })\n      .then(() => {\n        this.ready = true;\n      })\n      .catch((e: any) => console.error(`[DiscordRPC][connect] ${e}`));\n  }\n\n  /**\n   * Sets the activity\n   * @param attributes Music Attributes\n   */\n  private setActivity(attributes: any) {\n    if (!this._client || !attributes) {\n      return;\n    }\n\n    // Check if show buttons is (true) or (false)\n    let activity: Object = {\n      details: this._utils.getStoreValue(\"connectivity.discord_rpc.activity.details_format\"),\n      state: this._utils.getStoreValue(\"connectivity.discord_rpc.activity.state_format\"),\n      largeImageKey: attributes?.artwork?.url?.replace(\"{w}\", \"1024\").replace(\"{h}\", \"1024\"),\n      largeImageText: attributes.albumName,\n      instance: false, // Whether the activity is in a game session\n    };\n\n    // Filter the activity\n    activity = this.filterActivity(activity, attributes);\n\n    if (!this.ready) {\n      this._activityCache = activity;\n      return;\n    }\n\n    if (!activity) {\n      return;\n    }\n\n    if (!attributes.status && this._utils.getStoreValue(\"connectivity.discord_rpc.clear_on_pause\")) {\n      this._client.clearActivity();\n    } else if (activity && this._activityCache !== activity) {\n      if (this._utils.getStoreValue(\"general.privateEnabled\")) return;\n      this._client.setActivity(activity);\n    }\n    this._activityCache = activity;\n  }\n\n  /**\n   * Filter the Discord activity object\n   */\n  private filterActivity(activity: any, attributes: any): Object {\n    // Handling Activity Buttons\n    if (this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.enabled\") && this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.first\") != \"disabled\") {\n      const activityUrls: { [key: string]: any } = {\n        listenOnCider: \"cider\",\n        viewOnAppleMusic: \"appleMusic\",\n        viewOnOtherMusicServices: \"songLink\",\n      };\n\n      const firstActivity = this._utils.getLocale(this._utils.getStoreValue(\"general.language\"), `settings.option.connectivity.discordRPC.buttons.${this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.first\")}`);\n      const secondActivity = this._utils.getLocale(this._utils.getStoreValue(\"general.language\"), `settings.option.connectivity.discordRPC.buttons.${this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.second\")}`);\n\n      if (this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.second\") != \"disabled\") {\n        activity.buttons = [\n          { label: firstActivity, url: attributes.url[activityUrls[this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.first\")]] },\n          { label: secondActivity, url: attributes.url[activityUrls[this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.second\")]] },\n        ];\n      } else {\n        activity.buttons = [{ label: firstActivity, url: attributes.url[activityUrls[this._utils.getStoreValue(\"connectivity.discord_rpc.activity.buttons.first\")]] }];\n      }\n    }\n\n    // Add the timestamp if its playing and people want them\n    if (!this._utils.getStoreValue(\"connectivity.discord_rpc.hide_timestamp\") && attributes.status && new Date(attributes.endTime).getTime() > 0 && isFinite(attributes.endTime) && isFinite(attributes.startTime)) {\n      activity.startTimestamp = Date.now() - (attributes?.durationInMillis - attributes?.remainingTime);\n      activity.endTimestamp = attributes.endTime;\n    }\n\n    // If the user wants to keep the activity when paused\n    if (!this._utils.getStoreValue(\"connectivity.discord_rpc.clear_on_pause\")) {\n      activity.smallImageKey = attributes.status ? \"play\" : \"pause\";\n      activity.smallImageText = attributes.status ? \"Playing\" : \"Paused\";\n    }\n\n    /**\n     * Works with:\n     * {artist}\n     * {composer}\n     * {title}\n     * {album}\n     * {trackNumber}\n     */\n    const rpcVars: any = {\n      artist: attributes.artistName,\n      composer: attributes.composerName,\n      title: attributes.name,\n      album: attributes.albumName,\n      trackNumber: attributes.trackNumber,\n    };\n\n    // Replace the variables\n    Object.keys(rpcVars).forEach((key) => {\n      if (activity.details.includes(`{${key}}`)) {\n        activity.details = activity.details.replace(`{${key}}`, rpcVars[key]);\n      }\n      if (activity.state.includes(`{${key}}`)) {\n        activity.state = activity.state.replace(`{${key}}`, rpcVars[key]);\n      }\n    });\n\n    // Checks if the details is greater than 128 because some songs can be that long\n    if (activity.details && activity.details.length >= 128) {\n      activity.details = activity.details.substring(0, 125) + \"...\";\n    }\n\n    // Checks if the state is greater than 128 because some songs can be that long\n    if (activity.state && activity.state.length >= 128) {\n      activity.state = activity.state.substring(0, 125) + \"...\";\n    }\n\n    // Checks if the state is greater than 128 because some songs can be that long\n    if (activity.largeImageText && activity.largeImageText.length >= 128) {\n      activity.largeImageText = activity.largeImageText.substring(0, 125) + \"...\";\n    }\n\n    // Check large image\n    if (activity.largeImageKey == null || activity.largeImageKey === \"\" || activity.largeImageKey.length > 256) {\n      activity.largeImageKey = \"cider\";\n    }\n\n    // not sure\n    if (!attributes.artistName) {\n      delete activity.state;\n    }\n\n    if (!activity.largeImageText || activity.largeImageText.length < 2) {\n      delete activity.largeImageText;\n    }\n\n    if (activity.status === \"\" || activity.details === \"\") {\n      return false;\n    }\n    return activity;\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/lastfm.ts",
    "content": "// @ts-ignore\nimport LastfmAPI from \"lastfmapi\";\n\nexport default class lastfm {\n  /**\n   * Base Plugin Information\n   */\n  public name: string = \"LastFM Plugin\";\n  public version: string = \"2.0.0\";\n  public author: string = \"Core (Cider Collective)\";\n\n  private _apiCredentials = {\n    key: \"f9986d12aab5a0fe66193c559435ede3\",\n    secret: \"acba3c29bd5973efa38cc2f0b63cc625\",\n  };\n  /**\n   * Plugin Initialization\n   */\n  private _lfm: any = null;\n  private _authenticated: boolean = false;\n  private _utils: any = null;\n  private _scrobbleCache: any = {};\n  private _nowPlayingCache: any = {};\n\n  /**\n   * Public Methods\n   */\n\n  constructor(utils: any) {\n    this._utils = utils;\n  }\n\n  onReady(_win: Electron.BrowserWindow): void {\n    this.initializeLastFM(\"\", this._apiCredentials);\n  }\n\n  onRendererReady(): void {\n    // Register the ipcMain handlers\n    this._utils.getIPCMain().handle(\"lastfm:url\", (event: any) => {\n      console.debug(`[${lastfm.name}:url] Called.`);\n      return this._lfm.getAuthenticationUrl({ cb: \"cider://auth/lastfm\" });\n    });\n\n    this._utils.getIPCMain().on(\"lastfm:auth\", (event: any, token: string) => {\n      console.debug(`[${lastfm.name}:auth] Token: `, token);\n      this.authenticateLastFM(token);\n    });\n\n    this._utils.getIPCMain().on(\"lastfm:disconnect\", (_event: any) => {\n      this._lfm.setSessionCredentials(null, null);\n      this._authenticated = false;\n      console.debug(`[${lastfm.name}:disconnect] Disconnected`);\n    });\n\n    this._utils.getIPCMain().on(\"lastfm:nowPlayingChange\", (event: any, attributes: any) => {\n      if (this._utils.getStoreValue(\"connectivity.lastfm.filter_loop\") || this._utils.getStoreValue(\"general.privateEnabled\") || attributes.kind === \"radioStation\") return;\n      this.updateNowPlayingTrack(attributes);\n    });\n\n    this._utils.getIPCMain().on(\"lastfm:FilteredNowPlayingItemDidChange\", (event: any, attributes: any) => {\n      if (this._utils.getStoreValue(\"general.privateEnabled\") || attributes.kind === \"radioStation\") return;\n      this.updateNowPlayingTrack(attributes);\n    });\n\n    this._utils.getIPCMain().on(\"lastfm:scrobbleTrack\", (event: any, attributes: any) => {\n      if (this._utils.getStoreValue(\"general.privateEnabled\") || attributes.kind === \"radioStation\") return;\n      this.scrobbleTrack(attributes);\n    });\n  }\n\n  /**\n   * Initialize LastFM\n   * @param token\n   * @param api\n   * @private\n   */\n  private initializeLastFM(token: string, api: { key: string; secret: string }): void {\n    console.debug(`[${lastfm.name}:initialize] Initializing LastFM`);\n    this._lfm = new LastfmAPI({\n      api_key: api.key,\n      secret: api.secret,\n    });\n\n    if (this._utils.getStoreValue(\"connectivity.lastfm.secrets.username\") && this._utils.getStoreValue(\"connectivity.lastfm.secrets.key\")) {\n      this._lfm.setSessionCredentials(this._utils.getStoreValue(\"connectivity.lastfm.secrets.username\"), this._utils.getStoreValue(\"connectivity.lastfm.secrets.key\"));\n      this._authenticated = true;\n    } else {\n      this.authenticateLastFM(token);\n    }\n  }\n\n  /**\n   * Authenticate the user with the given token\n   * @param token\n   * @private\n   */\n  private authenticateLastFM(token: string): void {\n    if (!token) return;\n    this._lfm.authenticate(token, (err: any, session: any) => {\n      if (err) {\n        console.error(`[${lastfm.name}:authenticate] Error: ${typeof err === \"string\" ? err : err.message}`);\n\n        this._utils.getWindow().webContents.executeJavaScript(`app.notyf.error(\"${err.message}\");`);\n        return;\n      }\n      this._utils.getWindow().webContents.send(\"lastfm:authenticated\", session);\n      this._authenticated = true;\n      console.debug(`[${lastfm.name}:authenticate] Authenticated as ${session.username}`);\n    });\n  }\n\n  /**\n   * Verifies the track information with lastfm\n   * @param attributes\n   * @param callback\n   * @private\n   */\n  private verifyTrack(attributes: any, callback: Function): void {\n    if (!attributes) return attributes;\n\n    if (!attributes.lfmAlbum) {\n      this._lfm.album.getInfo(\n        {\n          artist: attributes.primaryArtist,\n          album: attributes.albumName.replace(/ - Single| - EP/g, \"\"),\n        },\n        (err: any, data: any) => {\n          if (err) {\n            console.error(`[${lastfm.name}] [album.getInfo] Error: ${typeof err === \"string\" ? err : err.message}`);\n            attributes.lfmAlbum = {\n              name: attributes.albumName.replace(/ - Single| - EP/g, \"\"),\n              artist: attributes.primaryArtist,\n            };\n            callback(attributes);\n          }\n          if (data) {\n            attributes.lfmAlbum = data;\n            callback(attributes);\n          }\n        },\n      );\n    } else {\n      this._lfm.track.getCorrection(attributes.primaryArtist, attributes.name, (err: any, data: any) => {\n        if (err) {\n          console.error(`[${lastfm.name}] [track.getCorrection] Error: ${typeof err === \"string\" ? err : err.message}`);\n          attributes.lfmTrack = {\n            name: attributes.name,\n            artist: {\n              name: attributes.primaryArtist,\n            },\n          };\n          callback(attributes);\n        }\n        if (data) {\n          attributes.lfmTrack = data.correction.track;\n          callback(attributes);\n        }\n      });\n    }\n  }\n\n  /**\n   * Scrobbles the track to lastfm\n   * @param attributes\n   * @private\n   */\n  private scrobbleTrack(attributes: any): void {\n    if (!attributes?.lfmTrack || !attributes?.lfmAlbum) {\n      this.verifyTrack(attributes, (a: any) => {\n        this.scrobbleTrack(a);\n      });\n      return;\n    }\n\n    if (!this._authenticated || !attributes || this._utils.getStoreValue(\"connectivity.lastfm.filter_types\")[attributes.playParams.kind] || this._utils.getStoreValue(\"connectivity.lastfm.filter_types\")[attributes.kind] || (this._utils.getStoreValue(\"connectivity.lastfm.filter_loop\") && this._scrobbleCache.track === attributes.lfmTrack.name)) return;\n\n    // Scrobble\n    const scrobble = {\n      artist: attributes.lfmTrack.artist.name,\n      track: attributes.lfmTrack.name,\n      album: attributes.lfmAlbum.name,\n      albumArtist: attributes.lfmAlbum.artist,\n      timestamp: new Date().getTime() / 1000,\n      trackNumber: attributes.trackNumber,\n      duration: attributes.durationInMillis / 1000,\n    };\n\n    // Easy Debugging\n    console.debug(`[${lastfm.name}:scrobble] Scrobbling ${scrobble.artist} - ${scrobble.track}`);\n\n    // Scrobble the track\n    this._lfm.track.scrobble(scrobble, (err: any, _res: any) => {\n      if (err) {\n        console.error(`[${lastfm.name}:scrobble] Scrobble failed: ${err.message}`);\n      } else {\n        console.debug(`[${lastfm.name}:scrobble] Track scrobbled: ${scrobble.artist} - ${scrobble.track}`);\n        this._scrobbleCache = scrobble;\n      }\n    });\n  }\n\n  /**\n   * Updates the now playing track\n   * @param attributes\n   * @private\n   */\n  private updateNowPlayingTrack(attributes: any): void {\n    if (!attributes?.lfmTrack || !attributes?.lfmAlbum) {\n      this.verifyTrack(attributes, (a: any) => {\n        this.updateNowPlayingTrack(a);\n      });\n      return;\n    }\n\n    if (!this._authenticated || !attributes || this._utils.getStoreValue(\"connectivity.lastfm.filter_types\")[attributes.playParams.kind] || this._utils.getStoreValue(\"connectivity.lastfm.filter_types\")[attributes.kind] || (this._utils.getStoreValue(\"connectivity.lastfm.filter_loop\") && this._nowPlayingCache.track === attributes.lfmTrack.name)) return;\n    console.log(this._utils.getStoreValue(\"connectivity.lastfm.filter_types\"));\n\n    const nowPlaying = {\n      artist: attributes.lfmTrack.artist.name,\n      track: attributes.lfmTrack.name,\n      album: attributes.lfmAlbum.name,\n      trackNumber: attributes.trackNumber,\n      duration: attributes.durationInMillis / 1000,\n      albumArtist: attributes.lfmAlbum.artist,\n    };\n\n    this._lfm.track.updateNowPlaying(nowPlaying, (err: any, res: any) => {\n      if (err) {\n        console.error(`[${lastfm.name}:updateNowPlaying] Now Playing Update failed: ${err.message}`);\n      } else {\n        console.debug(`[${lastfm.name}:updateNowPlaying] Now Playing Updated: ${nowPlaying.artist} - ${nowPlaying.track}`);\n        this._nowPlayingCache = nowPlaying;\n      }\n    });\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/menubar.ts",
    "content": "import { app, Menu, shell } from \"electron\";\nimport { utils } from \"../base/utils.js\";\n\nexport default class Thumbar {\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"Menubar Plugin\";\n  public description: string = \"Creates the menubar\";\n  public version: string = \"1.0.0\";\n  public author: string = \"Core\";\n  public contributors: string[] = [\"Core\", \"Qwack\", \"Monochromish\"];\n\n  /**\n   * Menubar Assets\n   * @private\n   */\n\n  private isNotMac: boolean = process.platform !== \"darwin\";\n  private isMac: boolean = process.platform === \"darwin\";\n  private _menuTemplate: any = [];\n\n  /*******************************************************************************************\n   * Public Methods\n   * ****************************************************************************************/\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(_utils: utils) {\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n  }\n\n  /**\n   * Runs on app ready\n   */\n  onReady(_win: Electron.BrowserWindow): void {\n    this._menuTemplate = [\n      {\n        label: app.getName(),\n        submenu: [\n          {\n            label: `${utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.about\")} ${app.getName()}`,\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('about')`),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.toggleprivate\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.togglePrivateSession\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.cfg.general.privateEnabled = !app.cfg.general.privateEnabled`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.settings\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.settings\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.openSettingsPage()`),\n          },\n          ...(this.isMac ? [{ type: \"separator\" }, { role: \"services\" }, { type: \"separator\" }, { role: \"hide\" }, { role: \"hideOthers\" }, { role: \"unhide\" }, { type: \"separator\" }, { role: \"quit\" }] : []),\n          ...(this.isNotMac\n            ? [\n                { type: \"separator\" },\n                {\n                  label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.quit\"),\n                  accelerator: \"Control+Q\",\n                  click: () => app.quit(),\n                },\n              ]\n            : []),\n        ],\n      },\n      {\n        label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.view\"),\n        submenu: [\n          ...(this.isMac ? [{ role: \"reload\" }, { role: \"forceReload\" }, { role: \"toggleDevTools\" }, { type: \"separator\" }, { role: \"resetZoom\" }, { role: \"zoomIn\" }, { role: \"zoomOut\" }, { type: \"separator\" }, { role: \"togglefullscreen\" }, { type: \"separator\" }] : []),\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.search\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.search\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(\"app.focusSearch()\"),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.listenNow\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.listnow\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('listen_now')`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.browse\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.browse\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('browse')`),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.recentlyAdded\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.recentAdd\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('library-recentlyadded')`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.songs\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.songs\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('library-songs')`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.albums\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.albums\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('library-albums')`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.artists\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.artists\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('library-artists')`),\n          },\n        ],\n      },\n      {\n        label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.window\"),\n        submenu: [\n          {\n            role: \"minimize\",\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.minimize\"),\n          },\n          { type: \"separator\" },\n          ...(this.isMac\n            ? [\n                {\n                  label: \"Show\",\n                  click: () => utils.getWindow().show(),\n                },\n                { role: \"zoom\" },\n                { type: \"separator\" },\n                { role: \"front\" },\n                { role: \"close\" },\n                {\n                  label: \"Edit\",\n                  submenu: [{ role: \"undo\" }, { role: \"redo\" }, { type: \"separator\" }, { role: \"cut\" }, { role: \"copy\" }, { role: \"paste\" }],\n                },\n                { type: \"separator\" },\n              ]\n            : []),\n          ...(this.isNotMac\n            ? [\n                {\n                  label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.zoom\"),\n                  submenu: [\n                    {\n                      label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.zoomin\"),\n                      role: \"zoomIn\",\n                      accelerator: utils.getStoreValue(\"general.keybindings.zoomn\").join(\"+\"),\n                    },\n                    {\n                      label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.zoomout\"),\n                      role: \"zoomOut\",\n                      accelerator: utils.getStoreValue(\"general.keybindings.zoomt\").join(\"+\"),\n                    },\n                    {\n                      label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.zoomreset\"),\n                      role: \"resetZoom\",\n                      accelerator: utils.getStoreValue(\"general.keybindings.zoomrst\").join(\"+\"),\n                    },\n                  ],\n                },\n                { type: \"separator\" },\n                {\n                  label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.fullscreen\"),\n                  accelerator: \"Control+Enter\",\n                  role: \"togglefullscreen\",\n                },\n                { type: \"separator\" },\n                {\n                  label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"action.close\"),\n                  accelerator: \"Control+W\",\n                  role: \"close\",\n                },\n                { type: \"separator\" },\n                {\n                  label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.reload\"),\n                  accelerator: \"Control+R\",\n                  role: \"reload\",\n                },\n                {\n                  label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.forcereload\"),\n                  accelerator: \"Control+Shift+R\",\n                  role: \"forceReload\",\n                },\n              ]\n            : []),\n        ],\n      },\n\n      {\n        label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.controls\"),\n        submenu: [\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.playpause\"),\n            accelerator: \"Space\",\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.SpacePause()`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.next\"),\n            accelerator: \"CommandOrControl+Right\",\n            click: () => utils.getWindow().webContents.executeJavaScript(`MusicKitInterop.next()`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.previous\"),\n            accelerator: \"CommandOrControl+Left\",\n            click: () => utils.getWindow().webContents.executeJavaScript(`MusicKitInterop.previous()`),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.volumeup\"),\n            accelerator: \"CommandOrControl+Up\",\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.volumeUp()`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.volumedown\"),\n            accelerator: \"CommandOrControl+Down\",\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.volumeDown()`),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.cast2\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.castToDevices\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.modals.castMenu = true`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.webremote\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.webRemote\").join(\"+\"),\n            sublabel: \"Opens in external window\",\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('remote-pair')`),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.audioSettings\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.audioSettings\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.modals.audioSettings = true`),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.plugins\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.pluginMenu\").join(\"+\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.modals.pluginMenu = true`),\n          },\n        ],\n      },\n      {\n        label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.account\"),\n        submenu: [\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.accountSettings\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.appRoute('apple-account-settings')`),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.signout\"),\n            click: () => utils.getWindow().webContents.executeJavaScript(`app.unauthorize()`),\n          },\n        ],\n      },\n      {\n        label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.support\"),\n        role: \"help\",\n        submenu: [\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.discord\"),\n            click: () => shell.openExternal(\"https://discord.gg/AppleMusic\").catch(console.error),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"term.github\"),\n            click: () => shell.openExternal(\"https://github.com/ciderapp/Cider/wiki/Troubleshooting\").catch(console.error),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.report\"),\n            submenu: [\n              {\n                label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.bug\"),\n                click: () => shell.openExternal(\"https://github.com/ciderapp/Cider/issues/new?assignees=&labels=bug%2Ctriage&template=bug_report.yaml&title=%5BBug%5D%3A+\").catch(console.error),\n              },\n              {\n                label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.feature\"),\n                click: () => shell.openExternal(\"https://github.com/ciderapp/Cider/discussions/new?category=feature-request\").catch(console.error),\n              },\n              {\n                label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.trans\"),\n                click: () => shell.openExternal(\"https://github.com/ciderapp/Cider/issues/new?assignees=&labels=%F0%9F%8C%90+Translations&template=translation.yaml&title=%5BTranslation%5D%3A+\").catch(console.error),\n              },\n            ],\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.license\"),\n            click: () => shell.openExternal(\"https://github.com/ciderapp/Cider/blob/main/LICENSE\").catch(console.error),\n          },\n          { type: \"separator\" },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.toggledevtools\"),\n            accelerator: utils.getStoreValue(\"general.keybindings.openDeveloperTools\").join(\"+\"),\n            click: () => utils.getWindow().webContents.openDevTools(),\n          },\n          {\n            label: utils.getLocale(utils.getStoreValue(\"general.language\"), \"menubar.options.conf\"),\n            click: () => utils.getStoreInstance().openInEditor(),\n          },\n        ],\n      },\n    ];\n\n    const menu = Menu.buildFromTemplate(this._menuTemplate);\n    Menu.setApplicationMenu(menu);\n  }\n\n  /**\n   * Runs on app stop\n   */\n  onBeforeQuit(): void {\n    console.debug(`[Plugin][${this.name}] Stopped.`);\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  onPlaybackStateDidChange(attributes: object): void {}\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  onNowPlayingItemDidChange(attributes: object): void {}\n}\n"
  },
  {
    "path": "src/main/plugins/mpris.ts",
    "content": "import Player from 'mpris-service';\n\nexport default class mpris {\n  /**\n   * Private variables for interaction in plugins\n   */\n  private static utils: any;\n  /**\n   * MPRIS Service\n   */\n  private static player: Player;\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"MPRIS Service\";\n  public description: string = \"Handles MPRIS service calls for Linux systems.\";\n  public version: string = \"1.0.0\";\n  public author: string = \"Core\";\n\n  /*******************************************************************************************\n   * Private Methods\n   * ****************************************************************************************/\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(utils: any) {\n    mpris.utils = utils;\n    console.debug(`[Plugin][${mpris.name}] Loading Complete.`);\n  }\n\n  /**\n   * Blocks non-linux systems from running this plugin\n   * @private\n   * @decorator\n   */\n  private static linuxOnly(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {\n    if (process.platform !== \"linux\") {\n      descriptor.value = function () {\n        return;\n      };\n    }\n  }\n\n  /**\n   * Connects to MPRIS Service\n   */\n  private static connect() {\n    const player = new Player({\n      name: \"cider\",\n      identity: \"Cider\",\n      supportedInterfaces: [\"player\"],\n    });\n\n    console.debug(`[${mpris.name}:connect] Successfully connected.`);\n\n    const renderer = mpris.utils.getWindow().webContents;\n    const loopType: { [key: string]: number } = {\n      none: 0,\n      track: 1,\n      playlist: 2,\n    };\n\n    player.on(\"next\", () => mpris.utils.playback.next());\n    player.on(\"previous\", () => mpris.utils.playback.previous());\n    player.on(\"playpause\", () => mpris.utils.playback.playPause());\n    player.on(\"play\", () => mpris.utils.playback.play());\n    player.on(\"pause\", () => mpris.utils.playback.pause());\n    player.on(\"quit\", () => mpris.utils.getApp().exit());\n    player.on(\"position\", (args: { position: any }) => mpris.utils.playback.seek(args.position / 1000 / 1000));\n    player.on(\"loopStatus\", (status: string) => renderer.executeJavaScript(`app.mk.repeatMode = ${loopType[status.toLowerCase()]}`));\n    player.on(\"shuffle\", () => renderer.executeJavaScript(\"app.mk.shuffleMode = (app.mk.shuffleMode === 0) ? 1 : 0\"));\n    player.on(\"volume\", (volume: string) => {\n      renderer.executeJavaScript(`app.mk.volume = ${parseFloat(volume)}`);\n    });\n    player.on(\"raise\", () => {\n      mpris.utils.getWindow().show();\n      mpris.utils.getWindow().focus();\n    });\n\n    mpris.utils.getIPCMain().on(\"mpris:playbackTimeDidChange\", (event: any, time: number) => {\n      player.getPosition = () => time;\n    });\n\n    mpris.utils.getIPCMain().on(\"repeatModeDidChange\", (_e: any, mode: number) => {\n      switch (mode) {\n        case 0:\n          player.loopStatus = Player.LOOP_STATUS_NONE;\n          break;\n        case 1:\n          player.loopStatus = Player.LOOP_STATUS_TRACK;\n          break;\n        case 2:\n          player.loopStatus = Player.LOOP_STATUS_PLAYLIST;\n          break;\n      }\n    });\n\n    mpris.utils.getIPCMain().on(\"mpris:volumeChange\", (_e: any, volume: number) => {\n      player.volume = volume;\n    });\n\n    mpris.utils.getIPCMain().on(\"shuffleModeDidChange\", (_e: any, mode: number) => {\n      player.shuffle = mode === 1;\n    });\n\n    mpris.player = player;\n  }\n\n  /**\n   * Update M.P.R.I.S Player Attributes\n   */\n  private static updateMetaData(attributes: any) {\n    mpris.player.metadata = {\n      \"mpris:trackid\": mpris.player.objectPath(`track/${attributes.playParams.id.replace(/[^a-zA-Z 0-9]+/g, \"\")}`),\n      \"mpris:length\": attributes.durationInMillis * 1000, // In microseconds\n      \"mpris:artUrl\": attributes.artwork.url.replace(\"/{w}x{h}bb\", \"/512x512bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n      \"xesam:title\": `${attributes.name}`,\n      \"xesam:album\": `${attributes.albumName}`,\n      \"xesam:artist\": [`${attributes.artistName}`],\n      \"xesam:genre\": attributes.genreNames,\n    };\n  }\n\n  /*******************************************************************************************\n   * Public Methods\n   * ****************************************************************************************/\n\n  /**\n   * Clear state\n   * @private\n   */\n  private static clearState() {\n    if (!mpris.player) {\n      return;\n    }\n    mpris.player.metadata = {\n      \"mpris:trackid\": \"/org/mpris/MediaPlayer2/TrackList/NoTrack\",\n    };\n    mpris.player.playbackStatus = Player.PLAYBACK_STATUS_STOPPED;\n  }\n\n  /**\n   * Runs on app ready\n   */\n  @mpris.linuxOnly\n  onReady(_: any): void {\n    console.debug(`[${mpris.name}:onReady] Ready.`);\n  }\n\n  /**\n   * Renderer ready\n   */\n  @mpris.linuxOnly\n  onRendererReady(): void {\n    mpris.connect();\n  }\n\n  /**\n   * Runs on app stop\n   */\n  @mpris.linuxOnly\n  onBeforeQuit(): void {\n    console.debug(`[Plugin][${mpris.name}] Stopped.`);\n    mpris.clearState();\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  @mpris.linuxOnly\n  onPlaybackStateDidChange(attributes: any): void {\n    mpris.player.playbackStatus = attributes?.status ? Player.PLAYBACK_STATUS_PLAYING : Player.PLAYBACK_STATUS_PAUSED;\n  }\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  @mpris.linuxOnly\n  playbackTimeDidChange(attributes: object): void {\n    mpris.updateMetaData(attributes);\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/playbackNotifications.ts",
    "content": "import fetch from \"node-fetch\";\nimport { app, nativeImage, Notification } from \"electron\";\nimport NativeImage = Electron.NativeImage;\nimport { createWriteStream } from \"fs\";\nimport { join } from \"path\";\n\nexport default class playbackNotifications {\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"Playback Notifications\";\n  public description: string = \"Creates notifications on playback.\";\n  public version: string = \"1.0.0\";\n  public author: string = \"Core\";\n  public contributors: string[] = [\"Core\", \"Monochromish\"];\n\n  private _utils: any;\n  private _notification: Notification | undefined;\n  private _artworkImage: { [key: string]: NativeImage } = {};\n  private _artworkNums: string[] = [];\n\n  /**\n   * Creates playback notification\n   * @param a: Music Attributes\n   */\n  createNotification(a: any): void {\n    if (this._notification) {\n      this._notification.close();\n    }\n\n    this._notification = new Notification({\n      title: a.name,\n      body: `${a.artistName} — ${a.albumName}`,\n      silent: true,\n      icon: this._artworkImage[a.artwork.url],\n      urgency: \"low\",\n      actions: [\n        {\n          type: \"button\",\n          text: `${this._utils.getLocale(this._utils.getStoreValue(\"general.language\"), \"term.skip\")}`,\n        },\n      ],\n      toastXml: `\n                <toast>\n                    <audio silent=\"true\" />\n                    <visual>\n                        <binding template=\"ToastImageAndText02\">\n                            <image id=\"1\" src=\"${join(app.getPath(\"temp\"), `${a.songId}-${a.artwork.url.split(\"/\").pop()}`)}\" name=\"Image\" />\n                            <text id=\"1\">${a?.name.replace(/&/g, \"&amp;\")}</text>\n                            <text id=\"2\">${a?.artistName.replace(/&/g, \"&amp;\")} — ${a?.albumName.replace(/&/g, \"&amp;\")}</text>\n                        </binding>\n                    </visual>\n                    <actions>\n                        <action content=\"${this._utils.getLocale(this._utils.getStoreValue(\"general.language\"), \"term.playpause\")}\" activationType=\"protocol\" arguments=\"cider://playpause/\"/>\n                        <action content=\"${this._utils.getLocale(this._utils.getStoreValue(\"general.language\"), \"term.next\")}\" activationType=\"protocol\" arguments=\"cider://nextitem/\"/>\n                    </actions>\n                </toast>`,\n    });\n\n    this._notification.on(\"click\", (_: any) => {\n      this._utils.getWindow().show();\n      this._utils.getWindow().focus();\n    });\n\n    this._notification.on(\"close\", (_: any) => {\n      this._notification = undefined;\n    });\n\n    this._notification.on(\"action\", (event: any, action: any) => {\n      this._utils.playback.next();\n    });\n\n    this._notification.show();\n  }\n\n  /*******************************************************************************************\n   * Public Methods\n   * ****************************************************************************************/\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(utils: any) {\n    this._utils = utils;\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n\n    utils.getIPCMain().on(\"playbackNotifications:create\", (event: any, a: any) => {\n      a.artwork.url = a.artwork.url.replace(\"/{w}x{h}bb\", \"/512x512bb\").replace(\"/2000x2000bb\", \"/35x35bb\");\n\n      if (this._artworkNums.length > 20) {\n        delete this._artworkImage[this._artworkNums[0]];\n        this._artworkNums.shift();\n      }\n\n      if (this._artworkImage[a.artwork.url]) {\n        this.createNotification(a);\n      } else {\n        if (process.platform === \"win32\") {\n          fetch(a.artwork.url).then((res) => {\n            console.log(join(app.getPath(\"temp\"), `${a.songId}-${a.artwork.url.split(\"/\").pop()}`));\n            const dest = createWriteStream(join(app.getPath(\"temp\"), `${a.songId}-${a.artwork.url.split(\"/\").pop()}`));\n            // @ts-ignore\n            let stream = res.body.pipe(dest);\n            stream.on(\"finish\", () => {\n              this.createNotification(a);\n            });\n          });\n        } else {\n          fetch(a.artwork.url).then(async (blob) => {\n            this._artworkImage[a.artwork.url] = nativeImage.createFromBuffer(Buffer.from(await blob.arrayBuffer()));\n            this._artworkNums[this._artworkNums.length] = a.artwork.url;\n            this.createNotification(a);\n          });\n        }\n      }\n    });\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/raop.ts",
    "content": "import electron from \"electron\";\nimport fetch from \"node-fetch\";\nimport { Stream } from \"stream\";\nimport { Worker } from \"worker_threads\";\nimport mdnsjs from \"mdns-js\";\n\nexport default class RAOP {\n  /**\n   * Private variables for interaction in plugins\n   */\n  private _utils: any;\n  private _win: any;\n  private _app: any;\n  private _store: any;\n  private _cacheAttr: any;\n  private u: any;\n  private ipairplay: any = \"\";\n  private portairplay: any = \"\";\n\n  private airtunes: any;\n  // private device: any;\n  private mdns = mdnsjs;\n  private ok: any = 1;\n  private devices: any = [];\n  private castDevices: any = [];\n  private i: any = false;\n  private audioStream: any = new Stream.PassThrough();\n  private ffmpeg: any = null;\n  private worker: any = null;\n\n  private processNode = `\n  const {\n    Worker, isMainThread, parentPort, workerData\n  } = require('node:worker_threads');\n    function getAudioConv (buffers) {\n\n        function interleave16(leftChannel, rightChannel) {\n            var length = leftChannel.length + rightChannel.length;\n            var result = new Int16Array(length);\n\n            var inputIndex = 0;\n\n            for (var index = 0; index < length;) {\n                result[index++] = leftChannel[inputIndex];\n                result[index++] = rightChannel[inputIndex];\n                inputIndex++;\n            }\n            return result;\n        }\n\n\n\n        function convert(n) {\n            var v = n < 0 ? n * 32768 : n * 32767;       // convert in range [-32768, 32767]\n            return Math.max(-32768, Math.min(32768, v)); // clamp\n        }\n\n        function bitratechange(e) {\n            var t = e.length;\n            let sampleRate = 96.0;\n            let outputSampleRate = 44.1;\n            var s = 0,\n                o = sampleRate / outputSampleRate,\n                u = Math.ceil(t * outputSampleRate / sampleRate),\n                a = new Int16Array(u);\n            for (let i = 0; i < u; i++) {\n                a[i] = e[Math.floor(s)];\n                s += o;\n            }\n\n            return a;\n        }\n\n        let newaudio = buffers;\n\n        let pcmData = new Int8Array(interleave16(bitratechange(Int16Array.from(newaudio[0], x => convert(x))), bitratechange(Int16Array.from(newaudio[1], x => convert(x)))).buffer);\n        return pcmData;\n    }\n    parentPort.on(\"message\", data => {\n        parentPort.postMessage({buffer: data.buffer, outbuffer: getAudioConv(data.buffer)});\n    });\n\n`;\n\n  private ondeviceup(name: any, host: any, port: any, addresses: any, text: any, airplay2: any = null) {\n    // console.log(this.castDevices.findIndex((item: any) => {return (item.name == host.replace(\".local\",\"\") && item.port == port )}))\n\n    let d = \"\";\n    let audiook = true;\n    try {\n      d = text.filter((u: any) => String(u).startsWith(\"features=\"));\n      if (d.length == 0) d = text.filter((u: any) => String(u).startsWith(\"ft=\"));\n      let features_set = d.length > 0 ? d[0].substring(d[0].indexOf(\"=\") + 1).split(\",\") : [];\n      let features = [...(features_set.length > 0 ? parseInt(features_set[0]).toString(2).split(\"\") : []), ...(features_set.length > 1 ? parseInt(features_set[1]).toString(2).split(\"\") : [])];\n      if (features.length > 0) {\n        audiook = features[features.length - 1 - 9] == \"1\";\n      }\n    } catch (_) {}\n    if (audiook) {\n      let shown_name = name;\n      try {\n        let model = text.filter((u: any) => String(u).startsWith(\"model=\"));\n        let manufacturer = text.filter((u: any) => String(u).startsWith(\"manufacturer=\"));\n        let name1 = text.filter((u: any) => String(u).startsWith(\"name=\"));\n        if (name1.length > 0) {\n          shown_name = name1[0].split(\"=\")[1];\n        } else if (manufacturer.length > 0) {\n          shown_name = (manufacturer.length > 0 ? manufacturer[0].substring(13) : \"\") + \" \" + (model.length > 0 ? model[0].substring(6) : \"\");\n          shown_name = shown_name.trim().length > 1 ? shown_name : (host ?? \"Unknown\").replace(\".local\", \"\");\n        }\n      } catch (e) {}\n      let host_name = addresses != null && typeof addresses == \"object\" && addresses.length > 0 ? addresses[0] : typeof addresses == \"string\" ? addresses : \"\";\n\n      if (\n        this.castDevices.findIndex((item: any) => {\n          return item != null && item.name == shown_name && item.host == host_name && item.host != \"Unknown\";\n        }) == -1\n      ) {\n        this.castDevices.push({\n          name: shown_name,\n          host: host_name,\n          port: port,\n          addresses: addresses,\n          txt: text,\n          airplay2: airplay2,\n        });\n        // if (this.devices.indexOf(host_name) === -1) {\n        //   this.devices.push(host_name);\n        // }\n        if (shown_name) {\n          this._win.webContents.executeJavaScript(`console.log('deviceFound','ip: ${host_name} name:${shown_name}')`).catch((err: any) => console.error(err));\n          console.log(\"deviceFound\", host_name, shown_name);\n        }\n      } else {\n        this._win.webContents.executeJavaScript(`console.log('deviceFound (added)','ip: ${host_name} name:${shown_name}')`).catch((err: any) => console.error(err));\n        console.log(\"deviceFound (added)\", host_name, shown_name);\n      }\n    }\n  }\n\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"RAOP\";\n  public description: string = \"RAOP Plugin\";\n  public version: string = \"0.0.1\";\n  public author: string = \"vapormusic / Cider Collective\";\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(utils: { getStore: () => any; getApp: () => any }) {\n    this._utils = utils;\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n    this._app = utils.getApp();\n  }\n\n  /**\n   * Runs on app ready\n   */\n  async onReady(win: any): Promise<void> {\n    this.u = (await import(\"airtunes2\")).default;\n    this._win = win;\n\n    electron.ipcMain.on(\"getKnownAirplayDevices\", (event) => {\n      event.returnValue = this.castDevices;\n    });\n\n    electron.ipcMain.on(\"getAirplayDevice\", (event, data) => {\n      this.castDevices = [];\n      console.debug(\"scan for airplay devices\");\n\n      const browser = this.mdns.createBrowser(this.mdns.tcp(\"raop\"));\n      browser.on(\"ready\", browser.discover);\n\n      browser.on(\"update\", (service: any) => {\n        if (service.addresses && service.fullname && service.fullname.includes(\"_raop._tcp\")) {\n          // console.log(service.txt)\n          this._win.webContents.executeJavaScript(`console.log(\n                    \"${service.name} ${service.host}:${service.port} ${service.addresses} ${service.fullname}\"\n                )`);\n          let itemname = service.fullname.substring(service.fullname.indexOf(\"@\") + 1, service.fullname.indexOf(\"._raop._tcp\"));\n          this.ondeviceup(itemname, service.host, service.port, service.addresses, service.txt);\n        }\n      });\n\n      const browser2 = this.mdns.createBrowser(this.mdns.tcp(\"airplay\"));\n      browser2.on(\"ready\", browser2.discover);\n\n      browser2.on(\"update\", (service: any) => {\n        if (service.addresses && service.fullname && service.fullname.includes(\"_airplay._tcp\")) {\n          // console.log(service.txt)\n          this._win.webContents.executeJavaScript(`console.log(\n                    \"${service.name} ${service.host}:${service.port} ${service.addresses}\"\n                )`);\n          let itemname = service.fullname.substring(service.fullname.indexOf(\"@\") + 1, service.fullname.indexOf(\"._airplay._tcp\"));\n          this.ondeviceup(itemname, service.host, service.port, service.addresses, service.txt, true);\n        }\n      });\n\n      // const browser2 = this.mdns.createBrowser(this.mdns.tcp('airplay'));\n      // browser2.on('ready', browser2.discover);\n\n      // browser2.on('update', (service: any) => {\n      //      if (service.addresses && service.fullname && (service.fullname.includes('_raop._tcp') ||  service.fullname.includes('_airplay._tcp'))) {\n      //         // console.log(service.txt)\n      //     this._win.webContents.executeJavaScript(`console.log(\n      //         \"${service.name} ${service.host}:${service.port} ${service.addresses}\"\n      //     )`);\n      //     this.ondeviceup(service.name, service.host, service.port, service.addresses, service.txt);\n      //  }\n      // });\n    });\n\n    electron.ipcMain.on(\"performAirplayPCM\", (event, ipv4, ipport, sepassword, title, artist, album, artworkURL, txt, airplay2dv, silent) => {\n      if (ipv4 != this.ipairplay || ipport != this.portairplay) {\n        if (this.airtunes == null) {\n          this.airtunes = new this.u();\n        }\n        this.ipairplay = ipv4;\n        this.portairplay = ipport;\n        let identifier = ipv4 + \":\" + ipport + \"ap\";\n        let idx = this.devices.findIndex((a: any) => {\n          return a.id == identifier;\n        });\n        if (idx != -1) {\n          delete this.devices[idx];\n          this.devices = this.devices.filter((n: any) => n); // remove old controller\n        }\n        this.devices.push({\n          id: identifier,\n          ip: ipv4,\n          port: ipport,\n          state: 0,\n          controller: this.airtunes.add(ipv4, {\n            port: ipport,\n            volume: airplay2dv ? 30 : 50,\n            password: sepassword,\n            txt: txt,\n            airplay2: airplay2dv,\n            debug: false,\n            forceAlac: false,\n          }),\n        });\n\n        idx = this.devices.findIndex((a: any) => {\n          return a.id == identifier;\n        });\n\n        // console.log('lol', this.devices)\n        this.devices[idx].controller.on(\"status\", (status: any) => {\n          console.log(\"device status\", status);\n          if (status == \"ready\") {\n            this._win.webContents.setAudioMuted(true);\n            this._win.webContents.executeJavaScript(`CiderAudio.sendAudio()`).catch((err: any) => console.error(err));\n          }\n          if (status == \"need_password\") {\n            this._win.webContents.executeJavaScript(`app.setAirPlayCodeUI('${this.devices[idx].id}')`);\n          }\n          if (status == \"pair_success\") {\n            this._win.webContents.executeJavaScript(`app.sendAirPlaySuccess(${silent},'${this.devices[idx].id}')`);\n          }\n          if (status == \"pair_failed\") {\n            this._win.webContents.executeJavaScript(`app.sendAirPlayFailed()`);\n            this.disconnectAirplay(this.devices[idx].id);\n          }\n          if (status == \"stopped\") {\n            // this.airtunes.stopAll(() => {\n            //   console.log(\"end\");\n            // });\n            if (this.devices[idx]?.state != null && this.devices[idx].state != -1) this._win.webContents.executeJavaScript(`app.airplayDisconnect(true, ${JSON.stringify([ipv4, ipport, sepassword, title, artist, album, artworkURL, txt, airplay2dv])})`).catch((err: any) => console.error(err));\n            // this.airtunes = null;\n            // this.device = null;\n            // this.ipairplay = \"\";\n            // this.portairplay = \"\";\n            // this.ok = 1;\n          } else {\n            setTimeout(() => {\n              if (this.ok == 1) {\n                console.log(this.devices[idx].controller.key, title ?? \"\", artist ?? \"\", album ?? \"\");\n                this.airtunes.setTrackInfo(this.devices[idx].controller.key, title ?? \"\", artist ?? \"\", album ?? \"\");\n                this.uploadImageAirplay(artworkURL);\n                console.log(\"done\", status);\n                this.ok == 2;\n              }\n            }, 1000);\n          }\n        });\n      }\n    });\n\n    electron.ipcMain.on(\"setAirPlayPasscode\", (event, passcode, identifier) => {\n      if (this.devices.length > 0) {\n        let idx = this.devices.findIndex((a: any) => {\n          return a.id == identifier;\n        });\n        if (idx != -1) {\n          this.devices[idx].controller.setPasscode(passcode);\n        }\n      }\n    });\n\n    electron.ipcMain.on(\"setAirPlayVolume\", (event, volume, identifier) => {\n      if (this.devices.length > 0) {\n        let idx = this.devices.findIndex((a: any) => {\n          return a.id == identifier;\n        });\n        if (idx != -1) {\n          this.devices[idx].controller.setVolume(volume);\n        }\n      }\n    });\n\n    electron.ipcMain.on(\"writeWAV\", (event, leftbuffer, rightbuffer) => {\n      if (this.airtunes != null) {\n        if (this.worker == null) {\n          try {\n            // const toDataUrl = (js: any) => new URL(`data:text/javascript,${encodeURIComponent(js)}`);\n            // let blob = new Blob([this.processNode], { type: 'application/javascript' });\n            //Create new worker\n            this.worker = new Worker(this.processNode, { eval: true });\n\n            //Listen for a message from worker\n            this.worker.on(\"message\", (result: any) => {\n              // fs.writeFile(join(electron.app.getPath('userData'), 'buffer.raw'), Buffer.from(Int8Array.from(result.outbuffer)),{flag: 'a+'}, function (err) {\n              //     if (err) throw err;\n              //     console.log('It\\'s saved!');\n              // });\n              this.airtunes.circularBuffer.write(Buffer.from(new Uint8Array(result.outbuffer)));\n            });\n\n            this.worker.on(\"error\", (error: any) => {\n              console.log(\"worker err\", error);\n            });\n            this.worker.postMessage({ buffer: [leftbuffer, rightbuffer] });\n          } catch (e) {\n            console.log(e);\n          }\n\n          // this.ffmpeg != null ? this.ffmpeg.kill() : null;\n          // this.ffmpeg = spawn(this._utils.getStoreValue(\"advanced.ffmpegLocation\"), [\n          //     '-f', 's16le',        // PCM 16bits, little-endian\n          //     '-ar', '48000',\n          //     '-ac', \"2\",\n          //     '-err_detect','ignore_err',\n          //     '-i', \"http://localhost:9000/audio.wav\",\n          //     '-acodec', 'pcm_s16le',\n          //     '-f', 's16le',        // PCM 16bits, little-endian\n          //     '-ar', '44100',       // Sampling rate\n          //     '-ac', \"2\",             // Stereo\n          //     'pipe:1'              // Output on stdout\n          //   ]);\n\n          //   // pipe data to AirTunes\n          // this.ffmpeg.stdout.pipe(this.airtunes);\n          // this.i = true;\n        } else {\n          this.worker.postMessage({ buffer: [leftbuffer, rightbuffer] });\n        }\n      }\n    });\n\n    electron.ipcMain.on(\"disconnectAirplay\", (event, identifier = \"\") => {\n      console.log(\"iden\", identifier);\n      this.disconnectAirplay(identifier);\n    });\n\n    electron.ipcMain.on(\"updateAirplayInfo\", (event, title, artist, album, artworkURL) => {\n      if (this.airtunes && this.devices.length > 0) {\n        for (let i in this.devices) {\n          console.log(this.devices[i].controller.key, title, artist, album);\n          this.airtunes.setTrackInfo(this.devices[i].controller.key, title, artist, album);\n        }\n        this.uploadImageAirplay(artworkURL);\n      }\n    });\n\n    electron.ipcMain.on(\"discordrpc:updateImage\", (_event, imageurl) => {\n      this.uploadImageAirplay(imageurl);\n    });\n  }\n  private disconnectAirplay(identifier: any = \"\") {\n    console.log(\"awdas\");\n    this._win.webContents\n      .executeJavaScript(`app.airplayDisconnect(false, [], '${identifier}')`)\n      .then(() => {\n        if (identifier == \"\") {\n          if (this.airtunes) {\n            for (let i in this.devices) {\n              this.devices[i].state = -1;\n            }\n            this.airtunes.stopAll(() => {\n              console.log(\"endAll\");\n              this.airtunes = null;\n              this.devices = [];\n              this.airtunes = null;\n\n              this.ipairplay = \"\";\n              this.portairplay = \"\";\n              this.ok = 1;\n              this.i = false;\n            });\n          } else {\n            this.devices = [];\n          }\n        } else {\n          let idx = this.devices.findIndex((a: any) => {\n            return a.id == identifier;\n          });\n          if (idx != -1) {\n            this.devices[idx].state = -1;\n            this.devices[idx].controller.stop(() => {\n              console.log(this.devices[idx].id, \"stopped\");\n            });\n\n            delete this.devices[idx];\n            this.devices = this.devices.filter((n: any) => n);\n          }\n        }\n        if (this.devices.length == 0) {\n          console.log(\"cleanup airtunes\");\n          this._win.webContents.setAudioMuted(false);\n          this.airtunes = null;\n\n          this.ipairplay = \"\";\n          this.portairplay = \"\";\n          this.ok = 1;\n          this.i = false;\n          this.devices = [];\n        }\n      })\n      .catch((err: any) => console.error(\"lsdsd\", err));\n  }\n  private uploadImageAirplay = (url: any) => {\n    try {\n      if (url != null && url != \"\") {\n        //console.log(join(this._app.getPath('userData'), 'temp.png'), url);\n        fetch(url)\n          .then((res) => res.buffer())\n          .then((buffer) => {\n            if (this.airtunes && this.devices.length > 0) {\n              for (let i in this.devices) {\n                this.airtunes.setArtwork(this.devices[i].controller.key, buffer, \"image/png\");\n              }\n            }\n          })\n          .catch((err) => {\n            console.log(err);\n          });\n      }\n    } catch (e) {\n      console.log(e);\n    }\n  };\n\n  /**\n   * Runs on app stop\n   */\n  onBeforeQuit(): void {}\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  onNowPlayingItemDidChange(attributes: any): void {\n    if (this.airtunes && this.devices.length > 0) {\n      let title = attributes?.name ?? \"\";\n      let artist = attributes?.artistName ?? \"\";\n      let album = attributes?.albumName ?? \"\";\n      for (let i in this.devices) {\n        console.log(this.devices[i].controller.key, title, artist, album);\n        this.airtunes.setTrackInfo(this.devices[i].controller.key, title, artist, album);\n      }\n      let artworkURL = attributes?.artwork?.url ?? null;\n\n      if (artworkURL != null) {\n        this.uploadImageAirplay(artworkURL.replace(\"{w}\", \"1024\").replace(\"{h}\", \"1024\"));\n      }\n    }\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  onPlaybackStateDidChange(attributes: any): void {\n    if (this.airtunes && this.devices.length > 0) {\n      let title = attributes?.name ?? \"\";\n      let artist = attributes?.artistName ?? \"\";\n      let album = attributes?.albumName ?? \"\";\n      for (let i in this.devices) {\n        console.log(this.devices[i].controller.key, title, artist, album);\n        this.airtunes.setTrackInfo(this.devices[i].controller.key, title, artist, album);\n      }\n      let artworkURL = attributes?.artwork?.url ?? null;\n\n      if (artworkURL != null) {\n        this.uploadImageAirplay(artworkURL.replace(\"{w}\", \"1024\").replace(\"{h}\", \"1024\"));\n      }\n    }\n  }\n\n  playbackTimeDidChange(attributes: any): void {\n    // console.log(attributes)\n    if (this.airtunes && this.devices.length > 0 && attributes?.currentPlaybackTime != null && attributes?.durationInMillis != null) {\n      for (let i in this.devices) {\n        this.airtunes.setProgress(this.devices[i].controller.key, Math.round(attributes.currentPlaybackTime), Math.floor(attributes.durationInMillis / 1000));\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/thumbar.ts",
    "content": "import { nativeImage, nativeTheme } from \"electron\";\nimport { utils } from \"../base/utils.js\";\nimport { join } from \"path\";\n\nexport default class Thumbar {\n  /**\n   * Private variables for interaction in plugins\n   */\n  private _win: any;\n  private _app: any;\n\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"Thumbnail Toolbar Plugin\";\n  public description: string = \"Creates and managed the thumbnail toolbar buttons and their events\";\n  public version: string = \"1.0.0\";\n  public author: string = \"Core\";\n\n  /**\n   * Thumbnail Toolbar Assets\n   */\n  private icons: { [key: string]: Electron.NativeImage } = {\n    pause: nativeImage.createFromPath(join(utils.getPath(\"resourcePath\"), \"icons/thumbar\", `${nativeTheme.shouldUseDarkColors ? \"light\" : \"dark\"}_pause.png`)),\n    play: nativeImage.createFromPath(join(utils.getPath(\"resourcePath\"), \"icons/thumbar\", `${nativeTheme.shouldUseDarkColors ? \"light\" : \"dark\"}_play.png`)),\n    next: nativeImage.createFromPath(join(utils.getPath(\"resourcePath\"), \"icons/thumbar\", `${nativeTheme.shouldUseDarkColors ? \"light\" : \"dark\"}_next.png`)),\n    previous: nativeImage.createFromPath(join(utils.getPath(\"resourcePath\"), \"icons/thumbar\", `${nativeTheme.shouldUseDarkColors ? \"light\" : \"dark\"}_previous.png`)),\n  };\n\n  /*******************************************************************************************\n   * Private Methods\n   * ****************************************************************************************/\n\n  /**\n   * Blocks non-windows systems from running this plugin\n   * @private\n   * @decorator\n   */\n  private static windowsOnly(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {\n    if (process.platform !== \"win32\") {\n      descriptor.value = function () {\n        return;\n      };\n    }\n  }\n\n  /**\n   * Update the thumbnail toolbar\n   */\n  private updateButtons(attributes: any) {\n    console.log(attributes);\n\n    if (!attributes) {\n      return;\n    }\n\n    const buttons = [\n      {\n        tooltip: \"Previous\",\n        icon: this.icons.previous,\n        click() {\n          utils.playback.previous();\n        },\n      },\n      {\n        tooltip: attributes.status ? \"Pause\" : \"Play\",\n        icon: attributes.status ? this.icons.pause : this.icons.play,\n        click() {\n          utils.playback.playPause();\n        },\n      },\n      {\n        tooltip: \"Next\",\n        icon: this.icons.next,\n        click() {\n          utils.playback.next();\n        },\n      },\n    ];\n\n    if (!attributes.playParams || attributes.playParams.id === \"no-id-found\") {\n      this._win.setThumbarButtons([]);\n    } else {\n      this._win.setThumbarButtons(buttons);\n    }\n  }\n\n  /*******************************************************************************************\n   * Public Methods\n   * ****************************************************************************************/\n\n  /**\n   * Runs on plugin load (Currently run on application start)\n   */\n  constructor(a: { getApp: () => any }) {\n    this._app = utils.getApp();\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n  }\n\n  /**\n   * Runs on app ready\n   */\n  @Thumbar.windowsOnly\n  onReady(win: Electron.BrowserWindow): void {\n    this._win = win;\n    console.debug(`[Plugin][${this.name}] Ready.`);\n  }\n\n  /**\n   * Runs on app stop\n   */\n  @Thumbar.windowsOnly\n  onBeforeQuit(): void {\n    console.debug(`[Plugin][${this.name}] Stopped.`);\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  @Thumbar.windowsOnly\n  onPlaybackStateDidChange(attributes: object): void {\n    this.updateButtons(attributes);\n  }\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  @Thumbar.windowsOnly\n  onNowPlayingItemDidChange(attributes: object): void {\n    this.updateButtons(attributes);\n  }\n}\n"
  },
  {
    "path": "src/main/plugins/webNowPlaying.ts",
    "content": "import WebSocket from \"ws\";\n\n/**\n * 0-pad a number.\n * @param {Number} number\n * @param {Number} length\n * @returns String\n */\nconst pad = (number: number, length: number) => String(number).padStart(length, \"0\");\n\n/**\n * Convert seconds to a time string acceptable to Rainmeter\n * https://github.com/tjhrulz/WebNowPlaying-BrowserExtension/blob/master/WebNowPlaying.js#L50-L59\n * @param {Number} timeInSeconds\n * @returns String\n */\nconst convertTimeToString = (timeInSeconds: number) => {\n  const timeInMinutes = Math.floor(timeInSeconds / 60);\n  if (timeInMinutes < 60) {\n    return timeInMinutes + \":\" + pad(Math.floor(timeInSeconds % 60), 2);\n  }\n  return Math.floor(timeInMinutes / 60) + \":\" + pad(Math.floor(timeInMinutes % 60), 2) + \":\" + pad(Math.floor(timeInSeconds % 60), 2);\n};\n\nexport default class WebNowPlaying {\n  /**\n   * Base Plugin Details (Eventually implemented into a GUI in settings)\n   */\n  public name: string = \"WebNowPlaying\";\n  public description: string = \"Song info and playback control for the Rainmeter WebNowPlaying plugin.\";\n  public version: string = \"1.0.1\";\n  public author: string = \"Zennn <me@jozen.blue>\";\n\n  private _win: any;\n  private ws?: WebSocket;\n  private wsapiConn?: WebSocket;\n  private playerName: string = \"Cider\";\n\n  constructor() {\n    console.debug(`[Plugin][${this.name}] Loading Complete.`);\n  }\n\n  /**\n   * Blocks non-windows systems from running this plugin\n   * @private\n   * @decorator\n   */\n  private static windowsOnly(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {\n    if (process.platform !== \"win32\") {\n      descriptor.value = () => void 0;\n    }\n  }\n\n  private sendSongInfo(attributes: any) {\n    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n    const fields = [\"STATE\", \"TITLE\", \"ARTIST\", \"ALBUM\", \"COVER\", \"DURATION\", \"POSITION\", \"VOLUME\", \"REPEAT\", \"SHUFFLE\"];\n    fields.forEach((field) => {\n      try {\n        let value: any = \"\";\n        switch (field) {\n          case \"STATE\":\n            value = attributes.status ? 1 : 2;\n            break;\n          case \"TITLE\":\n            value = attributes.name;\n            break;\n          case \"ARTIST\":\n            value = attributes.artistName;\n            break;\n          case \"ALBUM\":\n            value = attributes.albumName;\n            break;\n          case \"COVER\":\n            value = attributes.artwork.url.replace(\"{w}\", attributes.artwork.width).replace(\"{h}\", attributes.artwork.height);\n            break;\n          case \"DURATION\":\n            value = convertTimeToString(attributes.durationInMillis / 1000);\n            break;\n          case \"POSITION\":\n            value = convertTimeToString((attributes.durationInMillis - attributes.remainingTime) / 1000);\n            break;\n          case \"VOLUME\":\n            value = attributes.volume * 100;\n            break;\n          case \"REPEAT\":\n            value = attributes.repeatMode;\n            break;\n          case \"SHUFFLE\":\n            value = attributes.shuffleMode;\n            break;\n        }\n        this.ws?.send(`${field}:${value}`);\n      } catch (error) {\n        if (this.ws?.readyState === WebSocket.OPEN) {\n          this.ws.send(`Error:Error updating ${field} for ${this.playerName}`);\n          this.ws.send(`ErrorD:${error}`);\n        }\n      }\n    });\n  }\n\n  private fireEvent(evt: WebSocket.MessageEvent) {\n    if (!evt.data) return;\n    const data = <string>evt.data;\n\n    let value: string = \"\";\n    if (data.split(/ (.+)/).length > 1) {\n      value = data.split(/ (.+)/)[1];\n    }\n    const eventName = data.split(\" \")[0].toLowerCase();\n\n    try {\n      switch (eventName) {\n        case \"playpause\":\n          this._win.webContents.executeJavaScript(\"MusicKitInterop.playPause()\").catch(console.error);\n          break;\n        case \"next\":\n          this._win.webContents.executeJavaScript(\"MusicKitInterop.next()\").catch(console.error);\n          break;\n        case \"previous\":\n          this._win.webContents.executeJavaScript(\"MusicKitInterop.previous()\").catch(console.error);\n          break;\n        case \"setposition\":\n          this._win.webContents.executeJavaScript(`MusicKit.getInstance().seekToTime(${parseFloat(value)})`);\n          break;\n        case \"setvolume\":\n          this._win.webContents.executeJavaScript(`MusicKit.getInstance().volume = ${parseFloat(value) / 100}`);\n          break;\n        case \"repeat\":\n          this._win.webContents.executeJavaScript(\"wsapi.toggleRepeat()\").catch(console.error);\n          break;\n        case \"shuffle\":\n          this._win.webContents.executeJavaScript(\"wsapi.toggleShuffle()\").catch(console.error);\n          break;\n        case \"togglethumbsup\":\n          // not implemented\n          break;\n        case \"togglethumbsdown\":\n          // not implemented\n          break;\n        case \"rating\":\n          // not implemented\n          break;\n      }\n    } catch (error) {\n      console.debug(error);\n      if (this.ws?.readyState === WebSocket.OPEN) {\n        this.ws.send(`Error:Error sending event to ${this.playerName}`);\n        this.ws.send(`ErrorD:${error}`);\n      }\n    }\n  }\n\n  /**\n   * Runs on app ready\n   */\n  @WebNowPlaying.windowsOnly\n  public onReady(win: any) {\n    this._win = win;\n\n    // Connect to Rainmeter plugin and retry on disconnect.\n    const init = () => {\n      try {\n        this.ws = new WebSocket(\"ws://127.0.0.1:8974/\");\n        let retry: NodeJS.Timeout;\n        this.ws.onopen = () => {\n          console.info(\"[WebNowPlaying] Connected to Rainmeter\");\n          this.ws?.send(`PLAYER:${this.playerName}`);\n        };\n\n        this.ws.onclose = () => {\n          clearTimeout(retry);\n          retry = setTimeout(init, 2000);\n        };\n\n        this.ws.onerror = () => {\n          clearTimeout(retry);\n          this.ws?.close();\n        };\n\n        this.ws.onmessage = this.fireEvent?.bind(this);\n      } catch (error) {\n        console.error(error);\n      }\n    };\n\n    init();\n\n    // Connect to wsapi. Only used to update progress.\n    try {\n      this.wsapiConn = new WebSocket(\"ws://127.0.0.1:26369/\");\n\n      this.wsapiConn.onopen = () => {\n        console.info(\"[WebNowPlaying] Connected to wsapi\");\n      };\n\n      this.wsapiConn.onmessage = (evt: WebSocket.MessageEvent) => {\n        const response = JSON.parse(<string>evt.data);\n        if (response.type === \"playbackStateUpdate\") {\n          this.sendSongInfo(response.data);\n        }\n      };\n    } catch (error) {\n      console.error(error);\n    }\n\n    console.debug(`[Plugin][${this.name}] Ready.`);\n  }\n\n  /**\n   * Runs on app stop\n   */\n  @WebNowPlaying.windowsOnly\n  public onBeforeQuit() {\n    if (this.ws) {\n      this.ws.send(\"STATE:0\");\n      this.ws.onclose = () => void 0; // disable onclose handler first to stop it from retrying\n      this.ws.close();\n    }\n    if (this.wsapiConn) {\n      this.wsapiConn.close();\n    }\n    console.debug(`[Plugin][${this.name}] Stopped.`);\n  }\n\n  /**\n   * Runs on playback State Change\n   * @param attributes Music Attributes (attributes.status = current state)\n   */\n  @WebNowPlaying.windowsOnly\n  public onPlaybackStateDidChange(attributes: any) {\n    this.sendSongInfo(attributes);\n  }\n\n  /**\n   * Runs on song change\n   * @param attributes Music Attributes\n   */\n  @WebNowPlaying.windowsOnly\n  public onNowPlayingItemDidChange(attributes: any) {\n    this.sendSongInfo(attributes);\n  }\n}\n"
  },
  {
    "path": "src/main/providers/local/index.ts",
    "content": "// import { ProviderDB } from \"./db\";\nimport { EventEmitter } from \"events\";\nimport mm from \"music-metadata\";\nimport { resolve } from \"node:path\";\nimport { Md5 } from \"ts-md5\";\nimport { utils } from \"../../base/utils.js\";\nimport { readdirSync } from \"node:fs\";\n\nexport class LocalFiles {\n  static localSongs: any = [];\n  static localSongsArts: any = [];\n  // public static DB = ProviderDB.db;\n  static eventEmitter = new EventEmitter();\n\n  static getDataType(item_id: String | any) {\n    if ((item_id ?? \"\").startsWith(\"ciderlocalart\")) return \"artwork\";\n    else if ((item_id ?? \"\").startsWith(\"ciderlocal\")) return \"track\";\n  }\n\n  // static async sendOldLibrary() {\n  //   ProviderDB.init();\n  //   let rows = (await ProviderDB.db.allDocs({ include_docs: true, attachments: true })).rows.map((item: any) => {\n  //     return item.doc;\n  //   });\n  //   let tracks = rows.filter((item: any) => {\n  //     return this.getDataType(item._id) == \"track\";\n  //   });\n  //   let arts = rows.filter((item: any) => {\n  //     return this.getDataType(item._id) == \"artwork\";\n  //   });\n  //   this.localSongs = tracks;\n  //   this.localSongsArts = arts;\n  //   return tracks;\n  // }\n\n  static async scanLibrary() {\n    // ProviderDB.init();\n    let folders = utils.getStoreValue(\"libraryPrefs.localPaths\");\n    if (folders == null || folders.length == null || folders.length == 0) folders = [];\n    let files: any[] = [];\n    for (var folder of folders) {\n      // get files from the Music folder\n      files = files.concat(await LocalFiles.getFiles(folder));\n    }\n\n    let supporttedformats = [\"mp3\", \"aac\", \"webm\", \"flac\", \"m4a\", \"ogg\", \"wav\", \"opus\"];\n    let audiofiles = files.filter((f) => supporttedformats.includes(f.substring(f.lastIndexOf(\".\") + 1)));\n    let metadatalist = [];\n    let metadatalistart = [];\n    let numid = 0;\n    for (var audio of audiofiles) {\n      try {\n        const metadata = await mm.parseFile(audio);\n        let lochash = Md5.hashStr(audio) ?? numid;\n        if (metadata != null) {\n          let form = {\n            id: \"ciderlocal\" + lochash,\n            _id: \"ciderlocal\" + lochash,\n            type: \"podcast-episodes\",\n            href: audio,\n            attributes: {\n              artwork: {\n                width: 3000,\n                height: 3000,\n                url: \"/ciderlocalart/\" + \"ciderlocal\" + lochash,\n              },\n              topics: [],\n              url: \"\",\n              subscribable: true,\n              mediaKind: \"audio\",\n              genreNames: [\"\"],\n              // \"playParams\": {\n              //     \"id\": \"ciderlocal\" + numid,\n              //     \"kind\": \"podcast\",\n              //     \"isLibrary\": true,\n              //     \"reporting\": false },\n              trackNumber: metadata.common.track?.no ?? 0,\n              discNumber: metadata.common.disk?.no ?? 0,\n              name: metadata.common.title ?? audio.substring(audio.lastIndexOf(\"\\\\\") + 1),\n              albumName: metadata.common.album,\n              artistName: metadata.common.artist,\n              copyright: metadata.common.copyright ?? \"\",\n              assetUrl: \"file:///\" + audio,\n              contentAdvisory: \"\",\n              releaseDateTime: `${metadata?.common?.year ?? \"2022\"}-05-13T00:23:00Z`,\n              durationInMillis: Math.floor((metadata.format.duration ?? 0) * 1000),\n              bitrate: Math.floor((metadata.format?.bitrate ?? 0) / 1000),\n              offers: [\n                {\n                  kind: \"get\",\n                  type: \"STDQ\",\n                },\n              ],\n              contentRating: \"clean\",\n            },\n            flavor: Math.floor((metadata.format?.bitrate ?? 0) / 1000),\n            localFilesMetadata: {\n              lossless: metadata.format?.lossless,\n              container: metadata.format?.container,\n              bitDepth: metadata.format?.bitsPerSample ?? 0,\n              sampleRate: metadata.format?.sampleRate ?? 0,\n            },\n          };\n          let art = {\n            id: \"ciderlocal\" + lochash,\n            _id: \"ciderlocalart\" + lochash,\n            url: metadata.common.picture != undefined ? metadata.common.picture[0].data.toString(\"base64\") : \"\",\n          };\n          metadatalistart.push(art);\n          numid += 1;\n          // ProviderDB.db.putIfNotExists(form);\n          // ProviderDB.db.putIfNotExists(art);\n          metadatalist.push(form);\n\n          if (this.localSongs.length === 0 && numid % 10 === 0) {\n            // send updated chunks only if there is no previous database\n            this.eventEmitter.emit(\"newtracks\", metadatalist);\n          }\n        }\n      } catch (e) {\n        console.error(\"localfiles error:\", e);\n      }\n    }\n    // console.log('metadatalist', metadatalist);\n    this.localSongs = metadatalist;\n    this.localSongsArts = metadatalistart;\n    return metadatalist;\n  }\n\n  static async getFiles(dir: string): Promise<string[]> {\n    const dirents = readdirSync(dir, { withFileTypes: true });\n    const files = await Promise.all(\n      dirents.map((dirent: any) => {\n        const res = resolve(dir, dirent.name);\n        return dirent.isDirectory() ? this.getFiles(res) : res;\n      }),\n    );\n    return Array.prototype.concat(...files);\n  }\n\n  // static async cleanUpDB() {\n  //   let folders = utils.getStoreValue(\"libraryPrefs.localPaths\");\n  //   let rows = (await ProviderDB.db.allDocs({ include_docs: true, attachments: true })).rows.map((item: any) => {\n  //     return item.doc;\n  //   });\n  //   let tracks = rows.filter((item: any) => {\n  //     return (\n  //       this.getDataType(item._id) == \"track\" &&\n  //       !folders.some((i: String) => {\n  //         return item[\"attributes\"][\"assetUrl\"].startsWith(\"file:///\" + i);\n  //       })\n  //     );\n  //   });\n  //   let hashs = tracks.map((i: any) => {\n  //     return i._id;\n  //   });\n  //   for (let hash of hashs) {\n  //     try {\n  //       ProviderDB.db.get(hash).then(function (doc: any) {\n  //         return ProviderDB.db.remove(doc);\n  //       });\n  //     } catch (e) {}\n  //     try {\n  //       ProviderDB.db.get(hash.replace(\"ciderlocal\", \"ciderlocalart\")).then(function (doc: any) {\n  //         return ProviderDB.db.remove(doc);\n  //       });\n  //     } catch (e) {}\n  //   }\n  // }\n\n  static setupHandlers() {\n    const app = utils.getExpress();\n    console.log(\"Setting up handlers for local files\");\n    app.get(\"/ciderlocal/:songs\", (req: any, res: any) => {\n      const audio = atob(req.params.songs.replace(/_/g, \"/\").replace(/-/g, \"+\"));\n      // console.log('auss', LocalFiles.localSongs)\n      let data = {\n        data: LocalFiles.localSongs.filter((f: any) => audio.split(\",\").includes(f.id)),\n      };\n      res.send(data);\n    });\n\n    app.get(\"/ciderlocalart/:songs\", (req: any, res: any) => {\n      const audio = req.params.songs;\n      // metadata.common.picture[0].data.toString('base64')\n\n      res.setHeader(\"Cache-Control\", \"public, max-age=31536000\");\n      res.setHeader(\"Expires\", new Date(Date.now() + 31536000000).toUTCString());\n      res.setHeader(\"Content-Type\", \"image/jpeg\");\n\n      let data = LocalFiles.localSongsArts.filter((f: any) => f.id == audio);\n      res.status(200).send(Buffer.from(data[0]?.url, \"base64\"));\n    });\n\n    return app;\n  }\n}\n"
  },
  {
    "path": "src/preload/cider-preload.js",
    "content": "global.ipcRenderer = require(\"electron\").ipcRenderer;\nconsole.info(\"Loaded Preload\");\n\nlet cache = { playParams: { id: 0 }, status: null, remainingTime: 0 },\n  playbackCache = { status: null, time: Date.now() };\n\nconst MusicKitInterop = {\n  init: function () {\n    /* MusicKit.Events.playbackStateDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.playbackStateDidChange, () => {\n      const attributes = MusicKitInterop.getAttributes();\n      if (!attributes) return;\n      MusicKitInterop.updateMediaState(attributes);\n      if (MusicKitInterop.filterTrack(attributes, true, false)) {\n        global.ipcRenderer.send(\"playbackStateDidChange\", attributes);\n        global.ipcRenderer.send(\"wsapi-updatePlaybackState\", attributes);\n      }\n    });\n\n    /* MusicKit.Events.playbackProgressDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.playbackProgressDidChange, async () => {\n      const attributes = MusicKitInterop.getAttributes();\n      if (!attributes) return;\n      // wsapi call\n      ipcRenderer.send(\"wsapi-updatePlaybackState\", attributes);\n      // lastfm call\n      if (app.mk.currentPlaybackProgress === app.cfg.connectivity.lastfm.scrobble_after / 100) {\n        attributes.primaryArtist = app.cfg.connectivity.lastfm.remove_featured ? await this.fetchSongRelationships() : attributes.artistName;\n        ipcRenderer.send(\"lastfm:scrobbleTrack\", attributes);\n      }\n    });\n\n    /* MusicKit.Events.playbackTimeDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.playbackTimeDidChange, () => {\n      ipcRenderer.send(\"mpris:playbackTimeDidChange\", MusicKit.getInstance()?.currentPlaybackTime * 1000 * 1000 ?? 0);\n      const attributes = MusicKitInterop.getAttributes();\n      if (!attributes) return;\n      ipcRenderer.send(\"playbackTimeDidChange\", attributes);\n      MusicKitInterop.updatePositionState(attributes);\n    });\n\n    /* MusicKit.Events.nowPlayingItemDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.nowPlayingItemDidChange, async () => {\n      if (window?.localStorage) {\n        window.localStorage.setItem(\"currentTrack\", JSON.stringify(MusicKit.getInstance().nowPlayingItem));\n        window.localStorage.setItem(\"currentTime\", JSON.stringify(MusicKit.getInstance().currentPlaybackTime));\n        window.localStorage.setItem(\"currentQueue\", JSON.stringify(MusicKit.getInstance().queue?._unplayedQueueItems));\n      }\n\n      const attributes = MusicKitInterop.getAttributes();\n      if (!attributes) return;\n      attributes.primaryArtist = app.cfg.connectivity.lastfm.remove_featured ? await this.fetchSongRelationships() : attributes.artistName;\n\n      MusicKitInterop.updateMediaSession(attributes);\n      global.ipcRenderer.send(\"nowPlayingItemDidChange\", attributes);\n\n      if (MusicKitInterop.filterTrack(attributes, false, true)) {\n        global.ipcRenderer.send(\"lastfm:FilteredNowPlayingItemDidChange\", attributes);\n      } else if (attributes.name !== \"no-title-found\" && attributes.playParams.id !== \"no-id-found\") {\n        global.ipcRenderer.send(\"lastfm:nowPlayingChange\", attributes);\n      }\n\n      if (app.cfg.general.playbackNotifications && !document.hasFocus() && attributes.artistName && attributes.artwork && attributes.name) {\n        global.ipcRenderer.send(\"playbackNotifications:create\", attributes);\n      }\n\n      if (MusicKit.getInstance().nowPlayingItem) {\n        await this.sleep(750);\n        MusicKit.getInstance().playbackRate = app.cfg.audio.playbackRate;\n      }\n      console.debug(\"[cider:preload] nowPlayingItemDidChange\");\n    });\n\n    /* MusicKit.Events.authorizationStatusDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.authorizationStatusDidChange, () => {\n      global.ipcRenderer.send(\"authorizationStatusDidChange\", MusicKit.getInstance().authorizationStatus);\n    });\n\n    /* MusicKit.Events.mediaPlaybackError */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.mediaPlaybackError, (e) => {\n      console.warn(`[cider:preload] mediaPlaybackError] ${e}`);\n    });\n\n    /* MusicKit.Events.shuffleModeDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.shuffleModeDidChange, () => {\n      global.ipcRenderer.send(\"shuffleModeDidChange\", MusicKit.getInstance().shuffleMode);\n    });\n\n    /* MusicKit.Events.repeatModeDidChange */\n    MusicKit.getInstance().addEventListener(MusicKit.Events.repeatModeDidChange, () => {\n      global.ipcRenderer.send(\"repeatModeDidChange\", MusicKit.getInstance().repeatMode);\n    });\n  },\n\n  sleep(ms) {\n    return new Promise((resolve) => {\n      setTimeout(resolve, ms);\n    });\n  },\n\n  async fetchSongRelationships({ id = this.getAttributes().songId, relationship = \"primaryName\" } = {}) {\n    if (!id) return null;\n    const res = await MusicKit.getInstance().api.v3.music(\"/v1/catalog/\" + MusicKit.getInstance().storefrontId + `/songs/${id}`, {\n      include: {\n        songs: [\"artists\"],\n      },\n    });\n\n    if (!res || !res.data) {\n      console.warn(\"[cider:preload] fetchSongRelationships: no response\");\n      if (id === this.getAttributes().songId) {\n        return this.getAttributes().artistName;\n      }\n    }\n    if (!res.data.data.length) {\n      console.error(`[cider:preload] fetchSongRelationships: Unable to locate song with id of ${id}`);\n      if (id === this.getAttributes().songId) {\n        return this.getAttributes().artistName;\n      }\n    }\n\n    const songData = res.data.data[0];\n    const artistData = songData.relationships.artists.data;\n    const albumData = songData.relationships.albums.data;\n    const primaryArtist = artistData[0];\n\n    switch (relationship) {\n      default:\n      case \"primaryName\":\n        if (artistData.length < 1) {\n          console.error(`[cider:preload] fetchSongRelationships: Unable to find artists related to the song with id of ${id}`);\n          return app.mk.nowPlayingItem.attributes.artistName;\n        }\n        return primaryArtist.attributes.name;\n\n      case \"primaryArtist\":\n        return primaryArtist;\n\n      case \"album\":\n        return albumData[0];\n    }\n  },\n\n  getAttributes: function () {\n    const mk = MusicKit.getInstance();\n    const nowPlayingItem = mk.nowPlayingItem;\n    const isPlayingExport = mk.isPlaying;\n    const remainingTimeExport = mk.currentPlaybackTimeRemaining;\n    const currentPlaybackProgress = mk.currentPlaybackProgress;\n    const attributes = nowPlayingItem != null ? nowPlayingItem.attributes : {};\n\n    attributes.songId = attributes.songId ?? attributes.playParams?.catalogId ?? attributes.playParams?.id;\n    attributes.kind = nowPlayingItem?.type ?? attributes?.type ?? attributes.playParams?.kind ?? \"\";\n    attributes.status = nowPlayingItem == null ? null : !!isPlayingExport;\n    attributes.name = attributes?.name ?? \"no-title-found\";\n    attributes.artwork = attributes?.artwork ?? { url: \"\" };\n    attributes.artwork.url = (attributes?.artwork?.url ?? \"\").replace(`{f}`, \"png\");\n    attributes.playParams = attributes?.playParams ?? { id: \"no-id-found\" };\n    attributes.playParams.id = attributes?.playParams?.id ?? \"no-id-found\";\n    attributes.url = {\n      cider: `https://cider.sh/link?play/s/${nowPlayingItem?._songId ?? nowPlayingItem?.songId ?? \"no-id-found\"}`,\n      appleMusic: attributes.websiteUrl ? attributes.websiteUrl : `https://music.apple.com/${mk.storefrontId}/song/${nowPlayingItem?._songId ?? nowPlayingItem?.songId ?? \"no-id-found\"}`,\n      songLink: \"https://song.link/i/\" + attributes.songId,\n    };\n    if (attributes.playParams.id === \"no-id-found\") {\n      attributes.playParams.id = nowPlayingItem?.id ?? \"no-id-found\";\n    }\n    attributes.albumName = attributes?.albumName ?? \"\";\n    attributes.artistName = attributes?.artistName ?? \"\";\n    attributes.genreNames = attributes?.genreNames ?? [];\n    attributes.remainingTime = remainingTimeExport ? remainingTimeExport * 1000 : 0;\n    attributes.durationInMillis = attributes?.durationInMillis ?? 0;\n    attributes.currentPlaybackTime = mk?.currentPlaybackTime ?? 0;\n    attributes.currentPlaybackProgress = currentPlaybackProgress ?? 0;\n    attributes.startTime = Date.now();\n    attributes.endTime = Math.round(attributes?.playParams?.id === cache.playParams.id ? Date.now() + attributes?.remainingTime : attributes?.startTime + attributes?.durationInMillis);\n\n    if (attributes.name === \"no-title-found\") {\n      return;\n    }\n    return attributes;\n  },\n\n  filterTrack: function (a, playbackCheck, mediaCheck) {\n    if (a.name === \"no-title-found\" || a.playParams.id === \"no-id-found\") {\n      return;\n    } else if (mediaCheck && a.playParams.id === cache.playParams.id) {\n      return;\n    } else if (playbackCheck && a.status === playbackCache.status) {\n      return;\n    } else if (playbackCheck && !a.status && a.remainingTime === playbackCache.time) {\n      /* Pretty much have to do this to prevent multiple runs when a song starts playing */\n      return;\n    }\n    cache = a;\n    if (playbackCheck) playbackCache = { status: a.status, time: a.remainingTime };\n    return true;\n  },\n\n  play: () => {\n    MusicKit.getInstance().play().catch(console.error);\n  },\n\n  pause: () => {\n    MusicKit.getInstance().pause();\n  },\n\n  playPause: () => {\n    if (MusicKit.getInstance().isPlaying) {\n      MusicKit.getInstance().pause();\n    } else if (MusicKit.getInstance().nowPlayingItem != null) {\n      MusicKit.getInstance().play().catch(console.error);\n    }\n  },\n\n  next: () => {\n    if (app) {\n      app.skipToNextItem();\n    } else {\n      MusicKit.getInstance()\n        .skipToNextItem()\n        .then((r) => console.debug(`[cider:preload] [next] Skipping to Next ${r}`));\n    }\n  },\n\n  previous: () => {\n    if (app) {\n      app.skipToPreviousItem();\n    } else {\n      MusicKit.getInstance()\n        .skipToPreviousItem()\n        .then((r) => console.debug(`[cider:preload] [previous] Skipping to Previous ${r}`));\n    }\n  },\n\n  initMediaSession: () => {\n    if (\"mediaSession\" in navigator) {\n      console.debug(\"[cider:preload] [initMediaSession] Media Session API supported\");\n      navigator.mediaSession.setActionHandler(\"play\", () => {\n        MusicKitInterop.play();\n      });\n      navigator.mediaSession.setActionHandler(\"pause\", () => {\n        MusicKitInterop.pause();\n      });\n      navigator.mediaSession.setActionHandler(\"stop\", () => {\n        MusicKit.getInstance().stop();\n      });\n      navigator.mediaSession.setActionHandler(\"seekbackward\", (details) => {\n        if (details.seekOffset) {\n          MusicKit.getInstance().seekToTime(Math.max(MusicKit.getInstance().currentPlaybackTime - details.seekOffset, 0));\n        } else {\n          MusicKit.getInstance().seekBackward();\n        }\n      });\n      navigator.mediaSession.setActionHandler(\"seekforward\", (details) => {\n        if (details.seekOffset) {\n          MusicKit.getInstance().seekToTime(Math.max(MusicKit.getInstance().currentPlaybackTime + details.seekOffset, 0));\n        } else {\n          MusicKit.getInstance().seekForward();\n        }\n      });\n      navigator.mediaSession.setActionHandler(\"seekto\", ({ seekTime, fastSeek }) => {\n        MusicKit.getInstance().seekToTime(seekTime);\n      });\n      navigator.mediaSession.setActionHandler(\"previoustrack\", () => {\n        MusicKitInterop.previous();\n      });\n      navigator.mediaSession.setActionHandler(\"nexttrack\", () => {\n        MusicKitInterop.next();\n      });\n    } else {\n      console.debug(\"[cider:preload] [initMediaSession] Media Session API not supported\");\n    }\n  },\n\n  updateMediaSession: (a) => {\n    if (\"mediaSession\" in navigator) {\n      navigator.mediaSession.metadata = new MediaMetadata({\n        title: a.name,\n        artist: a.artistName,\n        album: a.albumName,\n        artwork: [\n          {\n            src: a.artwork.url.replace(\"/{w}x{h}bb\", \"/96x96bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n            sizes: \"96x96\",\n            type: \"image/jpeg\",\n          },\n          {\n            src: a.artwork.url.replace(\"/{w}x{h}bb\", \"/128x128bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n            sizes: \"128x128\",\n            type: \"image/jpeg\",\n          },\n          {\n            src: a.artwork.url.replace(\"/{w}x{h}bb\", \"/192x192bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n            sizes: \"192x192\",\n            type: \"image/jpeg\",\n          },\n          {\n            src: a.artwork.url.replace(\"/{w}x{h}bb\", \"/256x256bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n            sizes: \"256x256\",\n            type: \"image/jpeg\",\n          },\n          {\n            src: a.artwork.url.replace(\"/{w}x{h}bb\", \"/384x384bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n            sizes: \"384x384\",\n            type: \"image/jpeg\",\n          },\n          {\n            src: a.artwork.url.replace(\"/{w}x{h}bb\", \"/512x512bb\").replace(\"/2000x2000bb\", \"/35x35bb\"),\n            sizes: \"512x512\",\n            type: \"image/jpeg\",\n          },\n        ],\n      });\n    }\n  },\n\n  updateMediaState: (a) => {\n    if (\"mediaSession\" in navigator) {\n      console.debug(\"[cider:preload] [updateMediaState] Updating Media State to \" + a.status);\n      switch (a.status) {\n        default:\n        case null:\n          navigator.mediaSession.playbackState = \"none\";\n          break;\n\n        case false:\n          navigator.mediaSession.playbackState = \"paused\";\n          break;\n\n        case true:\n          navigator.mediaSession.playbackState = \"playing\";\n          break;\n      }\n    }\n  },\n\n  updatePositionState: (a) => {\n    if (\"mediaSession\" in navigator && a.currentPlaybackTime <= a.durationInMillis / 1000 && a.currentPlaybackTime >= 0) {\n      navigator.mediaSession.setPositionState({\n        duration: a.durationInMillis / 1000,\n        playbackRate: app?.cfg?.audio?.playbackRate ?? 1,\n        position: a.currentPlaybackTime,\n      });\n    }\n  },\n};\n\nprocess.once(\"loaded\", () => {\n  console.debug(\"[cider:preload] IPC Listeners Created!\");\n  global.MusicKitInterop = MusicKitInterop;\n});\n"
  },
  {
    "path": "src/renderer/apple-hls-old.js",
    "content": "/*! For license information please see hls.js.LICENSE.txt */ ! function Xy(Yy) {\n    const Jy = this;\n    var e, t;\n    e = this, t = function() {\n        \"use strict\";\n        var P, e = e => e && e.Math === Math && e,\n            l = e(\"object\" == typeof globalThis && globalThis) || e(\"object\" == typeof window && window) || e(\"object\" == typeof Jy && Jy) || e(\"object\" == typeof global && global) || Function(\"return this\")();\n        class d {\n            constructor() {\n                this.keySize = null, this.ksRows = null, this.keySchedule = null, this.invKeySchedule = null, this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)], this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)], this.sBox = new Uint32Array(256), this.invSBox = new Uint32Array(256), this.key = new Uint32Array(0), this.initTable()\n            }\n            uint8ArrayToUint32Array_(e) {\n                const t = new DataView(e),\n                    i = Math.floor(t.byteLength / 4),\n                    r = new Uint32Array(i);\n                for (let e = 0; e < i; e++) r[e] = t.getUint32(4 * e);\n                return r\n            }\n            initTable() {\n                const e = this[\"sBox\"],\n                    t = this[\"invSBox\"],\n                    i = this[\"subMix\"],\n                    r = i[0],\n                    n = i[1],\n                    s = i[2],\n                    a = i[3],\n                    o = this[\"invSubMix\"],\n                    l = o[0],\n                    d = o[1],\n                    u = o[2],\n                    c = o[3],\n                    h = new Uint32Array(256);\n                let p = 0,\n                    f = 0,\n                    m = 0;\n                for (m = 0; m < 256; m++) h[m] = m < 128 ? m << 1 : m << 1 ^ 283;\n                for (m = 0; m < 256; m++) {\n                    var g = (g = f ^ f << 1 ^ f << 2 ^ f << 3 ^ f << 4) >>> 8 ^ 255 & g ^ 99;\n                    e[p] = g, t[g] = p;\n                    const o = h[p],\n                        m = h[o],\n                        v = h[m];\n                    var y = 257 * h[g] ^ 16843008 * g;\n                    r[p] = y << 24 | y >>> 8, n[p] = y << 16 | y >>> 16, s[p] = y << 8 | y >>> 24, a[p] = y, y = 16843009 * v ^ 65537 * m ^ 257 * o ^ 16843008 * p, l[g] = y << 24 | y >>> 8, d[g] = y << 16 | y >>> 16, u[g] = y << 8 | y >>> 24, c[g] = y, p ? (p = o ^ h[h[h[v ^ o]]], f ^= h[h[f]]) : p = f = 1\n                }\n            }\n            expandKey(e) {\n                var n = this.uint8ArrayToUint32Array_(e);\n                let t = !0,\n                    i = 0;\n                for (; i < n.length && t;) t = n[i] === this.key[i], i++;\n                if (!t) {\n                    this.key = n;\n                    var s = this.keySize = n.length;\n                    if (4 !== s && 6 !== s && 8 !== s) throw new Error(\"Invalid aes key size=\" + s);\n                    var a = this.ksRows = 4 * (s + 6 + 1);\n                    let e, t;\n                    const o = this.keySchedule = new Uint32Array(a),\n                        l = this.invKeySchedule = new Uint32Array(a),\n                        d = this.sBox,\n                        u = this[\"rcon\"],\n                        c = this[\"invSubMix\"],\n                        h = c[0],\n                        p = c[1],\n                        f = c[2],\n                        m = c[3];\n                    let i, r;\n                    for (e = 0; e < a; e++) e < s ? i = o[e] = n[e] : (r = i, e % s == 0 ? (r = r << 8 | r >>> 24, r = d[r >>> 24] << 24 | d[r >>> 16 & 255] << 16 | d[r >>> 8 & 255] << 8 | d[255 & r], r ^= u[e / s | 0] << 24) : 6 < s && e % s == 4 && (r = d[r >>> 24] << 24 | d[r >>> 16 & 255] << 16 | d[r >>> 8 & 255] << 8 | d[255 & r]), o[e] = i = (o[e - s] ^ r) >>> 0);\n                    for (t = 0; t < a; t++) e = a - t, r = 3 & t ? o[e] : o[e - 4], l[t] = t < 4 || e <= 4 ? r : h[d[r >>> 24]] ^ p[d[r >>> 16 & 255]] ^ f[d[r >>> 8 & 255]] ^ m[d[255 & r]], l[t] = l[t] >>> 0\n                }\n            }\n            networkToHostOrderSwap(e) {\n                return e << 24 | (65280 & e) << 8 | (16711680 & e) >> 8 | e >>> 24\n            }\n            decrypt(e, t, i) {\n                var r = this.keySize + 6,\n                    n = this[\"invKeySchedule\"],\n                    s = this.invSBox,\n                    a = this[\"invSubMix\"],\n                    o = a[0],\n                    l = a[1],\n                    d = a[2],\n                    u = a[3],\n                    i = this.uint8ArrayToUint32Array_(i);\n                let c = i[0],\n                    h = i[1],\n                    p = i[2],\n                    f = i[3];\n                const m = new Int32Array(e),\n                    g = new Int32Array(m.length);\n                let y, v, S, b, T, E, I, w, A, O, k, C, D, M;\n                const x = this.networkToHostOrderSwap;\n                for (; t < m.length;) {\n                    for (A = x(m[t]), O = x(m[t + 1]), k = x(m[t + 2]), C = x(m[t + 3]), T = A ^ n[0], E = C ^ n[1], I = k ^ n[2], w = O ^ n[3], D = 4, M = 1; M < r; M++) y = o[T >>> 24] ^ l[E >> 16 & 255] ^ d[I >> 8 & 255] ^ u[255 & w] ^ n[D], v = o[E >>> 24] ^ l[I >> 16 & 255] ^ d[w >> 8 & 255] ^ u[255 & T] ^ n[D + 1], S = o[I >>> 24] ^ l[w >> 16 & 255] ^ d[T >> 8 & 255] ^ u[255 & E] ^ n[D + 2], b = o[w >>> 24] ^ l[T >> 16 & 255] ^ d[E >> 8 & 255] ^ u[255 & I] ^ n[D + 3], T = y, E = v, I = S, w = b, D += 4;\n                    y = s[T >>> 24] << 24 ^ s[E >> 16 & 255] << 16 ^ s[I >> 8 & 255] << 8 ^ s[255 & w] ^ n[D], v = s[E >>> 24] << 24 ^ s[I >> 16 & 255] << 16 ^ s[w >> 8 & 255] << 8 ^ s[255 & T] ^ n[D + 1], S = s[I >>> 24] << 24 ^ s[w >> 16 & 255] << 16 ^ s[T >> 8 & 255] << 8 ^ s[255 & E] ^ n[D + 2], b = s[w >>> 24] << 24 ^ s[T >> 16 & 255] << 16 ^ s[E >> 8 & 255] << 8 ^ s[255 & I] ^ n[D + 3], D += 3, g[t] = x(y ^ c), g[t + 1] = x(b ^ h), g[t + 2] = x(S ^ p), g[t + 3] = x(v ^ f), c = A, h = O, p = k, f = C, t += 4\n                }\n                return g.buffer\n            }\n            destroy() {\n                this.key = void 0, this.keySize = void 0, this.ksRows = void 0, this.sBox = void 0, this.invSBox = void 0, this.subMix = void 0, this.invSubMix = void 0, this.keySchedule = void 0, this.invKeySchedule = void 0, this.rcon = void 0\n            }\n        }\n        class i {\n            constructor(e, t) {\n                this.rpc = e, this.logger = t, this.decrypt = (r, n, s, a, o) => t => {\n                    const i = l.crypto;\n                    if (null != o && o.useJSCrypto || null == i || !i.subtle) {\n                        const s = new d;\n                        var e;\n                        s.expandKey(r);\n                        const i = s.decrypt(a, 0, n);\n                        e = o.plainTextLength ? i.slice(0, o.plainTextLength) : function(e) {\n                            var t = new Uint8Array(e),\n                                i = t[e.byteLength - 1],\n                                r = e.byteLength - 1;\n                            let n = 0;\n                            if (1 <= i && i <= 16)\n                                for (let e = r; e > r - i && t[e] === i; e--) n++;\n                            return e = n === i ? e.slice(0, r - i + 1) : e\n                        }(i), t(e, void 0, [e])\n                    } else i.subtle.importKey(\"raw\", r, s, !1, [\"decrypt\"]).then(e => i.subtle.decrypt({\n                        name: s,\n                        iv: n\n                    }, e, a)).then(e => {\n                        t(e, void 0, [e])\n                    }).catch(e => t(void 0, e))\n                }, e.register(\"decrypt\", this.decrypt)\n            }\n        }(vr = P = P || {}).MEDIA_ATTACHING = \"hlsMediaAttaching\", vr.MEDIA_ATTACHED = \"hlsMediaAttached\", vr.MEDIA_DETACHING = \"hlsMediaDetaching\", vr.MEDIA_DETACHED = \"hlsMediaDetached\", vr.BUFFER_CREATED = \"hlsBufferCreated\", vr.BUFFER_APPENDING = \"hlsBufferAppending\", vr.BUFFER_APPENDED = \"hlsBufferAppended\", vr.BUFFER_FLUSHED = \"hlsBufferFlushed\", vr.MANIFEST_LOADING = \"hlsManifestLoading\", vr.MANIFEST_LOADED = \"hlsManifestLoaded\", vr.MANIFEST_PARSED = \"hlsManifestParsed\", vr.LEVEL_SWITCHING = \"hlsLevelSwitching\", vr.LEVEL_SWITCHED = \"hlsLevelSwitched\", vr.LEVEL_LOADING = \"hlsLevelLoading\", vr.LEVEL_LOADED = \"hlsLevelLoaded\", vr.LEVEL_UPDATED = \"hlsLevelUpdated\", vr.LEVELS_CHANGED = \"hlsLevelsChanged\", vr.AUDIO_TRACKS_UPDATED = \"hlsAudioTracksUpdated\", vr.AUDIO_TRACK_SWITCH = \"hlsAudioTrackSwitch\", vr.AUDIO_TRACK_SWITCHED = \"hlsAudioTrackSwitched\", vr.AUDIO_TRACK_LOADED = \"hlsAudioTrackLoaded\", vr.SUBTITLE_TRACKS_UPDATED = \"hlsSubtitleTracksUpdated\", vr.SUBTITLE_TRACKS_CREATED = \"hlsSubtitleTracksCreated\", vr.SUBTITLE_TRACK_SWITCH = \"hlsSubtitleTrackSwitch\", vr.INLINE_STYLES_PARSED = \"hlsInlineStylesParsed\", vr.SESSION_DATA_COMPLETE = \"hlsSessionDataComplete\", vr.FRAG_LOADING = \"hlsFragLoading\", vr.FRAG_LOADED = \"hlsFragLoaded\", vr.FRAG_BUFFERED = \"hlsFragBuffered\", vr.FRAG_CHANGED = \"hlsFragChanged\", vr.INTERNAL_ERROR = \"hlsInternalError\", vr.ERROR = \"hlsError\", vr.DESTROYING = \"hlsDestroying\", vr.KEY_REQUEST_STARTED = \"hlsKeyRequestStarted\", vr.LICENSE_CHALLENGE_CREATED = \"hlsLicenseChallengeCreated\", vr.LICENSE_RELEASED = \"hlsLicenseReleased\", vr.KEY_LOADED = \"hlsKeyLoaded\", vr.UNRESOLVED_URI_LOADING = \"hlsUnresolvedUriLoading\", vr.DESIRED_RATE_CHANGED = \"hlsDesiredRateChanged\", vr.PLAYER_STATE_CHANGE = \"hlsPlayerStateChange\", vr.SEEKING = \"hlsSeeking\", vr.SEEKED = \"hlsSeeked\", vr.STALLED = \"hlsStalled\", vr.RESUME_FROM_STALL = \"hlsResumeFromStall\", vr.READY_FOR_NEXT_ITEM = \"hlsReadyForNextItem\", vr.ITEM_TRANSITIONED = \"hlsItemTransitioned\", vr.ITEM_EVICTED = \"hlsItemEvicted\", vr.DATERANGE_UPDATED = \"hlsDaterangeUpdated\";\n        var v, x = P;\n        (dl = v = v || {}).FRAG_PARSING_INIT_SEGMENT = \"hlsFragParsingInitSegment\", dl.FRAG_PARSING_DATA = \"hlsFragParsingData\", dl.FRAG_PARSED = \"hlsFragParsed\", dl.INIT_PTS_FOUND = \"hlsInitPtsFound\";\n        class p extends Error {\n            constructor(e, t, i, r, n) {\n                super(r), this.type = e, this.details = t, this.fatal = i, this.reason = r, this.response = n, this.handled = !1\n            }\n        }\n        class R extends p {\n            constructor(e, t, i, r, n) {\n                super(e, t, i, r, n), this.response = n\n            }\n        }\n        const $ = {\n                PlaylistNotReceived: {\n                    code: -12884,\n                    text: \"Playlist not received\"\n                },\n                CryptResponseReceivedSlowly: {\n                    code: -16833,\n                    text: \"Crypt key received slowly\"\n                },\n                LivePlaylistUpdateError: {\n                    code: -12888,\n                    text: \"Live playlist not updated\"\n                },\n                NoResponseFromMediaRequest: {\n                    code: -12889,\n                    text: \"No response for fragment\"\n                },\n                IncompatibleAsset: {\n                    code: -12927,\n                    text: \"IncompatibleAsset\"\n                },\n                CorruptStream: {\n                    code: -16041,\n                    text: \"Corrupt fragment\"\n                },\n                InternalError: {\n                    code: -12645,\n                    text: \"InternalException\"\n                },\n                CantSwitchInTime: {\n                    code: -12644,\n                    text: \"CantSwitchInTime\"\n                },\n                VideoDecoderBadDataErr: {\n                    code: -12909,\n                    text: \"Buffer error\"\n                },\n                InsufficientDataAvailable: {\n                    code: -12928,\n                    text: \"Incomplete data\"\n                },\n                AllocationFailed: {\n                    code: -12862,\n                    text: \"AllocationFailed\"\n                },\n                PlaylistErrorMissingEXTM3U: {\n                    code: -12269,\n                    text: \"Response doesnt have #EXTM3U tag\"\n                },\n                PlaylistErrorInvalidEntry: {\n                    code: -12264,\n                    text: \"Invalid entry\"\n                },\n                PlaylistErrorBadTargetDuration: {\n                    code: -12271,\n                    text: \"Invalid targetduration\"\n                },\n                NoValidAlternates: {\n                    code: -12925,\n                    text: \"No valid alternates\"\n                },\n                FormatError: {\n                    code: -12642,\n                    text: \"Incorrect playlist format\"\n                },\n                UnsupportedKeySystemError: {\n                    code: -6e4,\n                    text: \"Unsupported Key System\"\n                },\n                EmptyLoadSourceError: {\n                    code: -60001,\n                    text: \"Empty loadSource url\"\n                },\n                UndefinedItemIdError: {\n                    code: -60002,\n                    text: \"Undefined itemId\"\n                },\n                ManifestParseError: {\n                    code: -60003,\n                    text: \"Manifest parse error\"\n                },\n                DemuxWorkerError: {\n                    code: -60004,\n                    text: \"Demux worker error\"\n                },\n                DecryptWorkerError: {\n                    code: -60005,\n                    text: \"Decrypt worker error\"\n                },\n                OutOfRangeSeekError: {\n                    code: -60006,\n                    text: \"Seeked out of playable range\"\n                },\n                ExceptionInKeyLoadError: {\n                    code: -60007,\n                    text: \"Exception in Key load\"\n                },\n                FragmentAbortError: {\n                    code: -60008,\n                    text: \"Fragment abort error\"\n                },\n                ManifestTimeoutError: {\n                    code: -60009,\n                    text: \"Manifest Timeout Error\"\n                },\n                PlaylistTimeoutError: {\n                    code: -60010,\n                    text: \"Playlist Timeout Error\"\n                },\n                FragmentTimeoutError: {\n                    code: -60011,\n                    text: \"Fragment Timeout Error\"\n                },\n                IncompleteSessionData: {\n                    code: -60012,\n                    text: \"Session data not complete after loading all items\"\n                },\n                SessionDataLoadTimeout: {\n                    code: -60013,\n                    text: \"Session data load timeout\"\n                },\n                FailedDemuxerSanityCheck: {\n                    code: -60014,\n                    text: \"Failed demuxer sanity check\"\n                },\n                InvalidADTSSamplingIndex: {\n                    code: -60015,\n                    text: \"Invalid ADTS sampling index\"\n                },\n                DemuxerNotFound: {\n                    code: -60016,\n                    text: \"No demux matching with content found\"\n                },\n                InvalidAC3Magic: {\n                    code: -60029,\n                    text: \"Invalid ac-3 magic\"\n                },\n                InvalidInitTimestamp: {\n                    code: -60017,\n                    text: \"Invalid initPTS or initDTS\"\n                },\n                NoAVSamplesFound: {\n                    code: -60018,\n                    text: \"no audio/video samples found\"\n                },\n                NoTSSyncByteFound: {\n                    code: -60019,\n                    text: \"TS packet did not start with 0x47\"\n                },\n                PESDidNotStartWithADTS: {\n                    code: -60020,\n                    text: \"AAC PES did not start with ADTS header\"\n                },\n                NoADTSHeaderInPES: {\n                    code: -60021,\n                    text: \"No ADTS header found in AAC PES\"\n                },\n                InvalidDolbyAudioMagic: {\n                    code: -60022,\n                    text: \"Invalid dolby audio magic\"\n                },\n                FailedToAllocateVideoMdat: {\n                    code: -60023,\n                    text: \"Fail allocating video mdat\"\n                },\n                FailedToAllocateAudioMdat: {\n                    code: -60024,\n                    text: \"Fail allocating audio mdat\"\n                },\n                InsufficientEC3Data: {\n                    code: -60025,\n                    text: \"Error parsing ec-3, not enough data\"\n                },\n                InvalidEC3Magic: {\n                    code: -60026,\n                    text: \"Invalid ec-3 magic\"\n                },\n                ReservedStreamType: {\n                    code: -60027,\n                    text: \"Reserved stream type\"\n                },\n                InsufficientAC3Data: {\n                    code: -60028,\n                    text: \"error parsing ac-3, not enough data\"\n                },\n                InvalidAC3SamplingRateCode: {\n                    code: -60030,\n                    text: \"Invalid ac-3 samplingRateCode\"\n                },\n                PlaylistErrorInvalidEXTXDEFINE: {\n                    code: -61e3,\n                    text: \"Encountered undefined/not imported EXT-X-DEFINE property\"\n                },\n                PlaylistErrorMissingImportReference: {\n                    code: -61001,\n                    text: \"IMPORT references variable not in master playlist and/or NAME\"\n                },\n                PlaylistErrorInvalidSERVERURI: {\n                    code: -61002,\n                    text: \"Encountered undefined/invalid SERVER-URI attribute for EXT-X-CONTENT-STEERING tag\"\n                },\n                PlaylistErrorInvalidPATHWAYID: {\n                    code: -61003,\n                    text: \"Encountered invalid PATHWAY-ID attribute for EXT-X-CONTENT-STEERING tag\"\n                },\n                PlaylistErrorInvalidSCORE: {\n                    code: -61004,\n                    text: \"Encountered negative/non-number SCORE property\"\n                },\n                KeySystemFailedToUpdateSession: {\n                    code: -62e3,\n                    text: \"KeySystem: Promise Rejected while updating session\"\n                },\n                KeySystemFailedToGenerateLicenseRenewal: {\n                    code: -62001,\n                    text: \"KeySystem: Failed to generate license renewal\"\n                },\n                KeySystemFailedToGenerateLicenseRequest: {\n                    code: -62002,\n                    text: \"KeySystem: Failed to generate license request\"\n                },\n                KeySystemAbort: {\n                    code: -62003,\n                    text: \"KeySystem: Aborted\"\n                },\n                KeySystemUnexpectedStateTransition: {\n                    code: -62004,\n                    text: \"KeySystem: Unexpected state transition\"\n                },\n                KeySystemUnexpectedState: {\n                    code: -62005,\n                    text: \"KeySystem: Unexpected state\"\n                },\n                KeySystemCDMUnknownError: {\n                    code: -62006,\n                    text: \"KeySystem: Unknown error from CDM\"\n                },\n                KeySystemRequestTimedOut: {\n                    code: -62007,\n                    text: \"Key request timed out\"\n                },\n                KeySystemUnexpectedMETHOD: {\n                    code: -62008,\n                    text: \"Unexpected METHOD attribute\"\n                },\n                KeySystemUnmatchedString: {\n                    code: -62009,\n                    text: \"KeySystem: string does not match\"\n                },\n                KeySystemInternalError: {\n                    code: -62010,\n                    text: \"KeySystem: internal-error\"\n                },\n                KeySystemOutputRestricted: {\n                    code: -62011,\n                    text: \"KeySystem: output-restricted\"\n                },\n                KeySystemSetupError: {\n                    code: -62012,\n                    text: \"KeySystem: setup error\"\n                },\n                KeySystemFailedToInitialize: {\n                    code: -62013,\n                    text: \"KeySystem: could not initialize\"\n                },\n                KeySystemFailedToCreateSession: {\n                    code: -62014,\n                    text: \"KeySystem: could not create session\"\n                },\n                KeySystemUndefinedNavigator: {\n                    code: -62015,\n                    text: \"KeySystem: navigator undefined\"\n                },\n                KeySystemNoKeySystemsToTry: {\n                    code: -62016,\n                    text: \"KeySystem: no key systems to try\"\n                },\n                KeySystemNoConstructor: {\n                    code: -62017,\n                    text: \"KeySystem: No constructor\"\n                },\n                KeySystemNoKeySystemAccess: {\n                    code: -62018,\n                    text: \"KeySystem: No KeySystemAccess\"\n                },\n                KeySystemCertificateLoadError: {\n                    code: -62019,\n                    text: \"KeySystem: Certificate Load Error\"\n                }\n            },\n            o = \"networkError\",\n            L = \"mediaError\",\n            s = \"otherError\",\n            _ = \"manifestParsingError\",\n            f = \"manifestIncompatibleCodecsError\",\n            N = \"levelLoadError\",\n            n = \"bufferAppendError\",\n            r = \"internalException\";\n        class V extends p {\n            constructor(e, t, i) {\n                super(s, r, e, t, i)\n            }\n        }\n        class D extends p {\n            constructor(e, t, i) {\n                super(L, \"fragParsingError\", e, t, i)\n            }\n        }\n        class F extends p {\n            constructor(e, t, i, r) {\n                super(\"muxError\", \"remuxAllocError\", e, t, i), this.bytes = r\n            }\n        }\n\n        function S(e) {\n            return e.baseTime / e.timescale\n        }\n\n        function B(e, t) {\n            return {\n                baseTime: Math.floor(e * t),\n                timescale: t\n            }\n        }\n\n        function g(e, t) {\n            return S(e) < S(t) ? e : t\n        }\n\n        function y(e, t) {\n            return S(e) > S(t) ? e : t\n        }\n\n        function b(e, t) {\n            return S(e) - S(t)\n        }\n        var t = void 0 !== l.Buffer ? require(\"events\").EventEmitter : class {\n            constructor() {\n                this.eventMap = {}\n            }\n            _on(e, t, i = !1) {\n                return null == this.eventMap[e] && (this.eventMap[e] = []), i ? this.eventMap[e].splice(0, 0, t) : this.eventMap[e].push(t), this\n            }\n            _off(e, t) {\n                return null != this.eventMap[e] && (this.eventMap[e] = this.eventMap[e].filter(e => e.listener !== t.listener), 0 === this.eventMap[e].length && delete this.eventMap[e]), this\n            }\n            on(e, t) {\n                return this._on(e, {\n                    listener: t,\n                    once: !1\n                })\n            }\n            off(e, t) {\n                return this._off(e, {\n                    listener: t\n                })\n            }\n            addListener(e, t) {\n                return this.on(e, t)\n            }\n            once(e, t) {\n                return this._on(e, {\n                    listener: t,\n                    once: !0\n                })\n            }\n            removeListener(e, t) {\n                return this.off(e, t)\n            }\n            removeAllListeners(e) {\n                return delete this.eventMap[e], this\n            }\n            setMaxListeners(e) {\n                return this\n            }\n            getMaxListeners() {\n                return 1 / 0\n            }\n            listeners(e) {\n                return null == this.eventMap[e] ? [] : this.eventMap[e].map(e => e.listener)\n            }\n            rawListeners(e) {\n                return this.listeners(e)\n            }\n            emit(e, ...t) {\n                if (null == this.eventMap[e]) return !1;\n                let i = !1;\n                for (const r of this.eventMap[e]) {\n                    try {\n                        r.listener.apply(this, t)\n                    } catch (e) {}\n                    i = !0\n                }\n                return i\n            }\n            listenerCount(e) {\n                return null == this.eventMap[e] ? 0 : this.eventMap[e].length\n            }\n            prependListener(e, t) {\n                return this._on(e, {\n                    listener: t,\n                    once: !1\n                }, !0)\n            }\n            prependOnceListener(e, t) {\n                return this._on(e, {\n                    listener: t,\n                    once: !0\n                }, !0)\n            }\n            eventNames() {\n                return Object.keys(this.eventMap)\n            }\n        };\n        class a extends t {\n            trigger(e, t) {\n                this.emit(e, t)\n            }\n        }\n\n        function E(e, t, i, r, n) {\n            let s, a, o, l;\n            const d = navigator.userAgent.toLowerCase(),\n                u = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];\n            s = 1 + ((192 & t[i + 2]) >>> 6);\n            var c = (60 & t[i + 2]) >>> 2;\n            if (!(u.length - 1 < c)) return o = (1 & t[i + 2]) << 2, o |= (192 & t[i + 3]) >>> 6, /firefox/i.test(d) ? 6 <= c ? (s = 5, l = new Array(4), a = c - 3) : (s = 2, l = new Array(2)) : -1 !== d.indexOf(\"android\") ? (s = 2, l = new Array(2)) : (s = 5, l = new Array(4), a = r && (-1 !== r.indexOf(\"mp4a.40.29\") || -1 !== r.indexOf(\"mp4a.40.5\")) || !r && 6 <= c ? c - 3 : ((r && -1 !== r.indexOf(\"mp4a.40.2\") || !r && 1 == o) && (s = 2, l = new Array(2)), c)), l[0] = s << 3, l[0] |= (14 & c) >> 1, l[1] |= (1 & c) << 7, l[1] |= o << 3, 5 === s && (l[1] |= (14 & a) >> 1, l[2] = (1 & a) << 7, l[2] |= 8, l[3] = 0), {\n                esdsConfig: l,\n                samplerate: u[c],\n                channelCount: o,\n                segmentCodec: \"aac\",\n                codec: \"mp4a.40.\" + s\n            }; {\n                const t = new D(!0, `invalid ADTS sampling index:${c}`, $.InvalidADTSSamplingIndex);\n                e.trigger(x.INTERNAL_ERROR, t)\n            }\n        }\n        class u {\n            constructor(e, t, i, r, n) {\n                this.observer = e, this.remuxer = t, this.config = i, this.typeSupported = r, this.logger = n\n            }\n            static probe(e, t) {\n                throw new Error(\"Method not implemented\")\n            }\n            resetTimeStamp(e) {}\n            resetInitSegment(e, t, i, r) {}\n            destroy() {}\n        }\n        class c extends u {\n            constructor(e, t, i, r, n) {\n                super(e, t, i, r, n), this.observer = e, this.remuxer = t, this.config = i, this.typeSupported = r, this.logger = n, this.esRemuxer = t\n            }\n        }\n        class h {\n            constructor(e, t, i) {\n                this.observer = e, this.config = t, this.logger = i\n            }\n            resetInitSegment() {}\n            resetTimeStamp(e) {}\n            destroy() {}\n        }\n        let m, I;\n        var w = {\n                strToUtf8array: e => (m = m || new TextEncoder, m.encode(e)),\n                utf8arrayToStr: e => (I = I || new TextDecoder(\"utf-8\"), I.decode(e))\n            },\n            A = {\n                strToUtf8array(e) {\n                    e = l.Buffer.from(e, \"utf-8\");\n                    return new Uint8Array(e.buffer, e.byteOffset, e.byteLength)\n                },\n                utf8arrayToStr: e => l.Buffer.from(e).toString(\"utf-8\")\n            };\n        let O = {\n            strToUtf8array(e) {\n                const t = unescape(encodeURIComponent(e)),\n                    i = new Uint8Array(t.length);\n                for (let e = 0; e < t.length; e++) i[e] = t.charCodeAt(e);\n                return i\n            },\n            utf8arrayToStr: e => String.fromCharCode.apply(null, Array.from(e))\n        };\n        \"undefined\" != typeof TextEncoder && \"undefined\" != typeof TextDecoder ? O = w : \"function\" == typeof(null === (fl = l.Buffer) || void 0 === fl ? void 0 : fl.from) && (O = A);\n        const k = {\n            name: \"ID3\"\n        };\n        class C {\n            constructor(e, t) {\n                this.logger = t, this._hasTimeStamp = !1, this._audioType = null, this._length = 0, this._frames = [];\n                let i, r, n, s, a = 0;\n                for (;;)\n                    if (n = C.readUTF(e, a, 3), a += 3, \"ID3\" === n) {\n                        this._minor = e[a++], this._revision = e[a++];\n                        const t = e[a++];\n                        if (128 & t && (this._unsynchronized = !0, this.logger.error(k, \"id3 tag is unsynchronized\")), 64 & t && (this._hasExtendedHeader = !0, this.logger.warn(k, \"id3 tag has extended header\")), i = C.readSynchSafeUint32(e.subarray(a, a + 4)), a += 4, r = a + i, this._hasExtendedHeader) {\n                            const t = C.readSynchSafeUint32(e.subarray(a, a + 4));\n                            this.logger.warn(k, `id3 tag has ${t}-byte extended header. usually 6 or 10 bytes`), a += t\n                        }\n                        2 < this.minor ? this._parseID3Frames(e, a, r) : this.logger.error(k, \"[id3] doesn't support older than v2.3 tags\"), a = r\n                    } else {\n                        if (\"3DI\" !== n) return a -= 3, void((s = a) && (this.hasTimeStamp || this.logger.warn(k, \"ID3 tag found, but no timestamp\"), this._length = s, this._payload = e.slice(0, s)));\n                        a += 7\n                    }\n            }\n            static isHeader(e, t) {\n                return 73 === e[t] && 68 === e[t + 1] && 51 === e[t + 2] && e[t + 3] < 255 && e[t + 4] < 255 && e[t + 6] < 128 && e[t + 7] < 128 && e[t + 8] < 128 && e[t + 9] < 128\n            }\n            static readSynchSafeUint32(e) {\n                return 2097152 * (127 & e[0]) + 16384 * (127 & e[1]) + 128 * (127 & e[2]) + (127 & e[3])\n            }\n            static readUTF(e, t, i) {\n                let r = \"\",\n                    n = t;\n                for (var s = t + i; r += String.fromCharCode(e[n++]), n < s;);\n                return r\n            }\n            isID3Frame(e, t) {\n                return e[t + 4] < 128 && e[t + 5] < 128 && e[t + 6] < 128 && e[t + 7] < 128\n            }\n            decodeID3Frame(e) {\n                return \"TXXX\" === e.type ? this.decodeTxxxFrame(e) : \"WXXX\" === e.type ? this.decodeWxxxFrame(e) : \"PRIV\" === e.type ? this.decodePrivFrame(e) : \"T\" === e.type[0] ? this.decodeTextFrame(e) : {\n                    key: e.type,\n                    data: e.data\n                }\n            }\n            decodeTxxxFrame(e) {\n                if (!(e.size < 2) && 3 === e.data[0]) {\n                    var t = 1,\n                        i = this.id3utf8ArrayToStr(e.data.subarray(1));\n                    return t += i.length + 1, {\n                        key: \"TXXX\",\n                        description: i,\n                        data: this.id3utf8ArrayToStr(e.data.subarray(t))\n                    }\n                }\n            }\n            decodeWxxxFrame(e) {\n                if (!(e.size < 2) && 3 === e.data[0]) {\n                    var t = 1,\n                        i = this.id3utf8ArrayToStr(e.data.subarray(1));\n                    return t += i.length + 1, {\n                        key: \"WXXX\",\n                        description: i,\n                        data: O.utf8arrayToStr(e.data.subarray(t))\n                    }\n                }\n            }\n            decodeTextFrame(e) {\n                if (!(e.size < 2) && 3 === e.data[0]) {\n                    var t = e.data.subarray(1);\n                    return {\n                        key: e.type,\n                        data: this.id3utf8ArrayToStr(t)\n                    }\n                }\n            }\n            decodePrivFrame(e) {\n                if (!(e.size < 2)) {\n                    var t = this.id3utf8ArrayToStr(e.data);\n                    return {\n                        key: \"PRIV\",\n                        info: t,\n                        data: e.data.slice(t.length + 1)\n                    }\n                }\n            }\n            _extractID3Frame(e, t, i, r, n) {\n                var s = r + i;\n                let a;\n                return s <= n ? a = {\n                    type: t,\n                    data: e.slice(r, s)\n                } : this.logger.error(k, `id3 frame ${t} size ${i} exceeded ${n}`), a\n            }\n            _parseID3Frames(e, t, i) {\n                let r, n, s, a;\n                for (; t + 8 <= i;) {\n                    if (!this.isID3Frame(e, t)) return void this.logger.error(k, `[id3] illegal id3 frame @ offset ${t}. skip this id3 tag`);\n                    if (r = C.readUTF(e, t, 4), t += 4, \"\" === r) return;\n                    if (0 === (n = C.readSynchSafeUint32(e.subarray(t, t + 4)))) return;\n                    t += 4, e[t++], e[t++], s = t;\n                    var o = this._extractID3Frame(e, r, n, s, i);\n                    if (o) {\n                        const e = this.decodeID3Frame(o);\n                        this._frames.push(e)\n                    }\n                    if (\"PRIV\" === r)\n                        if (53 === n && \"com.apple.streaming.transportStreamTimestamp\" === C.readUTF(e, t, 44)) {\n                            t += 44, t += 4;\n                            const i = 1 & e[t++];\n                            this._hasTimeStamp = !0, a = ((e[t++] << 23) + (e[t++] << 15) + (e[t++] << 7) + e[t++]) / 45, i && (a += 47721858.84), a = Math.round(a), this._timeStamp = a\n                        } else 45 <= n && \"com.apple.streaming.audioDescription\" === C.readUTF(e, t, 36) ? (t += 37, this._audioType = C.readUTF(e, t, 4), t += 4, t += n - 41) : t += n;\n                    else t += n\n                }\n            }\n            id3utf8ArrayToStr(e) {\n                let t, i, r = \"\",\n                    n = 0;\n                const s = e.length;\n                for (; n < s;) {\n                    const s = e[n++];\n                    switch (s >> 4) {\n                        case 0:\n                            return r;\n                        case 1:\n                        case 2:\n                        case 3:\n                        case 4:\n                        case 5:\n                        case 6:\n                        case 7:\n                            r += String.fromCharCode(s);\n                            break;\n                        case 12:\n                        case 13:\n                            t = e[n++], r += String.fromCharCode((31 & s) << 6 | 63 & t);\n                            break;\n                        case 14:\n                            t = e[n++], i = e[n++], r += String.fromCharCode((15 & s) << 12 | (63 & t) << 6 | (63 & i) << 0)\n                    }\n                }\n            }\n            get hasTimeStamp() {\n                return this._hasTimeStamp\n            }\n            get timeStamp() {\n                return this._timeStamp\n            }\n            get audioType() {\n                return this._audioType\n            }\n            get length() {\n                return this._length\n            }\n            get payload() {\n                return this._payload\n            }\n            get frames() {\n                return this._frames\n            }\n            get minor() {\n                return this._minor\n            }\n            get revision() {\n                return this._revision\n            }\n        }\n        var M = C;\n        const U = {\n            name: \"AACDemuxer\"\n        };\n        class K extends c {\n            resetInitSegment(e, t) {\n                this.audioConfig = void 0, this.audioTrack = void 0, this.duration = t\n            }\n            static probe(e, t) {\n                let i, r;\n                for (i = new M(e, t).length, r = Math.min(e.length - 1, i + 100); i < r; i++)\n                    if (255 === e[i] && 240 == (246 & e[i + 1])) return !0;\n                return !1\n            }\n            append(e, t, i, r, n) {\n                var s = new M(e, this.logger),\n                    a = s.hasTimeStamp ? 90 * s.timeStamp : 9e4 * t;\n                let o, l, d, u, c, h, p, f, m, g;\n                for (s.length && (g = s.payload, s.frames.length && (m = s.frames), f = {\n                        id3Samples: [{\n                            pts: a,\n                            dts: a,\n                            data: g,\n                            frames: m\n                        }],\n                        inputTimescale: 9e4\n                    }), d = s.length, h = e.length; d < h - 1 && (255 !== e[d] || 240 != (246 & e[d + 1])); d++);\n                if (!this.audioConfig && (this.audioConfig = E(this.observer, e, d, void 0, this.logger), !this.audioConfig)) throw \"failed to parse adts config\";\n                if (!this.audioTrack) {\n                    const e = {\n                            id: 258,\n                            inputTimescale: 9e4,\n                            timescale: NaN,\n                            duration: this.duration,\n                            encrypted: !1,\n                            keyTagInfo: n\n                        },\n                        t = {\n                            len: 0,\n                            sequenceNumber: 0,\n                            esSamples: []\n                        };\n                    this.audioTrack = {\n                        info: e,\n                        parsingData: t,\n                        type: \"audio\",\n                        config: this.audioConfig\n                    }\n                }\n                \"zaac\" !== s.audioType && \"zach\" !== s.audioType && \"zacp\" !== s.audioType || (this.audioTrack.info.encrypted = !0), l = 0;\n                for (var y = 9216e4 / this.audioConfig.samplerate; d + 5 < h && (u = 1 & e[d + 1] ? 7 : 9, o = (3 & e[d + 3]) << 11 | e[d + 4] << 3 | (224 & e[d + 5]) >>> 5, o -= u, 0 < o && d + u + o <= h);)\n                    for (c = a + l * y, p = {\n                            unit: e.subarray(d + u, d + u + o),\n                            pts: c,\n                            dts: c,\n                            keyTagInfo: n\n                        }, this.audioTrack.parsingData.esSamples.push(p), this.audioTrack.parsingData.len += o, d += o + u, l++; d < h - 1; d++) {\n                        if (M.isHeader(e, d)) {\n                            const t = new M(e.subarray(d), this.logger);\n                            if (0 < t.length) {\n                                d += t.length;\n                                const e = t.hasTimeStamp ? 90 * t.timeStamp : a;\n                                f.id3Samples.push({\n                                    pts: e,\n                                    dts: e,\n                                    data: t.payload,\n                                    frames: t.frames\n                                })\n                            } else this.logger.error(U, `[id3] invalid length ${h}`)\n                        }\n                        if (255 === e[d] && 240 == (246 & e[d + 1])) break\n                    }\n                this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, f, void 0, t, i, r, n)\n            }\n        }\n        class q {\n            bsReadAndUpdate(e, t, i) {\n                e = this.readBits(e, t, i);\n                return this.updateOffset(t, i), e\n            }\n            bsWriteAndUpdate(e, t, i, r) {\n                r = this.writeBits(e, t, i, r);\n                return this.updateOffset(t, i), r\n            }\n            bsSkip(e, t) {\n                this.updateOffset(e, t)\n            }\n            readBits(i, r, n) {\n                if (i && r) {\n                    let t = r.byteOffset;\n                    const s = r[\"usedBits\"];\n                    if (!(8 <= s || 32 < s + n)) {\n                        let e;\n                        const a = new Uint32Array(1),\n                            o = new Uint32Array(1),\n                            l = new Uint8Array(1);\n                        if (!(8 <= s || 32 < n)) {\n                            if (s) {\n                                const r = 8 - s,\n                                    a = n < r ? r - n : 0;\n                                o[0] = 4278190080 >>> 32 - r, e = (i[t] & o[0]) >>> a, t += 1, n -= r\n                            }\n                            for (; 0 < n;) {\n                                l[0] = i[t];\n                                const r = Math.min(n, 8),\n                                    s = 8 - r;\n                                o[0] = 4278190080 >>> 24 + s << s, a[0] = (l[0] & o[0]) >> s, e = e ? e << r | a[0] : a[0], t += 1, n -= r\n                            }\n                            return e\n                        }\n                    }\n                }\n            }\n            writeBits(t, i, r, n) {\n                if (t && i) {\n                    let e = i.byteOffset;\n                    var i = i[\"usedBits\"];\n                    if (!(8 <= i || 32 < i + r)) {\n                        const s = new Uint32Array(1),\n                            a = new Uint32Array(1),\n                            o = new Uint32Array(1),\n                            l = new Uint8Array(1);\n                        for (s[0] = n, i && (a[0] = s[0] << 32 - r, o[0] = 4278190080, l[0] = (a[0] & o[0]) >>> 24 + i, t[e] &= ~(o[0] >>> 24 + i), t[e] |= l[0], e += 1, r -= 8 - i); 0 < r;) {\n                            a[0] = s[0] << 32 - r, o[0] = 4278190080, l[0] = (a[0] & o[0]) >>> 24;\n                            const d = r < 0 ? 8 - r : 0;\n                            t[e] &= ~(o[0] >>> 24 >>> d << d), t[e] |= l[0], r -= 8, e += 1\n                        }\n                        return 0\n                    }\n                }\n            }\n            updateOffset(e, t) {\n                var i, r;\n                !e || !t || 32 < e.usedBits + t || (i = e.usedBits % 8, r = Math.floor((i + t) / 8), t = (i + t) % 8, e.byteOffset += r, e.usedBits = t)\n            }\n        }\n\n        function H(e, t) {\n            return 1536 / e.samplerate * t\n        }\n\n        function j(e, t, i, r) {\n            let n;\n            if (i + 8 > t.length) return n = new D(!0, \"error parsing ac-3, not enough data\", $.InsufficientAC3Data), void e.trigger(x.INTERNAL_ERROR, n);\n            if (11 !== t[i] || 119 !== t[i + 1]) return n = new D(!0, \"invalid ac-3 magic\", $.InvalidAC3Magic), void e.trigger(x.INTERNAL_ERROR, n);\n            var s = t[i + 4] >> 6;\n            if (3 <= s) return n = new D(!0, `invalid ac-3 samplingRateCode:${s}`, $.InvalidAC3SamplingRateCode), void e.trigger(x.INTERNAL_ERROR, n);\n            var a = 63 & t[i + 4],\n                o = t[i + 6] >> 5;\n            let l = 0;\n            2 == o ? l += 2 : (1 & o && 1 != o && (l += 2), 4 & o && (l += 2));\n            var d = (t[i + 6] << 8 | t[i + 7]) >> 12 - l & 1,\n                u = [2, 1, 2, 3, 3, 4, 4, 5][o] + d,\n                e = t[i + 5] >> 3,\n                i = 7 & t[i + 5];\n            return {\n                samplerate: W[s],\n                channelCount: u,\n                segmentCodec: \"ac3\",\n                codec: \"ac-3\",\n                extraData: s << 22 | e << 17 | i << 14 | o << 11 | d << 10 | a >> 1 << 5\n            }\n        }\n\n        function Q(e, t, i) {\n            let r;\n            if (i + 8 > t.length) return r = new D(!0, \"error parsing ac-3, not enough data\", $.InsufficientAC3Data), void e.trigger(x.INTERNAL_ERROR, r);\n            if (11 !== t[i] || 119 !== t[i + 1]) return r = new D(!0, \"invalid ac-3 magic\", $.InvalidAC3Magic), void e.trigger(x.INTERNAL_ERROR, r);\n            var n = t[i + 4] >> 6;\n            return 3 <= n ? (r = new D(!0, `invalid ac-3 samplingRateCode:${n}`, $.InvalidAC3SamplingRateCode), void e.trigger(x.INTERNAL_ERROR, r)) : (i = 63 & t[i + 4], 2 * G[3 * i + n])\n        }\n        const W = [48e3, 44100, 32e3],\n            G = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920];\n        class z extends c {\n            resetInitSegment(e, t) {\n                this.audioConfig = void 0, this.audioTrack = void 0, this.duration = t\n            }\n            static probe(e, t) {\n                var i = new M(e, t),\n                    t = i.length;\n                return !!(i.hasTimeStamp && 11 === e[t] && 119 === e[t + 1] && (new q).bsReadAndUpdate(e, {\n                    byteOffset: t + 5,\n                    usedBits: 0\n                }, 5) < 16)\n            }\n            append(e, t, i, r, n) {\n                var s = new M(e, this.logger),\n                    a = 90 * s.timeStamp,\n                    o = e.byteLength;\n                let l = 0,\n                    d = s.length;\n                if (this.audioConfig || (this.audioConfig = j(this.observer, e, d, this.logger)), !this.audioConfig) throw \"failed to parse ac3 config\";\n                if (!this.audioTrack) {\n                    const e = {\n                            id: 258,\n                            inputTimescale: 9e4,\n                            timescale: NaN,\n                            duration: this.duration,\n                            encrypted: !1,\n                            keyTagInfo: n\n                        },\n                        t = {\n                            len: 0,\n                            sequenceNumber: 0,\n                            esSamples: []\n                        };\n                    this.audioTrack = {\n                        info: e,\n                        parsingData: t,\n                        type: \"audio\",\n                        config: this.audioConfig\n                    }\n                }\n                var u = H(this.audioConfig, this.audioTrack.info.inputTimescale);\n                for (\"zac3\" === s.audioType && (this.audioTrack.info.encrypted = !0); d < o;) {\n                    if (M.isHeader(e, d) && (d += new M(e.subarray(d), this.logger).length), 11 !== e[d] || 119 !== e[d + 1]) {\n                        const e = new D(!0, \"invalid ac-3 magic\", $.InvalidAC3Magic);\n                        return void this.observer.trigger(x.INTERNAL_ERROR, e)\n                    }\n                    const t = Q(this.observer, e, d),\n                        i = a + l * u,\n                        r = {\n                            unit: e.subarray(d, d + t),\n                            pts: i,\n                            dts: i,\n                            keyTagInfo: n\n                        };\n                    this.audioTrack.parsingData.esSamples.push(r), this.audioTrack.parsingData.len += t, d += t, l++\n                }\n                this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, {\n                    id3Samples: [{\n                        pts: a,\n                        dts: a,\n                        data: s.payload,\n                        frames: s.frames\n                    }],\n                    inputTimescale: this.audioTrack.info.inputTimescale\n                }, void 0, t, i, r, n)\n            }\n        }\n        var X = function(t, i, r, n) {\n                const s = new q;\n                let a, o = !1,\n                    l = 0;\n                for (; r < i.length;) {\n                    if (r + 8 > i.length) return a = new D(!0, \"error parsing ec-3, not enough data\", $.InsufficientEC3Data), void t.trigger(x.INTERNAL_ERROR, a);\n                    let e = 0;\n                    if (M.isHeader(i, r) && (e = new M(i.subarray(r), n).length || 0, r += e), 11 !== i[r] || 119 !== i[r + 1]) return a = new D(!0, \"invalid ec-3 magic\", $.InvalidEC3Magic), void t.trigger(x.INTERNAL_ERROR, a);\n                    var d = {\n                            byteOffset: r + 2,\n                            usedBits: 0\n                        },\n                        u = s.bsReadAndUpdate(i, d, 2),\n                        c = s.bsReadAndUpdate(i, d, 3);\n                    if (0 === u || 2 === u)\n                        if (!0 === o) {\n                            if (0 === c) break\n                        } else o = !0;\n                    else if (1 !== u) return a = new D(!0, \"reserved stream type\", $.ReservedStreamType), void t.trigger(x.INTERNAL_ERROR, a);\n                    d = 2 * (s.bsReadAndUpdate(i, d, 11) + 1);\n                    r += d, l += d + (e || 0)\n                }\n                return l\n            },\n            Y = function(t, i, r, n) {\n                const s = {\n                        frmsiz: 0,\n                        fscod: 0,\n                        numblkscod: 0,\n                        acmod: 0,\n                        lfeon: 0,\n                        bsid: 0,\n                        strmtyp: 0,\n                        substreamid: 0,\n                        chanmape: 0,\n                        chanmap: 0,\n                        mixdef: 0,\n                        mixdeflen: 0,\n                        bsmod: 0\n                    },\n                    a = {\n                        fscod: 0,\n                        acmod: 0,\n                        lfeon: 0,\n                        bsid: 0,\n                        bsmod: 0,\n                        chan_loc: 0,\n                        data_rate: 0,\n                        num_ind_sub: 0,\n                        num_dep_sub: [],\n                        complexity_index_type_a: 0\n                    },\n                    o = new q;\n                let l, d = !1,\n                    u = 0;\n                for (; r < i.length;) {\n                    if (r + 8 > i.length) return l = new D(!0, \"error parsing ec-3, not enough data\", $.InsufficientEC3Data), void t.trigger(x.INTERNAL_ERROR, l);\n                    let e = 0;\n                    if (M.isHeader(i, r) && (e = new M(i.subarray(r), n).length || 0, r += e), 11 !== i[r] || 119 !== i[r + 1]) return l = new D(!0, \"invalid ec-3 magic\", $.InvalidEC3Magic), void t.trigger(x.INTERNAL_ERROR, l);\n                    const h = {\n                        byteOffset: r + 2,\n                        usedBits: 0\n                    };\n                    if (s.strmtyp = o.bsReadAndUpdate(i, h, 2), s.substreamid = o.bsReadAndUpdate(i, h, 3), 0 === s.strmtyp || 2 === s.strmtyp) {\n                        if (!0 === d) {\n                            if (0 === s.substreamid) break\n                        } else d = !0;\n                        a.num_ind_sub++, a.num_dep_sub.push(0)\n                    } else {\n                        if (1 !== s.strmtyp) return l = new D(!0, \"reserved stream type\", $.ReservedStreamType), void t.trigger(x.INTERNAL_ERROR, l);\n                        a.num_dep_sub[a.num_ind_sub - 1]++\n                    }\n                    if (s.frmsiz = o.bsReadAndUpdate(i, h, 11), s.fscod = o.bsReadAndUpdate(i, h, 2), 3 === s.fscod ? (o.bsSkip(h, 2), s.numblkscod = 3) : s.numblkscod = o.bsReadAndUpdate(i, h, 2), s.acmod = o.bsReadAndUpdate(i, h, 3), s.lfeon = o.bsReadAndUpdate(i, h, 1), s.bsid = o.bsReadAndUpdate(i, h, 5), o.bsSkip(h, 5), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8), 0 === s.acmod && (o.bsSkip(h, 5), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8)), 1 === s.strmtyp && (s.chanmape = o.bsReadAndUpdate(i, h, 1), s.chanmape && (s.chanmap = o.bsReadAndUpdate(i, h, 16))), o.bsReadAndUpdate(i, h, 1) && (2 < s.acmod && o.bsSkip(h, 2), 1 & s.acmod && 2 < s.acmod && o.bsSkip(h, 6), 4 & s.acmod && o.bsSkip(h, 6), s.lfeon && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 5), 0 === s.strmtyp)) {\n                        if (o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 6), 0 === s.acmod && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 6), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 6), s.mixdef = o.bsReadAndUpdate(i, h, 2), 1 === s.mixdef) o.bsSkip(h, 5);\n                        else if (2 === s.mixdef) o.bsSkip(h, 12);\n                        else if (3 === s.mixdef) {\n                            s.mixdeflen = o.bsReadAndUpdate(i, h, 5), o.bsReadAndUpdate(i, h, 1) && (o.bsSkip(h, 5), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && (o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4))), o.bsReadAndUpdate(i, h, 1) && (o.bsSkip(h, 5), o.bsReadAndUpdate(i, h, 1) && (o.bsSkip(h, 7), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8)));\n                            const t = s.mixdeflen + 2 + (h.usedBits ? 1 : 0);\n                            h.byteOffset += t\n                        }\n                        if (s.acmod < 2 && (o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 14), 0 === s.acmod && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 14)), o.bsReadAndUpdate(i, h, 1))\n                            if (0 === s.numblkscod) o.bsSkip(h, 5);\n                            else\n                                for (let e = 0; e < s.numblkscod; e++) o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 5)\n                    }\n                    if (s.bsmod = 0, o.bsReadAndUpdate(i, h, 1) && (s.bsmod = o.bsReadAndUpdate(i, h, 3), o.bsSkip(h, 2), 2 === s.acmod && o.bsSkip(h, 4), 6 <= s.acmod && o.bsSkip(h, 2), o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8), 0 === s.acmod && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8), s.fscod < 3 && o.bsSkip(h, 1)), 0 === s.strmtyp && 3 !== s.numblkscod && o.bsSkip(h, 1), 2 !== s.strmtyp || (3 === s.numblkscod ? 1 : o.bsReadAndUpdate(i, h, 1)) && o.bsReadAndUpdate(i, h, 6), o.bsReadAndUpdate(i, h, 1)) {\n                        const t = o.bsReadAndUpdate(i, h, 6);\n                        if (0 === s.strmtyp && 0 === s.substreamid && 1 === t) {\n                            const t = o.bsReadAndUpdate(i, h, 7),\n                                r = o.bsReadAndUpdate(i, h, 1),\n                                n = o.bsReadAndUpdate(i, h, 8);\n                            0 === t && 1 === r && 1 <= n && n <= 16 && (a.complexity_index_type_a = n)\n                        }\n                    }\n                    if (s.chanmape) a.chan_loc |= s.chanmap;\n                    else {\n                        const t = [40960, 16384, 40960, 57344, 41472, 57856, 47104, 63488];\n                        a.chan_loc |= t[s.acmod]\n                    }\n                    0 === s.strmtyp && (a.fscod = s.fscod, a.bsid = s.bsid, a.bsmod = s.bsmod, a.acmod = s.acmod, a.lfeon = s.lfeon), a.chan_loc |= s.lfeon ? 1 : 0;\n                    const p = 2 * (s.frmsiz + 1);\n                    r += p, u += p + (e || 0)\n                }\n                let c = 0;\n                for (let e = 0; e < 16; e++) a.chan_loc & 1 << e && c++;\n                a.lfeon && c++;\n                let h = 10 + 3 * a.num_ind_sub;\n                const p = [48e3, 44100, 32e3][a.fscod];\n                a.data_rate = p / 1536 * u * 8, h = 10 + 3 * a.num_ind_sub;\n                for (let e = 0; e < a.num_ind_sub; e++) 0 < a.num_dep_sub[e] && h++;\n                0 < a.complexity_index_type_a && (h += 2);\n                var f = new Uint8Array(h),\n                    m = {\n                        byteOffset: 0,\n                        usedBits: 0\n                    };\n                o.bsWriteAndUpdate(f, m, 32, h), o.bsWriteAndUpdate(f, m, 32, 1684366131), o.bsWriteAndUpdate(f, m, 13, a.data_rate), o.bsWriteAndUpdate(f, m, 3, a.num_ind_sub);\n                for (let e = 0; e < a.num_ind_sub; e++) o.bsWriteAndUpdate(f, m, 2, a.fscod), o.bsWriteAndUpdate(f, m, 5, a.bsid), o.bsWriteAndUpdate(f, m, 1, 0), o.bsWriteAndUpdate(f, m, 1, 0 === e ? 0 : 1), o.bsWriteAndUpdate(f, m, 3, a.bsmod), o.bsWriteAndUpdate(f, m, 3, a.acmod), o.bsWriteAndUpdate(f, m, 1, a.lfeon), o.bsWriteAndUpdate(f, m, 3, 0), o.bsWriteAndUpdate(f, m, 4, a.num_dep_sub[e]), 0 < a.num_dep_sub[e] ? o.bsWriteAndUpdate(f, m, 9, a.chan_loc) : o.bsWriteAndUpdate(f, m, 1, 0);\n                return 0 < a.complexity_index_type_a && (o.bsWriteAndUpdate(f, m, 7, 0), o.bsWriteAndUpdate(f, m, 1, 1), o.bsWriteAndUpdate(f, m, 8, a.complexity_index_type_a)), {\n                    samplerate: p,\n                    channelCount: c,\n                    segmentCodec: \"ec3\",\n                    codec: \"ec-3\",\n                    extraDataBytes: f\n                }\n            };\n        class J extends c {\n            resetInitSegment(e, t) {\n                this.audioConfig = void 0, this.audioTrack = void 0, this.duration = t\n            }\n            static probe(e, t) {\n                var i = new M(e, t),\n                    t = i.length;\n                return !(!i.hasTimeStamp || 11 !== e[t] || 119 !== e[t + 1] || 16 !== (new q).bsReadAndUpdate(e, {\n                    byteOffset: t + 5,\n                    usedBits: 0\n                }, 5))\n            }\n            append(e, t, i, r, n) {\n                var s = new M(e, this.logger),\n                    a = 90 * s.timeStamp,\n                    o = e.length;\n                let l = 0,\n                    d = s.length;\n                if (this.audioConfig || (this.audioConfig = Y(this.observer, e, d, this.logger)), !this.audioConfig) throw \"failed to parse ec-3 config\";\n                if (!this.audioTrack) {\n                    const e = {\n                            id: 258,\n                            inputTimescale: 9e4,\n                            timescale: NaN,\n                            duration: this.duration,\n                            encrypted: !1,\n                            keyTagInfo: n\n                        },\n                        t = {\n                            len: 0,\n                            sequenceNumber: 0,\n                            esSamples: []\n                        };\n                    this.audioTrack = {\n                        info: e,\n                        parsingData: t,\n                        type: \"audio\",\n                        config: this.audioConfig\n                    }\n                }\n                var u = H(this.audioConfig, this.audioTrack.info.inputTimescale);\n                for (\"zec3\" === s.audioType && (this.audioTrack.info.encrypted = !0); d < o;) {\n                    const t = X(this.observer, e, d, this.logger),\n                        i = a + l * u,\n                        r = {\n                            unit: e.subarray(d, d + t),\n                            pts: i,\n                            dts: i,\n                            keyTagInfo: n\n                        };\n                    this.audioTrack.parsingData.esSamples.push(r), this.audioTrack.parsingData.len += t, d += t, l++\n                }\n                this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, {\n                    id3Samples: [{\n                        pts: a,\n                        dts: a,\n                        data: s.payload,\n                        frames: s.frames\n                    }],\n                    inputTimescale: this.audioTrack.info.inputTimescale\n                }, void 0, t, i, r, n)\n            }\n        }\n        const Z = {\n            BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],\n            SamplingRateMap: [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3],\n            SamplesCoefficients: [\n                [0, 72, 144, 12],\n                [0, 0, 0, 0],\n                [0, 72, 144, 12],\n                [0, 144, 144, 12]\n            ],\n            BytesInSlot: [0, 1, 1, 4],\n            onFrame: function(e, t, i, r, n, s, a) {\n                r = a + s * (10368e4 / r);\n                e.esSamples.push({\n                    unit: t,\n                    pts: r,\n                    dts: r\n                }), e.len += t.length\n            },\n            onNoise: function(e, t) {\n                t.warn(\"mpeg audio has noise: \" + e.length + \" bytes\")\n            },\n            parseFrames: function(e, t, i, r, n, s, a) {\n                if (r < i + 2) return -1;\n                if (255 === t[i] || 224 == (224 & t[i + 1])) {\n                    if (r < i + 24) return -1;\n                    const a = t[i + 1] >> 3 & 3,\n                        c = t[i + 1] >> 1 & 3,\n                        h = t[i + 2] >> 4 & 15,\n                        p = t[i + 2] >> 2 & 3,\n                        f = !!(2 & t[i + 2]);\n                    if (1 != a && 0 != h && 15 != h && 3 != p) {\n                        var o = 1e3 * [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160][14 * (3 == a ? 3 - c : 3 == c ? 3 : 4) + h - 1],\n                            l = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3][3 * (3 == a ? 0 : 2 == a ? 1 : 2) + p],\n                            d = f ? 1 : 0,\n                            u = t[i + 3] >> 6 == 3 ? 1 : 2,\n                            d = 3 == c ? (3 == a ? 12 : 6) * o / l + d << 2 : (3 == a ? 144 : 72) * o / l + d | 0;\n                        return r < i + d ? -1 : (Z.onFrame(e, t.subarray(i, i + d), o, l, u, n, s), d)\n                    }\n                }\n                let c = i + 2;\n                for (; c < r;) {\n                    if (255 === t[c - 1] && 224 == (224 & t[c])) return Z.onNoise(t.subarray(i, c - 1), a), c - i - 1;\n                    c++\n                }\n                return -1\n            },\n            parse: function(e, t, i, r, n) {\n                var s = t.length;\n                let a, o = 0;\n                for (; i < s && 0 < (a = Z.parseFrames(e, t, i, s, o++, r, n));) i += a\n            },\n            getAudioConfig: function(e, t) {\n                var i = e[t + 1] >> 3 & 3,\n                    r = e[t + 1] >> 1 & 3,\n                    n = e[t + 2] >> 4 & 15,\n                    s = e[t + 2] >> 2 & 3,\n                    a = e[t + 2] >> 1 & 1;\n                if (1 != i && 0 != n && 15 != n && 3 != s) {\n                    var o = 3 == i ? 3 - r : 3 == r ? 3 : 4,\n                        o = 1e3 * Z.BitratesMap[14 * o + n - 1],\n                        n = 3 == i ? 0 : 2 == i ? 1 : 2,\n                        s = Z.SamplingRateMap[3 * n + s],\n                        t = e[t + 3] >> 6 == 3 ? 1 : 2,\n                        i = Z.SamplesCoefficients[i][r],\n                        r = Z.BytesInSlot[r];\n                    return {\n                        segmentCodec: \"mp3\",\n                        codec: \"mp3\",\n                        samplerate: s,\n                        channelCount: t,\n                        frameLength: parseInt(i * o / s + a, 10) * r\n                    }\n                }\n            },\n            isHeaderPattern: function(e, t) {\n                return 255 === e[t] && 224 == (224 & e[t + 1]) && 0 != (6 & e[t + 1])\n            },\n            probe: function(t, i) {\n                if (i + 1 < t.length && Z.isHeaderPattern(t, i)) {\n                    var r = Z.getAudioConfig(t, i);\n                    let e = 4;\n                    r && r.frameLength && (e = r.frameLength);\n                    i = i + e;\n                    if (i === t.length || i + 1 < t.length && Z.isHeaderPattern(t, i)) return !0\n                }\n                return !1\n            }\n        };\n        var ee = Z;\n        const te = {\n            name: \"MP3Demuxer\"\n        };\n        class ie extends c {\n            resetInitSegment(e, t) {\n                this.audioConfig = void 0, this.audioTrack = void 0, this.duration = t\n            }\n            static probe(e, t) {\n                var i = new M(e, t);\n                let r, n;\n                if (i.hasTimeStamp)\n                    for (r = i.length, n = Math.min(e.length - 1, r + 100); r < n; r++)\n                        if (ee.probe(e, r)) return t.warn(te, \"MPEG Audio sync word found !\"), !0;\n                return !1\n            }\n            append(e, t, i, r, n) {\n                var s = new M(e, this.logger),\n                    a = 90 * s.timeStamp;\n                if (this.audioConfig || (this.audioConfig = ee.getAudioConfig(e, s.length)), !this.audioConfig) throw \"unable to parse mp3 header\";\n                if (!this.audioTrack) {\n                    const e = {\n                            id: 258,\n                            inputTimescale: 9e4,\n                            timescale: NaN,\n                            duration: this.duration,\n                            encrypted: !1,\n                            keyTagInfo: n\n                        },\n                        t = {\n                            len: 0,\n                            sequenceNumber: 0,\n                            esSamples: []\n                        };\n                    this.audioTrack = {\n                        info: e,\n                        parsingData: t,\n                        type: \"audio\",\n                        config: this.audioConfig\n                    }\n                }\n                ee.parse(this.audioTrack.parsingData, e, s.length, a, this.logger), this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, {\n                    id3Samples: [{\n                        pts: a,\n                        dts: a,\n                        data: s.payload,\n                        frames: s.frames\n                    }],\n                    inputTimescale: 9e4\n                }, void 0, t, i, r)\n            }\n        }\n\n        function re(e, t) {\n            if (\"mp4a.40.2\" === e) {\n                if (1 === t) return new Uint8Array([0, 200, 0, 128, 35, 128]);\n                if (2 === t) return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);\n                if (3 === t) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);\n                if (4 === t) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);\n                if (5 === t) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);\n                if (6 === t) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224])\n            } else {\n                if (1 === t) return new Uint8Array([1, 64, 34, 128, 163, 78, 230, 128, 186, 8, 0, 0, 0, 28, 6, 241, 193, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);\n                if (2 === t) return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);\n                if (3 === t) return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94])\n            }\n            return null\n        }\n\n        function ne(e) {\n            return \"number\" == typeof e && isFinite(e)\n        }\n\n        function se(e, t) {\n            return ne(e) ? e.toFixed(t) : `${e}`\n        }\n\n        function ae(e, i = 3) {\n            return JSON.stringify(e, (e, t) => !isNaN(t) && null != t && t.toFixed ? Number(null == t ? void 0 : t.toFixed(i)) : t)\n        }\n        let oe = !0;\n\n        function le(e) {\n            return oe ? \"<redacted>\" : e\n        }\n\n        function de(e) {\n            if (!e) return e;\n            if (\"object\" != typeof e) return e; {\n                if (Array.isArray(e)) return e.map(de);\n                const r = {};\n                for (var [t, i] of Object.entries(e)) r[t] = de(i);\n                return r\n            }\n        }\n\n        function ue(e) {\n            const t = [...e];\n            for (let e = 0; e < t.length; e++) t[e] = Object.assign({}, t[e]), t[e].url = le(t[e].url), t[e].attrs && (t[e].attrs = Object.assign({}, t[e].attrs), t[e].attrs.URI = le(t[e].attrs.URI));\n            return t\n        }\n\n        function ce(e) {\n            const t = [...e];\n            for (let e = 0; e < t.length; e++) t[e] = Object.assign({}, t[e]), t[e].url = le(t[e].url);\n            return t\n        }\n        const he = Math.pow(2, 32) - 1;\n        class pe {\n            static init() {\n                let e;\n                for (e in pe.types = {\n                        avc1: [],\n                        avcC: [],\n                        btrt: [],\n                        dinf: [],\n                        dref: [],\n                        esds: [],\n                        free: [],\n                        ftyp: [],\n                        hdlr: [],\n                        mdat: [],\n                        mdhd: [],\n                        mdia: [],\n                        mfhd: [],\n                        minf: [],\n                        moof: [],\n                        moov: [],\n                        mp4a: [],\n                        \".mp3\": [],\n                        dac3: [],\n                        \"ac-3\": [],\n                        dec3: [],\n                        \"ec-3\": [],\n                        mvex: [],\n                        mvhd: [],\n                        pasp: [],\n                        sdtp: [],\n                        stbl: [],\n                        stco: [],\n                        stsc: [],\n                        stsd: [],\n                        stsz: [],\n                        stts: [],\n                        tfdt: [],\n                        tfhd: [],\n                        traf: [],\n                        trak: [],\n                        trun: [],\n                        trex: [],\n                        tkhd: [],\n                        vmhd: [],\n                        smhd: [],\n                        uuid: [],\n                        encv: [],\n                        enca: [],\n                        frma: [],\n                        schm: [],\n                        schi: [],\n                        senc: [],\n                        saio: [],\n                        saiz: [],\n                        sinf: [],\n                        tenc: [],\n                        sbgp: [],\n                        seig: [],\n                        sgpd: [],\n                        pssh: []\n                    }, pe.types) pe.types.hasOwnProperty(e) && (pe.types[e] = [e.charCodeAt(0), e.charCodeAt(1), e.charCodeAt(2), e.charCodeAt(3)]);\n                var t = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 118, 105, 100, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 86, 105, 100, 101, 111, 72, 97, 110, 100, 108, 101, 114, 0]),\n                    i = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 115, 111, 117, 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 111, 117, 110, 100, 72, 97, 110, 100, 108, 101, 114, 0]);\n                pe.HDLR_TYPES = {\n                    video: t,\n                    audio: i\n                };\n                var r = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 117, 114, 108, 32, 0, 0, 0, 1]),\n                    n = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);\n                pe.STTS = pe.STSC = pe.STCO = n, pe.STSZ = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), pe.VMHD = new Uint8Array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]), pe.SMHD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]), pe.STSD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]);\n                t = new Uint8Array([105, 115, 111, 109]), i = new Uint8Array([97, 118, 99, 49]), n = new Uint8Array([0, 0, 0, 1]);\n                pe.FTYP = pe.box(pe.types.ftyp, t, n, t, i), pe.DINF = pe.box(pe.types.dinf, pe.box(pe.types.dref, r))\n            }\n            static set16(e, t, i) {\n                return t[i] = e >> 8 & 255, t[i + 1] = 255 & e, i + 2\n            }\n            static set32(e, t, i) {\n                return t[i] = e >> 24 & 255, t[i + 1] = e >> 16 & 255, t[i + 2] = e >> 8 & 255, t[i + 3] = 255 & e, i + 4\n            }\n            static box(e) {\n                var t = Array.prototype.slice.call(arguments, 1);\n                let i = 8,\n                    r = t.length;\n                for (var n = r; r--;) i += t[r].byteLength;\n                const s = new Uint8Array(i);\n                for (s[0] = i >> 24 & 255, s[1] = i >> 16 & 255, s[2] = i >> 8 & 255, s[3] = 255 & i, s.set(e, 4), r = 0, i = 8; r < n; r++) s.set(t[r], i), i += t[r].byteLength;\n                return s\n            }\n            static hdlr(e) {\n                return pe.box(pe.types.hdlr, pe.HDLR_TYPES[e])\n            }\n            static mdat(e) {\n                return pe.box(pe.types.mdat, e)\n            }\n            static mdhd(e, t) {\n                t *= e;\n                var i = Math.floor(t / (1 + he)),\n                    t = Math.floor(t % (1 + he));\n                return pe.box(pe.types.mdhd, new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, t >> 24, t >> 16 & 255, t >> 8 & 255, 255 & t, 85, 196, 0, 0]))\n            }\n            static mdia(e) {\n                var t = pe.mdhd(e.info.timescale, e.info.duration),\n                    i = pe.hdlr(e.type),\n                    e = pe.minf(e);\n                return pe.box(pe.types.mdia, t, i, e)\n            }\n            static mfhd(e) {\n                return pe.box(pe.types.mfhd, new Uint8Array([0, 0, 0, 0, e >> 24, e >> 16 & 255, e >> 8 & 255, 255 & e]))\n            }\n            static minf(e) {\n                return \"audio\" === e.type ? pe.box(pe.types.minf, pe.box(pe.types.smhd, pe.SMHD), pe.DINF, pe.stbl(e)) : pe.box(pe.types.minf, pe.box(pe.types.vmhd, pe.VMHD), pe.DINF, pe.stbl(e))\n            }\n            static moof(e, t) {\n                pe.types || pe.init();\n                e = pe.traf(t, e);\n                return pe.box(pe.types.moof, pe.mfhd(t.sequenceNumber), e)\n            }\n            static moov(e) {\n                let t = e.length;\n                const i = [];\n                for (; t--;) i[t] = pe.trak(e[t]);\n                return pe.box.apply(null, [pe.types.moov, pe.mvhd(e[0].info.timescale, e[0].info.duration)].concat(i).concat(pe.mvex(e)))\n            }\n            static mvex(e) {\n                let t = e.length;\n                const i = [];\n                for (; t--;) i[t] = pe.trex(e[t]);\n                return pe.box(pe.types.mvex, ...i)\n            }\n            static mvhd(e, t) {\n                t *= e;\n                var i = Math.floor(t / (1 + he)),\n                    t = Math.floor(t % (1 + he)),\n                    t = new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, t >> 24, t >> 16 & 255, t >> 8 & 255, 255 & t, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255]);\n                return pe.box(pe.types.mvhd, t)\n            }\n            static sdtp(e) {\n                const t = e.samples || [],\n                    i = new Uint8Array(4 + t.length);\n                let r, n;\n                for (n = 0; n < t.length; n++) r = t[n].flags, i[n + 4] = r.dependsOn << 4 | r.isDependedOn << 2 | r.hasRedundancy;\n                return pe.box(pe.types.sdtp, i)\n            }\n            static stbl(e) {\n                var t = pe.stsd(e),\n                    i = pe.box(pe.types.stts, pe.STTS),\n                    r = pe.box(pe.types.stsc, pe.STSC),\n                    n = pe.box(pe.types.stsz, pe.STSZ),\n                    e = pe.box(pe.types.stco, pe.STCO);\n                return pe.box(pe.types.stbl, t, i, r, n, e)\n            }\n            static avc1(e) {\n                let t, i, r, n = [],\n                    s = [];\n                var a = e.info.encrypted ? pe.types.encv : pe.types.avc1;\n                for (t = 0; t < e.config.sps.length; t++) i = e.config.sps[t], r = i.byteLength, n.push(r >>> 8 & 255), n.push(255 & r), n = n.concat(Array.prototype.slice.call(i));\n                for (t = 0; t < e.config.pps.length; t++) i = e.config.pps[t], r = i.byteLength, s.push(r >>> 8 & 255), s.push(255 & r), s = s.concat(Array.prototype.slice.call(i));\n                var o = pe.box(pe.types.avcC, new Uint8Array([1, n[3], n[4], n[5], 255, 224 | e.config.sps.length].concat(n).concat([e.config.pps.length]).concat(s))),\n                    l = e.config.width,\n                    d = e.config.height,\n                    u = e.config.pixelRatio[0],\n                    c = e.config.pixelRatio[1],\n                    h = e.info.encrypted && e.info.keyTagInfo ? pe.sinf(e.info.keyTagInfo, e.type, pe.types.avc1) : new Uint8Array;\n                return pe.box(a, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, l >> 8 & 255, 255 & l, d >> 8 & 255, 255 & d, 0, 72, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 1, 18, 100, 97, 105, 108, 121, 109, 111, 116, 105, 111, 110, 47, 104, 108, 115, 46, 106, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 17, 17]), o, h, pe.box(pe.types.btrt, new Uint8Array([0, 28, 156, 128, 0, 45, 198, 192, 0, 45, 198, 192])), pe.box(pe.types.pasp, new Uint8Array([u >> 24, u >> 16 & 255, u >> 8 & 255, 255 & u, c >> 24, c >> 16 & 255, c >> 8 & 255, 255 & c])))\n            }\n            static esds(e) {\n                var t = e.esdsConfig.length;\n                return new Uint8Array([0, 0, 0, 0, 3, 23 + t, 0, 1, 0, 4, 15 + t, 64, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5].concat([t]).concat(e.esdsConfig).concat([6, 1, 2]))\n            }\n            static audioStsd(e) {\n                var t = e.samplerate;\n                return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, e.channelCount, 0, 16, 0, 0, 0, 0, t >> 8 & 255, 255 & t, 0, 0])\n            }\n            static dac3(e) {\n                e = e.extraData;\n                return new Uint8Array([e >> 16 & 255, e >> 8 & 255, 255 & e])\n            }\n            static dec3(e) {\n                return e.extraDataBytes\n            }\n            static mp4a(e, t) {\n                let i = pe.types.mp4a,\n                    r = null;\n                r = e.encrypted && e.keyTagInfo ? (i = pe.types.enca, pe.sinf(e.keyTagInfo, \"audio\", pe.types.mp4a)) : new Uint8Array;\n                e = pe.audioStsd(t), t = pe.box(pe.types.esds, pe.esds(t));\n                return pe.box(i, e, t, r)\n            }\n            static mp3(e) {\n                return pe.box(pe.types[\".mp3\"], pe.audioStsd(e))\n            }\n            static ac3(e, t) {\n                let i = pe.types[\"ac-3\"],\n                    r = null;\n                return r = e.encrypted && e.keyTagInfo ? (i = pe.types.enca, pe.sinf(e.keyTagInfo, \"audio\", pe.types[\"ac-3\"])) : new Uint8Array, pe.box(i, pe.audioStsd(t), pe.box(pe.types.dac3, pe.dac3(t)), r)\n            }\n            static ec3(e, t) {\n                let i = pe.types[\"ec-3\"],\n                    r = null;\n                return r = e.encrypted && e.keyTagInfo ? (i = pe.types.enca, pe.sinf(e.keyTagInfo, \"audio\", pe.types[\"ec-3\"])) : new Uint8Array, pe.box(i, pe.audioStsd(t), pe.box(pe.types.dec3, pe.dec3(t)), r)\n            }\n            static stsd(e) {\n                if (\"audio\" !== e.type) return pe.box(pe.types.stsd, pe.STSD, pe.avc1(e));\n                if (\"mp3\" === e.config.segmentCodec && \"mp3\" === e.config.codec) return pe.box(pe.types.stsd, pe.STSD, pe.mp3(e.config));\n                if (\"ac3\" === e.config.segmentCodec) return pe.box(pe.types.stsd, pe.STSD, pe.ac3(e.info, e.config));\n                if (\"ec3\" === e.config.segmentCodec) return pe.box(pe.types.stsd, pe.STSD, pe.ec3(e.info, e.config));\n                if (\"aac\" === e.config.segmentCodec) return pe.box(pe.types.stsd, pe.STSD, pe.mp4a(e.info, e.config));\n                throw `unknown segmentCodec ${e.config.segmentCodec}`\n            }\n            static tkhd(e) {\n                var t = e.info.id,\n                    i = e.info.duration * e.info.timescale,\n                    r = Math.floor(i / (1 + he)),\n                    i = Math.floor(i % (1 + he));\n                let n = 0,\n                    s = 0;\n                return \"video\" === e.type && (n = e.config.width, s = e.config.height), pe.box(pe.types.tkhd, new Uint8Array([1, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, t >> 24 & 255, t >> 16 & 255, t >> 8 & 255, 255 & t, 0, 0, 0, 0, r >> 24, r >> 16 & 255, r >> 8 & 255, 255 & r, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, n >> 8 & 255, 255 & n, 0, 0, s >> 8 & 255, 255 & s, 0, 0]))\n            }\n            static traf(e, t) {\n                var i = pe.senc(e),\n                    r = pe.sdtp(e),\n                    n = i.boxData,\n                    s = n.length ? pe.saio(76) : new Uint8Array,\n                    a = n.length ? pe.saiz(i.defaultSampleInfoSize, i.sampleInfoSizes) : new Uint8Array,\n                    o = pe.sbgp(e),\n                    l = pe.sgpd(e),\n                    d = e.id,\n                    i = Math.floor(t / (1 + he)),\n                    t = Math.floor(t % (1 + he));\n                return pe.box(pe.types.traf, pe.box(pe.types.tfhd, new Uint8Array([0, 2, 0, 0, d >> 24, d >> 16 & 255, d >> 8 & 255, 255 & d])), pe.box(pe.types.tfdt, new Uint8Array([1, 0, 0, 0, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, t >> 24, t >> 16 & 255, t >> 8 & 255, 255 & t])), n, s, a, o, l, pe.trun(e, r.length + n.length + o.length + l.length + s.length + a.length + 16 + 20 + 8 + 16 + 8 + 8), r)\n            }\n            static trak(e) {\n                if (\"trakData\" in e) return e.trakData;\n                e.info.duration = e.info.duration || 4294967295;\n                var t = pe.types.trak,\n                    i = pe.tkhd(e),\n                    e = pe.mdia(e);\n                return pe.box(t, i, e)\n            }\n            static trex(e) {\n                e = e.info.id;\n                return pe.box(pe.types.trex, new Uint8Array([0, 0, 0, 0, e >> 24, e >> 16 & 255, e >> 8 & 255, 255 & e, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1]))\n            }\n            static trun(e, t) {\n                const i = e.samples || [],\n                    r = i.length,\n                    n = 12 + 16 * r,\n                    s = new Uint8Array(n);\n                let a, o, l, d, u, c;\n                for (t += 8 + n, s.set([0, 0, 15, 1, r >>> 24 & 255, r >>> 16 & 255, r >>> 8 & 255, 255 & r, t >>> 24 & 255, t >>> 16 & 255, t >>> 8 & 255, 255 & t], 0), a = 0; a < r; a++) l = (o = i[a]).duration, d = o.size, u = o.flags, c = o.cts, s.set([l >>> 24 & 255, l >>> 16 & 255, l >>> 8 & 255, 255 & l, d >>> 24 & 255, d >>> 16 & 255, d >>> 8 & 255, 255 & d, u.isLeading << 2 | u.dependsOn, u.isDependedOn << 6 | u.hasRedundancy << 4 | u.paddingValue << 1 | u.isNonSync, 61440 & u.degradPrio, 15 & u.degradPrio, c >>> 24 & 255, c >>> 16 & 255, c >>> 8 & 255, 255 & c], 12 + 16 * a);\n                return pe.box(pe.types.trun, s)\n            }\n            static initSegment(e) {\n                pe.types || pe.init();\n                const t = pe.moov(e),\n                    i = new Uint8Array(pe.FTYP.byteLength + t.byteLength);\n                return i.set(pe.FTYP), i.set(t, pe.FTYP.byteLength), i\n            }\n            static saio(e) {\n                e = e + 4 + 4;\n                return pe.box(pe.types.saio, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e]))\n            }\n            static saiz(e, t) {\n                ne(e) || (e = 0);\n                var i = t.length,\n                    t = 0 === e ? new Uint8Array(t) : new Uint8Array;\n                return pe.box(pe.types.saiz, new Uint8Array([0, 0, 0, 0, e, i >> 24 & 255, i >> 16 & 255, i >> 8 & 255, 255 & i]), t)\n            }\n            static senc(e) {\n                const t = e.samples || [],\n                    i = t.length;\n                let r = 0,\n                    n = NaN,\n                    s = !0;\n                const a = [];\n                if (!e.encrypted || i <= 0) return {\n                    boxData: new Uint8Array,\n                    sampleInfoSizes: a,\n                    defaultSampleInfoSize: 0\n                };\n                e = e.defaultPerSampleIVSize || 0;\n                for (const d of t) d.subsamples && (r += d.subsamples.length);\n                if (r <= 0) return {\n                    boxData: new Uint8Array,\n                    sampleInfoSizes: a,\n                    defaultSampleInfoSize: 0\n                };\n                const o = new Uint8Array(2 * i + i * e + 6 * r + 4);\n                let l = this.set32(i, o, 0);\n                for (const d of t) {\n                    const t = d.subsamples || [];\n                    let e = 2;\n                    d.iv && (o.set(d.iv, l), l += d.iv.byteLength, e += d.iv.byteLength), l = this.set16(t.length, o, l);\n                    for (const d of t) l = this.set16(d[0], o, l), l = this.set32(d[1], o, l), e += 6;\n                    a.push(e), ne(n) || (n = e), s = s && n === e, n = e\n                }\n                return {\n                    boxData: pe.box(pe.types.senc, new Uint8Array([0, 0, 0, 2]), o),\n                    defaultSampleInfoSize: s ? n : 0,\n                    sampleInfoSizes: a\n                }\n            }\n            static sinf(e, t, i) {\n                return pe.box(pe.types.sinf, pe.frma(i), pe.schm(), pe.schi(e, t))\n            }\n            static frma(e) {\n                return pe.box(pe.types.frma, new Uint8Array(e))\n            }\n            static schm() {\n                return pe.box(pe.types.schm, new Uint8Array([0, 0, 0, 0, 99, 98, 99, 115, 0, 1, 0, 0]))\n            }\n            static schi(e, t) {\n                return pe.box(pe.types.schi, pe.tenc(e, t))\n            }\n            static tenc(e, t) {\n                let i = 0;\n                \"video\" === t && (i = 25);\n                const r = new Uint8Array(17);\n                if (r[0] = 16, e.iv && 16 === e.iv.byteLength && r.set(e.iv, 1), !e.keyId) throw \"tenc: no key id found in decryptdata\";\n                return pe.box(pe.types.tenc, new Uint8Array([1, 0, 0, 0, 0, i, 1, 0]), e.keyId, r)\n            }\n            static sbgp(e) {\n                if (!e.encrypted || 0 === e.samples.length || !e.samples[0].keyTagInfo) return new Uint8Array;\n                e = e.samples.length;\n                return pe.box(pe.types.sbgp, new Uint8Array([0, 0, 0, 0]), new Uint8Array(pe.types.seig), new Uint8Array([0, 0, 0, 1, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e, 0, 1, 0, 1]))\n            }\n            static sgpd(e) {\n                if (!e.encrypted || 0 === e.samples.length || !e.samples[0].keyTagInfo) return new Uint8Array;\n                var t = e.samples[0].keyTagInfo;\n                let i = 0;\n                \"video\" === e.type && (i = 25);\n                const r = new Uint8Array(17);\n                if (r[0] = 16, t.iv && r.set(t.iv, 1), !t.keyId) throw \"sgpd: no keyid in decryptdata\";\n                return pe.box(pe.types.sgpd, new Uint8Array([1, 0, 0, 0]), new Uint8Array(pe.types.seig), new Uint8Array([0, 0, 0, 37, 0, 0, 0, 1]), new Uint8Array([0, i, 1, 0]), t.keyId, r)\n            }\n            static pssh(e, t, i) {\n                if (pe.types || pe.init(), !e) throw new TypeError(\"Bad system id\");\n                if (16 !== e.byteLength) throw new RangeError(\"Invalid system id\");\n                let r, n, s;\n                if (t) {\n                    r = 1, n = new Uint8Array(16 * t.length);\n                    for (let e = 0; e < t.length; e++) {\n                        const i = t[e];\n                        if (16 !== i.byteLength) throw new RangeError(\"Invalid key\");\n                        n.set(i, 16 * e)\n                    }\n                } else r = 0, n = new Uint8Array;\n                0 < r ? (s = new Uint8Array(4), 0 < t.length && new DataView(s.buffer).setUint32(0, t.length, !1)) : s = new Uint8Array;\n                var a = new Uint8Array(4);\n                return i && 0 < i.byteLength && new DataView(a.buffer).setUint32(0, i.byteLength, !1), pe.box(pe.types.pssh, new Uint8Array([r, 0, 0, 0]), e, s, n, a, i || new Uint8Array)\n            }\n        }\n        var fe, me, ge = pe;\n        (vi = fe = fe || {})[vi.SDR = 0] = \"SDR\", vi[vi.HDR = 1] = \"HDR\", vi[vi.HDR10 = 2] = \"HDR10\", vi[vi.DolbyVision = 3] = \"DolbyVision\", vi[vi.HLG = 4] = \"HLG\", (bi = me = me || {})[bi.H264 = 16] = \"H264\", bi[bi.HEVC = 64] = \"HEVC\", bi[bi.VP09 = 65] = \"VP09\";\n        const ye = new Set([\"ac-3\", \"mp4a.a5\", \"mp4a.A5\"]),\n            ve = new Set([\"ec-3\", \"mp4a.a6\", \"mp4a.A6\"]),\n            Se = {\n                aac: 1024,\n                mp3: 1024,\n                ac3: 1536,\n                ec3: 1536\n            },\n            be = {\n                isAC3: e => Boolean(e && ye.has(e)),\n                isEC3: e => Boolean(e && ve.has(e)),\n                isDolbyAtmos(e, t) {\n                    const i = t.split(\"/\");\n                    return Boolean(be.isEC3(e) && 1 < i.length && i[1].split(\",\").find(e => \"JOC\" === e))\n                },\n                isAAC(e) {\n                    return Boolean(e && (\"aac\" === e || null !== (e = e.match(/^mp4a\\.40\\.(.*)/)) && \"34\" !== e[1]))\n                },\n                isMP3(e) {\n                    return Boolean(e && (\"mp3\" === e || null !== (e = e.match(/^mp4a\\.40\\.(.*)/)) && \"34\" === e[1]))\n                },\n                isAVC: e => Boolean(e && e.match(/^avc[13]\\.(.*)/)),\n                isXHEAAC: function(e) {\n                    return Boolean(\"mp4a.40.42\" === e)\n                },\n                isALAC: function(e) {\n                    return Boolean(\"alac\" === e)\n                },\n                isFLAC: function(e) {\n                    return Boolean(\"fLaC\" === e)\n                },\n                isHEVC: e => Boolean(e && e.match(/^(hev|hvc)1\\..*/)),\n                isDolby: e => Boolean(e && e.match(/^dv(h1|he|a1|av)\\..*/)),\n                isVP09: e => Boolean(e && e.match(/^vp09\\..*/)),\n                isCompatibleCodecString(e, t) {\n                    const i = e.split(\",\"),\n                        r = t.split(\",\"),\n                        n = i.filter(e => be.isVideoCodec(e)),\n                        s = r.filter(e => be.isVideoCodec(e)),\n                        a = i.filter(e => be.isAudioCodec(e)),\n                        o = r.filter(e => be.isAudioCodec(e)),\n                        l = 0 === n.length && 0 === s.length || n.length === s.length && be.isCompatibleVideoCodec(n[0], s[0]),\n                        d = 0 === a.length && 0 === o.length || a.length === o.length && be.isCompatibleAudioCodec(a[0], o[0]);\n                    return l && d\n                },\n                isVideoCodec: e => be.isAVC(e) || be.isDolby(e) || be.isHEVC(e) || be.isVP09(e),\n                isAudioCodec: e => be.isAC3(e) || be.isEC3(e) || be.isAAC(e) || be.isMP3(e),\n                isCompatibleVideoCodec: (e, t) => Boolean(e && t && (e === t || be.isDolby(e) && be.isDolby(t) || be.isHEVC(e) && be.isHEVC(t) || be.isAVC(e) && be.isAVC(t) || be.isVP09(e) && be.isVP09(t))),\n                isCompatibleAudioCodec: (e, t) => Boolean(e && t && (e === t || be.isAAC(e) && be.isAAC(t) || be.isAC3(e) && be.isAC3(t) || be.isEC3(e) && be.isEC3(t) || be.isMP3(e) && be.isMP3(t))),\n                getSegmentCodec(e) {\n                    let t;\n                    if (be.isAAC(e)) t = \"aac\";\n                    else if (be.isAC3(e)) t = \"ac3\";\n                    else if (be.isEC3(e)) t = \"ec3\";\n                    else {\n                        if (\"mp3\" !== e) throw new Error(`invalid audio config, codec ${e}`);\n                        t = \"mp3\"\n                    }\n                    return t\n                },\n                getChannelCount(e) {\n                    if (!e) return 0;\n                    e = e.split(\"/\"), e = parseInt(e[0]);\n                    return ne(e) ? e : 0\n                },\n                avc1toavcoti(e) {\n                    var t;\n                    const i = e.split(\".\");\n                    let r;\n                    return 2 < i.length ? (r = i.shift() + \".\", r += parseInt(null !== (t = i.shift()) && void 0 !== t ? t : \"\").toString(16), r += (\"000\" + parseInt(null !== (t = i.shift()) && void 0 !== t ? t : \"\").toString(16)).substr(-4)) : r = e, r\n                },\n                getDynamicRangeType(e, t) {\n                    let i = fe.SDR;\n                    return \"PQ\" === e && be.isDolby(t) ? i = fe.DolbyVision : \"PQ\" === e && (be.isHEVC(t) || be.isVP09(t)) ? i = fe.HDR10 : \"HLG\" !== e || -1 === t.indexOf(\"hvc1\") && !be.isVP09(t) || (i = fe.HLG), i\n                },\n                getCompressionType(e) {\n                    let t = me.H264;\n                    return be.isHEVC(e) || be.isDolby(e) ? t = me.HEVC : be.isVP09(e) && (t = me.VP09), t\n                },\n                isHigherCodecByFamily(e, t) {\n                    if (!e) return !0;\n                    const i = e.split(\".\"),\n                        r = t.split(\".\");\n                    if (i[0] !== r[0]) throw new Error(`mismatch in codec family current/new: ${i[0]}/${r[0]}`);\n                    switch (i[0]) {\n                        case \"avc1\":\n                        case \"avc3\":\n                            return r[1] > i[1];\n                        case \"vp09\":\n                            return e < t;\n                        case \"hvc1\":\n                        case \"hev1\":\n                            var n = \"H\" === i[3].substring(0, 1) ? 1 : 0,\n                                s = i[3].substring(1),\n                                a = \"H\" === r[3].substring(0, 1) ? 1 : 0,\n                                o = r[3].substring(1);\n                            return r[1] > i[1] || r[2] > i[2] || n < a || s < o;\n                        case \"dvh1\":\n                            return r[1] > i[1] || r[2] > i[2]\n                    }\n                }\n            };\n        class Te {\n            static getTrack(e, t, i, r, n) {\n                let s;\n                switch (be.getSegmentCodec(i)) {\n                    case \"aac\":\n                        var a;\n                        (a = E(e, 1 === r ? new Uint8Array([255, 241, 92, 64, 1, 127, 252]) : new Uint8Array([255, 241, 92, 128, 1, 191, 252]), 0, i)) && (s = {\n                            type: \"audio\",\n                            info: {\n                                id: t,\n                                timescale: a.samplerate,\n                                duration: 0,\n                                encrypted: !1,\n                                keyTagInfo: void 0\n                            },\n                            config: a\n                        });\n                        break;\n                    case \"ac3\":\n                    case \"ec3\": {\n                        const i = j(e, new Uint8Array([11, 119, 69, 17, 128, 64, 47, 132]), 0);\n                        i && (s = {\n                            type: \"audio\",\n                            info: {\n                                id: t,\n                                timescale: i.samplerate,\n                                duration: 0,\n                                encrypted: !1,\n                                keyTagInfo: void 0\n                            },\n                            config: i\n                        })\n                    }\n                }\n                return s\n            }\n            static getSample(e, t) {\n                let i;\n                switch (e) {\n                    case \"mp4a.40.2\":\n                    case \"mp4a.40.5\":\n                        i = 1 === t ? new Uint8Array([0, 208, 0, 7]) : new Uint8Array([33, 0, 3, 64, 104, 28]);\n                        break;\n                    case \"ac-3\":\n                    case \"ec-3\":\n                        i = new Uint8Array([11, 119, 69, 17, 128, 64, 47, 132, 41, 3, 253, 214, 124, 253, 243, 215, 233, 95, 185, 123, 78, 20, 40, 106, 97, 190, 74, 253, 43, 218, 208, 140, 191, 176, 144, 120, 214, 181, 44, 124, 129, 251, 91, 109, 187, 109, 198, 225, 43, 172, 116, 140, 176, 123, 38, 144, 211, 247, 225, 64, 29, 53, 175, 96, 16, 57, 121, 87, 78, 203, 81, 37, 7, 72, 228, 132, 37, 169, 38, 231, 97, 229, 247, 194, 208, 8, 12, 83, 74, 139, 137, 17, 22, 26, 221, 203, 107, 113, 94, 93, 75, 33, 208, 247, 146, 105, 39, 143, 6, 36, 1, 227, 108, 70, 11, 180, 152, 218, 182, 218, 209, 59, 85, 104, 201, 70, 37, 82, 219, 68, 55, 225, 144, 99, 149, 0, 119, 26, 14, 69, 164, 241, 204, 222, 81, 177, 142, 80, 20, 100, 97, 143, 101, 221, 140, 113, 31, 208, 124, 25, 64, 29, 49, 77, 140, 30, 155, 74, 214, 204, 138, 229, 109, 172, 95, 130, 70, 230, 134, 88, 59, 179, 212, 155, 232, 0, 0, 0, 0, 0, 173, 234])\n                }\n                return i\n            }\n            static getSegment(e, i, r, n) {\n                if (e) {\n                    var s = e.info[\"timescale\"],\n                        a = e.config[\"segmentCodec\"],\n                        o = Te.getSample(e.config.codec, e.config.channelCount);\n                    if (o) {\n                        const l = [],\n                            d = {\n                                id: e.info.id,\n                                sequenceNumber: i,\n                                type: \"audio\",\n                                encrypted: !1,\n                                samples: l,\n                                defaultPerSampleIVSize: 0\n                            },\n                            u = Se[a],\n                            c = Math.ceil(n * s / u),\n                            h = {\n                                baseTime: Math.round(c * u + r),\n                                timescale: s\n                            };\n                        let t = 0;\n                        const p = c * o.byteLength + 8,\n                            f = new Uint8Array(p);\n                        f[0] = p >> 24 & 255, f[1] = p >> 16 & 255, f[2] = p >> 8 & 255, f[3] = 255 & p, ge.types || ge.init(), f.set(ge.types.mdat, 4), t += 8;\n                        for (let e = 0; e < c; e++) l.push({\n                            duration: u,\n                            size: o.byteLength,\n                            cts: 0,\n                            flags: {\n                                isLeading: 0,\n                                isDependedOn: 0,\n                                hasRedundancy: 0,\n                                degradPrio: 0,\n                                dependsOn: 1,\n                                isNonSync: 0,\n                                paddingValue: 0\n                            }\n                        }), f.set(o, t), t += o.byteLength;\n                        const m = ge.moof(r, d),\n                            g = new Uint8Array(m.byteLength + f.byteLength);\n                        return g.set(m), g.set(f, m.byteLength), {\n                            silentFragData: g,\n                            endTs: h\n                        }\n                    }\n                }\n            }\n        }\n        class Ee extends h {\n            constructor(e, t, i, r, n) {\n                super(e, t, n), this.typeSupported = i, this.isVideoContiguous = !1, this.logger = n.child({\n                    name: \"EsRemuxer\"\n                });\n                const s = navigator.userAgent;\n                this.isSafari = r && -1 < r.indexOf(\"Apple\") && s && !s.match(\"CriOS\")\n            }\n            resetTimeStamp(e) {\n                this._initPTS = this._initDTS = e\n            }\n            resetInitSegment() {\n                this.currentInitTrack = void 0, this._silentAudioTrack = void 0\n            }\n            remuxEsTracks(r, n, s, a, o, l, d, u, c, h) {\n                let p;\n                l || (this.isVideoContiguous = !1);\n                c = void 0 === c ? o : c;\n                if (!this.currentInitTrack) {\n                    if (r && r.config.codec && (this._audioTrackInfo = {\n                            id: r.info.id,\n                            codec: r.config.codec,\n                            channelCount: r.config.channelCount\n                        }), n && h && this._audioTrackInfo) {\n                        const r = Te.getTrack(this.observer, this._audioTrackInfo.id, this._audioTrackInfo.codec, this._audioTrackInfo.channelCount, this.logger);\n                        if (r) {\n                            this._silentAudioTrack = Object.assign(Object.assign({}, r), {\n                                info: Object.assign(Object.assign({}, r.info), {\n                                    inputTimescale: 9e4\n                                }),\n                                parsingData: {\n                                    len: 0,\n                                    sequenceNumber: 0,\n                                    esSamples: []\n                                }\n                            });\n                            const s = this._initPTS + Math.round(c * this._silentAudioTrack.info.timescale);\n                            p = Te.getSegment(this._silentAudioTrack, n.parsingData.sequenceNumber, s, h), n.parsingData.sequenceNumber++\n                        }\n                    } else this._silentAudioTrack = void 0;\n                    this.updateInitPTSDTS(n, r, o), this.generateIS(this._silentAudioTrack || r, n)\n                }\n                if (this.currentInitTrack) {\n                    const f = n && n.parsingData.esSamples.length,\n                        m = this.isVideoContiguous;\n                    let t, i, e;\n                    if (n && h && this._silentAudioTrack && !p) {\n                        const r = this._initPTS + Math.round((c + this.config.audioPrimingDelay) * this._silentAudioTrack.info.timescale);\n                        p = Te.getSegment(this._silentAudioTrack, n.parsingData.sequenceNumber, r, h)\n                    }\n                    if (r && r.parsingData.esSamples.length) {\n                        if (ne(r.info.timescale) || (this.logger.warn(\"regenerate InitSegment as audio detected\"), this.updateInitPTSDTS(n, r, o), this.generateIS(r, n)), t = this.remuxAudio(r, c, l, d, u), f) {\n                            let e;\n                            t && (e = S(t.endPTS) - S(t.startPTS)), ne(n.info.timescale) || (this.logger.warn(\"regenerate InitSegment as video detected\"), this.updateInitPTSDTS(n, r, o), this.generateIS(r, n)), i = this.remuxVideo(n, c, m, e, h)\n                        }\n                    } else f && (i = this.remuxVideo(n, c, m, void 0, h)), i && r && r.config.codec && (t = this.remuxEmptyAudio(r, c, l, d, i, u));\n                    p ? e = {\n                        data1: i.data1,\n                        data2: p.silentFragData,\n                        startDTS: i.startDTS,\n                        startPTS: i.startPTS,\n                        endDTS: y(i.endDTS, p.endTs),\n                        endPTS: y(i.endPTS, p.endTs),\n                        type: \"audiovideo\",\n                        track: this.currentInitTrack\n                    } : i && t ? e = {\n                        data1: i.data1,\n                        data2: t.data1,\n                        startDTS: g(i.startDTS, t.startDTS),\n                        startPTS: g(i.startPTS, t.startPTS),\n                        endDTS: y(i.endDTS, t.endDTS),\n                        endPTS: y(i.endPTS, t.endPTS),\n                        type: \"audiovideo\",\n                        track: this.currentInitTrack,\n                        dropped: i.dropped,\n                        framesWithoutIDR: i.framesWithoutIDR,\n                        firstKeyframePts: i.firstKeyframePts\n                    } : i ? e = {\n                        data1: i.data1,\n                        startDTS: i.startDTS,\n                        startPTS: i.startPTS,\n                        endDTS: i.endDTS,\n                        endPTS: i.endPTS,\n                        type: \"video\",\n                        track: this.currentInitTrack,\n                        dropped: i.dropped,\n                        framesWithoutIDR: i.framesWithoutIDR,\n                        firstKeyframePts: i.firstKeyframePts\n                    } : t ? e = {\n                        data1: t.data1,\n                        startDTS: t.startDTS,\n                        startPTS: t.startPTS,\n                        endDTS: t.endDTS,\n                        endPTS: t.endPTS,\n                        type: \"audio\",\n                        track: this.currentInitTrack\n                    } : this.logger.error(\"Missing video and audio data\"), a && a.captionSamples.length && this.remuxText(a, e), null !== (a = null == s ? void 0 : s.id3Samples) && void 0 !== a && a.length && this.remuxID3(s, e), this.observer.trigger(v.FRAG_PARSING_DATA, e)\n                } else this.logger.error(\"failed to generate IS\");\n                this.observer.trigger(v.FRAG_PARSED)\n            }\n            updateInitPTSDTS(e, t, i) {\n                let r = 1 / 0,\n                    n = 1 / 0;\n                var s = e ? e.parsingData.esSamples : [],\n                    a = t ? t.parsingData.esSamples : [];\n                if (!ne(this._initPTS)) {\n                    if (t && a.length && (r = n = a[0].pts - t.info.inputTimescale * i), e && s.length) {\n                        const t = e.info.inputTimescale;\n                        e.info.timescale = t, r = Math.min(r, s.reduce((e, t) => {\n                            var i = t.pts - e;\n                            return i < -4294967296 ? Ie(e, t.pts) : 0 < i ? e : t.pts\n                        }, s[0].pts) - t * i), n = Math.min(n, s[0].dts - t * i), this.observer.trigger(v.INIT_PTS_FOUND, {\n                            initPTS: B(r, t)\n                        })\n                    }\n                    if (ne(r) && ne(n)) this._initPTS = r, this._initDTS = n;\n                    else {\n                        const e = new D(!1, \"invalid initPTS or initDTS\", $.InvalidInitTimestamp);\n                        this.observer.trigger(x.INTERNAL_ERROR, e)\n                    }\n                }\n            }\n            generateIS(e, t) {\n                const i = t ? t.parsingData.esSamples : [],\n                    r = this.typeSupported;\n                let n, s = \"audio/mp4\";\n                if (e && t && i.length) {\n                    const i = t.info.inputTimescale;\n                    t.info.timescale = i, e.info.timescale = e.config.samplerate;\n                    const r = pe.initSegment([t, e]);\n                    n = {\n                        type: \"audiovideo\",\n                        container: \"video/mp4\",\n                        codec: `${t.config.codec},${e.config.codec}`,\n                        initSegment: r\n                    }\n                } else if (e) {\n                    \"mp3\" === (e.info.timescale = e.config.samplerate, e.config.segmentCodec) && (r.mpeg ? (s = \"audio/mpeg\", e.config.codec = \"\") : r.mp3 && (e.config.codec = \"mp3\"));\n                    const t = \"mp3\" === e.config.segmentCodec && r.mpeg ? new Uint8Array : pe.initSegment([e]);\n                    n = {\n                        type: \"audio\",\n                        container: s,\n                        codec: e.config.codec,\n                        initSegment: t\n                    }\n                } else if (t && i.length) {\n                    const e = t.info.inputTimescale;\n                    t.info.timescale = e;\n                    const i = pe.initSegment([t]);\n                    n = {\n                        type: \"video\",\n                        container: \"video/mp4\",\n                        codec: t.config.codec,\n                        initSegment: i\n                    }\n                }\n                if (n) {\n                    this.currentInitTrack = n;\n                    const e = {\n                        track: n\n                    };\n                    this.observer.trigger(v.FRAG_PARSING_INIT_SEGMENT, e)\n                } else {\n                    const e = new D(!1, \"no audio/video samples found\", $.NoAVSamplesFound);\n                    this.observer.trigger(x.INTERNAL_ERROR, e)\n                }\n            }\n            remuxVideo(n, e, s, a, o) {\n                let l, d, u, c, h, t, p = 8,\n                    i = n.parsingData.dropped;\n                const r = !s && this.config.forceKeyFrameOnDiscontinuity,\n                    f = n.parsingData.esSamples,\n                    m = n.info.inputTimescale,\n                    g = [],\n                    y = n.info.encrypted;\n                let v, S;\n                v = s ? this.nextAvcDts : Ie(f[0].dts, f[0].pts), f.forEach(function(e) {\n                    e.pts = Ie(e.pts, v), e.dts = Ie(e.dts, v)\n                }), f.sort(function(e, t) {\n                    var i = e.dts - t.dts,\n                        r = e.pts - t.pts;\n                    return i || r || e.id - t.id\n                });\n                var b = f.findIndex(e => e.key);\n                f[b] && (S = f[b].pts), r && (0 < b ? (this.logger.warn(`Dropped ${b} out of ${f.length} video samples due to a missing keyframe`), f.splice(0, b), i += b) : -1 === b && (this.logger.warn(`No keyframe found out of ${f.length} video samples`), i += f.length));\n                var T = f[0],\n                    E = f[f.length - 1],\n                    I = f.reduce((e, t) => Math.max(Math.min(e, t.pts - t.dts), -18e3), 0);\n                if (I < 0) {\n                    this.logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${Math.round(I/90)} ms to overcome this issue`);\n                    for (let e = 0; e < f.length; e++) f[e].dts += I\n                }\n                var w = this.isSafari;\n                if (l = Math.round((E.dts - T.dts) / (f.length - 1)), c = Math.max(T.dts, 0), u = Math.max(T.pts, 0), ne(o) && (c = e * m, u = e * m), s) {\n                    const n = c - v,\n                        M = n > l,\n                        s = n < -1;\n                    (M || s) && (M ? this.logger.warn(`AVC: ${n}/90000 hole between fragments detected`) : this.logger.warn(`AVC: ${n}/90000 overlapping between fragments detected`))\n                }\n                let A = 0,\n                    O = 0;\n                var k = f.length;\n                for (let e = 0; e < k; e++) {\n                    const M = f[e],\n                        s = M.units,\n                        a = s.length;\n                    let t = 0;\n                    for (let e = 0; e < a; e++) t += s[e].data.length;\n                    O += t, A += a, M.length = t, M.dts = w ? c + e * l : Math.max(M.dts, c), M.pts = Math.max(M.pts, M.dts)\n                }\n                t = Math.max(E.dts, 0), h = Math.max(E.pts, 0, t), ne(o) && (t = e * m, h = e * m);\n                e = O + 4 * A + 8;\n                try {\n                    d = new Uint8Array(e)\n                } catch (n) {\n                    const M = new F(!1, `fail allocating video mdat ${e}`, $.FailedToAllocateVideoMdat, e);\n                    return void this.observer.trigger(x.INTERNAL_ERROR, M)\n                }\n                const C = new DataView(d.buffer);\n                C.setUint32(0, e), d.set(pe.types.mdat, 4);\n                for (let t = 0; t < k; t++) {\n                    const M = f[t],\n                        s = M.units;\n                    let e, i = 0;\n                    const x = [];\n                    let r = 0;\n                    for (let e = 0, t = s.length; e < t; e++) {\n                        const M = s[e],\n                            a = M.data,\n                            o = M.data.byteLength;\n                        if (C.setUint32(p, o), p += 4, d.set(a, p), p += o, i += 4 + o, y)\n                            if (o <= 48 || 1 !== M.type && 5 !== M.type) r += 4 + o;\n                            else {\n                                let e = o - 32;\n                                e % 16 == 0 && (e -= 16), x.push([r + 36, e]), r = o - 32 - e\n                            }\n                    }\n                    if (0 < r && x.push([r, 0]), w) e = Math.max(0, l * Math.round((M.pts - M.dts) / l));\n                    else {\n                        if (t < k - 1) l = f[t + 1].dts - M.dts;\n                        else {\n                            const s = this.config,\n                                o = M.dts - f[0 < t ? t - 1 : t].dts;\n                            if (s.stretchShortVideoTrack) {\n                                const n = s.maxBufferHole,\n                                    d = s.maxSeekHole,\n                                    c = Math.floor(Math.min(n, d) * m),\n                                    h = (a ? u + a * m : this.nextAudioPts) - M.pts;\n                                h > c ? (l = h - o, l < 0 && (l = o)) : l = o\n                            } else l = o\n                        }\n                        e = Math.round(M.pts - M.dts)\n                    }\n                    ne(o) && (e = 0, l = o * m), g.push({\n                        size: i,\n                        duration: l,\n                        cts: e,\n                        flags: {\n                            isLeading: 0,\n                            isDependedOn: 0,\n                            hasRedundancy: 0,\n                            degradPrio: 0,\n                            dependsOn: M.key ? 2 : 1,\n                            isNonSync: M.key ? 0 : 1,\n                            paddingValue: 0\n                        },\n                        keyTagInfo: M.keyTagInfo,\n                        subsamples: x\n                    })\n                }\n                if (this.nextAvcDts = t + l, this.isVideoContiguous = !0, g.length && -1 < navigator.userAgent.toLowerCase().indexOf(\"chrome\")) {\n                    const n = g[0].flags;\n                    n.dependsOn = 2, n.isNonSync = 0\n                }\n                e = {\n                    sequenceNumber: n.parsingData.sequenceNumber++,\n                    id: n.info.id,\n                    type: n.type,\n                    encrypted: n.info.encrypted,\n                    samples: g,\n                    defaultPerSampleIVSize: 0\n                }, e = pe.moof(c + this.config.audioPrimingDelay * m, e);\n                n.parsingData.esSamples = [];\n                const D = new Uint8Array(e.byteLength + d.byteLength);\n                return D.set(e), D.set(d, e.byteLength), {\n                    data1: D,\n                    startPTS: B(u / m, m),\n                    endPTS: B((h + l) / m, m),\n                    startDTS: B(c / m, m),\n                    endDTS: B(this.nextAvcDts / m, m),\n                    type: \"video\",\n                    dropped: i,\n                    framesWithoutIDR: b,\n                    firstKeyframePts: B(S / m, m)\n                }\n            }\n            remuxAudio(r, i, n, e, s) {\n                const a = r.info.inputTimescale,\n                    o = a / r.info.timescale,\n                    l = (\"aac\" === r.config.segmentCodec ? 1024 : \"mp3\" === r.config.segmentCodec ? 1152 : 1536) * o,\n                    d = \"mp3\" === r.config.segmentCodec && this.typeSupported.mpeg,\n                    u = [],\n                    c = r.info.encrypted,\n                    t = this._initPTS + i * a;\n                let h, p, f, m, g, y, v, S, b, T, E, I, w, A, O = d ? 0 : 8;\n                const k = new q,\n                    C = r.parsingData.esSamples;\n                if (A = this.nextAudioPts, (n = n || C.length && A && (e && Math.abs(t - A) < 9e3 || Math.abs(Ie(C[0].pts - A, t)) < 20 * l)) || (A = Ie(C[0].pts, this._initPTS)), C.forEach(function(e) {\n                        e.pts = e.dts = Ie(e.pts, A)\n                    }), e && \"aac\" === r.config.segmentCodec)\n                    for (let t = 0, i = A; t < C.length;) {\n                        const M = C[t];\n                        T = M.pts;\n                        const o = T - i,\n                            d = Math.abs(1e3 * o / a);\n                        if (o <= -l) this.logger.warn(`Dropping 1 audio frame @ ${(i/a).toFixed(3)}s due to ${d} ms overlap.`), C.splice(t, 1), r.parsingData.len -= M.unit.length;\n                        else if (o >= l && d < 1e4 && i) {\n                            const d = Math.round(o / l);\n                            this.logger.warn(`Injecting ${d} audio frame @ ${(i/a).toFixed(3)}s due to ${Math.round(1e3*o/a)} ms gap.`);\n                            for (let e = 0; e < d; e++) w = Math.max(i, 0), I = re(r.config.codec, r.config.channelCount), I || (this.logger.warn(\"Unable to get silent frame for given audio codec; duplicating last frame instead.\"), I = M.unit.subarray(0)), C.splice(t, 0, {\n                                unit: I,\n                                pts: w,\n                                dts: w,\n                                keyTagInfo: s\n                            }), r.parsingData.len += I.length, i += l, t += 1;\n                            M.pts = M.dts = i, i += l, t += 1\n                        } else i += l, M.pts = M.dts = 0 === t ? A : C[t - 1].pts + l, t += 1\n                    }\n                for (let e = 0, t = C.length; e < t; e++) {\n                    if (p = C[e], m = p.unit, T = p.pts, E = p.dts, void 0 !== b) f.duration = Math.round((E - b) / o);\n                    else {\n                        const i = Math.round(1e3 * (T - A) / a);\n                        let t = 0;\n                        if (n && \"aac\" === r.config.segmentCodec && i) {\n                            if (0 < i && i < 1e4) t = Math.round((T - A) / l), 0 < t && (I = re(r.config.codec, r.config.channelCount), I = I || m.subarray(0), r.parsingData.len += t * I.length);\n                            else if (i < -12) {\n                                r.parsingData.len -= m.byteLength;\n                                continue\n                            }\n                            T = E = A\n                        }\n                        if (v = Math.max(0, T), S = Math.max(0, E), !(0 < r.parsingData.len)) return; {\n                            const i = d ? r.parsingData.len : r.parsingData.len + 8;\n                            try {\n                                g = new Uint8Array(i)\n                            } catch (r) {\n                                const n = new F(!1, `fail allocating audio mdat ${i}`, $.FailedToAllocateAudioMdat, i);\n                                return void this.observer.trigger(x.INTERNAL_ERROR, n)\n                            }\n                            d || (h = new DataView(g.buffer), h.setUint32(0, i), g.set(pe.types.mdat, 4))\n                        }\n                        for (let e = 0; e < t; e++) w = T - (t - e) * l, I = re(r.config.codec, r.config.channelCount), I || (this.logger.warn(\"Unable to get silent frame for given audio codec; duplicating this frame instead.\"), I = m.subarray(0)), g.set(I, O), O += I.byteLength, f = {\n                            size: I.byteLength,\n                            cts: 0,\n                            duration: 1024,\n                            flags: {\n                                isLeading: 0,\n                                isDependedOn: 0,\n                                hasRedundancy: 0,\n                                degradPrio: 0,\n                                dependsOn: 1,\n                                paddingValue: 0,\n                                isNonSync: 0\n                            },\n                            keyTagInfo: p.keyTagInfo,\n                            subsamples: c ? [\n                                [I.byteLength, 0]\n                            ] : []\n                        }, u.push(f)\n                    }\n                    g.set(m, O);\n                    const M = m.byteLength;\n                    O += M;\n                    const s = [];\n                    if (c)\n                        if (\"ec3\" === r.config.segmentCodec) {\n                            let e = 0;\n                            for (; e < m.byteLength;) {\n                                const i = 2 * (k.bsReadAndUpdate(m, {\n                                    byteOffset: e + 2,\n                                    usedBits: 5\n                                }, 11) + 1);\n                                e += i;\n                                const n = Math.min(i, 16);\n                                s.push([n, i - n])\n                            }\n                        } else {\n                            const r = Math.min(M, 16);\n                            s.push([r, M - r])\n                        } f = {\n                        size: M,\n                        cts: 0,\n                        duration: 0,\n                        flags: {\n                            isLeading: 0,\n                            isDependedOn: 0,\n                            hasRedundancy: 0,\n                            degradPrio: 0,\n                            dependsOn: 1,\n                            paddingValue: 0,\n                            isNonSync: 0\n                        },\n                        keyTagInfo: p.keyTagInfo,\n                        subsamples: s\n                    }, u.push(f), b = E\n                }\n                let D = 0;\n                e = u.length;\n                if (2 <= e && (D = u[e - 2].duration, f.duration = D), e) {\n                    if (this.nextAudioPts = T + o * D, r.parsingData.len = 0, d) y = new Uint8Array;\n                    else {\n                        const i = {\n                            sequenceNumber: r.parsingData.sequenceNumber++,\n                            id: r.info.id,\n                            type: r.type,\n                            encrypted: r.info.encrypted,\n                            samples: u,\n                            defaultPerSampleIVSize: 0\n                        };\n                        y = pe.moof((S + this.config.audioPrimingDelay * a) / o, i)\n                    }\n                    const i = new Uint8Array(y.byteLength + g.byteLength);\n                    return i.set(y), i.set(g, y.byteLength), r.parsingData.esSamples = [], {\n                        data1: i,\n                        startPTS: B(v / a, a),\n                        endPTS: B(this.nextAudioPts / a, a),\n                        startDTS: B(S / a, a),\n                        endDTS: B((E + o * D) / a, a),\n                        type: \"audio\"\n                    }\n                }\n                return null\n            }\n            remuxEmptyAudio(t, e, i, r, n, s) {\n                var a = t.info.inputTimescale,\n                    o = a / (t.config.samplerate || a),\n                    l = this.nextAudioPts,\n                    d = (void 0 !== l ? l : S(n.startDTS) * a) + this._initDTS,\n                    a = S(n.endDTS) * a + this._initDTS,\n                    u = 1024 * o,\n                    c = Math.ceil((a - d) / u),\n                    h = re(t.config.codec, t.config.channelCount);\n                if (this.logger.warn(\"remux empty Audio\"), !h) return this.logger.error(\"Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!\"), null;\n                const p = [];\n                for (let e = 0; e < c; e++) {\n                    const i = d + e * u;\n                    p.push({\n                        unit: h,\n                        pts: i,\n                        dts: i,\n                        keyTagInfo: s\n                    }), t.parsingData.len += h.length\n                }\n                return t.parsingData.esSamples = p, this.remuxAudio(t, e, i, r, s)\n            }\n            remuxID3(t, e) {\n                var i = t.id3Samples.length;\n                let r;\n                var n = t.inputTimescale;\n                if (i) {\n                    for (let e = 0; e < i; e++) r = t.id3Samples[e], r.pts = r.pts / n, r.dts = r.dts / n;\n                    e.id3Samples = t.id3Samples\n                }\n                t.id3Samples = []\n            }\n            remuxText(t, e) {\n                t.captionSamples.sort(function(e, t) {\n                    return e.pts - t.pts\n                });\n                var i = t.captionSamples.length;\n                let r;\n                var n = t.inputTimescale;\n                if (i) {\n                    for (let e = 0; e < i; e++) r = t.captionSamples[e], r.pts = r.pts / n;\n                    e.captionData || (e.captionData = {}), e.captionData.ts = t.captionSamples\n                }\n                t.captionSamples = []\n            }\n        }\n\n        function Ie(e, t) {\n            var i;\n            if (void 0 === t) return e;\n            for (i = t < e ? -8589934592 : 8589934592; 4294967296 < Math.abs(e - t);) e += i;\n            return e\n        }\n        e = \"undefined\" != typeof globalThis ? globalThis : \"undefined\" != typeof window ? window : \"undefined\" != typeof global ? global : void 0 !== Jy ? Jy : {};\n\n        function we(e) {\n            try {\n                return JSON.stringify(e)\n            } catch (e) {\n                return '\"[Circular]\"'\n            }\n        }\n\n        function Ae(e, t, i) {\n            var r = i && i.stringify || we;\n            if (\"object\" == typeof e && null !== e) {\n                var n = t.length + 1;\n                if (1 === n) return e;\n                var s = new Array(n);\n                s[0] = r(e);\n                for (var a = 1; a < n; a++) s[a] = r(t[a]);\n                return s.join(\" \")\n            }\n            if (\"string\" != typeof e) return e;\n            var o = t.length;\n            if (0 === o) return e;\n            for (var l = \"\", d = 0, u = -1, c = e && e.length || 0, h = 0; h < c;) {\n                if (37 === e.charCodeAt(h) && h + 1 < c) {\n                    switch (u = -1 < u ? u : 0, e.charCodeAt(h + 1)) {\n                        case 100:\n                            if (o <= d) break;\n                            if (u < h && (l += e.slice(u, h)), null == t[d]) break;\n                            l += Number(t[d]), u = h += 2;\n                            break;\n                        case 79:\n                        case 111:\n                        case 106:\n                            if (o <= d) break;\n                            if (u < h && (l += e.slice(u, h)), void 0 === t[d]) break;\n                            var p = typeof t[d];\n                            if (\"string\" == p) {\n                                l += \"'\" + t[d] + \"'\", u = h + 2, h++;\n                                break\n                            }\n                            if (\"function\" == p) {\n                                l += t[d].name || \"<anonymous>\", u = h + 2, h++;\n                                break\n                            }\n                            l += r(t[d]), u = h + 2, h++;\n                            break;\n                        case 115:\n                            if (o <= d) break;\n                            u < h && (l += e.slice(u, h)), l += String(t[d]), u = h + 2, h++;\n                            break;\n                        case 37:\n                            u < h && (l += e.slice(u, h)), l += \"%\", u = h + 2, h++\n                    }++d\n                }++h\n            }\n            return -1 === u ? e : (u < c && (l += e.slice(u)), l)\n        }\n        var Oe = De;\n        const ke = function() {\n                function t(e) {\n                    return void 0 !== e && e\n                }\n                try {\n                    return \"undefined\" != typeof globalThis || Object.defineProperty(Object.prototype, \"globalThis\", {\n                        get: function() {\n                            return delete Object.prototype.globalThis, this.globalThis = this\n                        },\n                        configurable: !0\n                    }), globalThis\n                } catch (e) {\n                    return t(Jy) || t(window) || t(this) || {}\n                }\n            }().console || {},\n            Ce = {\n                mapHttpRequest: Le,\n                mapHttpResponse: Le,\n                wrapRequestSerializer: _e,\n                wrapResponseSerializer: _e,\n                wrapErrorSerializer: _e,\n                req: Le,\n                res: Le,\n                err: function(e) {\n                    const t = {\n                        type: e.constructor.name,\n                        msg: e.message,\n                        stack: e.stack\n                    };\n                    for (const i in e) void 0 === t[i] && (t[i] = e[i]);\n                    return t\n                }\n            };\n\n        function De(s) {\n            (s = s || {}).browser = s.browser || {};\n            const a = s.browser.transmit;\n            if (a && \"function\" != typeof a.send) throw Error(\"pino: transmit option must have a send function\");\n            const e = s.browser.write || ke;\n            s.browser.write && (s.browser.asObject = !0);\n            const o = s.serializers || {},\n                l = (t = s.browser.serialize, i = o, Array.isArray(t) ? t.filter(function(e) {\n                    return \"!stdSerializers.err\" !== e\n                }) : !0 === t && Object.keys(i));\n            var t, i;\n            let r = s.browser.serialize;\n            Array.isArray(s.browser.serialize) && -1 < s.browser.serialize.indexOf(\"!stdSerializers.err\") && (r = !1), \"function\" == typeof e && (e.error = e.fatal = e.warn = e.info = e.debug = e.trace = e), !1 === s.enabled && (s.level = \"silent\");\n            const n = s.level || \"info\",\n                d = Object.create(e);\n            d.log || (d.log = Ne), Object.defineProperty(d, \"levelVal\", {\n                get: function() {\n                    return \"silent\" === this.level ? 1 / 0 : this.levels.values[this.level]\n                }\n            }), Object.defineProperty(d, \"level\", {\n                get: function() {\n                    return this._level\n                },\n                set: function(e) {\n                    if (\"silent\" !== e && !this.levels.values[e]) throw Error(\"unknown level \" + e);\n                    this._level = e, Me(u, d, \"error\", \"log\"), Me(u, d, \"fatal\", \"error\"), Me(u, d, \"warn\", \"error\"), Me(u, d, \"info\", \"log\"), Me(u, d, \"debug\", \"log\"), Me(u, d, \"trace\", \"log\")\n                }\n            });\n            const u = {\n                transmit: a,\n                serialize: l,\n                asObject: s.browser.asObject,\n                levels: [\"error\", \"fatal\", \"warn\", \"info\", \"debug\", \"trace\"],\n                timestamp: \"function\" == typeof(i = s).timestamp ? i.timestamp : !1 === i.timestamp ? Fe : Be\n            };\n            return d.levels = De.levels, d.level = n, d.setMaxListeners = d.getMaxListeners = d.emit = d.addListener = d.on = d.prependListener = d.once = d.prependOnceListener = d.removeListener = d.removeAllListeners = d.listeners = d.listenerCount = d.eventNames = d.write = d.flush = Ne, d.serializers = o, d._serialize = l, d._stdErrSerialize = r, d.child = function(t) {\n                if (!t) throw new Error(\"missing bindings for child Pino\");\n                var i, r, e = t.serializers;\n\n                function n(e) {\n                    this._childLevel = 1 + (0 | e._childLevel), this.error = Pe(e, t, \"error\"), this.fatal = Pe(e, t, \"fatal\"), this.warn = Pe(e, t, \"warn\"), this.info = Pe(e, t, \"info\"), this.debug = Pe(e, t, \"debug\"), this.trace = Pe(e, t, \"trace\"), i && (this.serializers = i, this._serialize = r), a && (this._logEvent = Re([].concat(e._logEvent.bindings, t)))\n                }\n                return l && e && (i = Object.assign({}, o, e), r = !0 === s.browser.serialize ? Object.keys(i) : l, delete t.serializers, xe([t], r, i, this._stdErrSerialize)), n.prototype = this, new n(this)\n            }, a && (d._logEvent = Re()), d\n        }\n\n        function Me(e, t, i, r) {\n            var n, s, a, o, l = Object.getPrototypeOf(t);\n            t[i] = !(t.levelVal > t.levels.values[i]) && (l[i] || ke[i] || ke[r]) || Ne, s = t, a = i, !(n = e).transmit && s[a] === Ne || (s[a] = (o = s[a], function() {\n                const e = n.timestamp(),\n                    t = new Array(arguments.length),\n                    i = Object.getPrototypeOf && Object.getPrototypeOf(this) === ke ? ke : this;\n                for (var r = 0; r < t.length; r++) t[r] = arguments[r];\n                if (n.serialize && !n.asObject && xe(t, this._serialize, this.serializers, this._stdErrSerialize), n.asObject ? o.call(i, function(e, t, i, r) {\n                        e._serialize && xe(i, e._serialize, e.serializers, e._stdErrSerialize);\n                        const n = i.slice();\n                        let s = n[0];\n                        const a = {};\n                        r && (a.time = r), a.level = De.levels.values[t];\n                        let o = 1 + (0 | e._childLevel);\n                        if (o < 1 && (o = 1), null !== s && \"object\" == typeof s) {\n                            for (; o-- && \"object\" == typeof n[0];) Object.assign(a, n.shift());\n                            s = n.length ? Ae(n.shift(), n) : void 0\n                        } else \"string\" == typeof s && (s = Ae(n.shift(), n));\n                        return void 0 !== s && (a.msg = s), a\n                    }(this, a, t, e)) : o.apply(i, t), n.transmit) {\n                    const o = n.transmit.level || s.level,\n                        i = De.levels.values[o],\n                        r = De.levels.values[a];\n                    r < i || function(e, t, i) {\n                        const r = t.send,\n                            n = t.ts,\n                            s = t.methodLevel,\n                            a = t.methodValue,\n                            o = t.val,\n                            l = e._logEvent.bindings;\n                        xe(i, e._serialize || Object.keys(e.serializers), e.serializers, void 0 === e._stdErrSerialize || e._stdErrSerialize), e._logEvent.ts = n, e._logEvent.messages = i.filter(function(e) {\n                            return -1 === l.indexOf(e)\n                        }), e._logEvent.level.label = s, e._logEvent.level.value = a, r(s, e._logEvent, o), e._logEvent = Re(l)\n                    }(this, {\n                        ts: e,\n                        methodLevel: a,\n                        methodValue: r,\n                        transmitLevel: o,\n                        transmitValue: De.levels.values[n.transmit.level || s.level],\n                        send: n.transmit.send,\n                        val: s.levelVal\n                    }, t)\n                }\n            }))\n        }\n\n        function xe(e, t, i, r) {\n            for (const n in e)\n                if (r && e[n] instanceof Error) e[n] = De.stdSerializers.err(e[n]);\n                else if (\"object\" == typeof e[n] && !Array.isArray(e[n]))\n                for (const r in e[n]) t && -1 < t.indexOf(r) && r in i && (e[n][r] = i[r](e[n][r]))\n        }\n\n        function Pe(i, r, n) {\n            return function() {\n                try{  const e = new Array(1 + arguments.length);\n                    e[0] = r;\n                    for (var t = 1; t < e.length; t++)\n                        e[t] = arguments[t - 1];\n                    return i[n].apply(this, e) } catch (e){}\n            }\n        }\n\n        function Re(e) {\n            return {\n                ts: 0,\n                messages: [],\n                bindings: e || [],\n                level: {\n                    label: \"\",\n                    value: 0\n                }\n            }\n        }\n\n        function Le() {\n            return {}\n        }\n\n        function _e(e) {\n            return e\n        }\n\n        function Ne() {}\n\n        function Fe() {\n            return !1\n        }\n\n        function Be() {\n            return Date.now()\n        }\n        let Ue;\n\n        function $e(e = {}) {\n            return Object.assign(Object.assign({}, e), {\n                customLevels: Object.assign(Object.assign({}, e.customLevels || {}), {\n                    qe: 35\n                })\n            })\n        }\n        De.levels = {\n            values: {\n                fatal: 60,\n                error: 50,\n                warn: 40,\n                info: 30,\n                debug: 20,\n                trace: 10\n            },\n            labels: {\n                10: \"trace\",\n                20: \"debug\",\n                30: \"info\",\n                40: \"warn\",\n                50: \"error\",\n                60: \"fatal\"\n            }\n        }, De.stdSerializers = Ce, De.stdTimeFunctions = Object.assign({}, {\n            nullTime: Fe,\n            epochTime: Be,\n            unixTime: function() {\n                return Math.round(Date.now() / 1e3)\n            },\n            isoTime: function() {\n                return new Date(Date.now()).toISOString()\n            }\n        });\n        const Ve = () => {};\n\n        function Ke(e, t) {\n            const i = (e = t in e ? e : console)[t] || e.log;\n            return i ? i.bind(e) : Ve\n        }\n\n        function qe(r, n, e) {\n            var {\n                time: s,\n                sessionId: t,\n                critical: i,\n                name: a,\n                msg: o\n            } = e;\n            let l = \"\";\n            if (\"data\" in e) try {\n                const r = [],\n                    n = [];\n                l = JSON.stringify(e.data, (e, t) => {\n                    if (\"object\" == typeof t && null !== t) {\n                        var i = n.indexOf(t);\n                        if (-1 !== i) return `[Circular object reference: '${r[i]}']`;\n                        r.push(e), n.push(t)\n                    }\n                    return t\n                })\n            } catch (r) {\n                l = `Log serialization error: \"${r}\"`\n            }\n            r(`${function(){const e=new Date(s),t=e.getTimezoneOffset(),i=He(Math.floor(Math.abs(t)/60)),r=He(Math.abs(t)%60);let n=t<=0?\"UTC+\"+i:\"UTC-\"+i;return n=r?n+\":\"+r:n,e.getFullYear()+\"-\"+He(e.getMonth()+1)+\"-\"+He(e.getDate())+\" \"+He(e.getHours())+\":\"+He(e.getMinutes())+\":\"+He(e.getSeconds())+\".\"+(e.getMilliseconds()/1e3).toFixed(3).slice(2,5)+\" \"+n}()}| [SessionID: ${t}] | [${n}] >${i?\" [QE Critical]\":\"\"} [${a}] ${o||\"\"} ${l}`)\n        }\n\n        function He(e) {\n            return e < 10 ? \"0\" + e : e.toString()\n        }\n\n        function je(e, t = 1 / 0) {\n            if (!e) return \"\";\n            const i = new Uint8Array(e);\n            let r, n = \"\";\n            for (r = 0; r < i.length && r < t; r++) {\n                let e = i[r].toString(16);\n                e.length < 2 && (e = \"0\" + e), n += e\n            }\n            return n\n        }\n        const Qe = () => (Ue || (Ue = Oe($e()).child({\n                name: \"hls\"\n            }), Ue.qe = e => Ue.info(e), Ue.warn(\"getLogger called without hls object instantiated, returning a logger that is not configured\")), Ue),\n            We = {\n                bin2str: e => String.fromCharCode.apply(null, Array.from(e)),\n                readUint16(e, t) {\n                    t = e[t] << 8 | e[t + 1];\n                    return t < 0 ? 65536 + t : t\n                },\n                readSint32: (e, t) => e[t] << 24 | e[t + 1] << 16 | e[t + 2] << 8 | e[t + 3],\n                readUint32(e, t) {\n                    t = We.readSint32(e, t);\n                    return t < 0 ? 4294967296 + t : t\n                },\n                writeUint32(e, t, i) {\n                    e[t] = i >> 24, e[t + 1] = i >> 16 & 255, e[t + 2] = i >> 8 & 255, e[t + 3] = 255 & i\n                },\n                readUint64(e, t) {\n                    var i = We.readUint32(e, t);\n                    return i *= Math.pow(2, 32), i += We.readUint32(e, t + 4)\n                },\n                writeUint64(e, t, i) {\n                    var r = Math.pow(2, 32) - 1,\n                        n = Math.floor(i / (1 + r)),\n                        r = Math.floor(i % (1 + r));\n                    We.writeUint32(e, t, n), We.writeUint32(e, t + 4, r)\n                },\n                findBox(e, t) {\n                    let i, r, n, s, a, o = [];\n                    if (!t.length) return [];\n                    for (i = 0; i < e.byteLength;) r = We.readUint32(e, i), n = We.bin2str(e.subarray(i + 4, i + 8)), s = 1 < r ? i + r : e.byteLength, n === t[0] && (1 === t.length ? o.push(e.subarray(i + 8, s)) : (a = We.findBox(e.subarray(i + 8, s), t.slice(1))).length && (o = o.concat(a))), i = s;\n                    return o\n                },\n                findBoxWithOffset(e, t, i, r) {\n                    let n, s, a, o, l, d = [];\n                    if (!i.length) return [];\n                    for (n = 0; n < e.byteLength;) s = We.readUint32(e, n), a = We.bin2str(e.subarray(n + 4, n + 8)), o = 1 < s ? n + s : e.byteLength, a === i[0] && (r && r.push({\n                        offset: n + t,\n                        type: a,\n                        size: s\n                    }), 1 === i.length ? d.push({\n                        offset: n + t,\n                        type: a,\n                        data: e.subarray(n + 8, o),\n                        boxSize: s,\n                        walkedPath: r ? r.slice(0) : void 0\n                    }) : (l = We.findBoxWithOffset(e.subarray(n + 8, o), n + t + 8, i.slice(1), r ? r.slice(0) : void 0)).length && (d = d.concat(l), r = r ? r.slice(0, -1) : void 0)), n = o;\n                    return d\n                }\n            },\n            Ge = {\n                name: \"MP4EncryptionRemuxer\"\n            };\n        class ze extends h {\n            constructor(e, t, i, r, n) {\n                super(e, t, n)\n            }\n            static _isCommonEncryptionInternal(e) {\n                return Boolean(e && !(\"NONE\" === e || \"AES-128\" === e))\n            }\n            static remuxInitSegment(c, h, p, f) {\n                if (!p) return c;\n                let e = c;\n                if (ze._isCommonEncryptionInternal(p.method)) {\n                    const m = p.keyId;\n                    let u = !1;\n                    const g = [];\n                    if (We.findBoxWithOffset(c, 0, [\"moov\", \"trak\"]).forEach(t => {\n                            const o = t.data;\n                            let l, i = 0;\n                            const d = We.findBoxWithOffset(o, 0, [\"mdia\", \"minf\", \"stbl\", \"stsd\"], [])[0],\n                                e = d.data.subarray(8);\n                            let r = !0,\n                                n = We.findBoxWithOffset(e, d.offset + 16, [\"enca\"]);\n                            0 === n.length && (r = !1, n = We.findBoxWithOffset(e, d.offset + 16, [\"encv\"])), n.forEach(s => {\n                                let e = null,\n                                    a = null;\n                                i = r ? (e = s.data.subarray(28), l = \"audio\", d.offset + 16 + 8 + 28) : (e = s.data.subarray(78), l = \"video\", d.offset + 16 + 8 + 78), e && We.findBoxWithOffset(e, i, [\"sinf\"]).forEach(e => {\n                                    const t = e.data,\n                                        i = We.findBox(t, [\"frma\"])[0],\n                                        r = We.findBox(t, [\"schm\"])[0];\n                                    if (i)\n                                        if (r) {\n                                            var n = We.bin2str(r.subarray(4, 8));\n                                            if (\"aac \" === We.bin2str(i.subarray(0, 4)) && (ge.types || ge.init(), i.set(ge.types.mp4a, 0)), \"cbcs\" === n || \"cenc\" === n) {\n                                                f && f.push(t);\n                                                const e = We.findBox(t, [\"schi\", \"tenc\"])[0];\n                                                if (e) {\n                                                    const h = 8;\n                                                    e.subarray(8, 24), e.set(m, 8);\n                                                    const f = e[6],\n                                                        t = e[7];\n                                                    if (1 === f && 0 === t) {\n                                                        const h = e[24];\n                                                        0 < h && p.iv && h === p.iv.length && e.set(p.iv, 25)\n                                                    }\n                                                }\n                                            } else if (\"cbc2\" === n) {\n                                                u = !0, ge.types || ge.init();\n                                                const h = We.findBoxWithOffset(t, 0, [\"frma\"])[0],\n                                                    f = ge.box(ge.types.schi, ge.tenc(p, l)),\n                                                    m = ge.box(ge.types.sinf, t.subarray(h.offset, h.boxSize), ge.schm(), f);\n                                                a = ge.box(ge.types.trak, o.subarray(0, e.offset), m, o.subarray(e.offset + e.boxSize));\n                                                const i = a.subarray(8),\n                                                    r = m.byteLength - e.boxSize;\n                                                d.walkedPath && (d.walkedPath.push({\n                                                    type: \"stsd\",\n                                                    offset: s.offset,\n                                                    size: s.boxSize\n                                                }), d.walkedPath.forEach(e => {\n                                                    We.writeUint32(i, e.offset, e.size + r)\n                                                }))\n                                            }\n                                        } else h.error(Ge, \"missing schm box\");\n                                    else h.error(Ge, \"missing frma box\")\n                                }), a = a || c.subarray(t.offset, t.offset + t.boxSize), g.push(a)\n                            });\n                            var s = We.findBoxWithOffset(o, 0, [\"edts\"])[0];\n                            s && (ge.types || ge.init(), o.set(ge.types.free, s.offset + 4))\n                        }), u) {\n                        const p = ze.remuxCbc2InitSegment(c, g, h);\n                        e = p || c\n                    }\n                }\n                return e\n            }\n            static remuxCbc2InitSegment(i, r, n) {\n                const s = We.findBoxWithOffset(i, 0, [\"ftyp\"])[0];\n                if (s) {\n                    const a = We.findBoxWithOffset(i, s.boxSize, [\"moov\"])[0];\n                    let e = [],\n                        t = 0;\n                    for (; t < a.data.byteLength;) {\n                        const i = We.readUint32(a.data, t),\n                            n = We.bin2str(a.data.subarray(t + 4, t + 8)),\n                            s = 1 < i ? t + i : a.data.byteLength;\n                        \"trak\" === n ? r && (e = e.concat(r), r = void 0) : e.push(a.data.subarray(t, s)), t = s\n                    }\n                    const o = ge.box(ge.types.moov, ...e),\n                        l = new Uint8Array(s.boxSize + o.byteLength);\n                    return l.set(i.subarray(0, s.boxSize)), l.set(o, s.boxSize), l\n                }\n                n.error(Ge, \"no ftyp found\")\n            }\n            static remuxOverflowSegment(i, e) {\n                ge.types || ge.init();\n                const t = We.findBoxWithOffset(i, 0, [\"moof\", \"traf\", \"tfdt\"], []);\n                let r, n = i.byteLength;\n                if (t.forEach(e => {\n                        0 === e.data[0] && (n += 4)\n                    }), n > i.byteLength) {\n                    r = new Uint8Array(n);\n                    let e = 0,\n                        t = 0;\n                    for (; t < i.byteLength;) {\n                        const n = We.readUint32(i, t),\n                            s = We.bin2str(i.subarray(t + 4, t + 8)),\n                            a = 1 < n ? t + n : i.byteLength;\n                        if (\"moof\" === s) {\n                            const n = ze.remuxOverflowMoof(i.subarray(t + 8, a));\n                            r.set(n, e), e += n.byteLength\n                        } else r.set(i.subarray(t, a), e), e += n;\n                        t = a\n                    }\n                } else e.warn(Ge, \"no increase in size\");\n                return r || i\n            }\n            static remuxOverflowMoof(e) {\n                let t = 0;\n                const i = [];\n                for (; t < e.byteLength;) {\n                    const r = We.readUint32(e, t);\n                    if (\"traf\" === We.bin2str(e.subarray(t + 4, t + 8))) {\n                        const s = ze.remuxOverflowTraf(e.subarray(t + 8, t + r));\n                        i.push(s)\n                    } else i.push(e.subarray(t, t + r));\n                    t = 1 < r ? t + r : e.byteLength\n                }\n                const r = ge.box(ge.types.moof, ...i),\n                    s = r.byteLength - e.byteLength - 8;\n                return We.findBoxWithOffset(r, 0, [\"moof\", \"traf\", \"trun\"], []).forEach(e => {\n                    var t;\n                    0 != (1 & e.data[3]) && (t = We.readUint32(e.data, 8), We.writeUint32(e.data, 8, t + s))\n                }), We.findBoxWithOffset(r, 0, [\"moof\", \"traf\", \"saio\"], []).forEach(t => {\n                    const i = 1 & t.data[0];\n                    let r = 4;\n                    1 & t.data[3] && (r += 8);\n                    var n = We.readUint32(t.data, r);\n                    if (r += 4, i)\n                        for (let e = 0; e < n; e++) {\n                            const i = We.readUint64(t.data, r);\n                            We.writeUint64(t.data, r, i + s), r += 8\n                        } else\n                            for (let e = 0; e < n; e++) {\n                                const i = We.readUint32(t.data, r);\n                                We.writeUint32(t.data, r, i + s), r += 4\n                            }\n                }), r\n            }\n            static remuxOverflowTraf(e) {\n                let t = 0;\n                const i = [];\n                for (; t < e.byteLength;) {\n                    var r, n = We.readUint32(e, t);\n                    \"tfdt\" === We.bin2str(e.subarray(t + 4, t + 8)) && 0 === e[t + 8] ? (r = We.readUint32(e, t + 12), r = ge.box(ge.types.tfdt, new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, r >> 24, r >> 16 & 255, r >> 8 & 255, 255 & r])), i.push(r)) : i.push(e.subarray(t, t + n)), t = 1 < n ? t + n : e.byteLength\n                }\n                return ge.box(ge.types.traf, ...i)\n            }\n            remuxText(e, t) {\n                e.captionSamples.sort(function(e, t) {\n                    return e.pts - t.pts\n                }), e.captionSamples.length && (t.captionData || (t.captionData = {}), t.captionData.mp4 = e.captionSamples), e.captionSamples = []\n            }\n            remuxIFrame(e, t, i, r, n) {\n                if (!t.samples || !t.samples.length || !t.samples[0].data) return null;\n                let s;\n                const a = ge.moof(e * t.timescale, t),\n                    o = new Uint8Array(a.byteLength + t.samples[0].data.byteLength + 8);\n                o.set(a), We.writeUint32(o, a.byteLength, t.samples[0].data.byteLength + 8), o.set(ge.types.mdat, a.byteLength + 4), o.set(t.samples[0].data, a.byteLength + 8), t.sequenceNumber++;\n                var l = t.timescale,\n                    d = B(e + r, l),\n                    l = B(e, l);\n                let u, c;\n                u = i ? (s = \"audiovideo\", i.sequenceNumber = t.sequenceNumber, t.sequenceNumber++, c = Te.getSegment(i, i.sequenceNumber, e * i.info.timescale, r), y(c.endTs, d)) : (s = \"video\", d);\n                n = {\n                    data1: o,\n                    data2: null == c ? void 0 : c.silentFragData,\n                    startPTS: l,\n                    startDTS: l,\n                    endPTS: u,\n                    endDTS: u,\n                    type: s,\n                    dropped: 0,\n                    track: n\n                };\n                this.observer.trigger(v.FRAG_PARSING_DATA, n), this.observer.trigger(v.FRAG_PARSED)\n            }\n            remuxEmsgAndRawData(e, t, i, r, n, s, a, o, l, d) {\n                let u;\n                t && r ? u = \"audiovideo\" : t ? u = \"audio\" : r && (u = \"video\");\n                const c = Math.max(i, e),\n                    h = {\n                        data1: l,\n                        track: d,\n                        startPTS: B(a, o),\n                        startDTS: B(a, o),\n                        endPTS: void 0,\n                        endDTS: void 0,\n                        type: u,\n                        dropped: 0\n                    };\n                return c && (h.endPTS = B(a + c, o), h.endDTS = B(a + c, o)), n && n.captionSamples.length && this.remuxText(n, h), s && 0 < s.id3Samples.length && this.remuxID3(s, h), this.observer.trigger(v.FRAG_PARSING_DATA, h), this.observer.trigger(v.FRAG_PARSED), h\n            }\n            remuxID3(t, e) {\n                let i;\n                var r = t.id3Samples.length;\n                if (r) {\n                    for (let e = 0; e < r; e++) i = t.id3Samples[e], i.pts = i.pts - 10, i.dts = i.dts - 10;\n                    e.id3Samples = [...t.id3Samples]\n                }\n                t.id3Samples = []\n            }\n        }\n        const Xe = Math.pow(2, 32) - 1,\n            Ye = Math.pow(2, 20) - 1,\n            Je = {\n                name: \"MP4Demuxer\"\n            };\n        class Ze extends u {\n            constructor(e, t, i, r, n) {\n                super(e, t, i, {}, n), this.mp4Remuxer = t, this.audioPrimingDelay = i.audioPrimingDelay\n            }\n            resetTimeStamp(e) {\n                ne(e) ? this.initData.audio && !this.initData.video ? this.initPtsTs = {\n                    baseTime: Math.round(e * this.initData.audio.timescale / 9e4),\n                    timescale: this.initData.audio.timescale\n                } : this.initPtsTs = {\n                    baseTime: e,\n                    timescale: 9e4\n                } : this.initPtsTs = void 0\n            }\n            static isHEVCFlavor(e) {\n                if (!e) return !1;\n                var t = e.indexOf(\".\"),\n                    t = t < 0 ? e : e.substring(0, t);\n                return \"hvc1\" === t || \"hev1\" === t || \"chvc\" === t || \"qhvc\" === t || \"qhev\" === t || \"muxa\" === t || \"dvh1\" === t || \"dvhe\" === t || \"cdh1\" === t || \"qdh1\" === t || \"qdhe\" === t\n            }\n            resetInitSegment(t, i, r) {\n                if (this._silentAudioTrack = void 0, t && t.byteLength) {\n                    var n = ze.remuxInitSegment(t, this.logger, r),\n                        s = this.initData = Ze.parseInitSegment(n);\n                    let e;\n                    s.foundLargeTimescale && this.logger.warn(Je, \"large timescale found, will check for 32 bit tfdts\");\n                    var a = s.audioCodec,\n                        r = s.videoCodec;\n                    if (s.audio && s.video ? e = {\n                            type: \"audiovideo\",\n                            container: \"video/mp4\",\n                            codec: a + \",\" + r,\n                            initSegment: n\n                        } : (s.audio && a && (e = {\n                            type: \"audio\",\n                            container: \"audio/mp4\",\n                            codec: a,\n                            initSegment: n\n                        }), s.video && r && (e = {\n                            type: \"video\",\n                            container: \"video/mp4\",\n                            codec: r,\n                            initSegment: n\n                        })), s.video) {\n                        const o = s.video,\n                            l = t.subarray(o.trakOffset, o.trakOffset + o.trakSize);\n                        this._videoTrack = Object.assign(Object.assign({}, o), {\n                            info: {\n                                id: o.id,\n                                timescale: o.timescale,\n                                duration: i\n                            },\n                            trakData: l,\n                            sequenceNumber: 0,\n                            samples: []\n                        }), this.trySEICaptions = !be.isVP09(r), this._captionTrack = Object.assign(Object.assign({}, s.caption), {\n                            sequenceNumber: 0,\n                            captionSamples: []\n                        })\n                    }\n                    s.audio && a && (this._audioTrack = Object.assign({}, s.audio)), s.caption && (this.trySEICaptions = !1, this._captionTrack = Object.assign(Object.assign({}, s.caption), {\n                        sequenceNumber: 0,\n                        captionSamples: []\n                    })), this.remuxedInitDataTrack = e;\n                    s = {\n                        track: e\n                    };\n                    this.observer.trigger(v.FRAG_PARSING_INIT_SEGMENT, s)\n                }\n            }\n            static probe(e, t) {\n                return 0 < We.findBox(e.subarray(0, Math.min(e.length, 512e3)), [\"moof\"]).length\n            }\n            static parseHvcC(e) {\n                let t;\n                var i, r;\n                return e ? 1 === (i = e[0]) ? (r = e[1], t = {\n                    profileSpace: r >> 6,\n                    tierFlag: (32 & r) >> 5 ? \"H\" : \"L\",\n                    profileIDC: 31 & r,\n                    profileCompat: We.readUint32(e, 2),\n                    constraintIndicator: e.subarray(6, 12),\n                    levelIDC: e[12]\n                }) : Qe().warn(Je, `Unhandled version ${i} in hvcC box`) : Qe().warn(Je, \"No hvcC box\"), t\n            }\n            static hvcCToCodecString(t, i) {\n                const r = t + \".\" + (i.profileSpace ? String.fromCharCode(i.profileSpace + \"A\" - 1) : \"\") + i.profileIDC + \".\" + i.profileCompat.toString(16).toUpperCase() + \".\" + i.tierFlag + i.levelIDC;\n                let n = \"\";\n                for (let e = i.constraintIndicator.length - 1; 0 <= e; --e) {\n                    const r = i.constraintIndicator[e];\n                    if (0 !== r || \"\" !== n) {\n                        const t = r.toString(16).toUpperCase();\n                        n = \".\" + (\"\" === n ? t : t + n)\n                    }\n                }\n                return r + n\n            }\n            static parseDvcC(e) {\n                let t;\n                return e ? t = {\n                    versionMajor: e[0],\n                    versionMinor: e[1],\n                    profile: e[2] >> 1 & 127,\n                    level: e[2] << 5 & 32 | e[3] >> 3 & 31\n                } : Qe().warn(Je, \"No dvcC box\"), t\n            }\n            static dvcCToCodecString(e, t) {\n                return e + \".\" + Ze.checkAndAddLeadingZero(t.profile) + \".\" + Ze.checkAndAddLeadingZero(t.level)\n            }\n            static parseVpcC(e) {\n                let t;\n                return e ? t = {\n                    profile: e[4],\n                    level: e[5],\n                    bitDepth: e[6] >> 4 & 15\n                } : Qe().warn(Je, \"No vpcC box\"), t\n            }\n            static vpcCToCodecString(e, t) {\n                return e + \".\" + Ze.checkAndAddLeadingZero(t.profile) + \".\" + Ze.checkAndAddLeadingZero(t.level) + \".\" + Ze.checkAndAddLeadingZero(t.bitDepth)\n            }\n            static checkAndAddLeadingZero(e) {\n                return (e < 10 ? \"0\" : \"\") + e\n            }\n            static parseInitSegment(e) {\n                const c = {\n                    foundLargeTimescale: !1,\n                    tracksById: {}\n                };\n                return We.findBoxWithOffset(e, 0, [\"moov\", \"trak\"]).forEach(t => {\n                    const i = t.data,\n                        r = We.findBox(i, [\"tkhd\"])[0];\n                    if (r) {\n                        var n = 0 === (a = r[0]) ? 12 : 20,\n                            s = We.readUint32(r, n),\n                            e = We.findBox(i, [\"mdia\", \"mdhd\"])[0];\n                        if (e) {\n                            var a, o = 0 === (a = e[0]) ? 12 : 20,\n                                n = We.readUint32(e, o);\n                            o += 4, 1e6 <= n && (c.foundLargeTimescale = !0);\n                            const l = 0 === a ? We.readUint32(e, o) : 0,\n                                d = We.findBox(i, [\"mdia\", \"hdlr\"])[0];\n                            if (d) {\n                                const r = We.bin2str(d.subarray(8, 12)),\n                                    u = {\n                                        soun: \"audio\",\n                                        vide: \"video\",\n                                        clcp: \"caption\"\n                                    } [r] || r;\n                                if (u) {\n                                    const r = We.findBox(i, [\"mdia\", \"minf\", \"stbl\", \"stsd\"]);\n                                    if (r.length) {\n                                        const i = r[0];\n                                        We.bin2str(i.subarray(12, 16));\n                                        o = Ze.parseStsd(i);\n                                        let e;\n                                        if (\"caption\" === u) {\n                                            const t = Object.assign({\n                                                id: s,\n                                                type: u,\n                                                timescale: n,\n                                                duration: l,\n                                                isTimingTrack: !1,\n                                                sequenceNumber: 0,\n                                                captionSamples: []\n                                            }, o);\n                                            c.caption = t, e = t\n                                        } else {\n                                            const i = Object.assign({\n                                                id: s,\n                                                type: u,\n                                                timescale: n,\n                                                duration: l,\n                                                isTimingTrack: !0,\n                                                trakOffset: t.offset,\n                                                trakSize: t.boxSize,\n                                                sequenceNumber: 0,\n                                                samples: [],\n                                                fragmentDuration: 0\n                                            }, o);\n                                            \"video\" === u ? (c.video = i, c.videoCodec = i.codec) : (c.audio = i, c.audioCodec = i.codec), e = i\n                                        }\n                                        c.tracksById[s] = e\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }), We.findBoxWithOffset(e, 0, [\"moov\", \"mvex\", \"trex\"]).forEach(e => {\n                    var t = e.data,\n                        e = We.readUint32(t, 4),\n                        t = We.readUint32(t, 16);\n                    c.tracksById[e].defaultSampleSize = t\n                }), c\n            }\n            static parseStsd(e) {\n                let r, t;\n                const i = e.subarray(8);\n                let n = We.bin2str(i.subarray(4, 8)),\n                    s = null,\n                    a = null;\n                \"enca\" === n ? (s = We.findBox(i, [\"enca\"])[0], a = s.subarray(28)) : \"encv\" === n && (s = We.findBox(i, [\"encv\"])[0], a = s.subarray(78));\n                e = !!a;\n                r = 0, a && We.findBox(a, [\"sinf\"]).forEach(e => {\n                    const t = We.findBox(e, [\"schm\"])[0];\n                    if (t) {\n                        var i = We.bin2str(t.subarray(4, 8));\n                        if (\"cbcs\" === i || \"cenc\" === i) {\n                            const t = We.findBox(e, [\"frma\"])[0];\n                            t && (n = We.bin2str(t));\n                            e = We.findBox(e, [\"schi\", \"tenc\"])[0];\n                            e && (r = e[7])\n                        }\n                    }\n                });\n                let o;\n                var l = i.subarray(86);\n                switch (n) {\n                    case \"mp4a\":\n                        t = \"mp4a.40.5\";\n                        break;\n                    case \"ac-3\":\n                    case \"ec-3\":\n                    case \"alac\":\n                    case \"fLaC\":\n                        t = n;\n                        break;\n                    case \"avc1\":\n                    case \"avc3\":\n                        t = n + \".640028\";\n                        break;\n                    case \"hvc1\":\n                    case \"hev1\":\n                        const d = We.findBox(l, [\"hvcC\"])[0];\n                        o = Ze.parseHvcC(d), t = o ? Ze.hvcCToCodecString(n, o) : n + \".2.4.H150.B0\";\n                        break;\n                    case \"dvh1\":\n                    case \"dvhe\":\n                        const r = We.findBox(l, [\"dvcC\"])[0];\n                        o = Ze.parseDvcC(r), t = o ? Ze.dvcCToCodecString(n, o) : n + \".05.01\";\n                        break;\n                    case \"c608\":\n                        t = n;\n                        break;\n                    case \"vp09\":\n                        const i = We.findBox(l, [\"vpcC\"])[0];\n                        o = Ze.parseVpcC(i), t = Ze.vpcCToCodecString(n, o);\n                        break;\n                    default:\n                        t = n\n                }\n                return {\n                    codec: t,\n                    encrypted: e,\n                    defaultPerSampleIVSize: r\n                }\n            }\n            static has32BitTfdts(e) {\n                const t = We.findBox(e, [\"moof\", \"traf\", \"tfdt\"]);\n                let i = !1;\n                return t.forEach(e => {\n                    0 === e[0] && (i = !0)\n                }), i\n            }\n            static getStartDtsTs(r, e) {\n                const t = We.findBox(e, [\"moof\", \"traf\"]);\n                let n, s = Number.MAX_SAFE_INTEGER;\n                return t.map(function(i) {\n                    return We.findBox(i, [\"tfhd\"]).forEach(e => {\n                        var t = We.readUint32(e, 4),\n                            e = r.tracksById[t];\n                        if (e) {\n                            if (!e.isTimingTrack) return 1 / 0;\n                            t = e.timescale || 9e4, e = We.findBox(i, [\"tfdt\"]).map(function(e) {\n                                let t;\n                                var i = e[0];\n                                return t = We.readUint32(e, 4), 1 === i && (t > Ye && Qe().warn(Je, `Value larger than can be represented by float for upper 32 bits ${t}`), t *= Math.pow(2, 32), t += We.readUint32(e, 8)), t\n                            }), e = 0 < e.length ? e[0] : 1 / 0;\n                            isFinite(e) && e / t < s && (s = e / t, n = {\n                                baseTime: e,\n                                timescale: t\n                            })\n                        }\n                    })\n                }), n\n            }\n            static offsetStartDTS(r, e, l, n) {\n                We.findBox(e, [\"moof\", \"traf\"]).map(function(i) {\n                    return We.findBox(i, [\"tfhd\"]).map(function(e) {\n                        const t = We.readUint32(e, 4),\n                            s = r.tracksById[t];\n                        if (s) {\n                            const a = s.timescale || 9e4,\n                                o = \"caption\" === s.type ? 0 : n;\n                            We.findBox(i, [\"tfdt\"]).map(function(t) {\n                                const i = t[0],\n                                    r = s.type;\n                                if (0 === i) {\n                                    let e = We.readUint32(t, 4) - Math.round(l.baseTime * a / l.timescale);\n                                    \"video\" === r && e < 0 && (Qe().warn(Je, `video tdft would have gone negative by ${e/a} seconds`), e = 0), e += Math.round(o * a), e = Math.max(e, 0), We.writeUint32(t, 4, e)\n                                } else {\n                                    const i = We.readUint32(t, 4);\n                                    i > Ye && Qe().error(Je, `baseMediaDecodeTime larger than can be represented by float for upper 32 bits ${i}`);\n                                    let e = i;\n                                    e *= Math.pow(2, 32), e += We.readUint32(t, 8), e -= Math.round(l.baseTime * a / l.timescale), \"video\" === r && e < 0 && (Qe().warn(Je, `video tdft would have gone negative by ${e/a} seconds`), e = 0), e += Math.round(o * a), e = Math.max(e, 0);\n                                    const n = Math.floor(e / (1 + Xe)),\n                                        s = Math.floor(e % (1 + Xe));\n                                    We.writeUint32(t, 4, n), We.writeUint32(t, 8, s)\n                                }\n                            })\n                        }\n                    })\n                })\n            }\n            static writeStartDTS(i, e, s) {\n                We.findBox(e, [\"moof\", \"traf\"]).map(function(t) {\n                    return We.findBox(t, [\"tfhd\"]).map(function(e) {\n                        e = We.readUint32(e, 4), e = i.tracksById[e];\n                        if (e) {\n                            const r = e.timescale || 9e4,\n                                n = Math.round(s * r) / r;\n                            .01 < Math.abs(n - s) && Qe().warn(Je, `[iframes] large rounding error when adjusting timestamps, startDTS: ${s}, roundedStartDTS: ${n}`), We.findBox(t, [\"tfdt\"]).map(function(e) {\n                                var t, i;\n                                0 === e[0] ? We.writeUint32(e, 4, n * r) : (i = n * r, i = Math.max(i, 0), t = Math.floor(i / (1 + Xe)), i = Math.floor(i % (1 + Xe)), We.writeUint32(e, 4, t), We.writeUint32(e, 8, i))\n                            })\n                        }\n                    })\n                })\n            }\n            static parseSAIO(e) {\n                let t = 0,\n                    i = 0;\n                var r = e[0];\n                i += 4, 0 != (1 & We.readUint32(e, 0)) && (i += 8);\n                var n = 16777215 & We.readUint32(e, i);\n                return 1 == n ? (i += 4, t = We.readUint32(e, i), 1 === r && (i += 4, t *= Math.pow(2, 32), t += We.readUint32(e, i))) : Qe().error(Je, `saio entry count error, count is: ${n}`), t\n            }\n            static parseSAIZ(e) {\n                let t = 0,\n                    i = 0;\n                return i += 4, 0 != (1 & We.readUint32(e, 0)) && (i += 8), t = e[i], i++, i += 4, 0 === t && (t = e[i]), t\n            }\n            static parseSubsample(e, t) {\n                const i = {\n                    subsamples: []\n                };\n                let r = 0;\n                for (e && (i.iv = t.subarray(0, e), r += e), r += 2; r + 6 <= t.byteLength;) {\n                    const e = We.readUint16(t, r);\n                    r += 2;\n                    var n = We.readUint32(t, r);\n                    r += 4, i.subsamples.push([e, n])\n                }\n                return i\n            }\n            static isSEIMessage(e, t) {\n                return e ? 39 === t || 40 === t : 6 === t\n            }\n            static parseCLCPSample(e, t, i) {\n                let r = 0;\n                const n = [];\n                let s = 0;\n                for (; r < i;) {\n                    var a = t + r,\n                        o = We.readUint32(e, a);\n                    a += 4;\n                    var l = We.bin2str(e.subarray(a, a + 4));\n                    if (a += 4, \"cdat\" !== l) break; {\n                        const t = o - 8,\n                            d = e.subarray(a, a + t);\n                        s += t, n.push(d), r += o\n                    }\n                }\n                return {\n                    cdatList: n,\n                    cdatTotalSize: s\n                }\n            }\n            static parseSamples(e, S, b, T, E, I) {\n                const w = b.timescale,\n                    d = b.id;\n                let A, O = e,\n                    k = 0,\n                    C = !1;\n                We.findBoxWithOffset(S, 0, [\"moof\"]).map(function(e) {\n                    const t = e.data,\n                        v = e.offset;\n                    We.findBox(t, [\"traf\"]).map(function(l) {\n                        var e = We.findBox(l, [\"tfdt\"]).map(function(e) {\n                            let t;\n                            var i = e[0];\n                            return t = We.readUint32(e, 4), 1 === i && (t *= Math.pow(2, 32), t += We.readUint32(e, 8)), t / w\n                        })[0];\n                        return void 0 !== e && (O = e), We.findBox(l, [\"tfhd\"]).map(function(e) {\n                            var t = We.readUint32(e, 4),\n                                i = 16777215 & We.readUint32(e, 0),\n                                r = 0 != (1 & i),\n                                n = 0 != (2 & i),\n                                s = 0 != (8 & i);\n                            let g = 0;\n                            var a = 0 != (16 & i);\n                            let y = 0;\n                            i = 0 != (32 & i);\n                            let o = 8;\n                            if (ne(b.defaultSampleSize) && (y = b.defaultSampleSize), t === d) {\n                                if (r && (We.readUint32(e, o), o += 4, We.readUint32(e, o), o += 4), n && (We.readUint32(e, o), o += 4), s && (g = We.readUint32(e, o), o += 4), a && (y = We.readUint32(e, o), o += 4), i && (We.readUint32(e, o), o += 4), \"video\" === b.type) {\n                                    let t = 0,\n                                        i = 0;\n                                    We.findBox(l, [\"saio\"]).map(function(e) {\n                                        t = Ze.parseSAIO(e)\n                                    }), We.findBox(l, [\"saiz\"]).map(function(e) {\n                                        i = Ze.parseSAIZ(e)\n                                    }), t && i && (A = Ze.parseSubsample(b.defaultPerSampleIVSize, S.subarray(t, t + i))), C = Ze.isHEVCFlavor(b.codec)\n                                }\n                                We.findBox(l, [\"trun\"]).map(function(i) {\n                                    var t = i[0],\n                                        e = 16777215 & We.readUint32(i, 0),\n                                        r = 0 != (1 & e);\n                                    let n = 0;\n                                    var s = 0 != (4 & e),\n                                        a = 0 != (256 & e);\n                                    let o = 0;\n                                    var l = 0 != (512 & e);\n                                    let d = 0;\n                                    var u = 0 != (1024 & e),\n                                        c = 0 != (2048 & e);\n                                    let h = 0;\n                                    var p = We.readUint32(i, 4);\n                                    let f = 8;\n                                    r && (n = We.readUint32(i, f), f += 4), s && (f += 4);\n                                    let m = n + v;\n                                    for (let e = 0; e < p && (I < 0 || k < I); e++) {\n                                        if (a ? (o = We.readUint32(i, f), f += 4) : o = g, l ? (d = We.readUint32(i, f), f += 4) : d = y, u && (f += 4), c && (h = 0 === t ? We.readUint32(i, f) : We.readSint32(i, f), f += 4), \"video\" === b.type) {\n                                            if (ne(T)) b.samples.push({\n                                                data: S.subarray(m, m + d),\n                                                size: d,\n                                                duration: T * w,\n                                                cts: 0,\n                                                flags: {\n                                                    isLeading: 0,\n                                                    isDependedOn: 0,\n                                                    hasRedundancy: 0,\n                                                    degradPrio: 0,\n                                                    dependsOn: 2,\n                                                    isNonSync: 0,\n                                                    paddingValue: 0\n                                                },\n                                                subsamples: A ? A.subsamples : [],\n                                                iv: A ? A.iv : void 0\n                                            });\n                                            else if (b.fragmentDuration += o, E) {\n                                                let e = 0;\n                                                for (; e < d;) {\n                                                    const T = We.readUint32(S, m);\n                                                    m += 4;\n                                                    const E = 31 & S[m];\n                                                    if (b.seiSamples || (b.seiSamples = []), Ze.isSEIMessage(C, E)) {\n                                                        const i = S.subarray(m, m + T);\n                                                        b.seiSamples.push({\n                                                            pts: O + h / w,\n                                                            type: E,\n                                                            data: i,\n                                                            sampleOffset: m,\n                                                            naluSize: T\n                                                        })\n                                                    }\n                                                    m += T, e += T + 4\n                                                }\n                                            }\n                                        } else if (\"audio\" === b.type) b.fragmentDuration += o;\n                                        else if (\"caption\" === b.type) {\n                                            const {\n                                                cdatList: i,\n                                                cdatTotalSize: T\n                                            } = Ze.parseCLCPSample(S, m, d);\n                                            if (m += d, i.length) {\n                                                let t;\n                                                if (1 === i.length) t = new Uint8Array(i[0]);\n                                                else if (1 < i.length) {\n                                                    let e = 0;\n                                                    t = new Uint8Array(T);\n                                                    for (const T of i) t.set(T, e), e += T.length\n                                                }\n                                                b.captionSamples.push({\n                                                    type: 3,\n                                                    pts: O,\n                                                    bytes: t\n                                                })\n                                            }\n                                        }\n                                        k++, O += o / w\n                                    }\n                                })\n                            }\n                        })\n                    })\n                })\n            }\n            static parseEmsg(e) {\n                let t, i, r, n, s, a = \"\",\n                    o = \"\",\n                    l = 0;\n                if (0 === e[0]) {\n                    for (;\n                        \"\\0\" !== We.bin2str(e.subarray(l, l + 1));) a += We.bin2str(e.subarray(l, l + 1)), l += 1;\n                    for (a += We.bin2str(e.subarray(l, l + 1)), l += 1;\n                        \"\\0\" !== We.bin2str(e.subarray(l, l + 1));) o += We.bin2str(e.subarray(l, l + 1)), l += 1;\n                    o += We.bin2str(e.subarray(l, l + 1)), l += 1, t = We.readUint32(e, 12), i = We.readUint32(e, 16), n = We.readUint32(e, 20), s = We.readUint32(e, 24), l = 28\n                } else {\n                    l += 4, t = We.readUint32(e, l), l += 4;\n                    const i = We.readUint32(e, l);\n                    l += 4;\n                    var d = We.readUint32(e, l);\n                    for (l += 4, r = Math.pow(2, 32) * i + d, Number.isSafeInteger(r) || (r = Number.MAX_SAFE_INTEGER, Qe().warn(Je, \"Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box\")), n = We.readUint32(e, l), l += 4, s = We.readUint32(e, l), l += 4;\n                        \"\\0\" !== We.bin2str(e.subarray(l, l + 1));) a += We.bin2str(e.subarray(l, l + 1)), l += 1;\n                    for (a += We.bin2str(e.subarray(l, l + 1)), l += 1;\n                        \"\\0\" !== We.bin2str(e.subarray(l, l + 1));) o += We.bin2str(e.subarray(l, l + 1)), l += 1;\n                    o += We.bin2str(e.subarray(l, l + 1)), l += 1\n                }\n                return {\n                    schemeIdUri: a,\n                    value: o,\n                    timeScale: t,\n                    presentationTime: r,\n                    presentationTimeDelta: i,\n                    eventDuration: n,\n                    id: s,\n                    payload: e.subarray(l, e.byteLength)\n                }\n            }\n            static extractID3PayloadCreateID3Track(e, t, i, r) {\n                const n = new M(e.payload, r),\n                    s = new Uint8Array(e.payload),\n                    a = s.byteLength;\n                let o = 0,\n                    l = 0;\n                var d = ne(e.presentationTime) ? e.presentationTime / e.timeScale : t + e.presentationTimeDelta / e.timeScale;\n                if (ne(d)) {\n                    const c = e.eventDuration,\n                        h = s.subarray(0, 10),\n                        p = We.bin2str(h.subarray(l, l + 3));\n                    l += 3, \"ID3\" !== p && Qe().error(Je, \"No ID3 tag found when extracting ID3 payload\"), l += 2;\n                    var t = s.subarray(l, l + 1),\n                        e = 64 & t[0],\n                        u = 16 & t[0];\n                    if (l += 1, M.readSynchSafeUint32(s.subarray(l, l + 4)), l += 4, e) {\n                        const f = M.readSynchSafeUint32(s.subarray(l, l + 4));\n                        l += 4, l += f\n                    }\n                    for (; l + 2 < a;) {\n                        We.bin2str(s.subarray(l, l + 4)), l += 4;\n                        const m = M.readSynchSafeUint32(s.subarray(l, l + 4));\n                        l += 4;\n                        const r = d + o * c,\n                            a = {\n                                data: s,\n                                pts: r,\n                                dts: r,\n                                keyTagInfo: void 0,\n                                frames: n.frames\n                            };\n                        i.id3Samples.push(a), l += m, o++, u && (\"DI3\" !== We.bin2str(s.subarray(l, l + 3)) && Qe().error(Je, \"End should be DI3 if footer present in extracting ID3 payload\"), l += 3, l += 7)\n                    }\n                    l + 2 === a && 0 !== We.readUint16(s, l) && Qe().warn(Je, \"Padding should be 0 when extracting ID3 payload\")\n                } else Qe().error(Je, \"No pts found in emsg info when extracting ID3 payload\")\n            }\n            append(e, t, i, r, n, s, a) {\n                let o = this.initData,\n                    l = 0,\n                    d = 0,\n                    u = !1,\n                    c = !1;\n                void 0 === o && (this.resetInitSegment(e, 0), o = this.initData);\n                let h, p = this.initPtsTs;\n                p || (h = Ze.getStartDtsTs(o, e), this.initPtsTs = p = {\n                    baseTime: h.baseTime - Math.round(t * h.timescale),\n                    timescale: h.timescale\n                }, this.observer.trigger(v.INIT_PTS_FOUND, {\n                    initPTS: p\n                })), o.foundLargeTimescale && Ze.has32BitTfdts(e) && !a && (e = ze.remuxOverflowSegment(e, this.logger)), h = Ze.getStartDtsTs(o, e);\n                const f = We.findBox(e, [\"emsg\"]);\n                if (o.video && o.video.encrypted && (We.findBox(e, [\"moof\", \"traf\"]).find(function(e) {\n                        return Boolean(We.findBox(e, [\"senc\"])[0] || We.findBox(e, [\"saiz\"])[0] && We.findBox(e, [\"saio\"])[0])\n                    }) || this.logger.warn(Je, `Missing subsample information for encrypted content codec=${o.videoCodec}`)), a) {\n                    const t = this._videoTrack.timescale;\n                    a = Math.ceil(a * t) / t;\n                    const i = (h.baseTime + this.audioPrimingDelay * h.timescale) / h.timescale;\n                    if (this._videoTrack && this._audioTrack && !this._silentAudioTrack) {\n                        const e = Te.getTrack(this.observer, this._audioTrack.id, this._audioTrack.codec, 2, this.logger);\n                        if (!e) throw `unable to create silent audio track for codec ${this._audioTrack.codec}`;\n                        this._silentAudioTrack = Object.assign(Object.assign({}, e), {\n                            sequenceNumber: 0\n                        });\n                        const t = ge.initSegment([this._videoTrack, this._silentAudioTrack]);\n                        this.remuxedInitDataTrack = {\n                            type: \"audiovideo\",\n                            container: \"video/mp4\",\n                            codec: this._silentAudioTrack.config.codec + \",\" + this._videoTrack.codec,\n                            initSegment: t\n                        };\n                        const i = {\n                            track: this.remuxedInitDataTrack\n                        };\n                        this.observer.trigger(v.FRAG_PARSING_INIT_SEGMENT, i)\n                    }\n                    Ze.parseSamples(i, e, this._videoTrack, a, !1, 1), this.mp4Remuxer.remuxIFrame(i, this._videoTrack, this._silentAudioTrack, a, this.remuxedInitDataTrack), this._videoTrack.samples = []\n                } else {\n                    a = (h.baseTime - this.audioPrimingDelay * h.timescale) / h.timescale, a = Math.max(0, a);\n                    if (f && 0 < f.length) {\n                        const e = f.map(e => {\n                            e = Ze.parseEmsg(e);\n                            return \"https://aomedia.org/emsg/ID3\\0\" !== e.schemeIdUri || this._id3Track || (this._id3Track = {\n                                id3Samples: [],\n                                inputTimescale: 9e4\n                            }), e\n                        });\n                        this._id3Track && e.map(e => {\n                            Ze.extractID3PayloadCreateID3Track(e, t, this._id3Track, this.logger)\n                        })\n                    }\n                    this._videoTrack && (Ze.parseSamples(a, e, this._videoTrack, void 0, this.trySEICaptions, -1), l = this._videoTrack.fragmentDuration / this._videoTrack.timescale, u = !0, this._videoTrack.fragmentDuration = 0, this.trySEICaptions ? (Ze.extractSEICaptionsFromNALu(this._videoTrack.seiSamples, this._captionTrack), this._videoTrack.seiSamples = []) : this._captionTrack && Ze.parseSamples(a, e, this._captionTrack, void 0, !1, Number.MAX_SAFE_INTEGER)), this._audioTrack && (Ze.parseSamples(a, e, this._audioTrack, void 0, !1, -1), d = this._audioTrack.fragmentDuration / this._audioTrack.timescale, c = !0, this._audioTrack.fragmentDuration = 0), this.mp4Remuxer.remuxEmsgAndRawData(d, c, l, u, this._captionTrack, this._id3Track, a, h.timescale, e, this.remuxedInitDataTrack), this._id3Track && (this._id3Track.id3Samples = [])\n                }\n            }\n            static extractSEICaptionsFromNALu(a, o) {\n                if (a) {\n                    for (let s = 0; s < a.length; ++s) {\n                        var l = a[s],\n                            d = l.pts;\n                        let t = 0;\n                        t++;\n                        let e = 0,\n                            i = 0,\n                            r = !1,\n                            n = 0;\n                        for (; !r && t < l.data.length;) {\n                            for (e = 0; !(t >= l.data.length) && (n = l.data[t++], e += n, 255 === n););\n                            for (i = 0; !(t >= l.data.length) && (n = l.data[t++], i += n, 255 === n););\n                            const a = l.data.length - t;\n                            if (4 === e && t < l.data.length) {\n                                if (r = !0, 181 === l.data[t++]) {\n                                    const a = We.readUint16(l.data, t);\n                                    if (t += 2, 49 === a) {\n                                        const a = We.readUint32(l.data, t);\n                                        if (t += 4, 1195456820 === a && 3 === l.data[t++]) {\n                                            const a = l.data[t++];\n                                            t++;\n                                            const u = 31 & a,\n                                                c = [];\n                                            if (64 & a)\n                                                for (let e = 0; e < u; e++) {\n                                                    const a = l.data[t++];\n                                                    if (a === (252 & a)) {\n                                                        const o = 3 & a;\n                                                        if (0 == o || 1 == o) {\n                                                            const a = l.data[t++],\n                                                                o = l.data[t++];\n                                                            c.push(a), c.push(o)\n                                                        }\n                                                    } else t += 2\n                                                }\n                                            0 < c.length && o.captionSamples.push({\n                                                type: 3,\n                                                pts: d,\n                                                bytes: c\n                                            })\n                                        }\n                                    }\n                                }\n                            } else if (i < a) t += i;\n                            else if (i > a) break\n                        }\n                    }\n                    return o\n                }\n            }\n        }\n        const et = {\n            name: \"ExpGolomb\"\n        };\n        class tt {\n            constructor(e, t) {\n                this.data = e, this.logger = t, this._bytesAvailable = e.byteLength, this.word = 0, this.bitsAvailable = 0\n            }\n            get bytesAvailable() {\n                return this._bytesAvailable\n            }\n            loadWord() {\n                const e = this.data,\n                    t = this._bytesAvailable,\n                    i = e.byteLength - t,\n                    r = new Uint8Array(4),\n                    n = Math.min(4, t);\n                if (0 === n) throw new Error(\"no bytes available\");\n                r.set(e.subarray(i, i + n)), this.word = new DataView(r.buffer).getUint32(0), this.bitsAvailable = 8 * n, this._bytesAvailable -= n\n            }\n            skipBits(e) {\n                var t;\n                this.bitsAvailable > e || (t = (e -= this.bitsAvailable) >> 3, e -= t >> 3, this._bytesAvailable -= t, this.loadWord()), this.word <<= e, this.bitsAvailable -= e\n            }\n            readBits(e) {\n                let t = Math.min(this.bitsAvailable, e);\n                var i = this.word >>> 32 - t;\n                return 32 < e && this.logger.error(et, \"Cannot read more than 32 bits at a time\"), this.bitsAvailable -= t, 0 < this.bitsAvailable ? this.word <<= t : 0 < this._bytesAvailable && this.loadWord(), t = e - t, 0 < t && this.bitsAvailable ? i << t | this.readBits(t) : i\n            }\n            skipLZ() {\n                let e;\n                for (e = 0; e < this.bitsAvailable; ++e)\n                    if (0 != (this.word & 2147483648 >>> e)) return this.word <<= e, this.bitsAvailable -= e, e;\n                return this.loadWord(), e + this.skipLZ()\n            }\n            skipUEG() {\n                this.skipBits(1 + this.skipLZ())\n            }\n            skipEG() {\n                this.skipBits(1 + this.skipLZ())\n            }\n            readUEG() {\n                var e = this.skipLZ();\n                return this.readBits(e + 1) - 1\n            }\n            readEG() {\n                var e = this.readUEG();\n                return 1 & e ? 1 + e >>> 1 : -1 * (e >>> 1)\n            }\n            readBoolean() {\n                return 1 === this.readBits(1)\n            }\n            readUByte() {\n                return this.readBits(8)\n            }\n            readUShort() {\n                return this.readBits(16)\n            }\n            readUInt() {\n                return this.readBits(32)\n            }\n            skipScalingList(e) {\n                let t, i, r = 8,\n                    n = 8;\n                for (t = 0; t < e; t++) 0 !== n && (i = this.readEG(), n = (r + i + 256) % 256), r = 0 === n ? r : n\n            }\n            readSPS() {\n                let e, t, i, r = 0,\n                    n = 0,\n                    s = 0,\n                    a = 0;\n                const o = this.readUByte.bind(this),\n                    l = this.readBits.bind(this),\n                    d = this.readUEG.bind(this),\n                    u = this.readBoolean.bind(this),\n                    c = this.skipBits.bind(this),\n                    h = this.skipEG.bind(this),\n                    p = this.skipUEG.bind(this),\n                    f = this.skipScalingList.bind(this);\n                o();\n                var m = o();\n                if (l(5), c(3), o(), p(), 100 === m || 110 === m || 122 === m || 244 === m || 44 === m || 83 === m || 86 === m || 118 === m || 128 === m) {\n                    const e = d();\n                    if (3 === e && c(1), p(), p(), c(1), u())\n                        for (t = 3 !== e ? 8 : 12, i = 0; i < t; i++) u() && f(i < 6 ? 16 : 64)\n                }\n                p();\n                var g = d();\n                if (0 === g) d();\n                else if (1 === g)\n                    for (c(1), h(), h(), e = d(), i = 0; i < e; i++) h();\n                p(), c(1);\n                var y = d(),\n                    m = d(),\n                    g = l(1);\n                0 === g && c(1), c(1), u() && (r = d(), n = d(), s = d(), a = d());\n                let v = [1, 1];\n                if (u() && u()) switch (o()) {\n                    case 1:\n                        v = [1, 1];\n                        break;\n                    case 2:\n                        v = [12, 11];\n                        break;\n                    case 3:\n                        v = [10, 11];\n                        break;\n                    case 4:\n                        v = [16, 11];\n                        break;\n                    case 5:\n                        v = [40, 33];\n                        break;\n                    case 6:\n                        v = [24, 11];\n                        break;\n                    case 7:\n                        v = [20, 11];\n                        break;\n                    case 8:\n                        v = [32, 11];\n                        break;\n                    case 9:\n                        v = [80, 33];\n                        break;\n                    case 10:\n                        v = [18, 11];\n                        break;\n                    case 11:\n                        v = [15, 11];\n                        break;\n                    case 12:\n                        v = [64, 33];\n                        break;\n                    case 13:\n                        v = [160, 99];\n                        break;\n                    case 14:\n                        v = [4, 3];\n                        break;\n                    case 15:\n                        v = [3, 2];\n                        break;\n                    case 16:\n                        v = [2, 1];\n                        break;\n                    case 255:\n                        v = [o() << 8 | o(), o() << 8 | o()]\n                }\n                return {\n                    width: Math.ceil(16 * (y + 1) - 2 * r - 2 * n),\n                    height: (2 - g) * (m + 1) * 16 - (g ? 2 : 4) * (s + a),\n                    pixelRatio: v\n                }\n            }\n            readSliceType() {\n                return this.readUByte(), this.readUEG(), this.readUEG()\n            }\n        }\n        const it = {\n            name: \"TS Demuxer\"\n        };\n        var rt, nt = class extends c {\n            constructor(e, t, i, r, n) {\n                super(e, t, i, r, n)\n            }\n            static probe(e, t) {\n                return 564 <= e.length && 71 === e[0] && 71 === e[188] && 71 === e[376]\n            }\n            resetInitSegment(e, t, i) {\n                this.pmtParsed = !1;\n                var r = {\n                        id: this._pmtId = -1,\n                        inputTimescale: 9e4,\n                        timescale: NaN,\n                        duration: 0,\n                        encrypted: i && i.isEncrypted,\n                        keyTagInfo: i\n                    },\n                    i = {\n                        len: 0,\n                        sequenceNumber: 0\n                    };\n                this._avcContext = {\n                    info: Object.assign({}, r),\n                    parsingData: Object.assign(Object.assign({}, i), {\n                        esSamples: new Array,\n                        dropped: 0\n                    }),\n                    config: {},\n                    container: \"video/mp2t\",\n                    type: \"video\"\n                }, this._audioContext = {\n                    info: Object.assign({}, r),\n                    parsingData: Object.assign(Object.assign({}, i), {\n                        esSamples: new Array\n                    }),\n                    container: \"video/mp2t\",\n                    type: \"audio\"\n                }, this._id3Track = {\n                    id: -1,\n                    inputTimescale: 9e4,\n                    id3Samples: []\n                }, this._txtTrack = {\n                    inputTimescale: 9e4,\n                    captionSamples: []\n                }, this._duration = t, this._initSegment = e\n            }\n            append(e, t, i, r, n, s, a) {\n                let o, l, d, u, c, h = !1;\n                this.contiguous = i;\n                const p = this._avcContext,\n                    f = this._audioContext,\n                    m = this._id3Track;\n                let g = this.pmtParsed,\n                    y = p.info.id,\n                    v = f.info.id,\n                    S = m.id,\n                    b = this._pmtId,\n                    T = p.pesData,\n                    E = f.pesData,\n                    I = m.pesData;\n                if (this.iframeMode = void 0 !== a, this._initSegment && 0 < this._initSegment.byteLength) {\n                    const t = new Uint8Array(this._initSegment.byteLength + e.byteLength);\n                    t.set(this._initSegment), t.set(e, this._initSegment.byteLength), this._initSegment = void 0, 71 === t[0] && (e = t)\n                }\n                let w, A, O = e.length;\n                for (O -= O % 188, o = 0; o < O; o += 188) {\n                    if (71 !== e[o]) {\n                        const e = new D(!1, \"TS packet did not start with 0x47\", $.NoTSSyncByteFound);\n                        return void this.observer.trigger(x.INTERNAL_ERROR, e)\n                    }\n                    if (l = !!(64 & e[o + 1]), d = ((31 & e[o + 1]) << 8) + e[o + 2], 1 < (48 & e[o + 3]) >> 4) {\n                        if (u = o + 5 + e[o + 4], u === o + 188) continue\n                    } else u = o + 4;\n                    switch (d) {\n                        case y:\n                            l && (T && (c = this._parsePES(T)) && this._parseAVCPES(c, !1), T = {\n                                data: [],\n                                size: 0,\n                                keyTagInfo: n\n                            }), T && (T.data.push(e.subarray(u, o + 188)), T.size += o + 188 - u);\n                            break;\n                        case v:\n                            if (l && !this.iframeMode) {\n                                if (E && (c = this._parsePES(E))) switch (f.segmentCodec) {\n                                    case \"aac\":\n                                        this._parseAACPES(c);\n                                        break;\n                                    case \"mp3\":\n                                        this._parseMPEGPES(c);\n                                        break;\n                                    case \"ac3\":\n                                    case \"ec3\":\n                                        this._parseDolbyPES(c)\n                                }\n                                E = {\n                                    data: [],\n                                    size: 0,\n                                    keyTagInfo: n\n                                }\n                            }\n                            E && (E.data.push(e.subarray(u, o + 188)), E.size += o + 188 - u);\n                            break;\n                        case S:\n                            l && (I && (c = this._parsePES(I)) && m.id3Samples.push(c), I = {\n                                data: [],\n                                size: 0\n                            }), I && (I.data.push(e.subarray(u, o + 188)), I.size += o + 188 - u);\n                            break;\n                        case 0:\n                            l && (u += e[u] + 1), b = this._pmtId = this._parsePAT(e, u);\n                            break;\n                        case b:\n                            l && (u += e[u] + 1);\n                            const t = this._parsePMT(e, u, this.typeSupported);\n                            y = t.avcId, 0 < y && (p.info.id = y, p.info.encrypted = t.videoEncrypted), v = t.audioId, 0 < v && (f.info.id = v, f.segmentCodec = t.audioSegmentCodec, f.info.encrypted = t.audioEncrypted), S = t.id3Id, 0 < S && (m.id = S), h && !g && (h = !1, o = -188), g = this.pmtParsed = !0;\n                            break;\n                        case 17:\n                        case 8191:\n                            break;\n                        default:\n                            h = !0\n                    }\n                }\n                if (T && (c = this._parsePES(T)) ? (this._parseAVCPES(c, !0), p.pesData = void 0) : p.pesData = T, E && (c = this._parsePES(E))) {\n                    switch (f.segmentCodec) {\n                        case \"aac\":\n                            this._parseAACPES(c);\n                            break;\n                        case \"mp3\":\n                            this._parseMPEGPES(c);\n                            break;\n                        case \"ac3\":\n                        case \"ec3\":\n                            this._parseDolbyPES(c)\n                    }\n                    f.pesData = void 0\n                } else E && E.size && this.logger.warn(it, \"last AAC PES packet truncated,might overlap between fragments\"), f.pesData = E;\n                I && (c = this._parsePES(I)) ? (m.id3Samples.push(c), m.pesData = void 0) : m.pesData = I, f.config && f.segmentCodec && (w = {\n                    type: \"audio\",\n                    info: f.info,\n                    config: f.config,\n                    parsingData: f.parsingData\n                });\n                var k, C = p.config;\n                \"string\" == typeof(k = C).codec && Array.isArray(k.sps) && Array.isArray(k.pps) && \"number\" == typeof k.width && \"number\" == typeof k.height && Array.isArray(k.pixelRatio) && (A = {\n                    type: \"video\",\n                    info: p.info,\n                    config: C,\n                    parsingData: p.parsingData\n                }), this.esRemuxer.remuxEsTracks(w, A, m, this._txtTrack, t, i, r, n, s, a)\n            }\n            destroy() {\n                this._duration = 0\n            }\n            _parsePAT(e, t) {\n                return (31 & e[t + 10]) << 8 | e[t + 11]\n            }\n            _parsePMT(e, t, i) {\n                var r;\n                const n = {\n                        audioId: -1,\n                        avcId: -1,\n                        id3Id: -1,\n                        audioEncrypted: !1,\n                        videoEncrypted: !1\n                    },\n                    s = t + 3 + ((15 & e[t + 1]) << 8 | e[t + 2]) - 4;\n                for (t += 12 + ((15 & e[t + 10]) << 8 | e[t + 11]); t < s;) {\n                    switch (r = (31 & e[t + 1]) << 8 | e[t + 2], e[t]) {\n                        case 207:\n                            n.audioEncrypted = !0;\n                        case 15:\n                            -1 === n.audioId && (n.audioId = r, n.audioSegmentCodec = \"aac\");\n                            break;\n                        case 21:\n                            -1 === n.id3Id && (n.id3Id = r);\n                            break;\n                        case 219:\n                            n.videoEncrypted = !0;\n                        case 27:\n                            -1 === n.avcId && (n.avcId = r);\n                            break;\n                        case 3:\n                        case 4:\n                            !0 !== i.mpeg && !0 !== i.mp3 ? this.logger.warn(it, \"MPEG audio found, not supported in this browser for now\") : -1 === n.audioId && (n.audioId = r, n.audioSegmentCodec = \"mp3\");\n                            break;\n                        case 193:\n                            n.audioEncrypted = !0;\n                        case 129:\n                            !0 !== i.ac3 ? this.logger.warn(it, \"AC-3 audio found, not supported in this browser for now\") : -1 === n.audioId && (n.audioId = r, n.audioSegmentCodec = \"ac3\");\n                            break;\n                        case 194:\n                            n.audioEncrypted = !0;\n                        case 135:\n                            !0 !== i.ec3 ? this.logger.warn(it, \"EC-3 audio found, not supported in this browser for now\") : -1 === n.audioId && (n.audioId = r, n.audioSegmentCodec = \"ec3\");\n                            break;\n                        case 36:\n                            this.logger.warn(it, \"HEVC stream type found, not supported for now\");\n                            break;\n                        default:\n                            this.logger.warn(it, \"unkown stream type:\" + e[t])\n                    }\n                    t += 5 + ((15 & e[t + 3]) << 8 | e[t + 4])\n                }\n                return n\n            }\n            _parsePES(e) {\n                let i, t, r, n, s, a, o = 0;\n                const l = e.data,\n                    d = e.keyTagInfo;\n                let u = NaN,\n                    c = NaN;\n                if (e && 0 !== e.size) {\n                    for (; l[0].length < 19 && 1 < l.length;) {\n                        const e = new Uint8Array(l[0].length + l[1].length);\n                        e.set(l[0]), e.set(l[1], l[0].length), l[0] = e, l.splice(1, 1)\n                    }\n                    if (i = l[0], 1 === (i[0] << 16) + (i[1] << 8) + i[2] && (r = (i[4] << 8) + i[5], !(r && r > e.size - 6))) {\n                        192 & (t = i[7]) && (u = 536870912 * (14 & i[9]) + 4194304 * (255 & i[10]) + 16384 * (254 & i[11]) + 128 * (255 & i[12]) + (254 & i[13]) / 2, 64 & t ? (c = 536870912 * (14 & i[14]) + 4194304 * (255 & i[15]) + 16384 * (254 & i[16]) + 128 * (255 & i[17]) + (254 & i[18]) / 2, 54e5 < u - c && (this.logger.warn(it, `${Math.round((u-c)/9e4)}s delta between PTS and DTS, align them`), u = c)) : c = u), n = i[8], a = n + 9, e.size -= a, s = new Uint8Array(e.size);\n                        for (let t = 0, e = l.length; t < e; t++) {\n                            i = l[t];\n                            let e = i.byteLength;\n                            if (a) {\n                                if (a > e) {\n                                    a -= e;\n                                    continue\n                                }\n                                i = i.subarray(a), e -= a, a = 0\n                            }\n                            s.set(i, o), o += e\n                        }\n                        return r && (r -= n + 3), {\n                            data: s,\n                            pts: u,\n                            dts: c,\n                            len: r,\n                            keyTagInfo: d\n                        }\n                    }\n                }\n            }\n            pushAccesUnit(e, t) {\n                const i = e.avcSample;\n                if (i && i.units.length && i.frame) {\n                    const r = e.parsingData.esSamples,\n                        n = r.length;\n                    (!0 === i.key || e.config.sps && (n || this.contiguous)) && (i.id = n, i.keyTagInfo = t, e.info.encrypted) && i.units.forEach(e => {\n                        if (48 < e.data.byteLength) switch (e.type) {\n                            case 1:\n                            case 5:\n                                e.data = this.discardEPB(e.data)\n                        }\n                    }), n || isFinite(i.pts) ? r.push(i) : e.parsingData.dropped++\n                }\n            }\n            _parseAVCPES(o, e) {\n                if (!o.data) throw \"invalid pes data\";\n                const l = this._avcContext,\n                    t = this._parseAVCNALu(o.data);\n                let d, u, c, h = l.avcSample;\n                const p = o.keyTagInfo;\n                o.data = void 0, t.forEach(n => {\n                    switch (n.type) {\n                        case 1:\n                            if (h && !this.iframeMode) {\n                                u = !0, h.frame = !0;\n                                const o = n.data;\n                                if (4 < o.length) {\n                                    const n = new tt(o, this.logger).readSliceType();\n                                    2 !== n && 4 !== n && 7 !== n && 9 !== n || (h.key = !0)\n                                }\n                            }\n                            break;\n                        case 5:\n                            u = !0, h && (h = h || (l.avcSample = this._createAVCSample(!0, o.pts, o.dts, \"\")), h.key = !0, h.frame = !0);\n                            break;\n                        case 6:\n                            u = !0, d = new tt(this.discardEPB(n.data), this.logger), d.readUByte();\n                            let e = 0,\n                                t = 0,\n                                i = !1,\n                                r = 0;\n                            for (; !i && 1 < d.bytesAvailable;) {\n                                for (e = 0; r = d.readUByte(), e += r, 255 === r;);\n                                for (t = 0; r = d.readUByte(), t += r, 255 === r;);\n                                if (4 === e && 0 !== d.bytesAvailable) {\n                                    if (i = !0, 181 === d.readUByte() && 49 === d.readUShort() && 1195456820 === d.readUInt() && 3 === d.readUByte()) {\n                                        const n = d.readUByte(),\n                                            l = 31 & n,\n                                            s = [n, d.readUByte()];\n                                        for (c = 0; c < l; c++) s.push(d.readUByte()), s.push(d.readUByte()), s.push(d.readUByte());\n                                        this._insertSampleInOrder(this._txtTrack.captionSamples, {\n                                            type: 3,\n                                            pts: o.pts,\n                                            bytes: s\n                                        })\n                                    }\n                                } else if (t < d.bytesAvailable)\n                                    for (c = 0; c < t; c++) d.readUByte()\n                            }\n                            break;\n                        case 7:\n                            if (u = !0, !l.config.sps) {\n                                d = new tt(n.data, this.logger);\n                                const o = d.readSPS();\n                                l.config.width = o.width, l.config.height = o.height, l.config.pixelRatio = o.pixelRatio, l.config.sps = [n.data], l.info.duration = this._duration;\n                                const a = n.data.subarray(1, 4);\n                                let t = \"avc1.\";\n                                for (c = 0; c < 3; c++) {\n                                    let e = a[c].toString(16);\n                                    e.length < 2 && (e = \"0\" + e), t += e\n                                }\n                                l.config.codec = t\n                            }\n                            break;\n                        case 8:\n                            u = !0, l.config.pps || (l.config.pps = [n.data]);\n                            break;\n                        case 9:\n                            u = !1, h && this.pushAccesUnit(l, p), h = l.avcSample = this._createAVCSample(!1, o.pts, o.dts, \"\");\n                            break;\n                        case 12:\n                            u = !1;\n                            break;\n                        default:\n                            u = !1, h && (h.debug += \"unknown NAL \" + n.type + \" \")\n                    }\n                    h && u && h.units.push(n)\n                }), e && h && (this.pushAccesUnit(l, p), l.avcSample = void 0)\n            }\n            _createAVCSample(e, t, i, r) {\n                return {\n                    id: NaN,\n                    key: e,\n                    pts: t,\n                    dts: i,\n                    units: new Array,\n                    debug: r\n                }\n            }\n            _insertSampleInOrder(t, i) {\n                var r = t.length;\n                if (0 < r) {\n                    if (i.pts >= t[r - 1].pts) t.push(i);\n                    else\n                        for (let e = r - 1; 0 <= e; e--)\n                            if (i.pts < t[e].pts) {\n                                t.splice(e, 0, i);\n                                break\n                            }\n                } else t.push(i)\n            }\n            _getLastNalUnit() {\n                const e = this._avcContext;\n                let t, i = e.avcSample;\n                if (!i || 0 === i.units.length) {\n                    const t = e.parsingData.esSamples;\n                    i = t[t.length - 1]\n                }\n                if (i) {\n                    const e = i.units;\n                    t = e[e.length - 1]\n                }\n                return t\n            }\n            _parseAVCNALu(e) {\n                const t = e.byteLength;\n                let i, r, n = 0;\n                const s = this._avcContext;\n                let a = s.naluState || 0;\n                const o = a,\n                    l = [];\n                let d, u, c, h = -1;\n                for (-1 === a && (h = 0, c = 31 & e[0], a = 0, n = 1); n < t;)\n                    if (i = e[n++], a)\n                        if (1 !== a)\n                            if (i)\n                                if (1 === i) {\n                                    if (0 <= h) d = {\n                                        data: e.subarray(h, n - a - 1),\n                                        type: c\n                                    }, l.push(d);\n                                    else {\n                                        const t = this._getLastNalUnit();\n                                        if (t && (o && n <= 4 - o && t.state && (t.data = t.data.subarray(0, t.data.byteLength - o)), r = n - a - 1, 0 < r)) {\n                                            const i = new Uint8Array(t.data.byteLength + r);\n                                            i.set(t.data, 0), i.set(e.subarray(0, r), t.data.byteLength), t.data = i, t.state = 0\n                                        }\n                                    }\n                                    a = n < t ? (u = 31 & e[n], h = n, c = u, 0) : -1\n                                } else a = 0;\n                else a = 3;\n                else a = i ? 0 : 2;\n                else a = i ? 0 : 1;\n                if (0 <= h && 0 <= a && (d = {\n                        data: e.subarray(h, t),\n                        type: c,\n                        state: a\n                    }, l.push(d)), 0 === l.length) {\n                    const t = this._getLastNalUnit();\n                    if (t) {\n                        const i = new Uint8Array(t.data.byteLength + e.byteLength);\n                        i.set(t.data, 0), i.set(e, t.data.byteLength), t.data = i\n                    }\n                }\n                return s.naluState = a, l\n            }\n            discardEPB(e) {\n                const t = e.byteLength,\n                    i = [];\n                let r = 1;\n                for (; r < t - 2;) 0 === e[r] && 0 === e[r + 1] && 3 === e[r + 2] ? (i.push(r + 2), r += 2) : r++;\n                if (0 === i.length) return e;\n                const n = t - i.length,\n                    s = new Uint8Array(n);\n                let a = 0;\n                for (r = 0; r < n; a++, r++) a === i[0] && (a++, i.shift()), s[r] = e[a];\n                return s\n            }\n            _parseAACPES(e) {\n                const t = this._audioContext,\n                    i = t.audioLastPTS,\n                    r = e.keyTagInfo;\n                let n, s, a, o, l, d, u, c = e.data,\n                    h = e.pts,\n                    p = t.audioOverFlow;\n                if (p) {\n                    const e = new Uint8Array(p.byteLength + c.byteLength);\n                    e.set(p, 0), e.set(c, p.byteLength), c = e\n                }\n                for (a = 0, d = c.length; a < d - 1 && (255 !== c[a] || 240 != (240 & c[a + 1])); a++);\n                if (a) {\n                    let e, t, i;\n                    i = a < d - 1 ? (e = `AAC PES did not start with ADTS header,offset:${a}`, t = !1, $.PESDidNotStartWithADTS) : (e = \"no ADTS header found in AAC PES\", t = !0, $.NoADTSHeaderInPES), this.logger.warn(it, `parsing error:${e}`);\n                    const r = new D(t, e, i);\n                    if (this.observer.trigger(x.INTERNAL_ERROR, r), t) return\n                }\n                if (!t.config) {\n                    const e = E(this.observer, c, a, void 0, this.logger);\n                    if (!e) throw \"unable to parse adts header\";\n                    t.config = e\n                }\n                s = 0;\n                var f = 9216e4 / t.config.samplerate;\n                if (p && i) {\n                    const e = i + f;\n                    1 < Math.abs(e - h) && (h = e)\n                }\n                for (; a + 5 < d && (o = 1 & c[a + 1] ? 7 : 9, n = (3 & c[a + 3]) << 11 | c[a + 4] << 3 | (224 & c[a + 5]) >>> 5, n -= o, 0 < n && a + o + n <= d);)\n                    for (l = h + s * f, u = {\n                            unit: c.subarray(a + o, a + o + n),\n                            pts: l,\n                            dts: l,\n                            keyTagInfo: r\n                        }, t.parsingData.esSamples.push(u), t.parsingData.len += n, a += n + o, s++; a < d - 1 && (255 !== c[a] || 240 != (240 & c[a + 1])); a++);\n                p = a < d ? c.subarray(a, d) : void 0, t.audioOverFlow = p, t.audioLastPTS = l\n            }\n            _parseMPEGPES(e) {\n                \"mp3\" === this._audioContext.segmentCodec && ee.parse(this._audioContext.parsingData, e.data, 0, e.pts, this.logger)\n            }\n            _parseDolbyPES(e) {\n                const t = this._audioContext;\n                let i = e.data,\n                    r = e.pts;\n                var n = e.keyTagInfo;\n                let s = 0,\n                    a = 0,\n                    o = t.audioOverFlow;\n                e = t.audioLastPTS;\n                if (!t.config) {\n                    let e;\n                    if (\"ac3\" === t.segmentCodec ? e = j(this.observer, i, a, this.logger) : \"ec3\" === t.segmentCodec && (e = Y(this.observer, i, a, this.logger)), !e) throw \"unable to parse dolby header\";\n                    t.config = e\n                }\n                if (\"ac3\" !== t.config.segmentCodec && \"ec3\" !== t.config.segmentCodec) throw \"unexpected config type\";\n                var l = 1536 / t.config.samplerate * t.info.inputTimescale;\n                if (o) {\n                    const c = new Uint8Array(o.byteLength + i.byteLength);\n                    c.set(o, 0), c.set(i, o.byteLength), i = c\n                }\n                var d = i.length;\n                if (o && e) {\n                    const c = e + l;\n                    1 < Math.abs(c - r) && (r = c)\n                }\n                let u = 0;\n                for (; a + u <= d;) {\n                    if (11 !== i[a] || 119 !== i[a + 1]) {\n                        const c = new D(!0, \"invalid dolby audio magic\", $.InvalidDolbyAudioMagic);\n                        return void this.observer.trigger(x.INTERNAL_ERROR, c)\n                    }\n                    \"ac3\" === t.segmentCodec ? u = Q(this.observer, i, a) : \"ec3\" === t.segmentCodec && (u = X(this.observer, i, a, this.logger));\n                    const c = r + s * l;\n                    t.audioLastPTS = c;\n                    const o = {\n                        unit: i.subarray(a, a + u),\n                        pts: c,\n                        dts: c,\n                        keyTagInfo: n\n                    };\n                    t.parsingData.esSamples.push(o), t.info.duration = this._duration, t.parsingData.len += u, a += u, s++\n                }\n                o = a < d ? i.subarray(a, d) : void 0, t.audioOverFlow = o\n            }\n        };\n        class st extends a {\n            constructor(e, t, i, r) {\n                super(), this.typeSupported = e, this.config = t, this.vendor = i, this.logger = r\n            }\n            destroy() {\n                this.removeAllListeners();\n                const e = this.demuxer,\n                    t = this.remuxer;\n                e && e.destroy(), t && t.destroy()\n            }\n            push(t, i, r, n, s, a, o, l, d, u, c, h) {\n                if (t) {\n                    let e = this.demuxer;\n                    var p = new Uint8Array(t);\n                    if (!e || (s || a) && !this.probeFn(p, this.logger)) {\n                        const {\n                            typeSupported: t,\n                            config: i\n                        } = this, r = [{\n                            demux: Ze,\n                            remux: ze\n                        }, {\n                            demux: nt,\n                            remux: Ee\n                        }, {\n                            demux: J,\n                            remux: Ee\n                        }, {\n                            demux: z,\n                            remux: Ee\n                        }, {\n                            demux: K,\n                            remux: Ee\n                        }, {\n                            demux: ie,\n                            remux: Ee\n                        }];\n                        for (const n of r) {\n                            const r = n.demux[\"probe\"];\n                            if (r(p, this.logger)) {\n                                this.remuxer = new n.remux(this, i, t, this.vendor, this.logger), e = new n.demux(this, this.remuxer, i, t, this.logger), this.probeFn = r;\n                                break\n                            }\n                        }\n                        if (!e) {\n                            const t = new D(!0, \"no demux matching with content found\", $.DemuxerNotFound);\n                            return void this.trigger(x.INTERNAL_ERROR, t)\n                        }\n                        this.demuxer = e\n                    }\n                    const f = this.remuxer,\n                        m = !this.lastKeyTagInfo || i && \"NONE\" !== i.method && this.lastKeyTagInfo.uri !== i.uri;\n                    if (this.lastKeyTagInfo = i, (s || a || m) && (e.resetInitSegment(new Uint8Array(r), l, i, s), f.resetInitSegment()), s) {\n                        const t = u ? S(u) : void 0;\n                        e.resetTimeStamp(t), f.resetTimeStamp(t)\n                    }\n                    e.append(p, n, o, d, i, c, h)\n                }\n            }\n        }\n\n        function at() {\n            let e = `${Date.now()}-${Math.random()}`;\n            return \"undefined\" != typeof performance && \"function\" == typeof performance.now && (e += `-${performance.now()}`), e\n        }\n        class ot {\n            constructor(e, t) {\n                this.rpc = e, this.logger = t, this.init = (t, n, s) => e => {\n                    const i = at(),\n                        r = this.demuxers[i] = new st(t, n, s, this.logger);\n                    [v.INIT_PTS_FOUND, v.FRAG_PARSING_INIT_SEGMENT, v.FRAG_PARSING_DATA, v.FRAG_PARSED, x.INTERNAL_ERROR].forEach(t => {\n                        r.on(t, e => this.rpc.invoke(\"demuxer.event\", [i, t, e])(() => {}))\n                    }), e(i)\n                }, this.push = (i, r, n, s, a, o, l, d, u, c, h, p, f) => e => {\n                    const t = this.demuxers[i];\n                    t ? (t.push(r, n, s, a, o, l, d, u, c, h, p, f), e()) : e(void 0, `Demuxer with id \"${i}\" does not exist on push`)\n                }, this.destroy = i => e => {\n                    const t = this.demuxers[i];\n                    t ? (t.destroy(), delete this.demuxers[i], e()) : this.logger.error(`Demuxer with id \"${i}\" does not exist on destroy`)\n                }, this.demuxers = {}, e.register(\"demuxer.init\", this.init), e.register(\"demuxer.push\", this.push), e.register(\"demuxer.destroy\", this.destroy)\n            }\n        }\n        class lt {\n            constructor(e) {\n                this.worker = e, this.handlers = {}, this.deferers = {}, this._messageHandler = e => {\n                    var {\n                        type: t,\n                        id: i,\n                        command: r,\n                        args: n,\n                        result: e,\n                        error: s\n                    } = e.data;\n                    if (t === rt.Invoke) try {\n                        if (null == this.handlers[r]) throw new Error(`command ${r} not found`);\n                        this.handlers[r](...n)(this._respond.bind(this, i, r))\n                    } catch (s) {\n                        this._respond(i, r, null, new Error(`command ${r} not found`))\n                    } else t === rt.Result && null != this.deferers[i] && (this.deferers[i](e, s), delete this.deferers[i])\n                }, e.addEventListener(\"message\", this._messageHandler)\n            }\n            register(e, t) {\n                if (null != this.handlers[e]) return !1;\n                this.handlers[e] = t\n            }\n            unregister(e) {\n                if (null != this.handlers[e]) return !1;\n                delete this.handlers[e]\n            }\n            invoke(i, r, n) {\n                return (e = lt._fallbackCallback) => {\n                    var t = at();\n                    this.deferers[t] = e;\n                    t = {\n                        type: rt.Invoke,\n                        id: t,\n                        command: i,\n                        args: r\n                    };\n                    this._send(t, n)\n                }\n            }\n            teardown(e) {\n                this.worker.removeEventListener(\"message\", this._messageHandler), e()\n            }\n            _respond(e, t, i, r, n) {\n                r instanceof Error && (r = `[${r.name}] ${r.message}\\n${r.stack}`);\n                r = {\n                    type: rt.Result,\n                    id: e,\n                    command: t,\n                    result: i,\n                    error: r\n                };\n                this._send(r, n)\n            }\n            _send(e, t = []) {\n                this.worker.postMessage(e, t.map(e => ArrayBuffer.isView(e) ? e.buffer : e).filter(e => void 0 !== e))\n            }\n        }\n        lt._fallbackCallback = (e, t) => {\n            if (null != t) throw t\n        }, (vr = rt = rt || {})[vr.Invoke = 0] = \"Invoke\", vr[vr.Result = 1] = \"Result\", ArrayBuffer.isView || (ArrayBuffer.isView = function(e) {\n            return null !== e && \"object\" == typeof e && e.buffer instanceof ArrayBuffer\n        }), void 0 !== Yy && Yy && (Vr = new lt(l), iu = (n => {\n            const t = (i = []) => {\n                const r = {};\n                return [\"fatal\", \"error\", \"warn\", \"info\", \"debug\", \"trace\", \"qe\"].forEach(e => {\n                    return r[e] = (t = e, (...e) => {\n                        n.invoke(\"logger.log\", [i, t, ...e])((e, t) => {\n                            if (null != t) throw t\n                        })\n                    });\n                    var t\n                }), r.child = e => t([...i, e]), r\n            };\n            return t()\n        })(Vr), new i(Vr, iu), new ot(Vr, iu));\n        var dt = function(e, t) {\n            return (dt = Object.setPrototypeOf || {\n                    __proto__: []\n                }\n                instanceof Array && function(e, t) {\n                    e.__proto__ = t\n                } || function(e, t) {\n                    for (var i in t) Object.prototype.hasOwnProperty.call(t, i) && (e[i] = t[i])\n                })(e, t)\n        };\n\n        function ut(e, t) {\n            if (\"function\" != typeof t && null !== t) throw new TypeError(\"Class extends value \" + String(t) + \" is not a constructor or null\");\n\n            function i() {\n                this.constructor = e\n            }\n            dt(e, t), e.prototype = null === t ? Object.create(t) : (i.prototype = t.prototype, new i)\n        }\n        var ct = function() {\n            return (ct = Object.assign || function(e) {\n                for (var t, i = 1, r = arguments.length; i < r; i++)\n                    for (var n in t = arguments[i]) Object.prototype.hasOwnProperty.call(t, n) && (e[n] = t[n]);\n                return e\n            }).apply(this, arguments)\n        };\n\n        function ht(e, t, i, r) {\n            var n, s = arguments.length,\n                a = s < 3 ? t : null === r ? r = Object.getOwnPropertyDescriptor(t, i) : r;\n            if (\"object\" == typeof Reflect && \"function\" == typeof Reflect.decorate) a = Reflect.decorate(e, t, i, r);\n            else\n                for (var o = e.length - 1; 0 <= o; o--)(n = e[o]) && (a = (s < 3 ? n(a) : 3 < s ? n(t, i, a) : n(t, i)) || a);\n            return 3 < s && a && Object.defineProperty(t, i, a), a\n        }\n\n        function pt(e, t) {\n            if (\"object\" == typeof Reflect && \"function\" == typeof Reflect.metadata) return Reflect.metadata(e, t)\n        }\n\n        function ft(e) {\n            var t = \"function\" == typeof Symbol && Symbol.iterator,\n                i = t && e[t],\n                r = 0;\n            if (i) return i.call(e);\n            if (e && \"number\" == typeof e.length) return {\n                next: function() {\n                    return {\n                        value: (e = e && r >= e.length ? void 0 : e) && e[r++],\n                        done: !e\n                    }\n                }\n            };\n            throw new TypeError(t ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\")\n        }\n\n        function mt(e, t) {\n            var i = \"function\" == typeof Symbol && e[Symbol.iterator];\n            if (!i) return e;\n            var r, n, s = i.call(e),\n                a = [];\n            try {\n                for (;\n                    (void 0 === t || 0 < t--) && !(r = s.next()).done;) a.push(r.value)\n            } catch (e) {\n                n = {\n                    error: e\n                }\n            } finally {\n                try {\n                    r && !r.done && (i = s.return) && i.call(s)\n                } finally {\n                    if (n) throw n.error\n                }\n            }\n            return a\n        }\n\n        function gt() {\n            for (var e = [], t = 0; t < arguments.length; t++) e = e.concat(mt(arguments[t]));\n            return e\n        }\n\n        function yt(e) {\n            return \"function\" == typeof e\n        }\n        var vt = !1,\n            St = {\n                Promise: void 0,\n                set useDeprecatedSynchronousErrorHandling(e) {\n                    vt = e\n                },\n                get useDeprecatedSynchronousErrorHandling() {\n                    return vt\n                }\n            };\n\n        function bt(e) {\n            setTimeout(function() {\n                throw e\n            }, 0)\n        }\n        var Tt = {\n                closed: !0,\n                next: function(e) {},\n                error: function(e) {\n                    if (St.useDeprecatedSynchronousErrorHandling) throw e;\n                    bt(e)\n                },\n                complete: function() {}\n            },\n            Et = Array.isArray || function(e) {\n                return e && \"number\" == typeof e.length\n            };\n\n        function It(e) {\n            return null !== e && \"object\" == typeof e\n        }\n        var wt = (kt.prototype = Object.create(Error.prototype), kt),\n            At = (Ot.prototype.unsubscribe = function() {\n                var t;\n                if (!this.closed) {\n                    var e = this._parentOrParents,\n                        i = this._ctorUnsubscribe,\n                        r = this._unsubscribe,\n                        n = this._subscriptions;\n                    if (this.closed = !0, this._parentOrParents = null, this._subscriptions = null, e instanceof Ot) e.remove(this);\n                    else if (null !== e)\n                        for (var s = 0; s < e.length; ++s) e[s].remove(this);\n                    if (yt(r)) {\n                        i && (this._unsubscribe = void 0);\n                        try {\n                            r.call(this)\n                        } catch (e) {\n                            t = e instanceof wt ? Ct(e.errors) : [e]\n                        }\n                    }\n                    if (Et(n))\n                        for (var s = -1, a = n.length; ++s < a;) {\n                            var o = n[s];\n                            if (It(o)) try {\n                                o.unsubscribe()\n                            } catch (e) {\n                                t = t || [], e instanceof wt ? t = t.concat(Ct(e.errors)) : t.push(e)\n                            }\n                        }\n                    if (t) throw new wt(t)\n                }\n            }, Ot.prototype.add = function(e) {\n                var t, i = e;\n                if (!e) return Ot.EMPTY;\n                switch (typeof e) {\n                    case \"function\":\n                        i = new Ot(e);\n                    case \"object\":\n                        if (i === this || i.closed || \"function\" != typeof i.unsubscribe) return i;\n                        if (this.closed) return i.unsubscribe(), i;\n                        i instanceof Ot || (t = i, (i = new Ot)._subscriptions = [t]);\n                        break;\n                    default:\n                        throw new Error(\"unrecognized teardown \" + e + \" added to Subscription.\")\n                }\n                var r = i._parentOrParents;\n                if (null === r) i._parentOrParents = this;\n                else if (r instanceof Ot) {\n                    if (r === this) return i;\n                    i._parentOrParents = [r, this]\n                } else {\n                    if (-1 !== r.indexOf(this)) return i;\n                    r.push(this)\n                }\n                r = this._subscriptions;\n                return null === r ? this._subscriptions = [i] : r.push(i), i\n            }, Ot.prototype.remove = function(e) {\n                var t = this._subscriptions;\n                !t || -1 !== (e = t.indexOf(e)) && t.splice(e, 1)\n            }, Ot.EMPTY = ((dl = new Ot).closed = !0, dl), Ot);\n\n        function Ot(e) {\n            this.closed = !1, this._parentOrParents = null, this._subscriptions = null, e && (this._ctorUnsubscribe = !0, this._unsubscribe = e)\n        }\n\n        function kt(e) {\n            return Error.call(this), this.message = e ? e.length + \" errors occurred during unsubscription:\\n\" + e.map(function(e, t) {\n                return t + 1 + \") \" + e.toString()\n            }).join(\"\\n  \") : \"\", this.name = \"UnsubscriptionError\", this.errors = e, this\n        }\n\n        function Ct(e) {\n            return e.reduce(function(e, t) {\n                return e.concat(t instanceof wt ? t.errors : t)\n            }, [])\n        }\n        var Dt, Mt, xt = \"function\" == typeof Symbol ? Symbol(\"rxSubscriber\") : \"@@rxSubscriber_\" + Math.random(),\n            Pt = (ut(_t, Mt = At), _t.prototype[xt] = function() {\n                return this\n            }, _t.create = function(e, t, i) {\n                i = new _t(e, t, i);\n                return i.syncErrorThrowable = !1, i\n            }, _t.prototype.next = function(e) {\n                this.isStopped || this._next(e)\n            }, _t.prototype.error = function(e) {\n                this.isStopped || (this.isStopped = !0, this._error(e))\n            }, _t.prototype.complete = function() {\n                this.isStopped || (this.isStopped = !0, this._complete())\n            }, _t.prototype.unsubscribe = function() {\n                this.closed || (this.isStopped = !0, Mt.prototype.unsubscribe.call(this))\n            }, _t.prototype._next = function(e) {\n                this.destination.next(e)\n            }, _t.prototype._error = function(e) {\n                this.destination.error(e), this.unsubscribe()\n            }, _t.prototype._complete = function() {\n                this.destination.complete(), this.unsubscribe()\n            }, _t.prototype._unsubscribeAndRecycle = function() {\n                var e = this._parentOrParents;\n                return this._parentOrParents = null, this.unsubscribe(), this.closed = !1, this.isStopped = !1, this._parentOrParents = e, this\n            }, _t),\n            Rt = (ut(Lt, Dt = Pt), Lt.prototype.next = function(e) {\n                var t;\n                !this.isStopped && this._next && (t = this._parentSubscriber, St.useDeprecatedSynchronousErrorHandling && t.syncErrorThrowable ? this.__tryOrSetError(t, this._next, e) && this.unsubscribe() : this.__tryOrUnsub(this._next, e))\n            }, Lt.prototype.error = function(e) {\n                if (!this.isStopped) {\n                    var t = this._parentSubscriber,\n                        i = St.useDeprecatedSynchronousErrorHandling;\n                    if (this._error) i && t.syncErrorThrowable ? this.__tryOrSetError(t, this._error, e) : this.__tryOrUnsub(this._error, e), this.unsubscribe();\n                    else if (t.syncErrorThrowable) i ? (t.syncErrorValue = e, t.syncErrorThrown = !0) : bt(e), this.unsubscribe();\n                    else {\n                        if (this.unsubscribe(), i) throw e;\n                        bt(e)\n                    }\n                }\n            }, Lt.prototype.complete = function() {\n                var e, t, i = this;\n                this.isStopped || (e = this._parentSubscriber, this._complete && (t = function() {\n                    return i._complete.call(i._context)\n                }, St.useDeprecatedSynchronousErrorHandling && e.syncErrorThrowable ? this.__tryOrSetError(e, t) : this.__tryOrUnsub(t)), this.unsubscribe())\n            }, Lt.prototype.__tryOrUnsub = function(e, t) {\n                try {\n                    e.call(this._context, t)\n                } catch (e) {\n                    if (this.unsubscribe(), St.useDeprecatedSynchronousErrorHandling) throw e;\n                    bt(e)\n                }\n            }, Lt.prototype.__tryOrSetError = function(e, t, i) {\n                if (!St.useDeprecatedSynchronousErrorHandling) throw new Error(\"bad call\");\n                try {\n                    t.call(this._context, i)\n                } catch (t) {\n                    return St.useDeprecatedSynchronousErrorHandling ? (e.syncErrorValue = t, e.syncErrorThrown = !0) : bt(t), !0\n                }\n                return !1\n            }, Lt.prototype._unsubscribe = function() {\n                var e = this._parentSubscriber;\n                this._context = null, this._parentSubscriber = null, e.unsubscribe()\n            }, Lt);\n\n        function Lt(e, t, i, r) {\n            var n, s = Dt.call(this) || this;\n            s._parentSubscriber = e;\n            e = s;\n            return yt(t) ? n = t : t && (n = t.next, i = t.error, r = t.complete, t !== Tt && (yt((e = Object.create(t)).unsubscribe) && s.add(e.unsubscribe.bind(e)), e.unsubscribe = s.unsubscribe.bind(s))), s._context = e, s._next = n, s._error = i, s._complete = r, s\n        }\n\n        function _t(e, t, i) {\n            var r = Mt.call(this) || this;\n            switch (r.syncErrorValue = null, r.syncErrorThrown = !1, r.syncErrorThrowable = !1, r.isStopped = !1, arguments.length) {\n                case 0:\n                    r.destination = Tt;\n                    break;\n                case 1:\n                    if (!e) {\n                        r.destination = Tt;\n                        break\n                    }\n                    if (\"object\" == typeof e) {\n                        e instanceof _t ? (r.syncErrorThrowable = e.syncErrorThrowable, (r.destination = e).add(r)) : (r.syncErrorThrowable = !0, r.destination = new Rt(r, e));\n                        break\n                    }\n                default:\n                    r.syncErrorThrowable = !0, r.destination = new Rt(r, e, t, i)\n            }\n            return r\n        }\n        var Nt = \"function\" == typeof Symbol && Symbol.observable || \"@@observable\";\n\n        function Ft(e) {\n            return e\n        }\n\n        function Bt() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            return Ut(e)\n        }\n\n        function Ut(t) {\n            return 0 === t.length ? Ft : 1 === t.length ? t[0] : function(e) {\n                return t.reduce(function(e, t) {\n                    return t(e)\n                }, e)\n            }\n        }\n        var $t = (Vt.prototype.lift = function(e) {\n            var t = new Vt;\n            return t.source = this, t.operator = e, t\n        }, Vt.prototype.subscribe = function(e, t, i) {\n            var r = this.operator,\n                i = function(e, t, i) {\n                    if (e) {\n                        if (e instanceof Pt) return e;\n                        if (e[xt]) return e[xt]()\n                    }\n                    return e || t || i ? new Pt(e, t, i) : new Pt(Tt)\n                }(e, t, i);\n            if (r ? i.add(r.call(i, this.source)) : i.add(this.source || St.useDeprecatedSynchronousErrorHandling && !i.syncErrorThrowable ? this._subscribe(i) : this._trySubscribe(i)), St.useDeprecatedSynchronousErrorHandling && i.syncErrorThrowable && (i.syncErrorThrowable = !1, i.syncErrorThrown)) throw i.syncErrorValue;\n            return i\n        }, Vt.prototype._trySubscribe = function(t) {\n            try {\n                return this._subscribe(t)\n            } catch (e) {\n                St.useDeprecatedSynchronousErrorHandling && (t.syncErrorThrown = !0, t.syncErrorValue = e),\n                    function(e) {\n                        for (; e;) {\n                            var t = e,\n                                i = t.closed,\n                                r = t.destination,\n                                t = t.isStopped;\n                            if (i || t) return;\n                            e = r && r instanceof Pt ? r : null\n                        }\n                        return 1\n                    }(t) ? t.error(e) : console.warn(e)\n            }\n        }, Vt.prototype.forEach = function(r, e) {\n            var n = this;\n            return new(e = Kt(e))(function(e, t) {\n                var i = n.subscribe(function(e) {\n                    try {\n                        r(e)\n                    } catch (e) {\n                        t(e), i && i.unsubscribe()\n                    }\n                }, t, e)\n            })\n        }, Vt.prototype._subscribe = function(e) {\n            var t = this.source;\n            return t && t.subscribe(e)\n        }, Vt.prototype[Nt] = function() {\n            return this\n        }, Vt.prototype.pipe = function() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            return 0 === e.length ? this : Ut(e)(this)\n        }, Vt.prototype.toPromise = function(e) {\n            var r = this;\n            return new(e = Kt(e))(function(e, t) {\n                var i;\n                r.subscribe(function(e) {\n                    return i = e\n                }, function(e) {\n                    return t(e)\n                }, function() {\n                    return e(i)\n                })\n            })\n        }, Vt.create = function(e) {\n            return new Vt(e)\n        }, Vt);\n\n        function Vt(e) {\n            this._isScalar = !1, e && (this._subscribe = e)\n        }\n\n        function Kt(e) {\n            if (!(e = e || (St.Promise || Promise))) throw new Error(\"no Promise impl found\");\n            return e\n        }\n        var qt, Ht, jt, Qt, Wt = (ii.prototype = Object.create(Error.prototype), ii),\n            Gt = (ut(ti, Qt = At), ti.prototype.unsubscribe = function() {\n                var e, t;\n                this.closed || (this.closed = !0, e = (t = this.subject).observers, this.subject = null, !e || 0 === e.length || t.isStopped || t.closed || -1 !== (t = e.indexOf(this.subscriber)) && e.splice(t, 1))\n            }, ti),\n            zt = (ut(ei, jt = Pt), ei),\n            Xt = (ut(Zt, Ht = $t), Zt.prototype[xt] = function() {\n                return new zt(this)\n            }, Zt.prototype.lift = function(e) {\n                var t = new Yt(this, this);\n                return t.operator = e, t\n            }, Zt.prototype.next = function(e) {\n                if (this.closed) throw new Wt;\n                if (!this.isStopped)\n                    for (var t = this.observers, i = t.length, r = t.slice(), n = 0; n < i; n++) r[n].next(e)\n            }, Zt.prototype.error = function(e) {\n                if (this.closed) throw new Wt;\n                this.hasError = !0, this.thrownError = e, this.isStopped = !0;\n                for (var t = this.observers, i = t.length, r = t.slice(), n = 0; n < i; n++) r[n].error(e);\n                this.observers.length = 0\n            }, Zt.prototype.complete = function() {\n                if (this.closed) throw new Wt;\n                this.isStopped = !0;\n                for (var e = this.observers, t = e.length, i = e.slice(), r = 0; r < t; r++) i[r].complete();\n                this.observers.length = 0\n            }, Zt.prototype.unsubscribe = function() {\n                this.isStopped = !0, this.closed = !0, this.observers = null\n            }, Zt.prototype._trySubscribe = function(e) {\n                if (this.closed) throw new Wt;\n                return Ht.prototype._trySubscribe.call(this, e)\n            }, Zt.prototype._subscribe = function(e) {\n                if (this.closed) throw new Wt;\n                return this.hasError ? (e.error(this.thrownError), At.EMPTY) : this.isStopped ? (e.complete(), At.EMPTY) : (this.observers.push(e), new Gt(this, e))\n            }, Zt.prototype.asObservable = function() {\n                var e = new $t;\n                return e.source = this, e\n            }, Zt.create = function(e, t) {\n                return new Yt(e, t)\n            }, Zt),\n            Yt = (ut(Jt, qt = Xt), Jt.prototype.next = function(e) {\n                var t = this.destination;\n                t && t.next && t.next(e)\n            }, Jt.prototype.error = function(e) {\n                var t = this.destination;\n                t && t.error && this.destination.error(e)\n            }, Jt.prototype.complete = function() {\n                var e = this.destination;\n                e && e.complete && this.destination.complete()\n            }, Jt.prototype._subscribe = function(e) {\n                return this.source ? this.source.subscribe(e) : At.EMPTY\n            }, Jt);\n\n        function Jt(e, t) {\n            var i = qt.call(this) || this;\n            return i.destination = e, i.source = t, i\n        }\n\n        function Zt() {\n            var e = Ht.call(this) || this;\n            return e.observers = [], e.closed = !1, e.isStopped = !1, e.hasError = !1, e.thrownError = null, e\n        }\n\n        function ei(e) {\n            var t = jt.call(this, e) || this;\n            return t.destination = e, t\n        }\n\n        function ti(e, t) {\n            var i = Qt.call(this) || this;\n            return i.subject = e, i.subscriber = t, i.closed = !1, i\n        }\n\n        function ii() {\n            return Error.call(this), this.message = \"object unsubscribed\", this.name = \"ObjectUnsubscribedError\", this\n        }\n\n        function ri() {\n            return function(e) {\n                return e.lift(new pi(e))\n            }\n        }\n        var ni, si, ai, oi, li, di, ui, ci, hi, pi = (Li.prototype.call = function(e, t) {\n                var i = this.connectable;\n                i._refCount++;\n                e = new fi(e, i), t = t.subscribe(e);\n                return e.closed || (e.connection = i.connect()), t\n            }, Li),\n            fi = (ut(Ri, hi = Pt), Ri.prototype._unsubscribe = function() {\n                var e, t = this.connectable;\n                t ? (this.connectable = null, (e = t._refCount) <= 0 ? this.connection = null : (t._refCount = e - 1, 1 < e ? this.connection = null : (e = this.connection, t = t._connection, this.connection = null, !t || e && t !== e || t.unsubscribe()))) : this.connection = null\n            }, Ri),\n            w = (ut(Pi, ci = $t), Pi.prototype._subscribe = function(e) {\n                return this.getSubject().subscribe(e)\n            }, Pi.prototype.getSubject = function() {\n                var e = this._subject;\n                return e && !e.isStopped || (this._subject = this.subjectFactory()), this._subject\n            }, Pi.prototype.connect = function() {\n                var e = this._connection;\n                return e || (this._isComplete = !1, (e = this._connection = new At).add(this.source.subscribe(new gi(this.getSubject(), this))), e.closed && (this._connection = null, e = At.EMPTY)), e\n            }, Pi.prototype.refCount = function() {\n                return ri()(this)\n            }, Pi),\n            mi = {\n                operator: {\n                    value: null\n                },\n                _refCount: {\n                    value: 0,\n                    writable: !0\n                },\n                _subject: {\n                    value: null,\n                    writable: !0\n                },\n                _connection: {\n                    value: null,\n                    writable: !0\n                },\n                _subscribe: {\n                    value: (fl = w.prototype)._subscribe\n                },\n                _isComplete: {\n                    value: fl._isComplete,\n                    writable: !0\n                },\n                getSubject: {\n                    value: fl.getSubject\n                },\n                connect: {\n                    value: fl.connect\n                },\n                refCount: {\n                    value: fl.refCount\n                }\n            },\n            gi = (ut(xi, ui = zt), xi.prototype._error = function(e) {\n                this._unsubscribe(), ui.prototype._error.call(this, e)\n            }, xi.prototype._complete = function() {\n                this.connectable._isComplete = !0, this._unsubscribe(), ui.prototype._complete.call(this)\n            }, xi.prototype._unsubscribe = function() {\n                var e, t = this.connectable;\n                t && (this.connectable = null, e = t._connection, t._refCount = 0, t._subject = null, t._connection = null, e && e.unsubscribe())\n            }, xi),\n            yi = (ut(Mi, di = Xt), Object.defineProperty(Mi.prototype, \"value\", {\n                get: function() {\n                    return this.getValue()\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Mi.prototype._subscribe = function(e) {\n                var t = di.prototype._subscribe.call(this, e);\n                return t && !t.closed && e.next(this._value), t\n            }, Mi.prototype.getValue = function() {\n                if (this.hasError) throw this.thrownError;\n                if (this.closed) throw new Wt;\n                return this._value\n            }, Mi.prototype.next = function(e) {\n                di.prototype.next.call(this, this._value = e)\n            }, Mi),\n            A = (ut(Di, li = At), Di.prototype.schedule = function(e, t) {\n                return this\n            }, ut(Ci, oi = Di), Ci.prototype.schedule = function(e, t) {\n                if (void 0 === t && (t = 0), this.closed) return this;\n                this.state = e;\n                var i = this.id,\n                    e = this.scheduler;\n                return null != i && (this.id = this.recycleAsyncId(e, i, t)), this.pending = !0, this.delay = t, this.id = this.id || this.requestAsyncId(e, this.id, t), this\n            }, Ci.prototype.requestAsyncId = function(e, t, i) {\n                return void 0 === i && (i = 0), setInterval(e.flush.bind(e, this), i)\n            }, Ci.prototype.recycleAsyncId = function(e, t, i) {\n                if (null !== (i = void 0 === i ? 0 : i) && this.delay === i && !1 === this.pending) return t;\n                clearInterval(t)\n            }, Ci.prototype.execute = function(e, t) {\n                if (this.closed) return new Error(\"executing a cancelled action\");\n                this.pending = !1;\n                t = this._execute(e, t);\n                if (t) return t;\n                !1 === this.pending && null != this.id && (this.id = this.recycleAsyncId(this.scheduler, this.id, null))\n            }, Ci.prototype._execute = function(e, t) {\n                var i = !1,\n                    r = void 0;\n                try {\n                    this.work(e)\n                } catch (e) {\n                    i = !0, r = !!e && e || new Error(e)\n                }\n                if (i) return this.unsubscribe(), r\n            }, Ci.prototype._unsubscribe = function() {\n                var e = this.id,\n                    t = this.scheduler,\n                    i = t.actions,\n                    r = i.indexOf(this);\n                this.work = null, this.state = null, this.pending = !1, this.scheduler = null, -1 !== r && i.splice(r, 1), null != e && (this.id = this.recycleAsyncId(t, e, null)), this.delay = null\n            }, Ci),\n            vi = (ut(ki, ai = A), ki.prototype.schedule = function(e, t) {\n                return 0 < (t = void 0 === t ? 0 : t) ? ai.prototype.schedule.call(this, e, t) : (this.delay = t, this.state = e, this.scheduler.flush(this), this)\n            }, ki.prototype.execute = function(e, t) {\n                return 0 < t || this.closed ? ai.prototype.execute.call(this, e, t) : this._execute(e, t)\n            }, ki.prototype.requestAsyncId = function(e, t, i) {\n                return null !== (i = void 0 === i ? 0 : i) && 0 < i || null === i && 0 < this.delay ? ai.prototype.requestAsyncId.call(this, e, t, i) : e.flush(this)\n            }, ki),\n            Si = (Oi.prototype.schedule = function(e, t, i) {\n                return void 0 === t && (t = 0), new this.SchedulerAction(this, e).schedule(i, t)\n            }, Oi.now = function() {\n                return Date.now()\n            }, Oi),\n            bi = (ut(Ai, si = Si), Ai.prototype.schedule = function(e, t, i) {\n                return void 0 === t && (t = 0), Ai.delegate && Ai.delegate !== this ? Ai.delegate.schedule(e, t, i) : si.prototype.schedule.call(this, e, t, i)\n            }, Ai.prototype.flush = function(e) {\n                var t, i = this.actions;\n                if (this.active) i.push(e);\n                else {\n                    this.active = !0;\n                    do {\n                        if (t = e.execute(e.state, e.delay)) break\n                    } while (e = i.shift());\n                    if (this.active = !1, t) {\n                        for (; e = i.shift();) e.unsubscribe();\n                        throw t\n                    }\n                }\n            }, Ai),\n            Ti = (ut(wi, ni = bi), new wi(vi)),\n            Ei = Ti,\n            Ii = new $t(function(e) {\n                return e.complete()\n            });\n\n        function wi() {\n            return null !== ni && ni.apply(this, arguments) || this\n        }\n\n        function Ai(e, t) {\n            void 0 === t && (t = Si.now);\n            var i = si.call(this, e, function() {\n                return Ai.delegate && Ai.delegate !== i ? Ai.delegate.now() : t()\n            }) || this;\n            return i.actions = [], i.active = !1, i.scheduled = void 0, i\n        }\n\n        function Oi(e, t) {\n            void 0 === t && (t = Oi.now), this.SchedulerAction = e, this.now = t\n        }\n\n        function ki(e, t) {\n            var i = ai.call(this, e, t) || this;\n            return i.scheduler = e, i.work = t, i\n        }\n\n        function Ci(e, t) {\n            var i = oi.call(this, e, t) || this;\n            return i.scheduler = e, i.work = t, i.pending = !1, i\n        }\n\n        function Di(e, t) {\n            return li.call(this) || this\n        }\n\n        function Mi(e) {\n            var t = di.call(this) || this;\n            return t._value = e, t\n        }\n\n        function xi(e, t) {\n            e = ui.call(this, e) || this;\n            return e.connectable = t, e\n        }\n\n        function Pi(e, t) {\n            var i = ci.call(this) || this;\n            return i.source = e, i.subjectFactory = t, i._refCount = 0, i._isComplete = !1, i\n        }\n\n        function Ri(e, t) {\n            e = hi.call(this, e) || this;\n            return e.connectable = t, e\n        }\n\n        function Li(e) {\n            this.connectable = e\n        }\n\n        function _i(e) {\n            return e ? (t = e, new $t(function(e) {\n                return t.schedule(function() {\n                    return e.complete()\n                })\n            })) : Ii;\n            var t\n        }\n\n        function Ni(e) {\n            return e && \"function\" == typeof e.schedule\n        }\n        var Fi = function(r) {\n            return function(e) {\n                for (var t = 0, i = r.length; t < i && !e.closed; t++) e.next(r[t]);\n                e.complete()\n            }\n        };\n\n        function Bi(r, n) {\n            return new $t(function(e) {\n                var t = new At,\n                    i = 0;\n                return t.add(n.schedule(function() {\n                    i !== r.length ? (e.next(r[i++]), e.closed || t.add(this.schedule())) : e.complete()\n                })), t\n            })\n        }\n\n        function Ui(e, t) {\n            return t ? Bi(e, t) : new $t(Fi(e))\n        }\n\n        function $i() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            var i = e[e.length - 1];\n            return Ni(i) ? (e.pop(), Bi(e, i)) : Ui(e)\n        }\n\n        function Vi(t, i) {\n            return new $t(i ? function(e) {\n                return i.schedule(Ki, 0, {\n                    error: t,\n                    subscriber: e\n                })\n            } : function(e) {\n                return e.error(t)\n            })\n        }\n\n        function Ki(e) {\n            var t = e.error;\n            e.subscriber.error(t)\n        }\n        var qi = (Hi.prototype.observe = function(e) {\n            switch (this.kind) {\n                case \"N\":\n                    return e.next && e.next(this.value);\n                case \"E\":\n                    return e.error && e.error(this.error);\n                case \"C\":\n                    return e.complete && e.complete()\n            }\n        }, Hi.prototype.do = function(e, t, i) {\n            switch (this.kind) {\n                case \"N\":\n                    return e && e(this.value);\n                case \"E\":\n                    return t && t(this.error);\n                case \"C\":\n                    return i && i()\n            }\n        }, Hi.prototype.accept = function(e, t, i) {\n            return e && \"function\" == typeof e.next ? this.observe(e) : this.do(e, t, i)\n        }, Hi.prototype.toObservable = function() {\n            switch (this.kind) {\n                case \"N\":\n                    return $i(this.value);\n                case \"E\":\n                    return Vi(this.error);\n                case \"C\":\n                    return _i()\n            }\n            throw new Error(\"unexpected notification kind value\")\n        }, Hi.createNext = function(e) {\n            return void 0 !== e ? new Hi(\"N\", e) : Hi.undefinedValueNotification\n        }, Hi.createError = function(e) {\n            return new Hi(\"E\", void 0, e)\n        }, Hi.createComplete = function() {\n            return Hi.completeNotification\n        }, Hi.completeNotification = new Hi(\"C\"), Hi.undefinedValueNotification = new Hi(\"N\", void 0), Hi);\n\n        function Hi(e, t, i) {\n            this.kind = e, this.value = t, this.error = i, this.hasValue = \"N\" === e\n        }\n\n        function ji(t, i) {\n            return void 0 === i && (i = 0),\n                function(e) {\n                    return e.lift(new zi(t, i))\n                }\n        }\n        var Qi, Wi, Gi, zi = (ar.prototype.call = function(e, t) {\n                return t.subscribe(new Xi(e, this.scheduler, this.delay))\n            }, ar),\n            Xi = (ut(sr, Gi = Pt), sr.dispatch = function(e) {\n                var t = e.notification,\n                    e = e.destination;\n                t.observe(e), this.unsubscribe()\n            }, sr.prototype.scheduleMessage = function(e) {\n                this.destination.add(this.scheduler.schedule(sr.dispatch, this.delay, new Yi(e, this.destination)))\n            }, sr.prototype._next = function(e) {\n                this.scheduleMessage(qi.createNext(e))\n            }, sr.prototype._error = function(e) {\n                this.scheduleMessage(qi.createError(e)), this.unsubscribe()\n            }, sr.prototype._complete = function() {\n                this.scheduleMessage(qi.createComplete()), this.unsubscribe()\n            }, sr),\n            Yi = function(e, t) {\n                this.notification = e, this.destination = t\n            },\n            Ji = (ut(nr, Wi = Xt), nr.prototype.nextInfiniteTimeWindow = function(e) {\n                var t;\n                this.isStopped || ((t = this._events).push(e), t.length > this._bufferSize && t.shift()), Wi.prototype.next.call(this, e)\n            }, nr.prototype.nextTimeWindow = function(e) {\n                this.isStopped || (this._events.push(new Zi(this._getNow(), e)), this._trimBufferThenGetEvents()), Wi.prototype.next.call(this, e)\n            }, nr.prototype._subscribe = function(e) {\n                var t, i = this._infiniteTimeWindow,\n                    r = i ? this._events : this._trimBufferThenGetEvents(),\n                    n = this.scheduler,\n                    s = r.length;\n                if (this.closed) throw new Wt;\n                if (t = this.isStopped || this.hasError ? At.EMPTY : (this.observers.push(e), new Gt(this, e)), n && e.add(e = new Xi(e, n)), i)\n                    for (var a = 0; a < s && !e.closed; a++) e.next(r[a]);\n                else\n                    for (a = 0; a < s && !e.closed; a++) e.next(r[a].value);\n                return this.hasError ? e.error(this.thrownError) : this.isStopped && e.complete(), t\n            }, nr.prototype._getNow = function() {\n                return (this.scheduler || Ei).now()\n            }, nr.prototype._trimBufferThenGetEvents = function() {\n                for (var e = this._getNow(), t = this._bufferSize, i = this._windowTime, r = this._events, n = r.length, s = 0; s < n && !(e - r[s].time < i);) s++;\n                return 0 < (s = t < n ? Math.max(s, n - t) : s) && r.splice(0, s), r\n            }, nr),\n            Zi = function(e, t) {\n                this.time = e, this.value = t\n            },\n            er = (ut(rr, Qi = Xt), rr.prototype._subscribe = function(e) {\n                return this.hasError ? (e.error(this.thrownError), At.EMPTY) : this.hasCompleted && this.hasNext ? (e.next(this.value), e.complete(), At.EMPTY) : Qi.prototype._subscribe.call(this, e)\n            }, rr.prototype.next = function(e) {\n                this.hasCompleted || (this.value = e, this.hasNext = !0)\n            }, rr.prototype.error = function(e) {\n                this.hasCompleted || Qi.prototype.error.call(this, e)\n            }, rr.prototype.complete = function() {\n                this.hasCompleted = !0, this.hasNext && Qi.prototype.next.call(this, this.value), Qi.prototype.complete.call(this)\n            }, rr),\n            tr = new bi(A),\n            ir = tr;\n\n        function rr() {\n            var e = null !== Qi && Qi.apply(this, arguments) || this;\n            return e.value = null, e.hasNext = !1, e.hasCompleted = !1, e\n        }\n\n        function nr(e, t, i) {\n            void 0 === e && (e = Number.POSITIVE_INFINITY), void 0 === t && (t = Number.POSITIVE_INFINITY);\n            var r = Wi.call(this) || this;\n            return r.scheduler = i, r._events = [], r._infiniteTimeWindow = !1, r._bufferSize = e < 1 ? 1 : e, r._windowTime = t < 1 ? 1 : t, t === Number.POSITIVE_INFINITY ? (r._infiniteTimeWindow = !0, r.next = r.nextInfiniteTimeWindow) : r.next = r.nextTimeWindow, r\n        }\n\n        function sr(e, t, i) {\n            void 0 === i && (i = 0);\n            e = Gi.call(this, e) || this;\n            return e.scheduler = t, e.delay = i, e\n        }\n\n        function ar(e, t) {\n            void 0 === t && (t = 0), this.scheduler = e, this.delay = t\n        }\n\n        function or() {}\n        var lr = (cr.prototype = Object.create(Error.prototype), cr),\n            dr = (ur.prototype = Object.create(Error.prototype), ur);\n\n        function ur() {\n            return Error.call(this), this.message = \"Timeout has occurred\", this.name = \"TimeoutError\", this\n        }\n\n        function cr() {\n            return Error.call(this), this.message = \"argument out of range\", this.name = \"ArgumentOutOfRangeError\", this\n        }\n\n        function hr(t, i) {\n            return function(e) {\n                if (\"function\" != typeof t) throw new TypeError(\"argument is not a function. Are you looking for `mapTo()`?\");\n                return e.lift(new gr(t, i))\n            }\n        }\n        var pr, fr, mr, gr = (Ir.prototype.call = function(e, t) {\n                return t.subscribe(new yr(e, this.project, this.thisArg))\n            }, Ir),\n            yr = (ut(Er, mr = Pt), Er.prototype._next = function(e) {\n                var t;\n                try {\n                    t = this.project.call(this.thisArg, e, this.count++)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.destination.next(t)\n            }, Er),\n            vr = (ut(Tr, fr = Pt), Tr.prototype.notifyNext = function(e, t, i, r, n) {\n                this.destination.next(t)\n            }, Tr.prototype.notifyError = function(e, t) {\n                this.destination.error(e)\n            }, Tr.prototype.notifyComplete = function(e) {\n                this.destination.complete()\n            }, Tr),\n            Sr = (ut(br, pr = Pt), br.prototype._next = function(e) {\n                this.parent.notifyNext(this.outerValue, e, this.outerIndex, this.index++, this)\n            }, br.prototype._error = function(e) {\n                this.parent.notifyError(e, this), this.unsubscribe()\n            }, br.prototype._complete = function() {\n                this.parent.notifyComplete(this), this.unsubscribe()\n            }, br);\n\n        function br(e, t, i) {\n            var r = pr.call(this) || this;\n            return r.parent = e, r.outerValue = t, r.outerIndex = i, r.index = 0, r\n        }\n\n        function Tr() {\n            return null !== fr && fr.apply(this, arguments) || this\n        }\n\n        function Er(e, t, i) {\n            e = mr.call(this, e) || this;\n            return e.project = t, e.count = 0, e.thisArg = i || e, e\n        }\n\n        function Ir(e, t) {\n            this.project = e, this.thisArg = t\n        }\n        var wr = \"function\" == typeof Symbol && Symbol.iterator ? Symbol.iterator : \"@@iterator\",\n            Ar = function(e) {\n                return e && \"number\" == typeof e.length && \"function\" != typeof e\n            };\n\n        function Or(e) {\n            return e && \"function\" != typeof e.subscribe && \"function\" == typeof e.then\n        }\n        var kr = function(e) {\n            if (e && \"function\" == typeof e[Nt]) return n = e,\n                function(e) {\n                    var t = n[Nt]();\n                    if (\"function\" != typeof t.subscribe) throw new TypeError(\"Provided object does not correctly implement Symbol.observable\");\n                    return t.subscribe(e)\n                };\n            if (Ar(e)) return Fi(e);\n            if (Or(e)) return i = e,\n                function(t) {\n                    return i.then(function(e) {\n                        t.closed || (t.next(e), t.complete())\n                    }, function(e) {\n                        return t.error(e)\n                    }).then(null, bt), t\n                };\n            if (e && \"function\" == typeof e[wr]) return r = e,\n                function(t) {\n                    for (var e = r[wr]();;) {\n                        var i = void 0;\n                        try {\n                            i = e.next()\n                        } catch (e) {\n                            return t.error(e), t\n                        }\n                        if (i.done) {\n                            t.complete();\n                            break\n                        }\n                        if (t.next(i.value), t.closed) break\n                    }\n                    return \"function\" == typeof e.return && t.add(function() {\n                        e.return && e.return()\n                    }), t\n                };\n            var r, i, n, e = It(e) ? \"an invalid object\" : \"'\" + e + \"'\";\n            throw new TypeError(\"You provided \" + e + \" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.\")\n        };\n\n        function Cr(e, t, i, r, n) {\n            if (!(n = void 0 === n ? new Sr(e, i, r) : n).closed) return t instanceof $t ? t.subscribe(n) : kr(t)(n)\n        }\n        var Dr = {};\n\n        function Mr() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            var i = void 0,\n                r = void 0;\n            return Ni(e[e.length - 1]) && (r = e.pop()), \"function\" == typeof e[e.length - 1] && (i = e.pop()), Ui(e = 1 === e.length && Et(e[0]) ? e[0] : e, r).lift(new Pr(i))\n        }\n        var xr, Pr = (_r.prototype.call = function(e, t) {\n                return t.subscribe(new Rr(e, this.resultSelector))\n            }, _r),\n            Rr = (ut(Lr, xr = vr), Lr.prototype._next = function(e) {\n                this.values.push(Dr), this.observables.push(e)\n            }, Lr.prototype._complete = function() {\n                var e = this.observables,\n                    t = e.length;\n                if (0 === t) this.destination.complete();\n                else {\n                    this.active = t, this.toRespond = t;\n                    for (var i = 0; i < t; i++) {\n                        var r = e[i];\n                        this.add(Cr(this, r, void 0, i))\n                    }\n                }\n            }, Lr.prototype.notifyComplete = function(e) {\n                0 == --this.active && this.destination.complete()\n            }, Lr.prototype.notifyNext = function(e, t, i) {\n                var r = this.values,\n                    n = r[i],\n                    n = this.toRespond ? n === Dr ? --this.toRespond : this.toRespond : 0;\n                r[i] = t, 0 === n && (this.resultSelector ? this._tryResultSelector(r) : this.destination.next(r.slice()))\n            }, Lr.prototype._tryResultSelector = function(e) {\n                var t;\n                try {\n                    t = this.resultSelector.apply(this, e)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.destination.next(t)\n            }, Lr);\n\n        function Lr(e, t) {\n            e = xr.call(this, e) || this;\n            return e.resultSelector = t, e.active = 0, e.values = [], e.observables = [], e\n        }\n\n        function _r(e) {\n            this.resultSelector = e\n        }\n\n        function Nr(e, t) {\n            if (null != e) {\n                if (e && \"function\" == typeof e[Nt]) return s = e, a = t, new $t(function(t) {\n                    var i = new At;\n                    return i.add(a.schedule(function() {\n                        var e = s[Nt]();\n                        i.add(e.subscribe({\n                            next: function(e) {\n                                i.add(a.schedule(function() {\n                                    return t.next(e)\n                                }))\n                            },\n                            error: function(e) {\n                                i.add(a.schedule(function() {\n                                    return t.error(e)\n                                }))\n                            },\n                            complete: function() {\n                                i.add(a.schedule(function() {\n                                    return t.complete()\n                                }))\n                            }\n                        }))\n                    })), i\n                });\n                if (Or(e)) return r = e, n = t, new $t(function(t) {\n                    var i = new At;\n                    return i.add(n.schedule(function() {\n                        return r.then(function(e) {\n                            i.add(n.schedule(function() {\n                                t.next(e), i.add(n.schedule(function() {\n                                    return t.complete()\n                                }))\n                            }))\n                        }, function(e) {\n                            i.add(n.schedule(function() {\n                                return t.error(e)\n                            }))\n                        })\n                    })), i\n                });\n                if (Ar(e)) return Bi(e, t);\n                if (e && \"function\" == typeof e[wr] || \"string\" == typeof e) return function(t, i) {\n                    if (!t) throw new Error(\"Iterable cannot be null\");\n                    return new $t(function(r) {\n                        var n, e = new At;\n                        return e.add(function() {\n                            n && \"function\" == typeof n.return && n.return()\n                        }), e.add(i.schedule(function() {\n                            n = t[wr](), e.add(i.schedule(function() {\n                                if (!r.closed) {\n                                    try {\n                                        var e = n.next(),\n                                            t = e.value,\n                                            i = e.done\n                                    } catch (t) {\n                                        return void r.error(t)\n                                    }\n                                    i ? r.complete() : (r.next(t), this.schedule())\n                                }\n                            }))\n                        })), e\n                    })\n                }(e, t)\n            }\n            var r, n, s, a;\n            throw new TypeError((null !== e && typeof e || e) + \" is not observable\")\n        }\n\n        function Fr(e, t) {\n            return t ? Nr(e, t) : e instanceof $t ? e : new $t(kr(e))\n        }\n        var Br, Ur, $r = (ut(qr, Ur = Pt), qr.prototype._next = function(e) {\n                this.parent.notifyNext(e)\n            }, qr.prototype._error = function(e) {\n                this.parent.notifyError(e), this.unsubscribe()\n            }, qr.prototype._complete = function() {\n                this.parent.notifyComplete(), this.unsubscribe()\n            }, qr),\n            Vr = (ut(Kr, Br = Pt), Kr.prototype.notifyNext = function(e) {\n                this.destination.next(e)\n            }, Kr.prototype.notifyError = function(e) {\n                this.destination.error(e)\n            }, Kr.prototype.notifyComplete = function() {\n                this.destination.complete()\n            }, Kr);\n\n        function Kr() {\n            return null !== Br && Br.apply(this, arguments) || this\n        }\n\n        function qr(e) {\n            var t = Ur.call(this) || this;\n            return t.parent = e, t\n        }\n\n        function Hr(e, t) {\n            if (!t.closed) return e instanceof $t ? e.subscribe(t) : kr(e)(t)\n        }\n\n        function jr(t, n, i) {\n            return void 0 === i && (i = Number.POSITIVE_INFINITY), \"function\" == typeof n ? function(e) {\n                return e.pipe(jr(function(i, r) {\n                    return Fr(t(i, r)).pipe(hr(function(e, t) {\n                        return n(i, e, r, t)\n                    }))\n                }, i))\n            } : (\"number\" == typeof n && (i = n), function(e) {\n                return e.lift(new Wr(t, i))\n            })\n        }\n        var Qr, Wr = (Xr.prototype.call = function(e, t) {\n                return t.subscribe(new Gr(e, this.project, this.concurrent))\n            }, Xr),\n            Gr = (ut(zr, Qr = Vr), zr.prototype._next = function(e) {\n                this.active < this.concurrent ? this._tryNext(e) : this.buffer.push(e)\n            }, zr.prototype._tryNext = function(e) {\n                var t, i = this.index++;\n                try {\n                    t = this.project(e, i)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.active++, this._innerSub(t)\n            }, zr.prototype._innerSub = function(e) {\n                var t = new $r(this),\n                    i = this.destination;\n                i.add(t);\n                e = Hr(e, t);\n                e !== t && i.add(e)\n            }, zr.prototype._complete = function() {\n                this.hasCompleted = !0, 0 === this.active && 0 === this.buffer.length && this.destination.complete(), this.unsubscribe()\n            }, zr.prototype.notifyNext = function(e) {\n                this.destination.next(e)\n            }, zr.prototype.notifyComplete = function() {\n                var e = this.buffer;\n                this.active--, 0 < e.length ? this._next(e.shift()) : 0 === this.active && this.hasCompleted && this.destination.complete()\n            }, zr);\n\n        function zr(e, t, i) {\n            void 0 === i && (i = Number.POSITIVE_INFINITY);\n            e = Qr.call(this, e) || this;\n            return e.project = t, e.concurrent = i, e.hasCompleted = !1, e.buffer = [], e.active = 0, e.index = 0, e\n        }\n\n        function Xr(e, t) {\n            void 0 === t && (t = Number.POSITIVE_INFINITY), this.project = e, this.concurrent = t\n        }\n\n        function Yr(e) {\n            return jr(Ft, e = void 0 === e ? Number.POSITIVE_INFINITY : e)\n        }\n\n        function Jr() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            return Yr(1)($i.apply(void 0, e))\n        }\n\n        function Zr(i) {\n            return new $t(function(t) {\n                var e;\n                try {\n                    e = i()\n                } catch (e) {\n                    return void t.error(e)\n                }\n                return (e ? Fr(e) : _i()).subscribe(t)\n            })\n        }\n\n        function en() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            if (1 === e.length) {\n                var i = e[0];\n                if (Et(i)) return tn(i, null);\n                if (It(i) && Object.getPrototypeOf(i) === Object.prototype) {\n                    var r = Object.keys(i);\n                    return tn(r.map(function(e) {\n                        return i[e]\n                    }), r)\n                }\n            }\n            if (\"function\" != typeof e[e.length - 1]) return tn(e, null);\n            var n = e.pop();\n            return tn(e = 1 === e.length && Et(e[0]) ? e[0] : e, null).pipe(hr(function(e) {\n                return n.apply(void 0, e)\n            }))\n        }\n\n        function tn(l, d) {\n            return new $t(function(r) {\n                var n = l.length;\n                if (0 !== n)\n                    for (var s = new Array(n), a = 0, o = 0, e = 0; e < n; e++) ! function(t) {\n                        var e = Fr(l[t]),\n                            i = !1;\n                        r.add(e.subscribe({\n                            next: function(e) {\n                                i || (i = !0, o++), s[t] = e\n                            },\n                            error: function(e) {\n                                return r.error(e)\n                            },\n                            complete: function() {\n                                ++a !== n && i || (o === n && r.next(d ? d.reduce(function(e, t, i) {\n                                    return e[t] = s[i], e\n                                }, {}) : s), r.complete())\n                            }\n                        }))\n                    }(e);\n                else r.complete()\n            })\n        }\n\n        function rn(e, i, r, t) {\n            return yt(r) && (t = r, r = void 0), t ? rn(e, i, r).pipe(hr(function(e) {\n                return Et(e) ? t.apply(void 0, e) : t(e)\n            })) : new $t(function(t) {\n                ! function e(t, i, r, n, s) {\n                    var a;\n                    if (function(e) {\n                            return e && \"function\" == typeof e.addEventListener && \"function\" == typeof e.removeEventListener\n                        }(t)) {\n                        var o = t;\n                        t.addEventListener(i, r, s), a = function() {\n                            return o.removeEventListener(i, r, s)\n                        }\n                    } else if (function(e) {\n                            return e && \"function\" == typeof e.on && \"function\" == typeof e.off\n                        }(t)) {\n                        var l = t;\n                        t.on(i, r), a = function() {\n                            return l.off(i, r)\n                        }\n                    } else if (function(e) {\n                            return e && \"function\" == typeof e.addListener && \"function\" == typeof e.removeListener\n                        }(t)) {\n                        var d = t;\n                        t.addListener(i, r), a = function() {\n                            return d.removeListener(i, r)\n                        }\n                    } else {\n                        if (!t || !t.length) throw new TypeError(\"Invalid event target\");\n                        for (var u = 0, c = t.length; u < c; u++) e(t[u], i, r, n, s)\n                    }\n                    n.add(a)\n                }(e, i, function(e) {\n                    1 < arguments.length ? t.next(Array.prototype.slice.call(arguments)) : t.next(e)\n                }, t, r)\n            })\n        }\n\n        function nn(e, t, i) {\n            return void 0 === t && (t = Ii), void 0 === i && (i = Ii), Zr(function() {\n                return e() ? t : i\n            })\n        }\n\n        function sn(e) {\n            return !Et(e) && 0 <= e - parseFloat(e) + 1\n        }\n\n        function an() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            var i = Number.POSITIVE_INFINITY,\n                r = null,\n                n = e[e.length - 1];\n            return Ni(n) ? (r = e.pop(), 1 < e.length && \"number\" == typeof e[e.length - 1] && (i = e.pop())) : \"number\" == typeof n && (i = e.pop()), null === r && 1 === e.length && e[0] instanceof $t ? e[0] : Yr(i)(Ui(e, r))\n        }\n        var on = new $t(or);\n\n        function ln(t, i) {\n            return function(e) {\n                return e.lift(new un(t, i))\n            }\n        }\n        var dn, un = (pn.prototype.call = function(e, t) {\n                return t.subscribe(new cn(e, this.predicate, this.thisArg))\n            }, pn),\n            cn = (ut(hn, dn = Pt), hn.prototype._next = function(e) {\n                var t;\n                try {\n                    t = this.predicate.call(this.thisArg, e, this.count++)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                t && this.destination.next(e)\n            }, hn);\n\n        function hn(e, t, i) {\n            e = dn.call(this, e) || this;\n            return e.predicate = t, e.thisArg = i, e.count = 0, e\n        }\n\n        function pn(e, t) {\n            this.predicate = e, this.thisArg = t\n        }\n\n        function fn() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            if (1 === e.length) {\n                if (!Et(e[0])) return e[0];\n                e = e[0]\n            }\n            return Ui(e, void 0).lift(new gn)\n        }\n        var mn, gn = (Sn.prototype.call = function(e, t) {\n                return t.subscribe(new yn(e))\n            }, Sn),\n            yn = (ut(vn, mn = vr), vn.prototype._next = function(e) {\n                this.observables.push(e)\n            }, vn.prototype._complete = function() {\n                var e = this.observables,\n                    t = e.length;\n                if (0 === t) this.destination.complete();\n                else {\n                    for (var i = 0; i < t && !this.hasFirst; i++) {\n                        var r = Cr(this, e[i], void 0, i);\n                        this.subscriptions && this.subscriptions.push(r), this.add(r)\n                    }\n                    this.observables = null\n                }\n            }, vn.prototype.notifyNext = function(e, t, i) {\n                if (!this.hasFirst) {\n                    this.hasFirst = !0;\n                    for (var r, n = 0; n < this.subscriptions.length; n++) n !== i && ((r = this.subscriptions[n]).unsubscribe(), this.remove(r));\n                    this.subscriptions = null\n                }\n                this.destination.next(t)\n            }, vn);\n\n        function vn(e) {\n            e = mn.call(this, e) || this;\n            return e.hasFirst = !1, e.observables = [], e.subscriptions = [], e\n        }\n\n        function Sn() {}\n\n        function bn(i, e, r) {\n            void 0 === i && (i = 0);\n            var n = -1;\n            return sn(e) ? n = Number(e) < 1 ? 1 : Number(e) : Ni(e) && (r = e), Ni(r) || (r = ir), new $t(function(e) {\n                var t = sn(i) ? i : +i - r.now();\n                return r.schedule(Tn, t, {\n                    index: 0,\n                    period: n,\n                    subscriber: e\n                })\n            })\n        }\n\n        function Tn(e) {\n            var t = e.index,\n                i = e.period,\n                r = e.subscriber;\n            if (r.next(t), !r.closed) {\n                if (-1 === i) return r.complete();\n                e.index = t + 1, this.schedule(e, i)\n            }\n        }\n\n        function En() {\n            for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n            var i = e[e.length - 1];\n            return \"function\" == typeof i && e.pop(), Ui(e, void 0).lift(new An(i))\n        }\n        var In, wn, An = (Ln.prototype.call = function(e, t) {\n                return t.subscribe(new On(e, this.resultSelector))\n            }, Ln),\n            On = (ut(Rn, wn = Pt), Rn.prototype._next = function(e) {\n                var t = this.iterators;\n                Et(e) ? t.push(new Cn(e)) : \"function\" == typeof e[wr] ? t.push(new kn(e[wr]())) : t.push(new Dn(this.destination, this, e))\n            }, Rn.prototype._complete = function() {\n                var e = this.iterators,\n                    t = e.length;\n                if (this.unsubscribe(), 0 !== t) {\n                    this.active = t;\n                    for (var i = 0; i < t; i++) {\n                        var r = e[i];\n                        r.stillUnsubscribed ? this.destination.add(r.subscribe()) : this.active--\n                    }\n                } else this.destination.complete()\n            }, Rn.prototype.notifyInactive = function() {\n                this.active--, 0 === this.active && this.destination.complete()\n            }, Rn.prototype.checkIterators = function() {\n                for (var e = this.iterators, t = e.length, i = this.destination, r = 0; r < t; r++)\n                    if (\"function\" == typeof(a = e[r]).hasValue && !a.hasValue()) return;\n                for (var n = !1, s = [], r = 0; r < t; r++) {\n                    var a, o = (a = e[r]).next();\n                    if (a.hasCompleted() && (n = !0), o.done) return void i.complete();\n                    s.push(o.value)\n                }\n                this.resultSelector ? this._tryresultSelector(s) : i.next(s), n && i.complete()\n            }, Rn.prototype._tryresultSelector = function(e) {\n                var t;\n                try {\n                    t = this.resultSelector.apply(this, e)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.destination.next(t)\n            }, Rn),\n            kn = (Pn.prototype.hasValue = function() {\n                return !0\n            }, Pn.prototype.next = function() {\n                var e = this.nextResult;\n                return this.nextResult = this.iterator.next(), e\n            }, Pn.prototype.hasCompleted = function() {\n                var e = this.nextResult;\n                return Boolean(e && e.done)\n            }, Pn),\n            Cn = (xn.prototype[wr] = function() {\n                return this\n            }, xn.prototype.next = function(e) {\n                var t = this.index++,\n                    i = this.array;\n                return t < this.length ? {\n                    value: i[t],\n                    done: !1\n                } : {\n                    value: null,\n                    done: !0\n                }\n            }, xn.prototype.hasValue = function() {\n                return this.array.length > this.index\n            }, xn.prototype.hasCompleted = function() {\n                return this.array.length === this.index\n            }, xn),\n            Dn = (ut(Mn, In = Vr), Mn.prototype[wr] = function() {\n                return this\n            }, Mn.prototype.next = function() {\n                var e = this.buffer;\n                return 0 === e.length && this.isComplete ? {\n                    value: null,\n                    done: !0\n                } : {\n                    value: e.shift(),\n                    done: !1\n                }\n            }, Mn.prototype.hasValue = function() {\n                return 0 < this.buffer.length\n            }, Mn.prototype.hasCompleted = function() {\n                return 0 === this.buffer.length && this.isComplete\n            }, Mn.prototype.notifyComplete = function() {\n                0 < this.buffer.length ? (this.isComplete = !0, this.parent.notifyInactive()) : this.destination.complete()\n            }, Mn.prototype.notifyNext = function(e) {\n                this.buffer.push(e), this.parent.checkIterators()\n            }, Mn.prototype.subscribe = function() {\n                return Hr(this.observable, new $r(this))\n            }, Mn);\n\n        function Mn(e, t, i) {\n            e = In.call(this, e) || this;\n            return e.parent = t, e.observable = i, e.stillUnsubscribed = !0, e.buffer = [], e.isComplete = !1, e\n        }\n\n        function xn(e) {\n            this.array = e, this.index = 0, this.length = 0, this.length = e.length\n        }\n\n        function Pn(e) {\n            this.iterator = e, this.nextResult = e.next()\n        }\n\n        function Rn(e, t, i) {\n            e = wn.call(this, e) || this;\n            return e.resultSelector = t, e.iterators = [], e.active = 0, e.resultSelector = \"function\" == typeof t ? t : void 0, e\n        }\n\n        function Ln(e) {\n            this.resultSelector = e\n        }\n        var _n, Nn = (Un.prototype.call = function(e, t) {\n                return t.subscribe(new Fn(e, this.durationSelector))\n            }, Un),\n            Fn = (ut(Bn, _n = Vr), Bn.prototype._next = function(e) {\n                if (this.value = e, this.hasValue = !0, !this.throttled) {\n                    var t = void 0;\n                    try {\n                        t = (0, this.durationSelector)(e)\n                    } catch (e) {\n                        return this.destination.error(e)\n                    }\n                    t = Hr(t, new $r(this));\n                    !t || t.closed ? this.clearThrottle() : this.add(this.throttled = t)\n                }\n            }, Bn.prototype.clearThrottle = function() {\n                var e = this.value,\n                    t = this.hasValue,\n                    i = this.throttled;\n                i && (this.remove(i), this.throttled = void 0, i.unsubscribe()), t && (this.value = void 0, this.hasValue = !1, this.destination.next(e))\n            }, Bn.prototype.notifyNext = function() {\n                this.clearThrottle()\n            }, Bn.prototype.notifyComplete = function() {\n                this.clearThrottle()\n            }, Bn);\n\n        function Bn(e, t) {\n            e = _n.call(this, e) || this;\n            return e.durationSelector = t, e.hasValue = !1, e\n        }\n\n        function Un(e) {\n            this.durationSelector = e\n        }\n\n        function $n(e, t) {\n            return void 0 === t && (t = ir), i = function() {\n                    return bn(e, t)\n                },\n                function(e) {\n                    return e.lift(new Nn(i))\n                };\n            var i\n        }\n\n        function Vn(i) {\n            return function(e) {\n                var t = new qn(i),\n                    e = e.lift(t);\n                return t.caught = e\n            }\n        }\n        var Kn, qn = (Qn.prototype.call = function(e, t) {\n                return t.subscribe(new Hn(e, this.selector, this.caught))\n            }, Qn),\n            Hn = (ut(jn, Kn = Vr), jn.prototype.error = function(e) {\n                if (!this.isStopped) {\n                    var t = void 0;\n                    try {\n                        t = this.selector(e, this.caught)\n                    } catch (e) {\n                        return void Kn.prototype.error.call(this, e)\n                    }\n                    this._unsubscribeAndRecycle();\n                    var i = new $r(this);\n                    this.add(i);\n                    t = Hr(t, i);\n                    t !== i && this.add(t)\n                }\n            }, jn);\n\n        function jn(e, t, i) {\n            e = Kn.call(this, e) || this;\n            return e.selector = t, e.caught = i, e\n        }\n\n        function Qn(e) {\n            this.selector = e\n        }\n\n        function Wn(e, t) {\n            return jr(e, t, 1)\n        }\n\n        function Gn(t, i) {\n            return void 0 === i && (i = ir),\n                function(e) {\n                    return e.lift(new Xn(t, i))\n                }\n        }\n        var zn, Xn = (Zn.prototype.call = function(e, t) {\n                return t.subscribe(new Yn(e, this.dueTime, this.scheduler))\n            }, Zn),\n            Yn = (ut(Jn, zn = Pt), Jn.prototype._next = function(e) {\n                this.clearDebounce(), this.lastValue = e, this.hasValue = !0, this.add(this.debouncedSubscription = this.scheduler.schedule(es, this.dueTime, this))\n            }, Jn.prototype._complete = function() {\n                this.debouncedNext(), this.destination.complete()\n            }, Jn.prototype.debouncedNext = function() {\n                var e;\n                this.clearDebounce(), this.hasValue && (e = this.lastValue, this.lastValue = null, this.hasValue = !1, this.destination.next(e))\n            }, Jn.prototype.clearDebounce = function() {\n                var e = this.debouncedSubscription;\n                null !== e && (this.remove(e), e.unsubscribe(), this.debouncedSubscription = null)\n            }, Jn);\n\n        function Jn(e, t, i) {\n            e = zn.call(this, e) || this;\n            return e.dueTime = t, e.scheduler = i, e.debouncedSubscription = null, e.lastValue = null, e.hasValue = !1, e\n        }\n\n        function Zn(e, t) {\n            this.dueTime = e, this.scheduler = t\n        }\n\n        function es(e) {\n            e.debouncedNext()\n        }\n        var ts, is = (ss.prototype.call = function(e, t) {\n                return t.subscribe(new rs(e, this.defaultValue))\n            }, ss),\n            rs = (ut(ns, ts = Pt), ns.prototype._next = function(e) {\n                this.isEmpty = !1, this.destination.next(e)\n            }, ns.prototype._complete = function() {\n                this.isEmpty && this.destination.next(this.defaultValue), this.destination.complete()\n            }, ns);\n\n        function ns(e, t) {\n            e = ts.call(this, e) || this;\n            return e.defaultValue = t, e.isEmpty = !0, e\n        }\n\n        function ss(e) {\n            this.defaultValue = e\n        }\n\n        function as(e) {\n            return e instanceof Date && !isNaN(+e)\n        }\n        var os, ls = (hs.prototype.call = function(e, t) {\n                return t.subscribe(new ds(e, this.delay, this.scheduler))\n            }, hs),\n            ds = (ut(cs, os = Pt), cs.dispatch = function(e) {\n                for (var t, i = e.source, r = i.queue, n = e.scheduler, s = e.destination; 0 < r.length && r[0].time - n.now() <= 0;) r.shift().notification.observe(s);\n                0 < r.length ? (t = Math.max(0, r[0].time - n.now()), this.schedule(e, t)) : (this.unsubscribe(), i.active = !1)\n            }, cs.prototype._schedule = function(e) {\n                this.active = !0, this.destination.add(e.schedule(cs.dispatch, this.delay, {\n                    source: this,\n                    destination: this.destination,\n                    scheduler: e\n                }))\n            }, cs.prototype.scheduleNotification = function(e) {\n                var t;\n                !0 !== this.errored && (t = this.scheduler, e = new us(t.now() + this.delay, e), this.queue.push(e), !1 === this.active && this._schedule(t))\n            }, cs.prototype._next = function(e) {\n                this.scheduleNotification(qi.createNext(e))\n            }, cs.prototype._error = function(e) {\n                this.errored = !0, this.queue = [], this.destination.error(e), this.unsubscribe()\n            }, cs.prototype._complete = function() {\n                this.scheduleNotification(qi.createComplete()), this.unsubscribe()\n            }, cs),\n            us = function(e, t) {\n                this.time = e, this.notification = t\n            };\n\n        function cs(e, t, i) {\n            e = os.call(this, e) || this;\n            return e.delay = t, e.scheduler = i, e.queue = [], e.active = !1, e.errored = !1, e\n        }\n\n        function hs(e, t) {\n            this.delay = e, this.scheduler = t\n        }\n        var ps, fs, ms, gs = (Es.prototype.call = function(e, t) {\n                return t.subscribe(new ys(e, this.delayDurationSelector))\n            }, Es),\n            ys = (ut(Ts, ms = vr), Ts.prototype.notifyNext = function(e, t, i, r, n) {\n                this.destination.next(e), this.removeSubscription(n), this.tryComplete()\n            }, Ts.prototype.notifyError = function(e, t) {\n                this._error(e)\n            }, Ts.prototype.notifyComplete = function(e) {\n                e = this.removeSubscription(e);\n                e && this.destination.next(e), this.tryComplete()\n            }, Ts.prototype._next = function(e) {\n                var t = this.index++;\n                try {\n                    var i = this.delayDurationSelector(e, t);\n                    i && this.tryDelay(i, e)\n                } catch (e) {\n                    this.destination.error(e)\n                }\n            }, Ts.prototype._complete = function() {\n                this.completed = !0, this.tryComplete(), this.unsubscribe()\n            }, Ts.prototype.removeSubscription = function(e) {\n                e.unsubscribe();\n                var t = this.delayNotifierSubscriptions.indexOf(e);\n                return -1 !== t && this.delayNotifierSubscriptions.splice(t, 1), e.outerValue\n            }, Ts.prototype.tryDelay = function(e, t) {\n                t = Cr(this, e, t);\n                t && !t.closed && (this.destination.add(t), this.delayNotifierSubscriptions.push(t))\n            }, Ts.prototype.tryComplete = function() {\n                this.completed && 0 === this.delayNotifierSubscriptions.length && this.destination.complete()\n            }, Ts),\n            vs = (ut(bs, fs = $t), bs.prototype._subscribe = function(e) {\n                this.subscriptionDelay.subscribe(new vs(e, this.source))\n            }, ut(Ss, ps = Pt), Ss.prototype._next = function(e) {\n                this.subscribeToSource()\n            }, Ss.prototype._error = function(e) {\n                this.unsubscribe(), this.parent.error(e)\n            }, Ss.prototype._complete = function() {\n                this.unsubscribe(), this.subscribeToSource()\n            }, Ss.prototype.subscribeToSource = function() {\n                this.sourceSubscribed || (this.sourceSubscribed = !0, this.unsubscribe(), this.source.subscribe(this.parent))\n            }, Ss);\n\n        function Ss(e, t) {\n            var i = ps.call(this) || this;\n            return i.parent = e, i.source = t, i.sourceSubscribed = !1, i\n        }\n\n        function bs(e, t) {\n            var i = fs.call(this) || this;\n            return i.source = e, i.subscriptionDelay = t, i\n        }\n\n        function Ts(e, t) {\n            e = ms.call(this, e) || this;\n            return e.delayDurationSelector = t, e.completed = !1, e.delayNotifierSubscriptions = [], e.index = 0, e\n        }\n\n        function Es(e) {\n            this.delayDurationSelector = e\n        }\n\n        function Is(t, i) {\n            return function(e) {\n                return e.lift(new As(t, i))\n            }\n        }\n        var ws, As = (Cs.prototype.call = function(e, t) {\n                return t.subscribe(new Os(e, this.compare, this.keySelector))\n            }, Cs),\n            Os = (ut(ks, ws = Pt), ks.prototype.compare = function(e, t) {\n                return e === t\n            }, ks.prototype._next = function(e) {\n                try {\n                    var t = this.keySelector,\n                        i = t ? t(e) : e\n                } catch (e) {\n                    return this.destination.error(e)\n                }\n                t = !1;\n                if (this.hasKey) try {\n                    t = (0, this.compare)(this.key, i)\n                } catch (e) {\n                    return this.destination.error(e)\n                } else this.hasKey = !0;\n                t || (this.key = i, this.destination.next(e))\n            }, ks);\n\n        function ks(e, t, i) {\n            e = ws.call(this, e) || this;\n            return e.keySelector = i, e.hasKey = !1, \"function\" == typeof t && (e.compare = t), e\n        }\n\n        function Cs(e, t) {\n            this.compare = e, this.keySelector = t\n        }\n\n        function Ds(t) {\n            return function(e) {\n                return 0 === t ? _i() : e.lift(new xs(t))\n            }\n        }\n        var Ms, xs = (Ls.prototype.call = function(e, t) {\n                return t.subscribe(new Ps(e, this.total))\n            }, Ls),\n            Ps = (ut(Rs, Ms = Pt), Rs.prototype._next = function(e) {\n                var t = this.total,\n                    i = ++this.count;\n                i <= t && (this.destination.next(e), i === t && (this.destination.complete(), this.unsubscribe()))\n            }, Rs);\n\n        function Rs(e, t) {\n            e = Ms.call(this, e) || this;\n            return e.total = t, e.count = 0, e\n        }\n\n        function Ls(e) {\n            if (this.total = e, this.total < 0) throw new lr\n        }\n\n        function _s(t, n) {\n            return n ? function(e) {\n                return e.pipe(_s(function(i, r) {\n                    return Fr(t(i, r)).pipe(hr(function(e, t) {\n                        return n(i, e, r, t)\n                    }))\n                }))\n            } : function(e) {\n                return e.lift(new Fs(t))\n            }\n        }\n        var Ns, Fs = ($s.prototype.call = function(e, t) {\n                return t.subscribe(new Bs(e, this.project))\n            }, $s),\n            Bs = (ut(Us, Ns = Vr), Us.prototype._next = function(e) {\n                this.hasSubscription || this.tryNext(e)\n            }, Us.prototype.tryNext = function(e) {\n                var t, i = this.index++;\n                try {\n                    t = this.project(e, i)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.hasSubscription = !0, this._innerSub(t)\n            }, Us.prototype._innerSub = function(e) {\n                var t = new $r(this),\n                    i = this.destination;\n                i.add(t);\n                e = Hr(e, t);\n                e !== t && i.add(e)\n            }, Us.prototype._complete = function() {\n                this.hasCompleted = !0, this.hasSubscription || this.destination.complete(), this.unsubscribe()\n            }, Us.prototype.notifyNext = function(e) {\n                this.destination.next(e)\n            }, Us.prototype.notifyError = function(e) {\n                this.destination.error(e)\n            }, Us.prototype.notifyComplete = function() {\n                this.hasSubscription = !1, this.hasCompleted && this.destination.complete()\n            }, Us);\n\n        function Us(e, t) {\n            e = Ns.call(this, e) || this;\n            return e.project = t, e.hasSubscription = !1, e.hasCompleted = !1, e.index = 0, e\n        }\n\n        function $s(e) {\n            this.project = e\n        }\n\n        function Vs(t) {\n            return function(e) {\n                return e.lift(new qs(t))\n            }\n        }\n        var Ks, qs = (Qs.prototype.call = function(e, t) {\n                return t.subscribe(new Hs(e, this.callback))\n            }, Qs),\n            Hs = (ut(js, Ks = Pt), js);\n\n        function js(e, t) {\n            e = Ks.call(this, e) || this;\n            return e.add(new At(t)), e\n        }\n\n        function Qs(e) {\n            this.callback = e\n        }\n\n        function Ws(t) {\n            return function(e) {\n                return 0 === t ? _i() : e.lift(new zs(t))\n            }\n        }\n        var Gs, zs = (Js.prototype.call = function(e, t) {\n                return t.subscribe(new Xs(e, this.total))\n            }, Js),\n            Xs = (ut(Ys, Gs = Pt), Ys.prototype._next = function(e) {\n                var t = this.ring,\n                    i = this.total,\n                    r = this.count++;\n                t.length < i ? t.push(e) : t[r % i] = e\n            }, Ys.prototype._complete = function() {\n                var e = this.destination,\n                    t = this.count;\n                if (0 < t)\n                    for (var i = this.count >= this.total ? this.total : this.count, r = this.ring, n = 0; n < i; n++) {\n                        var s = t++ % i;\n                        e.next(r[s])\n                    }\n                e.complete()\n            }, Ys);\n\n        function Ys(e, t) {\n            e = Gs.call(this, e) || this;\n            return e.total = t, e.ring = new Array, e.count = 0, e\n        }\n\n        function Js(e) {\n            if (this.total = e, this.total < 0) throw new lr\n        }\n\n        function Zs(t) {\n            return function(e) {\n                return e.lift(new ta(t))\n            }\n        }\n        var ea, ta = (na.prototype.call = function(e, t) {\n                return t.subscribe(new ia(e, this.value))\n            }, na),\n            ia = (ut(ra, ea = Pt), ra.prototype._next = function(e) {\n                this.destination.next(this.value)\n            }, ra);\n\n        function ra(e, t) {\n            e = ea.call(this, e) || this;\n            return e.value = t, e\n        }\n\n        function na(e) {\n            this.value = e\n        }\n\n        function sa(t, i) {\n            var r = 2 <= arguments.length ? !0 : !1;\n            return function(e) {\n                return e.lift(new oa(t, i, r))\n            }\n        }\n        var aa, oa = (ua.prototype.call = function(e, t) {\n                return t.subscribe(new la(e, this.accumulator, this.seed, this.hasSeed))\n            }, ua),\n            la = (ut(da, aa = Pt), Object.defineProperty(da.prototype, \"seed\", {\n                get: function() {\n                    return this._seed\n                },\n                set: function(e) {\n                    this.hasSeed = !0, this._seed = e\n                },\n                enumerable: !0,\n                configurable: !0\n            }), da.prototype._next = function(e) {\n                if (this.hasSeed) return this._tryNext(e);\n                this.seed = e, this.destination.next(e)\n            }, da.prototype._tryNext = function(e) {\n                var t, i = this.index++;\n                try {\n                    t = this.accumulator(this.seed, e, i)\n                } catch (e) {\n                    this.destination.error(e)\n                }\n                this.seed = t, this.destination.next(t)\n            }, da);\n\n        function da(e, t, i, r) {\n            e = aa.call(this, e) || this;\n            return e.accumulator = t, e._seed = i, e.hasSeed = r, e.index = 0, e\n        }\n\n        function ua(e, t, i) {\n            void 0 === i && (i = !1), this.accumulator = e, this.seed = t, this.hasSeed = i\n        }\n        ca.prototype.call = function(e, t) {\n            var i = this.selector,\n                r = this.subjectFactory(),\n                e = i(r).subscribe(e);\n            return e.add(t.subscribe(r)), e\n        };\n\n        function ca(e, t) {\n            this.subjectFactory = e, this.selector = t\n        }\n\n        function ha() {\n            return function(e) {\n                return e.lift(new fa)\n            }\n        }\n        var pa, fa = (ya.prototype.call = function(e, t) {\n                return t.subscribe(new ma(e))\n            }, ya),\n            ma = (ut(ga, pa = Pt), ga.prototype._next = function(e) {\n                var t;\n                this.hasPrev ? t = [this.prev, e] : this.hasPrev = !0, this.prev = e, t && this.destination.next(t)\n            }, ga);\n\n        function ga(e) {\n            e = pa.call(this, e) || this;\n            return e.hasPrev = !1, e\n        }\n\n        function ya() {}\n\n        function va(t) {\n            return function(e) {\n                return e.lift(new ba(t, e))\n            }\n        }\n        var Sa, ba = (Ia.prototype.call = function(e, t) {\n                return t.subscribe(new Ta(e, this.notifier, this.source))\n            }, Ia),\n            Ta = (ut(Ea, Sa = Vr), Ea.prototype.error = function(e) {\n                if (!this.isStopped) {\n                    var t = this.errors,\n                        i = this.retries,\n                        r = this.retriesSubscription;\n                    if (i) this.errors = void 0, this.retriesSubscription = void 0;\n                    else {\n                        t = new Xt;\n                        try {\n                            i = (0, this.notifier)(t)\n                        } catch (e) {\n                            return Sa.prototype.error.call(this, e)\n                        }\n                        r = Hr(i, new $r(this))\n                    }\n                    this._unsubscribeAndRecycle(), this.errors = t, this.retries = i, this.retriesSubscription = r, t.next(e)\n                }\n            }, Ea.prototype._unsubscribe = function() {\n                var e = this.errors,\n                    t = this.retriesSubscription;\n                e && (e.unsubscribe(), this.errors = void 0), t && (t.unsubscribe(), this.retriesSubscription = void 0), this.retries = void 0\n            }, Ea.prototype.notifyNext = function() {\n                var e = this._unsubscribe;\n                this._unsubscribe = null, this._unsubscribeAndRecycle(), this._unsubscribe = e, this.source.subscribe(this)\n            }, Ea);\n\n        function Ea(e, t, i) {\n            e = Sa.call(this, e) || this;\n            return e.notifier = t, e.source = i, e\n        }\n\n        function Ia(e, t) {\n            this.notifier = e, this.source = t\n        }\n\n        function wa() {\n            return new Xt\n        }\n\n        function Aa() {\n            return function(e) {\n                return ri()((t = e, i = \"function\" == typeof(r = wa) ? r : function() {\n                    return r\n                }, (e = Object.create(t, mi)).source = t, e.subjectFactory = i, e));\n                var t, i, r\n            }\n        }\n\n        function Oa(e, t, i) {\n            var c = e && \"object\" == typeof e ? e : {\n                bufferSize: e,\n                windowTime: t,\n                refCount: !1,\n                scheduler: i\n            };\n            return function(e) {\n                return e.lift((e = c.bufferSize, n = void 0 === e ? Number.POSITIVE_INFINITY : e, e = c.windowTime, s = void 0 === e ? Number.POSITIVE_INFINITY : e, a = c.refCount, o = c.scheduler, l = 0, u = d = !1, function(e) {\n                    var t;\n                    l++, !i || d ? (d = !1, i = new Ji(n, s, o), t = i.subscribe(this), r = e.subscribe({\n                        next: function(e) {\n                            i.next(e)\n                        },\n                        error: function(e) {\n                            d = !0, i.error(e)\n                        },\n                        complete: function() {\n                            u = !0, r = void 0, i.complete()\n                        }\n                    }), u && (r = void 0)) : t = i.subscribe(this), this.add(function() {\n                        l--, t.unsubscribe(), t = void 0, r && !u && a && 0 === l && (r.unsubscribe(), i = r = void 0)\n                    })\n                }));\n                var i, r, n, s, a, o, l, d, u\n            }\n        }\n\n        function ka(t) {\n            return function(e) {\n                return e.lift(new Da(t))\n            }\n        }\n        var Ca, Da = (Pa.prototype.call = function(e, t) {\n                return t.subscribe(new Ma(e, this.total))\n            }, Pa),\n            Ma = (ut(xa, Ca = Pt), xa.prototype._next = function(e) {\n                ++this.count > this.total && this.destination.next(e)\n            }, xa);\n\n        function xa(e, t) {\n            e = Ca.call(this, e) || this;\n            return e.total = t, e.count = 0, e\n        }\n\n        function Pa(e) {\n            this.total = e\n        }\n\n        function Ra() {\n            for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];\n            var i = t[t.length - 1];\n            return Ni(i) ? (t.pop(), function(e) {\n                return Jr(t, e, i)\n            }) : function(e) {\n                return Jr(t, e)\n            }\n        }\n\n        function La(t, n) {\n            return \"function\" == typeof n ? function(e) {\n                return e.pipe(La(function(i, r) {\n                    return Fr(t(i, r)).pipe(hr(function(e, t) {\n                        return n(i, e, r, t)\n                    }))\n                }))\n            } : function(e) {\n                return e.lift(new Na(t))\n            }\n        }\n        var _a, Na = (Ua.prototype.call = function(e, t) {\n                return t.subscribe(new Fa(e, this.project))\n            }, Ua),\n            Fa = (ut(Ba, _a = Vr), Ba.prototype._next = function(e) {\n                var t, i = this.index++;\n                try {\n                    t = this.project(e, i)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this._innerSub(t)\n            }, Ba.prototype._innerSub = function(e) {\n                var t = this.innerSubscription;\n                t && t.unsubscribe();\n                var i = new $r(this),\n                    t = this.destination;\n                t.add(i), this.innerSubscription = Hr(e, i), this.innerSubscription !== i && t.add(this.innerSubscription)\n            }, Ba.prototype._complete = function() {\n                var e = this.innerSubscription;\n                e && !e.closed || _a.prototype._complete.call(this), this.unsubscribe()\n            }, Ba.prototype._unsubscribe = function() {\n                this.innerSubscription = void 0\n            }, Ba.prototype.notifyComplete = function() {\n                this.innerSubscription = void 0, this.isStopped && _a.prototype._complete.call(this)\n            }, Ba.prototype.notifyNext = function(e) {\n                this.destination.next(e)\n            }, Ba);\n\n        function Ba(e, t) {\n            e = _a.call(this, e) || this;\n            return e.project = t, e.index = 0, e\n        }\n\n        function Ua(e) {\n            this.project = e\n        }\n\n        function $a(e, t) {\n            return t ? La(function() {\n                return e\n            }, t) : La(function() {\n                return e\n            })\n        }\n\n        function Va(t) {\n            return function(e) {\n                return e.lift(new qa(t))\n            }\n        }\n        var Ka, qa = (Qa.prototype.call = function(e, t) {\n                var i = new Ha(e),\n                    e = Hr(this.notifier, new $r(i));\n                return e && !i.seenValue ? (i.add(e), t.subscribe(i)) : i\n            }, Qa),\n            Ha = (ut(ja, Ka = Vr), ja.prototype.notifyNext = function() {\n                this.seenValue = !0, this.complete()\n            }, ja.prototype.notifyComplete = function() {}, ja);\n\n        function ja(e) {\n            e = Ka.call(this, e) || this;\n            return e.seenValue = !1, e\n        }\n\n        function Qa(e) {\n            this.notifier = e\n        }\n\n        function Wa(t, i) {\n            return void 0 === i && (i = !1),\n                function(e) {\n                    return e.lift(new za(t, i))\n                }\n        }\n        var Ga, za = (Ja.prototype.call = function(e, t) {\n                return t.subscribe(new Xa(e, this.predicate, this.inclusive))\n            }, Ja),\n            Xa = (ut(Ya, Ga = Pt), Ya.prototype._next = function(e) {\n                var t, i = this.destination;\n                try {\n                    t = this.predicate(e, this.index++)\n                } catch (e) {\n                    return void i.error(e)\n                }\n                this.nextOrComplete(e, t)\n            }, Ya.prototype.nextOrComplete = function(e, t) {\n                var i = this.destination;\n                Boolean(t) ? i.next(e) : (this.inclusive && i.next(e), i.complete())\n            }, Ya);\n\n        function Ya(e, t, i) {\n            e = Ga.call(this, e) || this;\n            return e.predicate = t, e.inclusive = i, e.index = 0, e\n        }\n\n        function Ja(e, t) {\n            this.predicate = e, this.inclusive = t\n        }\n\n        function Za(t, i, r) {\n            return function(e) {\n                return e.lift(new to(t, i, r))\n            }\n        }\n        var eo, to = (so.prototype.call = function(e, t) {\n                return t.subscribe(new io(e, this.nextOrObserver, this.error, this.complete))\n            }, so),\n            io = (ut(no, eo = Pt), no.prototype._next = function(e) {\n                try {\n                    this._tapNext.call(this._context, e)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.destination.next(e)\n            }, no.prototype._error = function(e) {\n                try {\n                    this._tapError.call(this._context, e)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.destination.error(e)\n            }, no.prototype._complete = function() {\n                try {\n                    this._tapComplete.call(this._context)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                return this.destination.complete()\n            }, no),\n            ro = {\n                leading: !0,\n                trailing: !1\n            };\n\n        function no(e, t, i, r) {\n            e = eo.call(this, e) || this;\n            return e._tapNext = or, e._tapError = or, e._tapComplete = or, e._tapError = i || or, e._tapComplete = r || or, yt(t) ? (e._context = e)._tapNext = t : t && (e._context = t, e._tapNext = t.next || or, e._tapError = t.error || or, e._tapComplete = t.complete || or), e\n        }\n\n        function so(e, t, i) {\n            this.nextOrObserver = e, this.error = t, this.complete = i\n        }\n\n        function ao(t, i, r) {\n            return void 0 === i && (i = ir), void 0 === r && (r = ro),\n                function(e) {\n                    return e.lift(new lo(t, i, r.leading, r.trailing))\n                }\n        }\n        var oo, lo = (ho.prototype.call = function(e, t) {\n                return t.subscribe(new uo(e, this.duration, this.scheduler, this.leading, this.trailing))\n            }, ho),\n            uo = (ut(co, oo = Pt), co.prototype._next = function(e) {\n                this.throttled ? this.trailing && (this._trailingValue = e, this._hasTrailingValue = !0) : (this.add(this.throttled = this.scheduler.schedule(po, this.duration, {\n                    subscriber: this\n                })), this.leading ? this.destination.next(e) : this.trailing && (this._trailingValue = e, this._hasTrailingValue = !0))\n            }, co.prototype._complete = function() {\n                this._hasTrailingValue && this.destination.next(this._trailingValue), this.destination.complete()\n            }, co.prototype.clearThrottle = function() {\n                var e = this.throttled;\n                e && (this.trailing && this._hasTrailingValue && (this.destination.next(this._trailingValue), this._trailingValue = null, this._hasTrailingValue = !1), e.unsubscribe(), this.remove(e), this.throttled = null)\n            }, co);\n\n        function co(e, t, i, r, n) {\n            e = oo.call(this, e) || this;\n            return e.duration = t, e.scheduler = i, e.leading = r, e.trailing = n, e._hasTrailingValue = !1, e._trailingValue = null, e\n        }\n\n        function ho(e, t, i, r) {\n            this.duration = e, this.scheduler = t, this.leading = i, this.trailing = r\n        }\n\n        function po(e) {\n            e.subscriber.clearThrottle()\n        }\n        var fo, mo = (vo.prototype.call = function(e, t) {\n                return t.subscribe(new go(e, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler))\n            }, vo),\n            go = (ut(yo, fo = Vr), yo.dispatchTimeout = function(e) {\n                var t = e.withObservable;\n                e._unsubscribeAndRecycle(), e.add(Hr(t, new $r(e)))\n            }, yo.prototype.scheduleTimeout = function() {\n                var e = this.action;\n                e ? this.action = e.schedule(this, this.waitFor) : this.add(this.action = this.scheduler.schedule(yo.dispatchTimeout, this.waitFor, this))\n            }, yo.prototype._next = function(e) {\n                this.absoluteTimeout || this.scheduleTimeout(), fo.prototype._next.call(this, e)\n            }, yo.prototype._unsubscribe = function() {\n                this.action = void 0, this.scheduler = null, this.withObservable = null\n            }, yo);\n\n        function yo(e, t, i, r, n) {\n            e = fo.call(this, e) || this;\n            return e.absoluteTimeout = t, e.waitFor = i, e.withObservable = r, e.scheduler = n, e.scheduleTimeout(), e\n        }\n\n        function vo(e, t, i, r) {\n            this.waitFor = e, this.absoluteTimeout = t, this.withObservable = i, this.scheduler = r\n        }\n\n        function So(e, t) {\n            return void 0 === t && (t = ir), r = e, n = Vi(new dr), void 0 === (s = t) && (s = ir),\n                function(e) {\n                    var t = as(r),\n                        i = t ? +r - s.now() : Math.abs(r);\n                    return e.lift(new mo(i, t, n, s))\n                };\n            var r, n, s\n        }\n\n        function bo() {\n            for (var i = [], e = 0; e < arguments.length; e++) i[e] = arguments[e];\n            return function(e) {\n                var t;\n                return \"function\" == typeof i[i.length - 1] && (t = i.pop()), e.lift(new Io(i, t))\n            }\n        }\n        var To, Eo, Io = (Co.prototype.call = function(e, t) {\n                return t.subscribe(new wo(e, this.observables, this.project))\n            }, Co),\n            wo = (ut(ko, To = vr), ko.prototype.notifyNext = function(e, t, i) {\n                this.values[i] = t;\n                t = this.toRespond;\n                0 < t.length && (-1 !== (i = t.indexOf(i)) && t.splice(i, 1))\n            }, ko.prototype.notifyComplete = function() {}, ko.prototype._next = function(e) {\n                0 === this.toRespond.length && (e = [e].concat(this.values), this.project ? this._tryProject(e) : this.destination.next(e))\n            }, ko.prototype._tryProject = function(e) {\n                var t;\n                try {\n                    t = this.project.apply(this, e)\n                } catch (e) {\n                    return void this.destination.error(e)\n                }\n                this.destination.next(t)\n            }, ko),\n            Ao = {\n                type: null,\n                entityIds: null,\n                skip: !1\n            },\n            Oo = !1;\n\n        function ko(e, t, i) {\n            var r = To.call(this, e) || this;\n            r.observables = t, r.project = i, r.toRespond = [];\n            var n = t.length;\n            r.values = new Array(n);\n            for (var s = 0; s < n; s++) r.toRespond.push(s);\n            for (s = 0; s < n; s++) {\n                var a = t[s];\n                r.add(Cr(r, a, void 0, s))\n            }\n            return r\n        }\n\n        function Co(e, t) {\n            this.observables = e, this.project = t\n        }\n\n        function Do(e, t) {\n            Mo(e, t), Oo = !0\n        }\n\n        function Mo(e, t) {\n            !1 === Oo && (Ao.type = e, Ao.entityIds = t)\n        }\n\n        function xo(e, t) {\n            return e.hasOwnProperty(t)\n        }\n\n        function Po(e) {\n            return null == e\n        }\n\n        function Ro(e) {\n            return Po(e) ? [] : Array.isArray(e) ? e : [e]\n        }(iu = Eo = Eo || {}).Set = \"Set\", iu.Add = \"Add\", iu.Update = \"Update\", iu.Remove = \"Remove\";\n        var Lo = \"undefined\" != typeof window,\n            _o = !0;\n\n        function No(e) {\n            var t = typeof e;\n            return null != e && (\"object\" == t || \"function\" == t)\n        }\n\n        function Fo(e) {\n            return Array.isArray(e)\n        }\n\n        function Bo(e) {\n            return !1 === Po(e)\n        }\n\n        function Uo(e) {\n            return Fo(e) && 0 === e.length\n        }\n\n        function $o(e) {\n            return \"function\" == typeof e\n        }\n\n        function Vo(e) {\n            return void 0 === e\n        }\n\n        function Ko(e) {\n            return e.hasOwnProperty(\"active\")\n        }\n\n        function qo(e) {\n            return Fo(e)\n        }\n\n        function Ho(e) {\n            var t, i = e.active,\n                r = e.ids,\n                n = e.entities;\n            return qo(i) ? (t = r, (r = (e = i).filter(function(e) {\n                return -1 < t.indexOf(e)\n            })).length === e.length ? e : r) : !1 === xo(n, i) ? null : i\n        }\n\n        function jo(e, t) {\n            var i, r, n = {};\n            try {\n                for (var s = ft(Object.keys(e)), a = s.next(); !a.done; a = s.next()) {\n                    var o = a.value;\n                    n[o] = t(e[o])\n                }\n            } catch (e) {\n                i = {\n                    error: e\n                }\n            } finally {\n                try {\n                    a && !a.done && (r = s.return) && r.call(s)\n                } finally {\n                    if (i) throw i.error\n                }\n            }\n            return n\n        }\n        var Qo = {\n            resettable: !1,\n            ttl: null,\n            producerFn: void 0\n        };\n\n        function Wo(t) {\n            Object.freeze(t);\n            var i = \"function\" == typeof t,\n                r = Object.prototype.hasOwnProperty;\n            return Object.getOwnPropertyNames(t).forEach(function(e) {\n                !r.call(t, e) || i && (\"caller\" === e || \"callee\" === e || \"arguments\" === e) || null === t[e] || \"object\" != typeof t[e] && \"function\" != typeof t[e] || Object.isFrozen(t[e]) || Wo(t[e])\n            }), t\n        }\n        var Go, zo = new Xt,\n            Xo = new Ji(50, 5e3),\n            Yo = new Xt;\n\n        function Jo(e) {\n            return null != e && \"\" + e != \"false\"\n        }\n\n        function Zo(e) {\n            return Jo(e) && \"Object\" === e.constructor.name\n        }\n        ut(function(e) {\n            return Go.call(this, e) || this\n        }, Go = Error);\n        var el = {},\n            tl = {};\n        Lo && (window.$$stores = el, window.$$queries = tl);\n        var il = new Xt,\n            rl = new yi(!1),\n            nl = {\n                activeTransactions: 0,\n                batchTransaction: null\n            };\n\n        function sl() {\n            return 0 < nl.activeTransactions\n        }\n\n        function al(e, t) {\n            void 0 === t && (t = void 0), sl() || (nl.batchTransaction = new Xt), nl.activeTransactions++, rl.next(!0);\n            try {\n                return e.apply(t)\n            } finally {\n                Do(\"@Transaction\"), 0 == --nl.activeTransactions && (nl.batchTransaction.next(!0), nl.batchTransaction.complete(), rl.next(!1), il.next(!0))\n            }\n        }\n\n        function ol() {\n            return function(e, t, i) {\n                var r = i.value;\n                return i.value = function() {\n                    for (var e = this, t = [], i = 0; i < arguments.length; i++) t[i] = arguments[i];\n                    return al(function() {\n                        return r.apply(e, t)\n                    }, this)\n                }, i\n            }\n        }\n\n        function ll(t) {\n            return function(e) {\n                return e.pipe(Za(function(e) {\n                    return al(function() {\n                        return t(e)\n                    })\n                }))\n            }\n        }\n        var dl = (ul.prototype.setLoading = function(t) {\n            (t = void 0 === t ? !1 : t) !== this._value().loading && (_o && Mo(\"Set Loading\"), this._setState(function(e) {\n                return ct({}, e, {\n                    loading: t\n                })\n            }))\n        }, ul.prototype.setHasCache = function(e, t) {\n            var i, r = this;\n            void 0 === t && (t = {\n                restartTTL: !1\n            }), e !== this.cache.active.value && this.cache.active.next(e), t.restartTTL && (i = this.getCacheTTL()) && (null !== this.cache.ttl && clearTimeout(this.cache.ttl), this.cache.ttl = setTimeout(function() {\n                return r.setHasCache(!1)\n            }, i))\n        }, ul.prototype.getValue = function() {\n            return this.storeValue\n        }, ul.prototype.setError = function(t) {\n            t !== this._value().error && (_o && Mo(\"Set Error\"), this._setState(function(e) {\n                return ct({}, e, {\n                    error: t\n                })\n            }))\n        }, ul.prototype._select = function(t) {\n            return this.store.asObservable().pipe(hr(function(e) {\n                return t(e.state)\n            }), Is())\n        }, ul.prototype._value = function() {\n            return this.storeValue\n        }, ul.prototype._cache = function() {\n            return this.cache.active\n        }, Object.defineProperty(ul.prototype, \"config\", {\n            get: function() {\n                return this.constructor.akitaConfig || {}\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty(ul.prototype, \"storeName\", {\n            get: function() {\n                return this.config.storeName || this.options.storeName || this.options.name\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty(ul.prototype, \"deepFreeze\", {\n            get: function() {\n                return this.config.deepFreezeFn || this.options.deepFreezeFn || Wo\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty(ul.prototype, \"cacheConfig\", {\n            get: function() {\n                return this.config.cache || this.options.cache\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty(ul.prototype, \"_producerFn\", {\n            get: function() {\n                return this.config.producerFn || this.options.producerFn || Qo.producerFn\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty(ul.prototype, \"resettable\", {\n            get: function() {\n                return (Bo(this.config.resettable) ? this.config : this.options).resettable\n            },\n            enumerable: !0,\n            configurable: !0\n        }), ul.prototype._setState = function(e, t) {\n            var i, r = this;\n            if (void 0 === t && (t = !0), $o(e) ? (i = e(this._value()), this.storeValue = _o ? this.deepFreeze(i) : i) : this.storeValue = e, !this.store) return this.store = new yi({\n                state: this.storeValue\n            }), void(_o && this.store.subscribe(function(e) {\n                var t = e.action;\n                t && (e = r.storeName, Yo.next({\n                    storeName: e,\n                    action: t\n                }))\n            }));\n            sl() ? this.handleTransaction() : this.dispatch(this.storeValue, t)\n        }, ul.prototype.reset = function() {\n            var e = this;\n            this.isResettable() ? (_o && Mo(\"Reset\"), this._setState(function() {\n                return Object.assign({}, e._initialState)\n            }), this.setHasCache(!1)) : _o && console.warn(\"You need to enable the reset functionality\")\n        }, ul.prototype.update = function(e) {\n            _o && Mo(\"Update\");\n            var t = this._value(),\n                e = $o(e) ? $o(this._producerFn) ? this._producerFn(t, e) : e(t) : e,\n                e = this.akitaPreUpdate(t, ct({}, t, e)),\n                e = Zo(t) ? e : new t.constructor(e);\n            this._setState(e)\n        }, ul.prototype.updateStoreConfig = function(e) {\n            this.options = ct({}, this.options, e)\n        }, ul.prototype.akitaPreUpdate = function(e, t) {\n            return t\n        }, ul.prototype.ngOnDestroy = function() {\n            this.destroy()\n        }, ul.prototype.destroy = function() {\n            var e;\n            Lo && window.hmrEnabled || this !== el[this.storeName] || (delete el[this.storeName], e = this.storeName, zo.next(e), this.setHasCache(!1), this.cache.active.complete(), this.store.complete())\n        }, ul.prototype.onInit = function(e) {\n            var t, i;\n            (el[this.storeName] = this)._setState(function() {\n                return e\n            }), i = this.storeName, Xo.next(i), this.isResettable() && (this._initialState = e), _o && (t = this.storeName, i = this.constructor.name, t || console.error(\"@StoreConfig({ name }) is missing in \" + i))\n        }, ul.prototype.dispatch = function(e, t) {\n            var i = void 0;\n            (t = void 0 === t ? !0 : t) && (i = Ao, Oo = !1), this.store.next({\n                state: e,\n                action: i\n            })\n        }, ul.prototype.watchTransaction = function() {\n            var e = this;\n            (nl.batchTransaction ? nl.batchTransaction.asObservable() : $i(!0)).subscribe(function() {\n                e.inTransaction = !1, e.dispatch(e._value())\n            })\n        }, ul.prototype.isResettable = function() {\n            return !1 !== this.resettable && (this.resettable || Qo.resettable)\n        }, ul.prototype.handleTransaction = function() {\n            this.inTransaction || (this.watchTransaction(), this.inTransaction = !0)\n        }, ul.prototype.getCacheTTL = function() {\n            return this.cacheConfig && this.cacheConfig.ttl || Qo.ttl\n        }, ul);\n\n        function ul(e, t) {\n            this.options = t = void 0 === t ? {} : t, this.inTransaction = !1, this.cache = {\n                active: new yi(!1),\n                ttl: null\n            }, this.onInit(e)\n        }\n        var cl, hl, pl, fl = (ut(yl, pl = dl), Object.defineProperty(yl.prototype, \"selectEntityAction$\", {\n                get: function() {\n                    return this.entityActions.asObservable()\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(yl.prototype, \"selectEntityIdChanges$\", {\n                get: function() {\n                    return this.entityIdChanges.asObservable()\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(yl.prototype, \"idKey\", {\n                get: function() {\n                    return this.config.idKey || this.options.idKey || \"id\"\n                },\n                enumerable: !0,\n                configurable: !0\n            }), yl.prototype.set = function(a, o) {\n                var l, d = this;\n                void 0 === o && (o = {}), Po(a) || (_o && Mo(\"Set Entity\"), l = this.akitaPreAddEntity === yl.prototype.akitaPreAddEntity, this.setHasCache(!0, {\n                    restartTTL: !0\n                }), this._setState(function(e) {\n                    var t, i, r, n, s, e = (t = {\n                        state: e,\n                        entities: a,\n                        idKey: d.idKey,\n                        preAddEntity: d.akitaPreAddEntity,\n                        isNativePreAdd: l\n                    }, r = t.state, n = t.entities, s = t.idKey, e = t.preAddEntity, t = t.isNativePreAdd, e = Fo(n) ? (i = (s = function(e, t, i) {\n                        var r, n, s = {\n                            entities: {},\n                            ids: []\n                        };\n                        try {\n                            for (var a = ft(e), o = a.next(); !o.done; o = a.next()) {\n                                var l = i(o.value);\n                                s.entities[l[t]] = l, s.ids.push(l[t])\n                            }\n                        } catch (e) {\n                            r = {\n                                error: e\n                            }\n                        } finally {\n                            try {\n                                o && !o.done && (n = a.return) && n.call(a)\n                            } finally {\n                                if (r) throw r.error\n                            }\n                        }\n                        return s\n                    }(n, s, e)).entities, s.ids) : n.entities && n.ids ? (i = t ? n.entities : jo(n.entities, e), n.ids) : (i = t ? n : jo(n, e), Object.keys(i).map(function(e) {\n                        return isNaN(e) ? e : Number(e)\n                    })), e = ct({}, r, {\n                        entities: i,\n                        ids: e,\n                        loading: !1\n                    }), Ko(r) && (e.active = Ho(e)), e);\n                    return !1 === Vo(o.activeId) && (e.active = o.activeId), e\n                }), this.hasInitialUIState() && this.handleUICreation(), this.entityActions.next({\n                    type: Eo.Set,\n                    ids: this.ids\n                }))\n            }, yl.prototype.add = function(e, t) {\n                void 0 === t && (t = {\n                    loading: !1\n                });\n                var i, e = Ro(e);\n                Uo(e) || (i = function(e) {\n                    var t, i, r = e.state,\n                        n = e.entities,\n                        s = e.idKey,\n                        a = e.options,\n                        o = void 0 === a ? {} : a,\n                        l = e.preAddEntity,\n                        d = {},\n                        u = [],\n                        c = !1;\n                    try {\n                        for (var h = ft(n), p = h.next(); !p.done; p = h.next()) {\n                            var f, m, g = p.value;\n                            !1 === xo(r.entities, g[s]) && (d[m = (f = l(g))[s]] = f, o.prepend ? u.unshift(m) : u.push(m), c = !0)\n                        }\n                    } catch (e) {\n                        t = {\n                            error: e\n                        }\n                    } finally {\n                        try {\n                            p && !p.done && (i = h.return) && i.call(h)\n                        } finally {\n                            if (t) throw t.error\n                        }\n                    }\n                    return c ? {\n                        newState: ct({}, r, {\n                            entities: ct({}, r.entities, d),\n                            ids: o.prepend ? gt(u, r.ids) : gt(r.ids, u)\n                        }),\n                        newIds: u\n                    } : null\n                }({\n                    state: this._value(),\n                    preAddEntity: this.akitaPreAddEntity,\n                    entities: e,\n                    idKey: this.idKey,\n                    options: t\n                })) && (_o && Mo(\"Add Entity\"), i.newState.loading = t.loading, this._setState(function() {\n                    return i.newState\n                }), this.hasInitialUIState() && this.handleUICreation(!0), this.entityActions.next({\n                    type: Eo.Add,\n                    ids: i.newIds\n                }))\n            }, yl.prototype.update = function(t, i) {\n                var r, n, s = this;\n                Vo(i) ? pl.prototype.update.call(this, t) : (n = [], Uo(n = $o(t) ? this.ids.filter(function(e) {\n                    return t(s.entities[e])\n                }) : Po(t) ? this.ids : Ro(t)) || (_o && Mo(\"Update Entity\", n), this._setState(function(e) {\n                    return function(e) {\n                        var t = e.state,\n                            i = e.ids,\n                            r = e.idKey,\n                            n = e.newStateOrFn,\n                            s = e.preUpdateEntity,\n                            a = e.producerFn,\n                            o = e.onEntityIdChanges,\n                            l = {},\n                            d = !1;\n                        try {\n                            for (var u = ft(i), c = u.next(); !c.done; c = u.next()) {\n                                var h, p, f, m, g, y, v = c.value;\n                                !1 !== xo(t.entities, v) && (h = t.entities[v], p = void 0, f = (p = $o(n) ? $o(a) ? a(h, n) : n(h) : n).hasOwnProperty(r) && p[r] !== h[r], y = void 0, m = v, f && (d = !0, m = p[r]), g = ct({}, h, p), y = Zo(h) ? g : new(Zo(p) ? h : p).constructor(g), l[m] = s(h, y))\n                            }\n                        } catch (e) {\n                            T = {\n                                error: e\n                            }\n                        } finally {\n                            try {\n                                c && !c.done && (b = u.return) && b.call(u)\n                            } finally {\n                                if (T) throw T.error\n                            }\n                        }\n                        var S, b = t.ids,\n                            T = t.entities;\n                        return d && (S = mt(i, 1)[0], T = function(e, t) {\n                            var i = {};\n                            for (n in e) Object.prototype.hasOwnProperty.call(e, n) && t.indexOf(n) < 0 && (i[n] = e[n]);\n                            if (null != e && \"function\" == typeof Object.getOwnPropertySymbols)\n                                for (var r = 0, n = Object.getOwnPropertySymbols(e); r < n.length; r++) t.indexOf(n[r]) < 0 && Object.prototype.propertyIsEnumerable.call(e, n[r]) && (i[n[r]] = e[n[r]]);\n                            return i\n                        }(t.entities, [\"symbol\" == typeof S ? S : S + \"\"]), b = t.ids.map(function(e) {\n                            return e === S ? m : e\n                        }), o(S, m)), ct({}, t, {\n                            entities: ct({}, T, l),\n                            ids: b\n                        })\n                    }({\n                        idKey: s.idKey,\n                        ids: n,\n                        preUpdateEntity: s.akitaPreUpdateEntity,\n                        state: e,\n                        newStateOrFn: i,\n                        producerFn: s._producerFn,\n                        onEntityIdChanges: function(e, t) {\n                            r = {\n                                oldId: e,\n                                newId: t\n                            }, s.entityIdChanges.next(ct({}, r, {\n                                pending: !0\n                            }))\n                        }\n                    })\n                }), r && this.entityIdChanges.next(ct({}, r, {\n                    pending: !1\n                })), this.entityActions.next({\n                    type: Eo.Update,\n                    ids: n\n                })))\n            }, yl.prototype.upsert = function(e, i, r, t) {\n                var n = this;\n                void 0 === t && (t = {});\n                var s = Ro(e),\n                    e = function(t) {\n                        return function(e) {\n                            return xo(n.entities, e) === t\n                        }\n                    },\n                    a = $o(r) ? t.baseClass : r ? r.baseClass : void 0,\n                    o = $o(a),\n                    t = s.filter(e(!0)),\n                    e = s.filter(e(!1)).map(function(e) {\n                        var t = \"function\" == typeof i ? i({}) : i,\n                            t = $o(r) ? r(e, t) : t,\n                            t = ct({}, t, ((t = {})[n.idKey] = e, t));\n                        return o ? new a(t) : t\n                    });\n                this.update(t, i), this.add(e), _o && Do(\"Upsert Entity\")\n            }, yl.prototype.upsertMany = function(e, t) {\n                var i, r;\n                void 0 === t && (t = {});\n                var n = [],\n                    s = [],\n                    a = {};\n                try {\n                    for (var o = ft(e), l = o.next(); !l.done; l = o.next()) {\n                        var d, u, c, h, p, f, m = l.value,\n                            g = this.akitaPreCheckEntity(m),\n                            y = g[this.idKey];\n                        xo(this.entities, y) ? (d = this._value().entities[y], u = ct({}, this._value().entities[y], g), c = t.baseClass ? new t.baseClass(u) : u, f = (h = this.akitaPreUpdateEntity(d, c))[this.idKey], a[f] = h, s.push(f)) : (p = t.baseClass ? new t.baseClass(g) : g, f = (h = this.akitaPreAddEntity(p))[this.idKey], n.push(f), a[f] = h)\n                    }\n                } catch (e) {\n                    i = {\n                        error: e\n                    }\n                } finally {\n                    try {\n                        l && !l.done && (r = o.return) && r.call(o)\n                    } finally {\n                        if (i) throw i.error\n                    }\n                }\n                _o && Do(\"Upsert Many\"), this._setState(function(e) {\n                    return ct({}, e, {\n                        ids: n.length ? gt(e.ids, n) : e.ids,\n                        entities: ct({}, e.entities, a),\n                        loading: !!t.loading\n                    })\n                }), s.length && this.entityActions.next({\n                    type: Eo.Update,\n                    ids: s\n                }), n.length && this.entityActions.next({\n                    type: Eo.Add,\n                    ids: n\n                }), n.length && this.hasUIStore() && this.handleUICreation(!0)\n            }, yl.prototype.replace = function(e, t) {\n                var i, r, n = Ro(e);\n                if (!Uo(n)) {\n                    var s = {};\n                    try {\n                        for (var a = ft(n), o = a.next(); !o.done; o = a.next()) {\n                            var l = o.value;\n                            t[this.idKey] = l, s[l] = t\n                        }\n                    } catch (e) {\n                        i = {\n                            error: e\n                        }\n                    } finally {\n                        try {\n                            o && !o.done && (r = a.return) && r.call(a)\n                        } finally {\n                            if (i) throw i.error\n                        }\n                    }\n                    _o && Mo(\"Replace Entity\", e), this._setState(function(e) {\n                        return ct({}, e, {\n                            entities: ct({}, e.entities, s)\n                        })\n                    })\n                }\n            }, yl.prototype.move = function(e, t) {\n                var i = this.ids.slice();\n                i.splice(t < 0 ? i.length + t : t, 0, i.splice(e, 1)[0]), _o && Mo(\"Move Entity\"), this._setState(function(e) {\n                    return ct({}, e, {\n                        entities: ct({}, e.entities),\n                        ids: i\n                    })\n                })\n            }, yl.prototype.remove = function(t) {\n                var e, i, r = this;\n                Uo(this.ids) || (e = Bo(t), i = [], Uo(i = $o(t) ? this.ids.filter(function(e) {\n                    return t(r.entities[e])\n                }) : e ? Ro(t) : this.ids) || (_o && Mo(\"Remove Entity\", i), this._setState(function(e) {\n                    return function(e) {\n                        var t, i = e.state,\n                            r = e.ids;\n                        if (Po(r)) return ct({}, i, {\n                            entities: {},\n                            ids: [],\n                            active: qo(i.active) ? [] : null\n                        });\n                        var n = i.entities,\n                            s = {};\n                        try {\n                            for (var a = ft(i.ids), o = a.next(); !o.done; o = a.next()) {\n                                var l = o.value;\n                                !1 === r.includes(l) && (s[l] = n[l])\n                            }\n                        } catch (e) {\n                            d = {\n                                error: e\n                            }\n                        } finally {\n                            try {\n                                o && !o.done && (t = a.return) && t.call(a)\n                            } finally {\n                                if (d) throw d.error\n                            }\n                        }\n                        var d = ct({}, i, {\n                            entities: s,\n                            ids: i.ids.filter(function(e) {\n                                return !1 === r.includes(e)\n                            })\n                        });\n                        return Ko(i) && (d.active = Ho(d)), d\n                    }({\n                        state: e,\n                        ids: i\n                    })\n                }), e || this.setHasCache(!1), this.handleUIRemove(i), this.entityActions.next({\n                    type: Eo.Remove,\n                    ids: i\n                })))\n            }, yl.prototype.updateActive = function(e) {\n                var t = Ro(this.active);\n                _o && Mo(\"Update Active\", t), this.update(t, e)\n            }, yl.prototype.setActive = function(e) {\n                e = function(e, t, i) {\n                    var r;\n                    if (Fo(e)) r = e;\n                    else if (No(e)) {\n                        if (Po(i)) return;\n                        e = Object.assign({\n                            wrap: !0\n                        }, e);\n                        var n = t.indexOf(i);\n                        if (e.prev) {\n                            var s = 0 === n;\n                            if (s && !e.wrap) return;\n                            r = s ? t[t.length - 1] : t[n - 1]\n                        } else if (e.next) {\n                            s = t.length === n + 1;\n                            if (s && !e.wrap) return;\n                            r = s ? t[0] : t[n + 1]\n                        }\n                    } else {\n                        if (e === i) return;\n                        r = e\n                    }\n                    return r\n                }(e, this.ids, this.active);\n                void 0 !== e && (_o && Mo(\"Set Active\", e), this._setActive(e))\n            }, yl.prototype.addActive = function(e) {\n                var t = this,\n                    i = Ro(e);\n                Uo(i) || i.every(function(e) {\n                    return -1 < t.active.indexOf(e)\n                }) || (_o && Mo(\"Add Active\", e), this._setState(function(e) {\n                    var t = Array.from(new Set(gt(e.active, i)));\n                    return ct({}, e, {\n                        active: t\n                    })\n                }))\n            }, yl.prototype.removeActive = function(e) {\n                var t = this,\n                    i = Ro(e);\n                Uo(i) || i.some(function(e) {\n                    return -1 < t.active.indexOf(e)\n                }) && (_o && Mo(\"Remove Active\", e), this._setState(function(e) {\n                    return ct({}, e, {\n                        active: Array.isArray(e.active) ? e.active.filter(function(e) {\n                            return -1 === i.indexOf(e)\n                        }) : null\n                    })\n                }))\n            }, yl.prototype.toggleActive = function(e) {\n                var i = this,\n                    t = Ro(e),\n                    r = function(t) {\n                        return function(e) {\n                            return i.active.includes(e) === t\n                        }\n                    },\n                    e = t.filter(r(!0)),\n                    r = t.filter(r(!1));\n                this.removeActive(e), this.addActive(r), _o && Do(\"Toggle Active\")\n            }, yl.prototype.createUIStore = function(e, t) {\n                var i = {\n                    name: \"UI/\" + this.storeName,\n                    idKey: this.idKey\n                };\n                return this.ui = new ml(e = void 0 === e ? {} : e, ct({}, i, t = void 0 === t ? {} : t)), this.ui\n            }, yl.prototype.destroy = function() {\n                pl.prototype.destroy.call(this), this.ui instanceof yl && this.ui.destroy(), this.entityActions.complete()\n            }, yl.prototype.akitaPreUpdateEntity = function(e, t) {\n                return t\n            }, yl.prototype.akitaPreAddEntity = function(e) {\n                return e\n            }, yl.prototype.akitaPreCheckEntity = function(e) {\n                return e\n            }, Object.defineProperty(yl.prototype, \"ids\", {\n                get: function() {\n                    return this._value().ids\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(yl.prototype, \"entities\", {\n                get: function() {\n                    return this._value().entities\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(yl.prototype, \"active\", {\n                get: function() {\n                    return this._value().active\n                },\n                enumerable: !0,\n                configurable: !0\n            }), yl.prototype._setActive = function(t) {\n                this._setState(function(e) {\n                    return ct({}, e, {\n                        active: t\n                    })\n                })\n            }, yl.prototype.handleUICreation = function(e) {\n                var r = this,\n                    t = this.ids,\n                    n = $o(this.ui._akitaCreateEntityFn),\n                    i = function(e) {\n                        var t = r.entities[e],\n                            i = n ? r.ui._akitaCreateEntityFn(t) : r.ui._akitaCreateEntityFn;\n                        return ct(((e = {})[r.idKey] = t[r.idKey], e), i)\n                    },\n                    i = ((e = void 0 === e ? !1 : e) ? this.ids.filter(function(e) {\n                        return Vo(r.ui.entities[e])\n                    }) : t).map(i);\n                e ? this.ui.add(i) : this.ui.set(i)\n            }, yl.prototype.hasInitialUIState = function() {\n                return this.hasUIStore() && !1 === Vo(this.ui._akitaCreateEntityFn)\n            }, yl.prototype.handleUIRemove = function(e) {\n                this.hasUIStore() && this.ui.remove(e)\n            }, yl.prototype.hasUIStore = function() {\n                return this.ui instanceof ml\n            }, ht([ol(), pt(\"design:type\", Function), pt(\"design:paramtypes\", [Object, Object, Object, Object]), pt(\"design:returntype\", void 0)], yl.prototype, \"upsert\", null), ht([ol(), pt(\"design:type\", Function), pt(\"design:paramtypes\", [\"function\" == typeof(w = \"undefined\" != typeof T && T) ? w : Object]), pt(\"design:returntype\", void 0)], yl.prototype, \"toggleActive\", null), yl),\n            ml = (ut(gl, hl = fl), gl.prototype.setInitialEntityState = function(e) {\n                this._akitaCreateEntityFn = e\n            }, gl);\n\n        function gl(e, t) {\n            return hl.call(this, e = void 0 === e ? {} : e, t = void 0 === t ? {} : t) || this\n        }\n\n        function yl(e, t) {\n            void 0 === t && (t = {});\n            e = pl.call(this, ct({}, {\n                entities: {},\n                ids: [],\n                loading: !0,\n                error: null\n            }, e = void 0 === e ? {} : e), t) || this;\n            return e.options = t, e.entityActions = new Xt, e.entityIdChanges = new Xt, e\n        }\n\n        function vl() {\n            return Is(function(e, t) {\n                return e === t || !1 !== Fo(e) && !1 !== Fo(t) && (!(!Uo(e) || !Uo(t)) || !Sl(t, e) && !1 === Sl(e, t))\n            })\n        }\n\n        function Sl(e, t) {\n            return t.some(function(t) {\n                return void 0 === e.find(function(e) {\n                    return e === t\n                })\n            })\n        }\n\n        function bl(i, e) {\n            for (var r, n, s, a = [], o = i.ids, l = i.entities, d = e.filterBy, t = e.limitTo, u = e.sortBy, e = e.sortByOrder, c = 0; c < o.length; c++) ! function(t) {\n                var i = l[o[t]];\n                if (!d) return a.push(i);\n                Ro(d).every(function(e) {\n                    return e(i, t)\n                }) && a.push(i)\n            }(c);\n            u && (s = $o(u) ? u : (r = u, void 0 === (n = e) && (n = cl.ASC), function(e, t) {\n                if (!e.hasOwnProperty(r) || !t.hasOwnProperty(r)) return 0;\n                var i = \"string\" == typeof e[r] ? e[r].toUpperCase() : e[r],\n                    e = \"string\" == typeof t[r] ? t[r].toUpperCase() : t[r],\n                    t = 0;\n                return e < i ? t = 1 : i < e && (t = -1), n == cl.DESC ? -1 * t : t\n            }), a = a.sort(function(e, t) {\n                return s(e, t, i)\n            }));\n            t = Math.min(t || a.length, a.length);\n            return t === a.length ? a : a.slice(0, t)\n        }\n\n        function Tl(e) {\n            return \"string\" == typeof e\n        }\n\n        function El(t, i) {\n            return function(e) {\n                e = e[t];\n                if (!Vo(e)) return i ? Tl(i) ? e[i] : i(e) : e\n            }\n        }(vi = cl = cl || {}).ASC = \"asc\", vi.DESC = \"desc\";\n        Il.prototype.select = function(t) {\n            var e, n;\n            if ($o(t)) e = t;\n            else if (Tl(t)) e = function(e) {\n                return e[t]\n            };\n            else {\n                if (Array.isArray(t)) return this.store._select(function(e) {\n                    return e\n                }).pipe(Is((n = t, function(t, i) {\n                    var r = $o(n[0]);\n                    return !1 === n.some(function(e) {\n                        return r ? e(t) !== e(i) : t[e] !== i[e]\n                    })\n                })), hr(function(i) {\n                    return $o(t[0]) ? t.map(function(e) {\n                        return e(i)\n                    }) : t.reduce(function(e, t) {\n                        return e[t] = i[t], e\n                    }, {})\n                }));\n                e = function(e) {\n                    return e\n                }\n            }\n            return this.store._select(e)\n        }, Il.prototype.selectLoading = function() {\n            return this.select(function(e) {\n                return e.loading\n            })\n        }, Il.prototype.selectError = function() {\n            return this.select(function(e) {\n                return e.error\n            })\n        }, Il.prototype.getValue = function() {\n            return this.store._value()\n        }, Il.prototype.selectHasCache = function() {\n            return this.store._cache().asObservable()\n        }, Il.prototype.getHasCache = function() {\n            return this.store._cache().value\n        }, Object.defineProperty(Il.prototype, \"config\", {\n            get: function() {\n                return this.constructor.akitaQueryConfig\n            },\n            enumerable: !0,\n            configurable: !0\n        }), bi = Il;\n\n        function Il(e) {\n            this.store = e, this.__store__ = e, _o && (tl[e.storeName] = this)\n        }\n\n        function wl(e) {\n            return e.pipe(ln(function(e) {\n                return null != e\n            }))\n        }\n        var Al, Ol, kl = (ut(Ml, Ol = bi), Ml.prototype.selectAll = function(e) {\n                var t = this;\n                return void 0 === e && (e = {\n                    asObject: !1\n                }), this.select(function(e) {\n                    return e.entities\n                }).pipe(hr(function() {\n                    return t.getAll(e)\n                }))\n            }, Ml.prototype.getAll = function(e) {\n                return (e = void 0 === e ? {\n                    asObject: !1,\n                    filterBy: void 0,\n                    limitTo: void 0\n                } : e).asObject ? function(e, t) {\n                    var r = {},\n                        n = t.filterBy,\n                        s = t.limitTo,\n                        a = e.ids,\n                        o = e.entities;\n                    if (!n && !s) return o;\n                    e = !1 === Po(s);\n                    if (n && e)\n                        for (var l = 0, i = 0, d = a.length; i < d && \"break\" !== function(t) {\n                                if (l === s) return \"break\";\n                                var e = a[t],\n                                    i = o[e];\n                                Ro(n).every(function(e) {\n                                    return e(i, t)\n                                }) && (r[e] = i, l++)\n                            }(i); i++);\n                    else\n                        for (var u = Math.min(s || a.length, a.length), i = 0; i < u; i++) ! function(t) {\n                            var e = a[t],\n                                i = o[e];\n                            if (!n) return r[e] = i;\n                            Ro(n).every(function(e) {\n                                return e(i, t)\n                            }) && (r[e] = i)\n                        }(i);\n                    return r\n                }(this.getValue(), e) : (t = e, i = this.config || this.options, t.sortBy = t.sortBy || i && i.sortBy, t.sortByOrder = t.sortByOrder || i && i.sortByOrder, bl(this.getValue(), e));\n                var t, i\n            }, Ml.prototype.selectMany = function(e, i) {\n                return e && e.length ? this.select(function(e) {\n                    return e.entities\n                }).pipe(hr(function(t) {\n                    return n = function(e) {\n                        return El(e, i)(t)\n                    }, e.reduce(function(e, t, i, r) {\n                        t = n(t);\n                        return void 0 !== t && e.push(t), e\n                    }, []);\n                    var n\n                }), vl()) : $i([])\n            }, Ml.prototype.selectEntity = function(e, t) {\n                var i = e;\n                return $o(e) && (i = function(e, t) {\n                    var i, r;\n                    try {\n                        for (var n = ft(Object.keys(t)), s = n.next(); !s.done; s = n.next()) {\n                            var a = s.value;\n                            if (!0 === e(t[a])) return a\n                        }\n                    } catch (e) {\n                        i = {\n                            error: e\n                        }\n                    } finally {\n                        try {\n                            s && !s.done && (r = n.return) && r.call(n)\n                        } finally {\n                            if (i) throw i.error\n                        }\n                    }\n                }(e, this.getValue().entities)), this.select(function(e) {\n                    return e.entities\n                }).pipe(hr(El(i, t)), Is())\n            }, Ml.prototype.getEntity = function(e) {\n                return this.getValue().entities[e]\n            }, Ml.prototype.selectActiveId = function() {\n                return this.select(function(e) {\n                    return e.active\n                })\n            }, Ml.prototype.getActiveId = function() {\n                return this.getValue().active\n            }, Ml.prototype.selectActive = function(t) {\n                var i = this;\n                return Fo(this.getActive()) ? this.selectActiveId().pipe(La(function(e) {\n                    return i.selectMany(e, t)\n                })) : this.selectActiveId().pipe(La(function(e) {\n                    return i.selectEntity(e, t)\n                }))\n            }, Ml.prototype.getActive = function() {\n                var t = this,\n                    e = this.getActiveId();\n                return Fo(e) ? e.map(function(e) {\n                    return t.getValue().entities[e]\n                }) : Jo(e) ? this.getEntity(e) : void 0\n            }, Ml.prototype.selectCount = function(e) {\n                var t = this;\n                return this.select(function(e) {\n                    return e.entities\n                }).pipe(hr(function() {\n                    return t.getCount(e)\n                }))\n            }, Ml.prototype.getCount = function(e) {\n                return ($o(e) ? this.getAll().filter(e) : this.getValue().ids).length\n            }, Ml.prototype.selectLast = function(e) {\n                return this.selectAt(function(e) {\n                    return e[e.length - 1]\n                }, e)\n            }, Ml.prototype.selectFirst = function(e) {\n                return this.selectAt(function(e) {\n                    return e[0]\n                }, e)\n            }, Ml.prototype.selectEntityAction = function(e) {\n                if (Po(e)) return this.store.selectEntityAction$;\n                var t = Fo(e) ? function(e) {\n                        return e\n                    } : function(e) {\n                        return e.ids\n                    },\n                    i = Ro(e);\n                return this.store.selectEntityAction$.pipe(ln(function(e) {\n                    e = e.type;\n                    return i.includes(e)\n                }), hr(function(e) {\n                    return t(e)\n                }))\n            }, Ml.prototype.hasEntity = function(e) {\n                var t = this;\n                return Po(e) ? 0 < this.getValue().ids.length : $o(e) ? this.getAll().some(e) : Fo(e) ? e.every(function(e) {\n                    return e in t.getValue().entities\n                }) : e in this.getValue().entities\n            }, Ml.prototype.hasActive = function(e) {\n                var t = this.getValue().active,\n                    i = Bo(e);\n                return Array.isArray(t) ? i ? t.includes(e) : 0 < t.length : i ? t === e : Bo(t)\n            }, Ml.prototype.createUIQuery = function() {\n                this.ui = new Cl(this.__store__.ui)\n            }, Ml.prototype.selectAt = function(e, t) {\n                var i = this;\n                return this.select(function(e) {\n                    return e.ids\n                }).pipe(hr(e), Is(), La(function(e) {\n                    return i.selectEntity(e, t)\n                }))\n            }, Ml),\n            Cl = (ut(Dl, Al = kl), Dl);\n\n        function Dl(e) {\n            return Al.call(this, e) || this\n        }\n\n        function Ml(e, t) {\n            void 0 === t && (t = {});\n            var i = Ol.call(this, e) || this;\n            return i.options = t, i.__store__ = e, i\n        }\n\n        function xl(e, t) {\n            return 1 === t.split(\".\").length ? e : t.split(\".\").slice(1).join(\".\").split(\".\").reduce(function(e, t) {\n                return e && e[t]\n            }, e)\n        }\n\n        function Pl(e, t, r) {\n            var i = t.split(\".\");\n            if (1 === i.length) return ct({}, e, r);\n            e = ct({}, e);\n            var n = i.length - 2;\n            return t.split(\".\").slice(1).reduce(function(e, t, i) {\n                return e[t] = i !== n ? ct({}, e[t]) : Array.isArray(e[t]) || !No(e[t]) ? r : ct({}, e[t], r), e && e[t]\n            }, e), e\n        }\n        new Ji(1);\n        var Rl, Ll, _l, Nl, A = (Bl.prototype.getQuery = function() {\n                return this.query\n            }, Bl.prototype.getStore = function() {\n                return this.getQuery().__store__\n            }, Bl.prototype.isEntityBased = Jo, Bl.prototype.selectSource = function(e, t) {\n                var i = this;\n                return this.isEntityBased(e) ? this.getQuery().selectEntity(e).pipe(wl) : t ? this.getQuery().select(function(e) {\n                    return xl(e, i.withStoreName(t))\n                }) : this.getQuery().select()\n            }, Bl.prototype.getSource = function(e, t) {\n                if (this.isEntityBased(e)) return this.getQuery().getEntity(e);\n                e = this.getQuery().getValue();\n                return t ? xl(e, this.withStoreName(t)) : e\n            }, Bl.prototype.withStoreName = function(e) {\n                return this.storeName + \".\" + e\n            }, Object.defineProperty(Bl.prototype, \"storeName\", {\n                get: function() {\n                    return this.getStore().storeName\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Bl.prototype.updateStore = function(t, e, i) {\n                var r = this;\n                this.isEntityBased(e) ? this.getStore().update(e, t) : i ? this.getStore()._setState(function(e) {\n                    return Pl(e, r.withStoreName(i), t)\n                }) : this.getStore()._setState(function(e) {\n                    return ct({}, e, t)\n                })\n            }, Bl.prototype.onReset = function(i) {\n                var r = this,\n                    n = this.getStore().reset;\n                this.getStore().reset = function() {\n                    for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n                    setTimeout(function() {\n                        n.apply(r.getStore(), e), i()\n                    })\n                }\n            }, Bl),\n            Fl = {\n                pagesControls: !1,\n                range: !1,\n                startWith: 1,\n                cacheTimeout: void 0,\n                clearStoreWithCache: !0\n            };\n\n        function Bl(e, t) {\n            this.query = e\n        }\n\n        function Ul(e, t, i) {\n            void 0 === i && (i = {});\n            var r = Rl.call(this, e) || this;\n            return r.query = e, r.factoryFnOrPath = t, r.params = i, r.params = ct({\n                debounceTime: 300,\n                formKey: \"akitaForm\",\n                emitEvent: !1,\n                arrControlFactory: function(e) {\n                    return r.builder.control(e)\n                }\n            }, i), r.isRootKeys = !1 === Jo(t), r.isKeyBased = Tl(t) || r.isRootKeys, r\n        }\n\n        function $l(e, t) {\n            void 0 === t && (t = {});\n            var i = Ll.call(this, e, {\n                resetFn: function() {\n                    i.initial = !1, i.destroy({\n                        clearCache: !0,\n                        currentPage: 1\n                    })\n                }\n            }) || this;\n            i.query = e, i.config = t, i.metadata = new Map, i.pages = new Map, i.pagination = {\n                currentPage: 1,\n                perPage: 0,\n                total: 0,\n                lastPage: 0,\n                data: []\n            }, i.initial = !0, i.isLoading$ = i.query.selectLoading().pipe(function(t) {\n                void 0 === t && (t = ir);\n                var i = as(0) ? 0 - t.now() : Math.abs(0);\n                return function(e) {\n                    return e.lift(new ls(i, t))\n                }\n            }()), i.config = Object.assign(Fl, t);\n            e = i.config, t = e.startWith, e = e.cacheTimeout;\n            return i.page = new yi(t), e && (e instanceof $t || \"function\" == typeof e.lift && \"function\" == typeof e.subscribe) && (i.clearCacheSubscription = e.subscribe(function() {\n                return i.clearCache()\n            })), i\n        }\n        ut($l, Ll = A), Object.defineProperty($l.prototype, \"pageChanges\", {\n            get: function() {\n                return this.page.asObservable()\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty($l.prototype, \"currentPage\", {\n            get: function() {\n                return this.pagination.currentPage\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty($l.prototype, \"isFirst\", {\n            get: function() {\n                return 1 === this.currentPage\n            },\n            enumerable: !0,\n            configurable: !0\n        }), Object.defineProperty($l.prototype, \"isLast\", {\n            get: function() {\n                return this.currentPage === this.pagination.lastPage\n            },\n            enumerable: !0,\n            configurable: !0\n        }), $l.prototype.withControls = function() {\n            return this.config.pagesControls = !0, this\n        }, $l.prototype.withRange = function() {\n            return this.config.range = !0, this\n        }, $l.prototype.setLoading = function(e) {\n            void 0 === e && (e = !0), this.getStore().setLoading(e)\n        }, $l.prototype.update = function(e) {\n            this.pagination = e, this.addPage(e.data)\n        }, $l.prototype.addPage = function(e) {\n            var t = this;\n            this.pages.set(this.currentPage, {\n                ids: e.map(function(e) {\n                    return e[t.getStore().idKey]\n                })\n            }), this.getStore().upsertMany(e)\n        }, $l.prototype.clearCache = function(e) {\n            void 0 === e && (e = {}), this.initial || (Do(\"@Pagination - Clear Cache\"), !1 !== e.clearStore && (this.config.clearStoreWithCache || e.clearStore) && this.getStore().remove(), this.pages = new Map, this.metadata = new Map), this.initial = !1\n        }, $l.prototype.clearPage = function(e) {\n            this.pages.delete(e)\n        }, $l.prototype.destroy = function(e) {\n            var t = void 0 === e ? {} : e,\n                e = t.clearCache,\n                t = t.currentPage;\n            this.clearCacheSubscription && this.clearCacheSubscription.unsubscribe(), e && this.clearCache(), Vo(t) || this.setPage(t), this.initial = !0\n        }, $l.prototype.isPageActive = function(e) {\n            return this.currentPage === e\n        }, $l.prototype.setPage = function(e) {\n            e === this.currentPage && this.hasPage(e) || this.page.next(this.pagination.currentPage = e)\n        }, $l.prototype.nextPage = function() {\n            this.currentPage !== this.pagination.lastPage && this.setPage(this.pagination.currentPage + 1)\n        }, $l.prototype.prevPage = function() {\n            1 < this.pagination.currentPage && this.setPage(this.pagination.currentPage - 1)\n        }, $l.prototype.setLastPage = function() {\n            this.setPage(this.pagination.lastPage)\n        }, $l.prototype.setFirstPage = function() {\n            this.setPage(1)\n        }, $l.prototype.hasPage = function(e) {\n            return this.pages.has(e)\n        }, $l.prototype.getPage = function(e) {\n            var t = this,\n                i = this.pagination.currentPage;\n            return this.hasPage(i) ? this.selectPage(i) : (this.setLoading(!0), Fr(e()).pipe(La(function(e) {\n                return i = e.currentPage, al(function() {\n                    t.setLoading(!1), t.update(e)\n                }), t.selectPage(i)\n            })))\n        }, $l.prototype.getQuery = function() {\n            return this.query\n        }, $l.prototype.refreshCurrentPage = function() {\n            !1 === Po(this.currentPage) && (this.clearPage(this.currentPage), this.setPage(this.currentPage))\n        }, $l.prototype.getFrom = function() {\n            return this.isFirst ? 1 : (this.currentPage - 1) * this.pagination.perPage + 1\n        }, $l.prototype.getTo = function() {\n            return this.isLast ? this.pagination.total : this.currentPage * this.pagination.perPage\n        }, $l.prototype.selectPage = function(n) {\n            var s = this;\n            return this.query.selectAll({\n                asObject: !0\n            }).pipe(Ds(1), hr(function(t) {\n                var e = ct({}, s.pagination, {\n                        data: s.pages.get(n).ids.map(function(e) {\n                            return t[e]\n                        })\n                    }),\n                    i = s.config,\n                    r = i.range,\n                    i = i.pagesControls;\n                return isNaN(s.pagination.total) && (1 === e.lastPage ? e.total = e.data ? e.data.length : 0 : e.total = e.perPage * e.lastPage, s.pagination.total = e.total), r && (e.from = s.getFrom(), e.to = s.getTo()), i && (e.pageControls = function(e, t) {\n                    for (var i = Math.ceil(e / t), r = [], n = 0; n < i; n++) r.push(n + 1);\n                    return r\n                }(s.pagination.total, s.pagination.perPage)), e\n            }))\n        }, ht([(_l = \"@Pagination - New Page\", function(e, t, i) {\n            var r = i.value;\n            return i.value = function() {\n                for (var e = [], t = 0; t < arguments.length; t++) e[t] = arguments[t];\n                return Do(_l, Nl), r.apply(this, e)\n            }, i\n        }), pt(\"design:type\", Function), pt(\"design:paramtypes\", [Object]), pt(\"design:returntype\", void 0)], $l.prototype, \"update\", null), ut(Ul, Rl = A), Ul.prototype.setForm = function(e, t) {\n            return this.form = e, this.builder = t, this.activate(), this\n        }, Ul.prototype.reset = function(e) {\n            var r = this,\n                e = e || (this.isKeyBased ? this.initialValue : this.factoryFnOrPath());\n            this.isKeyBased && Object.keys(this.initialValue).forEach(function(i) {\n                var e, t = r.initialValue[i];\n                Array.isArray(t) && r.builder && (e = r.form.controls[i], r.cleanArray(e), t.forEach(function(e, t) {\n                    r.form.get(i).insert(t, r.params.arrControlFactory(e))\n                }))\n            }), this.form.patchValue(e, {\n                emitEvent: this.params.emitEvent\n            });\n            var t = this.isKeyBased ? Pl(this.getQuery().getValue(), this.getStore().storeName + \".\" + this.factoryFnOrPath, e) : ((t = {})[this.params.formKey] = e, t);\n            this.updateStore(t)\n        }, Ul.prototype.cleanArray = function(e) {\n            for (; 0 !== e.length;) e.removeAt(0)\n        }, Ul.prototype.resolveInitialValue = function(e, n) {\n            var s = this;\n            if (e) return Object.keys(e).reduce(function(e, i) {\n                var r, t = n[i];\n                return Array.isArray(t) && s.builder && (r = s.params.arrControlFactory, s.cleanArray(s.form.get(i)), t.forEach(function(e, t) {\n                    s.form.get(i).insert(t, r(e))\n                })), e[i] = n[i], e\n            }, {})\n        }, Ul.prototype.activate = function() {\n            var i, e, t, r = this;\n            this.isKeyBased ? (this.isRootKeys ? this.initialValue = this.resolveInitialValue(this.form.value, this.getQuery().getValue()) : (i = this.getStore().storeName + \".\" + this.factoryFnOrPath, e = xl(this.getQuery().getValue(), i), this.initialValue = this.resolveInitialValue(e, e)), this.form.patchValue(this.initialValue, {\n                emitEvent: this.params.emitEvent\n            })) : (this.getQuery().getValue()[this.params.formKey] || (Do(\"@PersistNgFormPlugin activate\"), this.updateStore(((t = {})[this.params.formKey] = this.factoryFnOrPath(), t))), t = this.getQuery().getValue()[this.params.formKey], this.form.patchValue(t)), this.formChanges = this.form.valueChanges.pipe(Gn(this.params.debounceTime)).subscribe(function(t) {\n                var e;\n                Do(\"@PersistForm - Update\"), e = r.isKeyBased ? r.isRootKeys ? function(e) {\n                    return ct({}, e, t)\n                } : function(e) {\n                    return Pl(e, i, t)\n                } : function() {\n                    var e;\n                    return (e = {})[r.params.formKey] = t, e\n                }, r.updateStore(e(r.getQuery().getValue()))\n            })\n        }, Ul.prototype.destroy = function() {\n            this.formChanges && this.formChanges.unsubscribe(), this.form = null, this.builder = null\n        };\n        var Vl, Kl, Vr = (jl.prototype.getEntity = function(e) {\n                return this.entities.get(e)\n            }, jl.prototype.hasEntity = function(e) {\n                return this.entities.has(e)\n            }, jl.prototype.removeEntity = function(e) {\n                return this.destroy(e), this.entities.delete(e)\n            }, jl.prototype.createEntity = function(e, t) {\n                return this.entities.set(e, t)\n            }, jl.prototype.getIds = function() {\n                return Vo(this.entityIds) ? this.query.getValue().ids : Ro(this.entityIds)\n            }, jl.prototype.resolvedIds = function(e) {\n                return Vo(e) ? this.getIds() : Ro(e)\n            }, jl.prototype.rebase = function(i, r) {\n                var n = this;\n                if (void 0 === r && (r = {}), Jo(i))\n                    if (Vo(this.entityIds)) {\n                        for (var e = 0, t = i.length; e < t; e++) {\n                            var s, a = i[e];\n                            !1 === this.hasEntity(a) && ($o(r.beforeAdd) && r.beforeAdd(a), s = this.instantiatePlugin(a), this.entities.set(a, s), $o(r.afterAdd) && r.afterAdd(s))\n                        }\n                        this.entities.forEach(function(e, t) {\n                            -1 === i.indexOf(t) && ($o(r.beforeRemove) && r.beforeRemove(e), n.removeEntity(t))\n                        })\n                    } else\n                        for (var o = Ro(this.entityIds), e = 0, t = o.length; e < t; e++) a = o[e], -1 < i.indexOf(a) && !1 === this.hasEntity(a) ? ($o(r.beforeAdd) && r.beforeAdd(a), s = this.instantiatePlugin(a), this.entities.set(a, s), $o(r.afterAdd) && r.afterAdd(s)) : this.entities.forEach(function(e, t) {\n                            -1 === i.indexOf(t) && !0 === n.hasEntity(t) && ($o(r.beforeRemove) && r.beforeRemove(e), n.removeEntity(t))\n                        });\n                else this.getIds().forEach(function(e) {\n                    n.hasEntity(e) || n.createEntity(e, n.instantiatePlugin(e))\n                })\n            }, jl.prototype.selectIds = function() {\n                return this.query.select(function(e) {\n                    return e.ids\n                })\n            }, jl.prototype.activate = function(e) {\n                this.rebase(e)\n            }, jl.prototype.forEachId = function(e, t) {\n                for (var i = this.resolvedIds(e), r = 0, n = i.length; r < n; r++) {\n                    var s = i[r];\n                    this.hasEntity(s) && t(this.getEntity(s))\n                }\n            }, jl),\n            ql = (ut(Hl, Vl = A), Object.defineProperty(Hl.prototype, \"hasPast$\", {\n                get: function() {\n                    return this._hasPast$\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(Hl.prototype, \"hasFuture$\", {\n                get: function() {\n                    return this._hasFuture$\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(Hl.prototype, \"hasPast\", {\n                get: function() {\n                    return 0 < this.history.past.length\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(Hl.prototype, \"hasFuture\", {\n                get: function() {\n                    return 0 < this.history.future.length\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Object.defineProperty(Hl.prototype, \"property\", {\n                get: function() {\n                    return this.params.watchProperty\n                },\n                enumerable: !0,\n                configurable: !0\n            }), Hl.prototype.updateHasHistory = function() {\n                this.hasFutureSubject.next(this.hasFuture), this.hasPastSubject.next(this.hasPast)\n            }, Hl.prototype.activate = function() {\n                var r = this;\n                this.hasPastSubject = new yi(!1), this._hasPast$ = this.hasPastSubject.asObservable().pipe(Is()), this.hasFutureSubject = new yi(!1), this._hasFuture$ = this.hasFutureSubject.asObservable().pipe(Is()), this.history.present = this.getSource(this._entityId, this.property), this.subscription = this.selectSource(this._entityId, this.property).pipe(ha()).subscribe(function(e) {\n                    var t = mt(e, 2),\n                        i = t[0],\n                        e = t[1];\n                    r.skip ? r.skip = !1 : (t = r.params.comparator(i, e), !r.skipUpdate && t && (r.history.past.length === r.params.maxAge && (r.history.past = r.history.past.slice(1)), r.history.past = gt(r.history.past, [i]), r.history.present = e, r.updateHasHistory()))\n                })\n            }, Hl.prototype.undo = function() {\n                var e, t, i;\n                0 < this.history.past.length && (e = (i = this.history).past, t = i.present, i = e[e.length - 1], this.history.past = e.slice(0, e.length - 1), this.history.present = i, this.history.future = gt([t], this.history.future), this.update())\n            }, Hl.prototype.redo = function() {\n                var e, t, i, r;\n                0 < this.history.future.length && (e = (r = this.history).past, t = r.present, i = this.history.future[0], r = this.history.future.slice(1), this.history.past = gt(e, [t]), this.history.present = i, this.history.future = r, this.update(\"Redo\"))\n            }, Hl.prototype.jumpToPast = function(e) {\n                var t, i, r, n;\n                e < 0 || e >= this.history.past.length || (t = (r = this.history).past, n = r.future, i = r.present, r = t.slice(0, e), n = gt(t.slice(e + 1), [i], n), e = t[e], this.history.past = r, this.history.present = e, this.history.future = n, this.update())\n            }, Hl.prototype.jumpToFuture = function(e) {\n                var t, i, r;\n                e < 0 || e >= this.history.future.length || (i = (r = this.history).past, t = r.future, i = gt(i, [r.present], t.slice(0, e)), r = t[e], e = t.slice(e + 1), this.history.past = i, this.history.present = r, this.history.future = e, this.update(\"Redo\"))\n            }, Hl.prototype.jump = function(e) {\n                return 0 < e ? this.jumpToFuture(e - 1) : e < 0 ? this.jumpToPast(this.history.past.length + e) : void 0\n            }, Hl.prototype.clear = function(e) {\n                this.history = $o(e) ? e(this.history) : {\n                    past: [],\n                    present: null,\n                    future: []\n                }, this.updateHasHistory()\n            }, Hl.prototype.destroy = function(e) {\n                (e = void 0 === e ? !1 : e) && this.clear(), this.subscription.unsubscribe()\n            }, Hl.prototype.ignoreNext = function() {\n                this.skip = !0\n            }, Hl.prototype.update = function(e) {\n                void 0 === e && (e = \"Undo\"), this.skipUpdate = !0, Do(\"@StateHistory - \" + e), this.updateStore(this.history.present, this._entityId, this.property), this.updateHasHistory(), this.skipUpdate = !1\n            }, Hl);\n\n        function Hl(e, t, i) {\n            void 0 === t && (t = {});\n            var r = Vl.call(this, e, {\n                resetFn: function() {\n                    return r.clear()\n                }\n            }) || this;\n            return r.query = e, r.params = t, r._entityId = i, r.skip = !1, r.history = {\n                past: [],\n                present: null,\n                future: []\n            }, r.skipUpdate = !1, t.maxAge = t.maxAge || 10, t.comparator = t.comparator || function() {\n                return !0\n            }, r.activate(), r\n        }\n\n        function jl(e, t) {\n            this.query = e, this.entityIds = t, this.entities = new Map\n        }\n\n        function Ql(e, t) {\n            var i = Kl.call(this, e, (t = void 0 === t ? {} : t).entityIds) || this;\n            return i.query = e, (i.params = t).maxAge = Jo(t.maxAge) ? t.maxAge : 10, i.activate(), i.selectIds().pipe(ka(1)).subscribe(function(e) {\n                return i.activate(e)\n            }), i\n        }\n        ut(Ql, Kl = Vr), Ql.prototype.redo = function(e) {\n            this.forEachId(e, function(e) {\n                return e.redo()\n            })\n        }, Ql.prototype.undo = function(e) {\n            this.forEachId(e, function(e) {\n                return e.undo()\n            })\n        }, Ql.prototype.hasPast = function(e) {\n            if (this.hasEntity(e)) return this.getEntity(e).hasPast\n        }, Ql.prototype.hasFuture = function(e) {\n            if (this.hasEntity(e)) return this.getEntity(e).hasFuture\n        }, Ql.prototype.jumpToFuture = function(e, t) {\n            this.forEachId(e, function(e) {\n                return e.jumpToFuture(t)\n            })\n        }, Ql.prototype.jumpToPast = function(e, t) {\n            this.forEachId(e, function(e) {\n                return e.jumpToPast(t)\n            })\n        }, Ql.prototype.clear = function(e) {\n            this.forEachId(e, function(e) {\n                return e.clear()\n            })\n        }, Ql.prototype.destroy = function(e, t) {\n            void 0 === t && (t = !1), this.forEachId(e, function(e) {\n                return e.destroy(t)\n            })\n        }, Ql.prototype.ignoreNext = function(e) {\n            this.forEachId(e, function(e) {\n                return e.ignoreNext()\n            })\n        }, Ql.prototype.instantiatePlugin = function(e) {\n            return new ql(this.query, this.params, e)\n        };\n        var Wl = {\n            comparator: function(e, t) {\n                return JSON.stringify(e) !== JSON.stringify(t)\n            }\n        };\n\n        function Gl(e, t) {\n            return t.split(\".\").reduce(function(e, t) {\n                return e && \"undefined\" !== e[t] ? e[t] : void 0\n            }, e)\n        }\n        var zl, Xl, Yl = (ut(Jl, zl = A), Jl.prototype.reset = function(e) {\n            var t = this.head;\n            $o((e = void 0 === e ? {} : e).updateFn) && (t = this.isEntityBased(this._entityId) ? e.updateFn(this.head, this.getQuery().getEntity(this._entityId)) : e.updateFn(this.head, this.getQuery().getValue())), Do(\"@DirtyCheck - Revert\"), this.updateStore(t, this._entityId), this._reset.next()\n        }, Jl.prototype.setHead = function() {\n            return this.active ? this.head = this._getHead() : (this.activate(), this.active = !0), this.updateDirtiness(!1), this\n        }, Jl.prototype.isDirty = function() {\n            return !!this.dirty.value\n        }, Jl.prototype.hasHead = function() {\n            return !!this.getHead()\n        }, Jl.prototype.destroy = function() {\n            this.head = null, this.subscription && this.subscription.unsubscribe(), this._reset && this._reset.complete()\n        }, Jl.prototype.isPathDirty = function(e) {\n            var t = this.getHead(),\n                i = Gl(this.getQuery().getValue(), e),\n                e = Gl(t, e);\n            return this.params.comparator(i, e)\n        }, Jl.prototype.getHead = function() {\n            return this.head\n        }, Jl.prototype.activate = function() {\n            var i = this;\n            this.head = this._getHead();\n            var e = this.params.watchProperty ? this.params.watchProperty.map(function(t) {\n                return i.query.select(function(e) {\n                    return e[t]\n                }).pipe(hr(function(e) {\n                    return {\n                        val: e,\n                        __akitaKey: t\n                    }\n                }))\n            }) : [this.selectSource(this._entityId)];\n            this.subscription = Mr.apply(void 0, gt(e)).pipe(ka(1)).subscribe(function(e) {\n                Vo(i.head) || (e = e.some(function(e) {\n                    var t = e.__akitaKey ? i.head[e.__akitaKey] : i.head,\n                        e = e.__akitaKey ? e.val : e;\n                    return i.params.comparator(t, e)\n                }), i.updateDirtiness(e))\n            })\n        }, Jl.prototype.updateDirtiness = function(e) {\n            this.dirty.next(e)\n        }, Jl.prototype._getHead = function() {\n            var e = this.getSource(this._entityId);\n            return e = this.params.watchProperty ? this.getWatchedValues(e) : e\n        }, Jl.prototype.getWatchedValues = function(i) {\n            return this.params.watchProperty.reduce(function(e, t) {\n                return e[t] = i[t], e\n            }, {})\n        }, Jl);\n\n        function Jl(e, t, i) {\n            var r = zl.call(this, e) || this;\n            return r.query = e, r.params = t, r._entityId = i, r.dirty = new yi(!1), r.active = !1, r._reset = new Xt, r.isDirty$ = r.dirty.asObservable().pipe(Is()), r.reset$ = r._reset.asObservable(), r.params = ct({}, Wl, t), r.params.watchProperty && (t = Ro(r.params.watchProperty), e instanceof kl && t.includes(\"entities\") && !t.includes(\"ids\") && t.push(\"ids\"), r.params.watchProperty = t), r\n        }\n\n        function Zl() {\n            return Math.random().toString(36).slice(2)\n        }\n\n        function ed(e) {\n            return Mr(e).pipe($n(0))\n        }\n\n        function td(e, t) {\n            var i = Xl.call(this, e, (t = void 0 === t ? {} : t).entityIds) || this;\n            return i.query = e, i.params = t, i._someDirty = new Xt, i.someDirty$ = an(i.query.select(function(e) {\n                return e.entities\n            }), i._someDirty.asObservable()).pipe($n(0), hr(function() {\n                return i.checkSomeDirty()\n            })), i.params = ct({}, Wl, t), i.activate(), i.selectIds().pipe(ka(1)).subscribe(function(e) {\n                Xl.prototype.rebase.call(i, e, {\n                    afterAdd: function(e) {\n                        return e.setHead()\n                    }\n                })\n            }), i\n        }\n        ut(td, Xl = Vr), td.prototype.setHead = function(e) {\n            if (this.params.entityIds && e) {\n                var t = Ro(e);\n                if (!1 === Ro(this.params.entityIds).some(function(e) {\n                        return -1 < t.indexOf(e)\n                    })) return this\n            }\n            return this.forEachId(e, function(e) {\n                return e.setHead()\n            }), this._someDirty.next(), this\n        }, td.prototype.hasHead = function(e) {\n            return !!this.entities.has(e) && this.getEntity(e).hasHead()\n        }, td.prototype.reset = function(e, t) {\n            void 0 === t && (t = {}), this.forEachId(e, function(e) {\n                return e.reset(t)\n            })\n        }, td.prototype.isDirty = function(e, t) {\n            if (void 0 === t && (t = !0), this.entities.has(e)) {\n                e = this.getEntity(e);\n                return t ? e.isDirty$ : e.isDirty()\n            }\n            return !1\n        }, td.prototype.someDirty = function() {\n            return this.checkSomeDirty()\n        }, td.prototype.isPathDirty = function(e, t) {\n            if (this.entities.has(e)) {\n                var i = this.getEntity(e).getHead(),\n                    e = Gl(this.query.getEntity(e), t),\n                    t = Gl(i, t);\n                return this.params.comparator(e, t)\n            }\n            return null\n        }, td.prototype.destroy = function(e) {\n            this.forEachId(e, function(e) {\n                return e.destroy()\n            }), e || this._someDirty.complete()\n        }, td.prototype.instantiatePlugin = function(e) {\n            return new Yl(this.query, this.params, e)\n        }, td.prototype.checkSomeDirty = function() {\n            var e, t, i = this.resolvedIds();\n            try {\n                for (var r = ft(i), n = r.next(); !n.done; n = r.next()) {\n                    var s = n.value;\n                    if (this.getEntity(s).isDirty()) return !0\n                }\n            } catch (t) {\n                e = {\n                    error: t\n                }\n            } finally {\n                try {\n                    n && !n.done && (t = r.return) && t.call(r)\n                } finally {\n                    if (e) throw e.error\n                }\n            }\n            return !1\n        }, (tu = tu || {}).Update = \"UPDATE\", {} [tu.Update] = \"update\", (vr = ru = ru || {}).Update = \"UPDATE\", vr.AddEntities = \"ADD_ENTITIES\", vr.SetEntities = \"SET_ENTITIES\", vr.UpdateEntities = \"UPDATE_ENTITIES\", vr.RemoveEntities = \"REMOVE_ENTITIES\", vr.UpsertEntities = \"UPSERT_ENTITIES\", vr.UpsertManyEntities = \"UPSERT_MANY_ENTITIES\", (iu = {})[ru.Update] = \"update\", iu[ru.AddEntities] = \"add\", iu[ru.SetEntities] = \"set\", iu[ru.UpdateEntities] = \"update\", iu[ru.RemoveEntities] = \"remove\", iu[ru.UpsertEntities] = \"upsert\", iu[ru.UpsertManyEntities] = \"upsertMany\";\n        w = {};\n        Object.defineProperty(w, \"__esModule\", {\n            value: !0\n        });\n        var vi = \"undefined\" != typeof Symbol && \"symbol\" == typeof Symbol(\"x\"),\n            id = \"undefined\" != typeof Map,\n            rd = \"undefined\" != typeof Set,\n            nd = \"undefined\" != typeof Proxy && void 0 !== Proxy.revocable && \"undefined\" != typeof Reflect,\n            sd = vi ? Symbol.for(\"immer-nothing\") : ((nu = {})[\"immer-nothing\"] = !0, nu),\n            ad = vi ? Symbol.for(\"immer-draftable\") : \"__$immer_draftable\",\n            od = vi ? Symbol.for(\"immer-state\") : \"__$immer_state\",\n            ld = \"undefined\" != typeof Symbol && Symbol.iterator || \"@@iterator\",\n            dd = {\n                0: \"Illegal state\",\n                1: \"Immer drafts cannot have computed properties\",\n                2: \"This object has been frozen and should not be mutated\",\n                3: function(e) {\n                    return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + e\n                },\n                4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n                5: \"Immer forbids circular references\",\n                6: \"The first or second argument to `produce` must be a function\",\n                7: \"The third argument to `produce` must be a function or undefined\",\n                8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n                9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n                10: \"The given draft is already finalized\",\n                11: \"Object.defineProperty() cannot be used on an Immer draft\",\n                12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n                13: \"Immer only supports deleting array indices\",\n                14: \"Immer only supports setting array indices and the 'length' property\",\n                15: function(e) {\n                    return \"Cannot apply patch, path doesn't resolve: \" + e\n                },\n                16: 'Sets cannot have \"replace\" patches.',\n                17: function(e) {\n                    return \"Unsupported patch operation: \" + e\n                },\n                18: function(e) {\n                    return \"The plugin for '\" + e + \"' has not been loaded into Immer. To enable the plugin, import and call `enable\" + e + \"()` when initializing your application.\"\n                },\n                20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n                21: function(e) {\n                    return \"produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '\" + e + \"'\"\n                },\n                22: function(e) {\n                    return \"'current' expects a draft, got: \" + e\n                },\n                23: function(e) {\n                    return \"'original' expects a draft, got: \" + e\n                }\n            };\n\n        function ud(e) {\n            for (var t = arguments.length, i = new Array(1 < t ? t - 1 : 0), r = 1; r < t; r++) i[r - 1] = arguments[r];\n            var n = dd[e],\n                e = n ? \"function\" == typeof n ? n.apply(null, i) : n : \"unknown error nr: \" + e;\n            throw new Error(\"[Immer] \" + e)\n        }\n\n        function cd(e) {\n            return !!e && !!e[od]\n        }\n\n        function hd(t) {\n            return !!t && (function() {\n                if (!t || \"object\" != typeof t) return !1;\n                var e = Object.getPrototypeOf(t);\n                return !e || e === Object.prototype\n            }() || Array.isArray(t) || !!t[ad] || !!t.constructor[ad] || Td(t) || Ed(t))\n        }\n        var pd = \"undefined\" != typeof Reflect && Reflect.ownKeys ? Reflect.ownKeys : void 0 !== Object.getOwnPropertySymbols ? function(e) {\n                return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))\n            } : Object.getOwnPropertyNames,\n            fd = Object.getOwnPropertyDescriptors || function(t) {\n                var i = {};\n                return pd(t).forEach(function(e) {\n                    i[e] = Object.getOwnPropertyDescriptor(t, e)\n                }), i\n            };\n\n        function md(i, r, t) {\n            void 0 === t && (t = !1), 0 === gd(i) ? (t ? Object.keys : pd)(i).forEach(function(e) {\n                t && \"symbol\" == typeof e || r(e, i[e], i)\n            }) : i.forEach(function(e, t) {\n                return r(t, e, i)\n            })\n        }\n\n        function gd(e) {\n            var t = e[od];\n            return t ? 3 < t.type_ ? t.type_ - 4 : t.type_ : Array.isArray(e) ? 1 : Td(e) ? 2 : Ed(e) ? 3 : 0\n        }\n\n        function yd(e, t) {\n            return 2 === gd(e) ? e.has(t) : Object.prototype.hasOwnProperty.call(e, t)\n        }\n\n        function vd(e, t) {\n            return 2 === gd(e) ? e.get(t) : e[t]\n        }\n\n        function Sd(e, t, i) {\n            var r = gd(e);\n            2 === r ? e.set(t, i) : 3 === r ? (e.delete(t), e.add(i)) : e[t] = i\n        }\n\n        function bd(e, t) {\n            return e === t ? 0 !== e || 1 / e == 1 / t : e != e && t != t\n        }\n\n        function Td(e) {\n            return id && e instanceof Map\n        }\n\n        function Ed(e) {\n            return rd && e instanceof Set\n        }\n\n        function Id(e) {\n            return e.copy_ || e.base_\n        }\n\n        function wd(e) {\n            if (Array.isArray(e)) return Array.prototype.slice.call(e);\n            var t = fd(e);\n            delete t[od];\n            for (var i = pd(t), r = 0; r < i.length; r++) {\n                var n = i[r],\n                    s = t[n];\n                !1 === s.writable && (s.writable = !0, s.configurable = !0), (s.get || s.set) && (t[n] = {\n                    configurable: !0,\n                    writable: !0,\n                    enumerable: s.enumerable,\n                    value: e[n]\n                })\n            }\n            return Object.create(Object.getPrototypeOf(e), t)\n        }\n\n        function Ad(e, t) {\n            kd(e) || cd(e) || !hd(e) || (1 < gd(e) && (e.set = e.add = e.clear = e.delete = Od), Object.freeze(e), t && md(e, function(e, t) {\n                return Ad(t, !0)\n            }, !0))\n        }\n\n        function Od() {\n            ud(2)\n        }\n\n        function kd(e) {\n            return null == e || \"object\" != typeof e || Object.isFrozen(e)\n        }\n        var Cd, Dd = {};\n\n        function Md(e) {\n            var t = Dd[e];\n            return t || ud(18, e), t\n        }\n\n        function xd(e, t) {\n            Dd[e] || (Dd[e] = t)\n        }\n\n        function Pd() {\n            return Cd || ud(0), Cd\n        }\n\n        function Rd(e, t) {\n            t && (Md(\"Patches\"), e.patches_ = [], e.inversePatches_ = [], e.patchListener_ = t)\n        }\n\n        function Ld(e) {\n            _d(e), e.drafts_.forEach(Fd), e.drafts_ = null\n        }\n\n        function _d(e) {\n            e === Cd && (Cd = e.parent_)\n        }\n\n        function Nd(e) {\n            return Cd = {\n                drafts_: [],\n                parent_: Cd,\n                immer_: e,\n                canAutoFreeze_: !0,\n                unfinalizedDrafts_: 0\n            }\n        }\n\n        function Fd(e) {\n            e = e[od];\n            0 === e.type_ || 1 === e.type_ ? e.revoke_() : e.revoked_ = !0\n        }\n\n        function Bd(e, t) {\n            t.unfinalizedDrafts_ = t.drafts_.length;\n            var i = t.drafts_[0],\n                r = void 0 !== e && e !== i;\n            return t.immer_.useProxies_ || Md(\"ES5\").willFinalizeES5_(t, e, r), r ? (i[od].modified_ && (Ld(t), ud(4)), hd(e) && (e = Ud(t, e), t.parent_ || Vd(t, e)), t.patches_ && Md(\"Patches\").generateReplacementPatches_(i[od], e, t.patches_, t.inversePatches_)) : e = Ud(t, i, []), Ld(t), t.patches_ && t.patchListener_(t.patches_, t.inversePatches_), e !== sd ? e : void 0\n        }\n\n        function Ud(i, r, n) {\n            if (kd(r)) return r;\n            var s, a = r[od];\n            return a ? a.scope_ !== i ? r : a.modified_ ? (a.finalized_ || (a.finalized_ = !0, a.scope_.unfinalizedDrafts_--, s = 4 === a.type_ || 5 === a.type_ ? a.copy_ = wd(a.draft_) : a.copy_, md(3 === a.type_ ? new Set(s) : s, function(e, t) {\n                return $d(i, a, s, e, t, n)\n            }), Vd(i, s, !1), n && i.patches_ && Md(\"Patches\").generatePatches_(a, n, i.patches_, i.inversePatches_)), a.copy_) : (Vd(i, a.base_, !0), a.base_) : (md(r, function(e, t) {\n                return $d(i, a, r, e, t, n)\n            }, !0), r)\n        }\n\n        function $d(e, t, i, r, n, s) {\n            if (n === i && ud(5), cd(n)) {\n                s = Ud(e, n, s && t && 3 !== t.type_ && !yd(t.assigned_, r) ? s.concat(r) : void 0);\n                if (Sd(i, r, s), !cd(s)) return;\n                e.canAutoFreeze_ = !1\n            }\n            hd(n) && !kd(n) && (!e.immer_.autoFreeze_ && e.unfinalizedDrafts_ < 1 || (Ud(e, n), t && t.scope_.parent_ || Vd(e, n)))\n        }\n\n        function Vd(e, t, i) {\n            void 0 === i && (i = !1), e.immer_.autoFreeze_ && e.canAutoFreeze_ && Ad(t, i)\n        }\n        var Kd = {\n                get: function(e, t) {\n                    if (t === od) return e;\n                    var i, r, n = Id(e);\n                    if (!yd(n, t)) return i = e, (r = jd(n, t)) ? \"value\" in r ? r.value : null === (r = r.get) || void 0 === r ? void 0 : r.call(i.draft_) : void 0;\n                    n = n[t];\n                    return !e.finalized_ && hd(n) && n === Hd(e.base_, t) ? (Wd(e), e.copy_[t] = zd(e.scope_.immer_, n, e)) : n\n                },\n                has: function(e, t) {\n                    return t in Id(e)\n                },\n                ownKeys: function(e) {\n                    return Reflect.ownKeys(Id(e))\n                },\n                set: function(e, t, i) {\n                    var r = jd(Id(e), t);\n                    if (null != r && r.set) return r.set.call(e.draft_, i), !0;\n                    if (!e.modified_) {\n                        var n = Hd(Id(e), t),\n                            r = null == n ? void 0 : n[od];\n                        if (r && r.base_ === i) return e.copy_[t] = i, !(e.assigned_[t] = !1);\n                        if (bd(i, n) && (void 0 !== i || yd(e.base_, t))) return !0;\n                        Wd(e), Qd(e)\n                    }\n                    return e.copy_[t] = i, e.assigned_[t] = !0\n                },\n                deleteProperty: function(e, t) {\n                    return void 0 !== Hd(e.base_, t) || t in e.base_ ? (e.assigned_[t] = !1, Wd(e), Qd(e)) : delete e.assigned_[t], e.copy_ && delete e.copy_[t], !0\n                },\n                getOwnPropertyDescriptor: function(e, t) {\n                    var i = Id(e),\n                        r = Reflect.getOwnPropertyDescriptor(i, t);\n                    return r && {\n                        writable: !0,\n                        configurable: 1 !== e.type_ || \"length\" !== t,\n                        enumerable: r.enumerable,\n                        value: i[t]\n                    }\n                },\n                defineProperty: function() {\n                    ud(11)\n                },\n                getPrototypeOf: function(e) {\n                    return Object.getPrototypeOf(e.base_)\n                },\n                setPrototypeOf: function() {\n                    ud(12)\n                }\n            },\n            qd = {};\n\n        function Hd(e, t) {\n            var i = e[od];\n            return (i ? Id(i) : e)[t]\n        }\n\n        function jd(e, t) {\n            if (t in e)\n                for (var i = Object.getPrototypeOf(e); i;) {\n                    var r = Object.getOwnPropertyDescriptor(i, t);\n                    if (r) return r;\n                    i = Object.getPrototypeOf(i)\n                }\n        }\n\n        function Qd(e) {\n            e.modified_ || (e.modified_ = !0, e.parent_ && Qd(e.parent_))\n        }\n\n        function Wd(e) {\n            e.copy_ || (e.copy_ = wd(e.base_))\n        }\n        md(Kd, function(e, t) {\n            qd[e] = function() {\n                return arguments[0] = arguments[0][0], t.apply(this, arguments)\n            }\n        }), qd.deleteProperty = function(e, t) {\n            return isNaN(parseInt(t)) && ud(13), Kd.deleteProperty.call(this, e[0], t)\n        }, qd.set = function(e, t, i) {\n            return \"length\" !== t && isNaN(parseInt(t)) && ud(14), Kd.set.call(this, e[0], t, i, e[0])\n        };\n        (A = Gd.prototype).produce = function(e, s, t) {\n            if (\"function\" == typeof e && \"function\" != typeof s) {\n                var a = s;\n                s = e;\n                var o = this;\n                return function(e) {\n                    var t = this;\n                    void 0 === e && (e = a);\n                    for (var i = arguments.length, r = new Array(1 < i ? i - 1 : 0), n = 1; n < i; n++) r[n - 1] = arguments[n];\n                    return o.produce(e, function(e) {\n                        return s.call.apply(s, [t, e].concat(r))\n                    })\n                }\n            }\n            var i;\n            if (\"function\" != typeof s && ud(6), void 0 !== t && \"function\" != typeof t && ud(7), hd(e)) {\n                var r = Nd(this),\n                    n = zd(this, e, void 0),\n                    l = !0;\n                try {\n                    i = s(n), l = !1\n                } finally {\n                    (l ? Ld : _d)(r)\n                }\n                return \"undefined\" != typeof Promise && i instanceof Promise ? i.then(function(e) {\n                    return Rd(r, t), Bd(e, r)\n                }, function(e) {\n                    throw Ld(r), e\n                }) : (Rd(r, t), Bd(i, r))\n            }\n            if (!e || \"object\" != typeof e) return (i = s(e)) === sd ? void 0 : (void 0 === i && (i = e), this.autoFreeze_ && Ad(i, !0), i);\n            ud(21, e)\n        }, A.produceWithPatches = function(n, e, t) {\n            var i, r, s = this;\n            return \"function\" == typeof n ? function(e) {\n                for (var t = arguments.length, i = new Array(1 < t ? t - 1 : 0), r = 1; r < t; r++) i[r - 1] = arguments[r];\n                return s.produceWithPatches(e, function(e) {\n                    return n.apply(void 0, [e].concat(i))\n                })\n            } : [this.produce(n, e, function(e, t) {\n                i = e, r = t\n            }), i, r]\n        }, A.createDraft = function(e) {\n            hd(e) || ud(8), cd(e) && (e = Xd(e));\n            var t = Nd(this),\n                e = zd(this, e, void 0);\n            return e[od].isManual_ = !0, _d(t), e\n        }, A.finishDraft = function(e, t) {\n            e = e && e[od];\n            e && e.isManual_ || ud(9), e.finalized_ && ud(10);\n            e = e.scope_;\n            return Rd(e, t), Bd(void 0, e)\n        }, A.setAutoFreeze = function(e) {\n            this.autoFreeze_ = e\n        }, A.setUseProxies = function(e) {\n            e && !nd && ud(20), this.useProxies_ = e\n        }, A.applyPatches = function(e, t) {\n            for (var i = t.length - 1; 0 <= i; i--) {\n                var r = t[i];\n                if (0 === r.path.length && \"replace\" === r.op) {\n                    e = r.value;\n                    break\n                }\n            }\n            var n = Md(\"Patches\").applyPatches_;\n            return cd(e) ? n(e, t) : this.produce(e, function(e) {\n                return n(e, t.slice(i + 1))\n            })\n        }, Vr = Gd;\n\n        function Gd(e) {\n            this.useProxies_ = nd, this.autoFreeze_ = !0, \"boolean\" == typeof(null == e ? void 0 : e.useProxies) && this.setUseProxies(e.useProxies), \"boolean\" == typeof(null == e ? void 0 : e.autoFreeze) && this.setAutoFreeze(e.autoFreeze), this.produce = this.produce.bind(this), this.produceWithPatches = this.produceWithPatches.bind(this)\n        }\n\n        function zd(e, t, i) {\n            t = Td(t) ? Md(\"MapSet\").proxyMap_(t, i) : Ed(t) ? Md(\"MapSet\").proxySet_(t, i) : e.useProxies_ ? function(e, t) {\n                var i = Array.isArray(e),\n                    r = {\n                        type_: i ? 1 : 0,\n                        scope_: t ? t.scope_ : Pd(),\n                        modified_: !1,\n                        finalized_: !1,\n                        assigned_: {},\n                        parent_: t,\n                        base_: e,\n                        draft_: null,\n                        copy_: null,\n                        revoke_: null,\n                        isManual_: !1\n                    },\n                    t = r,\n                    e = Kd;\n                i && (t = [r], e = qd);\n                t = Proxy.revocable(t, e), e = t.revoke, t = t.proxy;\n                return r.draft_ = t, r.revoke_ = e, t\n            }(t, i) : Md(\"ES5\").createES5Proxy_(t, i);\n            return (i ? i.scope_ : Pd()).drafts_.push(t), t\n        }\n\n        function Xd(e) {\n            return cd(e) || ud(22, e),\n                function i(e) {\n                    if (!hd(e)) return e;\n                    var r, n = e[od],\n                        t = gd(e);\n                    if (n) {\n                        if (!n.modified_ && (n.type_ < 4 || !Md(\"ES5\").hasChanges_(n))) return n.base_;\n                        n.finalized_ = !0, r = Yd(e, t), n.finalized_ = !1\n                    } else r = Yd(e, t);\n                    return md(r, function(e, t) {\n                        n && vd(n.base_, e) === t || Sd(r, e, i(t))\n                    }), 3 === t ? new Set(r) : r\n                }(e)\n        }\n\n        function Yd(e, t) {\n            switch (t) {\n                case 2:\n                    return new Map(e);\n                case 3:\n                    return Array.from(e)\n            }\n            return wd(e)\n        }\n\n        function Jd() {\n            var r = {};\n\n            function l(i, e) {\n                var t = r[i];\n                return t ? t.enumerable = e : r[i] = t = {\n                    configurable: !0,\n                    enumerable: e,\n                    get: function() {\n                        var e = this[od];\n                        return a(e), Kd.get(e, i)\n                    },\n                    set: function(e) {\n                        var t = this[od];\n                        a(t), Kd.set(t, i, e)\n                    }\n                }, t\n            }\n\n            function n(e) {\n                for (var t = e.length - 1; 0 <= t; t--) {\n                    var i = e[t][od];\n                    if (!i.modified_) switch (i.type_) {\n                        case 5:\n                            u(i) && Qd(i);\n                            break;\n                        case 4:\n                            s(i) && Qd(i)\n                    }\n                }\n            }\n\n            function s(e) {\n                for (var t = e.base_, i = e.draft_, r = pd(i), n = r.length - 1; 0 <= n; n--) {\n                    var s = r[n];\n                    if (s !== od) {\n                        var a = t[s];\n                        if (void 0 === a && !yd(t, s)) return !0;\n                        var o = i[s],\n                            s = o && o[od];\n                        if (s ? s.base_ !== a : !bd(o, a)) return !0\n                    }\n                }\n                e = !!t[od];\n                return r.length !== pd(t).length + (e ? 0 : 1)\n            }\n\n            function u(e) {\n                var t = e.draft_;\n                if (t.length !== e.base_.length) return !0;\n                t = Object.getOwnPropertyDescriptor(t, t.length - 1);\n                return !(!t || t.get)\n            }\n\n            function a(e) {\n                e.revoked_ && ud(3, JSON.stringify(Id(e)))\n            }\n            xd(\"ES5\", {\n                createES5Proxy_: function(e, t) {\n                    var i = Array.isArray(e),\n                        r = function(e, t) {\n                            if (e) {\n                                for (var i = new Array(t.length), r = 0; r < t.length; r++) Object.defineProperty(i, \"\" + r, l(r, !0));\n                                return i\n                            }\n                            var n = fd(t);\n                            delete n[od];\n                            for (var s = pd(n), a = 0; a < s.length; a++) {\n                                var o = s[a];\n                                n[o] = l(o, e || !!n[o].enumerable)\n                            }\n                            return Object.create(Object.getPrototypeOf(t), n)\n                        }(i, e),\n                        e = {\n                            type_: i ? 5 : 4,\n                            scope_: t ? t.scope_ : Pd(),\n                            modified_: !1,\n                            finalized_: !1,\n                            assigned_: {},\n                            parent_: t,\n                            base_: e,\n                            draft_: r,\n                            copy_: null,\n                            revoked_: !1,\n                            isManual_: !1\n                        };\n                    return Object.defineProperty(r, od, {\n                        value: e,\n                        writable: !0\n                    }), r\n                },\n                willFinalizeES5_: function(e, t, i) {\n                    i ? cd(t) && t[od].scope_ === e && n(e.drafts_) : (e.patches_ && function t(e) {\n                        if (e && \"object\" == typeof e) {\n                            var i = e[od];\n                            if (i) {\n                                var r = i.base_,\n                                    n = i.draft_,\n                                    s = i.assigned_;\n                                if (4 === (e = i.type_)) md(n, function(e) {\n                                    e !== od && (void 0 !== r[e] || yd(r, e) ? s[e] || t(n[e]) : (s[e] = !0, Qd(i)))\n                                }), md(r, function(e) {\n                                    void 0 !== n[e] || yd(n, e) || (s[e] = !1, Qd(i))\n                                });\n                                else if (5 === e) {\n                                    if (u(i) && (Qd(i), s.length = !0), n.length < r.length)\n                                        for (var a = n.length; a < r.length; a++) s[a] = !1;\n                                    else\n                                        for (var o = r.length; o < n.length; o++) s[o] = !0;\n                                    for (var l = Math.min(n.length, r.length), d = 0; d < l; d++) void 0 === s[d] && t(n[d])\n                                }\n                            }\n                        }\n                    }(e.drafts_[0]), n(e.drafts_))\n                },\n                hasChanges_: function(e) {\n                    return (4 === e.type_ ? s : u)(e)\n                }\n            })\n        }\n\n        function Zd() {\n            var m = \"replace\",\n                g = \"add\",\n                y = \"remove\";\n\n            function d(e) {\n                if (!hd(e)) return e;\n                if (Array.isArray(e)) return e.map(d);\n                if (Td(e)) return new Map(Array.from(e.entries()).map(function(e) {\n                    return [e[0], d(e[1])]\n                }));\n                if (Ed(e)) return new Set(Array.from(e).map(d));\n                var t, i = Object.create(Object.getPrototypeOf(e));\n                for (t in e) i[t] = d(e[t]);\n                return i\n            }\n\n            function v(e) {\n                return cd(e) ? d(e) : e\n            }\n            xd(\"Patches\", {\n                applyPatches_: function(l, e) {\n                    return e.forEach(function(e) {\n                        for (var t = e.path, i = e.op, r = l, n = 0; n < t.length - 1; n++) \"object\" != typeof(r = vd(r, t[n])) && ud(15, t.join(\"/\"));\n                        var s = gd(r),\n                            a = d(e.value),\n                            o = t[t.length - 1];\n                        switch (i) {\n                            case m:\n                                switch (s) {\n                                    case 2:\n                                        return r.set(o, a);\n                                    case 3:\n                                        ud(16);\n                                    default:\n                                        return r[o] = a\n                                }\n                            case g:\n                                switch (s) {\n                                    case 1:\n                                        return r.splice(o, 0, a);\n                                    case 2:\n                                        return r.set(o, a);\n                                    case 3:\n                                        return r.add(a);\n                                    default:\n                                        return r[o] = a\n                                }\n                            case y:\n                                switch (s) {\n                                    case 1:\n                                        return r.splice(o, 1);\n                                    case 2:\n                                        return r.delete(o);\n                                    case 3:\n                                        return r.delete(e.value);\n                                    default:\n                                        return delete r[o]\n                                }\n                            default:\n                                ud(17, i)\n                        }\n                    }), l\n                },\n                generatePatches_: function(c, e, t, i) {\n                    switch (c.type_) {\n                        case 0:\n                        case 4:\n                        case 2:\n                            return d = e, u = t, h = i, p = c.base_, f = c.copy_, void md(c.assigned_, function(e, t) {\n                                var i = vd(p, e),\n                                    r = vd(f, e),\n                                    t = t ? yd(p, e) ? m : g : y;\n                                i === r && t == m || (e = d.concat(e), u.push(t == y ? {\n                                    op: t,\n                                    path: e\n                                } : {\n                                    op: t,\n                                    path: e,\n                                    value: r\n                                }), h.push(t == g ? {\n                                    op: y,\n                                    path: e\n                                } : t == y ? {\n                                    op: g,\n                                    path: e,\n                                    value: v(i)\n                                } : {\n                                    op: m,\n                                    path: e,\n                                    value: v(i)\n                                }))\n                            });\n                        case 5:\n                        case 1:\n                            return function(e, t, i) {\n                                var r, n = c.base_,\n                                    s = c.assigned_,\n                                    a = c.copy_;\n                                a.length < n.length && (n = (r = [a, n])[0], a = r[1], t = (r = [i, t])[0], i = r[1]);\n                                for (var o, l = 0; l < n.length; l++) s[l] && a[l] !== n[l] && (o = e.concat([l]), t.push({\n                                    op: m,\n                                    path: o,\n                                    value: v(a[l])\n                                }), i.push({\n                                    op: m,\n                                    path: o,\n                                    value: v(n[l])\n                                }));\n                                for (var d = n.length; d < a.length; d++) {\n                                    var u = e.concat([d]);\n                                    t.push({\n                                        op: g,\n                                        path: u,\n                                        value: v(a[d])\n                                    })\n                                }\n                                n.length < a.length && i.push({\n                                    op: m,\n                                    path: e.concat([\"length\"]),\n                                    value: n.length\n                                })\n                            }(e, t, i);\n                        case 3:\n                            return r = e, n = t, s = i, a = c.base_, o = c.copy_, l = 0, a.forEach(function(e) {\n                                var t;\n                                o.has(e) || (t = r.concat([l]), n.push({\n                                    op: y,\n                                    path: t,\n                                    value: e\n                                }), s.unshift({\n                                    op: g,\n                                    path: t,\n                                    value: e\n                                })), l++\n                            }), l = 0, void o.forEach(function(e) {\n                                var t;\n                                a.has(e) || (t = r.concat([l]), n.push({\n                                    op: g,\n                                    path: t,\n                                    value: e\n                                }), s.unshift({\n                                    op: y,\n                                    path: t,\n                                    value: e\n                                })), l++\n                            })\n                    }\n                    var r, n, s, a, o, l, d, u, h, p, f\n                },\n                generateReplacementPatches_: function(e, t, i, r) {\n                    i.push({\n                        op: m,\n                        path: [],\n                        value: t\n                    }), r.push({\n                        op: m,\n                        path: [],\n                        value: e.base_\n                    })\n                }\n            })\n        }\n\n        function eu() {\n            var r = function(e, t) {\n                return (r = Object.setPrototypeOf || {\n                        __proto__: []\n                    }\n                    instanceof Array && function(e, t) {\n                        e.__proto__ = t\n                    } || function(e, t) {\n                        for (var i in t) t.hasOwnProperty(i) && (e[i] = t[i])\n                    })(e, t)\n            };\n\n            function i(e, t) {\n                function i() {\n                    this.constructor = e\n                }\n                r(e, t), e.prototype = (i.prototype = t.prototype, new i)\n            }\n            var n = function() {\n                function e(e, t) {\n                    return this[od] = {\n                        type_: 2,\n                        parent_: t,\n                        scope_: t ? t.scope_ : Pd(),\n                        modified_: !1,\n                        finalized_: !1,\n                        copy_: void 0,\n                        assigned_: void 0,\n                        base_: e,\n                        draft_: this,\n                        isManual_: !1,\n                        revoked_: !1\n                    }, this\n                }\n                i(e, Map);\n                var t = e.prototype;\n                return Object.defineProperty(t, \"size\", {\n                    get: function() {\n                        return Id(this[od]).size\n                    }\n                }), t.has = function(e) {\n                    return Id(this[od]).has(e)\n                }, t.set = function(e, t) {\n                    var i = this[od];\n                    return l(i), Id(i).has(e) && Id(i).get(e) === t || (s(i), Qd(i), i.assigned_.set(e, !0), i.copy_.set(e, t), i.assigned_.set(e, !0)), this\n                }, t.delete = function(e) {\n                    if (!this.has(e)) return !1;\n                    var t = this[od];\n                    return l(t), s(t), Qd(t), t.assigned_.set(e, !1), t.copy_.delete(e), !0\n                }, t.clear = function() {\n                    var t = this[od];\n                    l(t), Id(t).size && (s(t), Qd(t), t.assigned_ = new Map, md(t.base_, function(e) {\n                        t.assigned_.set(e, !1)\n                    }), t.copy_.clear())\n                }, t.forEach = function(r, n) {\n                    var s = this;\n                    Id(this[od]).forEach(function(e, t, i) {\n                        r.call(n, s.get(t), t, s)\n                    })\n                }, t.get = function(e) {\n                    var t = this[od];\n                    l(t);\n                    var i = Id(t).get(e);\n                    if (t.finalized_ || !hd(i)) return i;\n                    if (i !== t.base_.get(e)) return i;\n                    i = zd(t.scope_.immer_, i, t);\n                    return s(t), t.copy_.set(e, i), i\n                }, t.keys = function() {\n                    return Id(this[od]).keys()\n                }, t.values = function() {\n                    var e, t = this,\n                        i = this.keys();\n                    return (e = {})[ld] = function() {\n                        return t.values()\n                    }, e.next = function() {\n                        var e = i.next();\n                        return e.done ? e : {\n                            done: !1,\n                            value: t.get(e.value)\n                        }\n                    }, e\n                }, t.entries = function() {\n                    var e, i = this,\n                        r = this.keys();\n                    return (e = {})[ld] = function() {\n                        return i.entries()\n                    }, e.next = function() {\n                        var e = r.next();\n                        if (e.done) return e;\n                        var t = i.get(e.value);\n                        return {\n                            done: !1,\n                            value: [e.value, t]\n                        }\n                    }, e\n                }, t[ld] = function() {\n                    return this.entries()\n                }, e\n            }();\n\n            function s(e) {\n                e.copy_ || (e.assigned_ = new Map, e.copy_ = new Map(e.base_))\n            }\n            var a = function() {\n                function e(e, t) {\n                    return this[od] = {\n                        type_: 3,\n                        parent_: t,\n                        scope_: t ? t.scope_ : Pd(),\n                        modified_: !1,\n                        finalized_: !1,\n                        copy_: void 0,\n                        base_: e,\n                        draft_: this,\n                        drafts_: new Map,\n                        revoked_: !1,\n                        isManual_: !1\n                    }, this\n                }\n                i(e, Set);\n                var t = e.prototype;\n                return Object.defineProperty(t, \"size\", {\n                    get: function() {\n                        return Id(this[od]).size\n                    }\n                }), t.has = function(e) {\n                    var t = this[od];\n                    return l(t), t.copy_ ? !!t.copy_.has(e) || !(!t.drafts_.has(e) || !t.copy_.has(t.drafts_.get(e))) : t.base_.has(e)\n                }, t.add = function(e) {\n                    var t = this[od];\n                    return l(t), this.has(e) || (o(t), Qd(t), t.copy_.add(e)), this\n                }, t.delete = function(e) {\n                    if (!this.has(e)) return !1;\n                    var t = this[od];\n                    return l(t), o(t), Qd(t), t.copy_.delete(e) || !!t.drafts_.has(e) && t.copy_.delete(t.drafts_.get(e))\n                }, t.clear = function() {\n                    var e = this[od];\n                    l(e), Id(e).size && (o(e), Qd(e), e.copy_.clear())\n                }, t.values = function() {\n                    var e = this[od];\n                    return l(e), o(e), e.copy_.values()\n                }, t.entries = function() {\n                    var e = this[od];\n                    return l(e), o(e), e.copy_.entries()\n                }, t.keys = function() {\n                    return this.values()\n                }, t[ld] = function() {\n                    return this.values()\n                }, t.forEach = function(e, t) {\n                    for (var i = this.values(), r = i.next(); !r.done;) e.call(t, r.value, r.value, this), r = i.next()\n                }, e\n            }();\n\n            function o(i) {\n                i.copy_ || (i.copy_ = new Set, i.base_.forEach(function(e) {\n                    var t;\n                    hd(e) ? (t = zd(i.scope_.immer_, e, i), i.drafts_.set(e, t), i.copy_.add(t)) : i.copy_.add(e)\n                }))\n            }\n\n            function l(e) {\n                e.revoked_ && ud(3, JSON.stringify(Id(e)))\n            }\n            xd(\"MapSet\", {\n                proxyMap_: function(e, t) {\n                    return new n(e, t)\n                },\n                proxySet_: function(e, t) {\n                    return new a(e, t)\n                }\n            })\n        }\n        var tu = new Vr,\n            vr = tu.produce,\n            iu = tu.produceWithPatches.bind(tu),\n            ru = tu.setAutoFreeze.bind(tu),\n            nu = tu.setUseProxies.bind(tu),\n            vi = tu.applyPatches.bind(tu),\n            A = tu.createDraft.bind(tu),\n            tu = tu.finishDraft.bind(tu);\n        w.Immer = Vr, w.applyPatches = vi, w.castDraft = function(e) {\n            return e\n        }, w.castImmutable = function(e) {\n            return e\n        }, w.createDraft = A, w.current = Xd, w.default = vr, w.enableAllPlugins = function() {\n            Jd(), eu(), Zd()\n        }, w.enableES5 = Jd;\n        A = w.enableMapSet = eu;\n        w.enablePatches = Zd, w.finishDraft = tu, w.immerable = ad, w.isDraft = cd, w.isDraftable = hd, w.nothing = sd, w.original = function(e) {\n            return cd(e) || ud(23, e), e[od].base_\n        };\n        var su = w.produce = vr;\n        w.produceWithPatches = iu;\n        var au = w.setAutoFreeze = ru;\n        w.setUseProxies = nu;\n        const ou = /^((?:[^\\/;?#]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/,\n            lu = /^([^\\/;?#]*)(.*)$/,\n            du = /(?:\\/|^)\\.(?=\\/)/g,\n            uu = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/).*?(?=\\/)/g,\n            cu = {\n                buildAbsoluteURL: function(e, t, i) {\n                    if (i = i || {}, e = e.trim(), !(t = t.trim())) {\n                        if (!i.alwaysNormalize) return e;\n                        const t = cu.parseURL(e);\n                        if (!t) throw new Error(\"Error trying to parse base URL.\");\n                        return t.path = cu.normalizePath(t.path), cu.buildURLFromParts(t)\n                    }\n                    const r = cu.parseURL(t);\n                    if (!r) throw new Error(\"Error trying to parse relative URL.\");\n                    if (r.scheme) return i.alwaysNormalize ? (r.path = cu.normalizePath(r.path), cu.buildURLFromParts(r)) : t;\n                    const n = cu.parseURL(e);\n                    if (!n) throw new Error(\"Error trying to parse base URL.\");\n                    if (!n.netLoc && n.path && \"/\" !== n.path[0]) {\n                        const e = lu.exec(n.path);\n                        n.netLoc = e[1], n.path = e[2]\n                    }\n                    n.netLoc && !n.path && (n.path = \"/\");\n                    const s = {\n                        scheme: n.scheme,\n                        netLoc: r.netLoc,\n                        path: null,\n                        params: r.params,\n                        query: r.query,\n                        fragment: r.fragment\n                    };\n                    if (!r.netLoc && (s.netLoc = n.netLoc, \"/\" !== r.path[0]))\n                        if (r.path) {\n                            i.inheritQuery && (r.query || (s.query = n.query));\n                            const e = n.path,\n                                t = e.substring(0, e.lastIndexOf(\"/\") + 1) + r.path;\n                            s.path = cu.normalizePath(t)\n                        } else s.path = n.path, r.params || (s.params = n.params, r.query || (s.query = n.query));\n                    return null === s.path && (s.path = i.alwaysNormalize ? cu.normalizePath(r.path) : r.path), cu.buildURLFromParts(s)\n                },\n                parseURL: function(e) {\n                    e = ou.exec(e);\n                    return e ? {\n                        scheme: e[1] || \"\",\n                        netLoc: e[2] || \"\",\n                        path: e[3] || \"\",\n                        params: e[4] || \"\",\n                        query: e[5] || \"\",\n                        fragment: e[6] || \"\"\n                    } : null\n                },\n                normalizePath: function(e) {\n                    for (e = e.split(\"\").reverse().join(\"\").replace(du, \"\"); e.length !== (e = e.replace(uu, \"\")).length;);\n                    return e.split(\"\").reverse().join(\"\")\n                },\n                buildURLFromParts: function(e) {\n                    return e.scheme + e.netLoc + e.path + e.params + e.query + e.fragment\n                },\n                getHostName: function(e) {\n                    let t;\n                    return e && (t = -1 < e.indexOf(\"://\") ? e.split(\"/\")[2] : e.split(\"/\")[0], t = t.split(\":\")[0], t = t.split(\"?\")[0]), t\n                }\n            };\n        var hu, pu, fu, mu, gu, yu, vu, Su, bu = cu;\n\n        function Tu(e) {\n            return null != e && !e.startsWith(\"http://\") && !e.startsWith(\"https://\")\n        }\n\n        function Eu(e) {\n            return null == e || Tu(e) ? null : cu.getHostName(e)\n        }\n        const Iu = [\".*.itunes.apple.com\"],\n            wu = {\n                deviceName: \"&xapdn=\",\n                deviceModel: \"&xapdm=\",\n                language: \"&xapdl=\",\n                dsid: \"&xapdsid=\",\n                subs: \"&xapsub=\"\n            };\n\n        function Au(e, t) {\n            return !e || e === Eu(t)\n        }(iu = hu = hu || {})[iu.DOVI = 4] = \"DOVI\", iu[iu.HEVC = 3] = \"HEVC\", iu[iu.VP09 = 2] = \"VP09\", iu[iu.AVC = 1] = \"AVC\", iu[iu.UNKNOWN = 0] = \"UNKNOWN\", (ru = pu = pu || {})[ru.PQ = 3] = \"PQ\", ru[ru.HLG = 2] = \"HLG\", ru[ru.SDR = 1] = \"SDR\", ru[ru.UNKNOWN = 0] = \"UNKNOWN\", (w = fu = fu || {})[w.ALAC = 7] = \"ALAC\", w[w.FLAC = 6] = \"FLAC\", w[w.EC3 = 5] = \"EC3\", w[w.AC3 = 4] = \"AC3\", w[w.XHEAAC = 3] = \"XHEAAC\", w[w.AAC = 2] = \"AAC\", w[w.MP3 = 1] = \"MP3\", w[w.UNKNOWN = 0] = \"UNKNOWN\", (nu = mu = mu || {})[nu.VALID = 1] = \"VALID\", nu[nu.INVALID = 0] = \"INVALID\";\n        const Ou = [\"via\", \"x-apple-request-uuid\"],\n            ku = {\n                maxNumRetry: 4,\n                retryDelayMs: 0,\n                maxRetryDelayMs: 0\n            },\n            Cu = {\n                maxNumRetry: 6,\n                retryDelayMs: 1e3,\n                maxRetryDelayMs: 8e3\n            },\n            Du = {\n                maxNumRetry: 0,\n                retryDelayMs: 0,\n                maxRetryDelayMs: 0\n            },\n            Mu = {\n                default: {\n                    maxTimeToFirstByteMs: 5e3,\n                    maxLoadTimeMs: 2e4,\n                    autoRetry: !1,\n                    timeoutRetry: Du,\n                    errorRetry: Du\n                },\n                customURL: {\n                    maxTimeToFirstByteMs: 1e4,\n                    maxLoadTimeMs: 2e4,\n                    autoRetry: !1,\n                    timeoutRetry: Du,\n                    errorRetry: Du\n                }\n            },\n            xu = {\n                maxNumRetry: 8,\n                retryDelayMs: 1e3,\n                maxRetryDelayMs: 2e4,\n                backoff: \"linear\"\n            },\n            Pu = Object.assign(Object.assign({}, xu), {\n                maxNumRetry: 1\n            }),\n            Ru = {\n                autoStartLoad: !0,\n                startPosition: NaN,\n                defaultAudioCodec: void 0,\n                defaultVideoCodec: void 0,\n                debug: !1,\n                debugLevel: \"info\",\n                buildType: void 0,\n                minFramesBeforeSwitchingLevel: 11,\n                minTargetDurations: 3,\n                maxBufferLength: 60,\n                maxBufferHole: .5,\n                maxSeekHole: 2,\n                nudgeFromEventSeek: !0,\n                jaggedSeekTolerance: 0,\n                discontinuitySeekTolerance: 2,\n                bufferedSegmentEjectionToleranceMs: .5,\n                almostDryBufferSec: .5,\n                maxTotalDurationTolerance: .1,\n                lowBufferThreshold: .5,\n                lowBufferWatchdogPeriod: .5,\n                highBufferWatchdogPeriod: 3,\n                seekWatchdogPeriod: 5,\n                nudgeOffset: .1,\n                nudgeMaxRetry: 3,\n                maxFragLookUpTolerance: .2,\n                initialLiveManifestSize: 1,\n                liveSyncDurationCount: 3,\n                liveMaxLatencyDurationCount: 1 / 0,\n                liveSyncDuration: void 0,\n                liveMaxLatencyDuration: void 0,\n                liveFlushExpiredFrags: !0,\n                liveMaxUnchangedPlaylistRefresh: 3,\n                liveEdgeForZeroStartPositon: !1,\n                livePlaylistUpdateStaleness: 2,\n                livePlaylistDurationNudge: .001,\n                allowFastSwitchUp: !1,\n                minMatchGroupDuration: 5,\n                desiredIframeFPS: 8,\n                initialIframeFPS: 6,\n                minRemainingTimeInMediaPipeline: 3,\n                leftMediaTimeToAutoPause: 10,\n                startTargetDurationFactor: .9,\n                minRequiredStartDuration: 4,\n                maxRequiredStartDuration: 15,\n                enableWorker: !0,\n                enableWebCrypto: !0,\n                keySystemPreference: void 0,\n                useMultipleKeySessions: !1,\n                enablePlayReadyKeySystem: !1,\n                useMediaKeySystemAccessFilter: !1,\n                playReadyMessageFormat: \"utf16\",\n                startLevel: void 0,\n                livePlaylistRefreshDelay: 2500,\n                liveMinPlayingBufferLen: 5,\n                enableIFramePreloading: !0,\n                useMediaCapabilities: !1,\n                enableID3Cues: !0,\n                certLoadPolicy: Mu,\n                keyLoadPolicy: {\n                    default: {\n                        maxTimeToFirstByteMs: 5e3,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: Pu,\n                        errorRetry: xu\n                    },\n                    customURL: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: Pu,\n                        errorRetry: xu\n                    }\n                },\n                manifestLoadPolicy: {\n                    default: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 0,\n                            maxRetryDelayMs: 0\n                        },\n                        errorRetry: {\n                            maxNumRetry: 1,\n                            retryDelayMs: 1e3,\n                            maxRetryDelayMs: 8e3\n                        }\n                    },\n                    customURL: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 1e4,\n                        autoRetry: !1,\n                        timeoutRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 0,\n                            maxRetryDelayMs: 0\n                        },\n                        errorRetry: {\n                            maxNumRetry: 1,\n                            retryDelayMs: 1e3,\n                            maxRetryDelayMs: 8e3\n                        }\n                    }\n                },\n                trickPlaybackConfig: {\n                    enabled: !0,\n                    minIframeDuration: 8\n                },\n                playlistLoadPolicy: {\n                    default: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 0,\n                            maxRetryDelayMs: 0\n                        },\n                        errorRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 1e3,\n                            maxRetryDelayMs: 8e3\n                        }\n                    },\n                    customURL: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 1e4,\n                        autoRetry: !1,\n                        timeoutRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 0,\n                            maxRetryDelayMs: 0\n                        },\n                        errorRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 1e3,\n                            maxRetryDelayMs: 8e3\n                        }\n                    }\n                },\n                fragLoadPolicy: {\n                    default: {\n                        maxTimeToFirstByteMs: 5e3,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: ku,\n                        errorRetry: Cu,\n                        forceContentLenCheckIfNoHeader: !1,\n                        reportCDNServer: !0\n                    },\n                    customURL: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: ku,\n                        errorRetry: Cu,\n                        reportCDNServer: !0\n                    }\n                },\n                steeringManifestLoadPolicy: {\n                    default: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 2e4,\n                        autoRetry: !1,\n                        timeoutRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 0,\n                            maxRetryDelayMs: 0\n                        },\n                        errorRetry: {\n                            maxNumRetry: 1,\n                            retryDelayMs: 1e3,\n                            maxRetryDelayMs: 8e3\n                        }\n                    },\n                    customURL: {\n                        maxTimeToFirstByteMs: 1e4,\n                        maxLoadTimeMs: 1e4,\n                        autoRetry: !1,\n                        timeoutRetry: {\n                            maxNumRetry: 2,\n                            retryDelayMs: 0,\n                            maxRetryDelayMs: 0\n                        },\n                        errorRetry: {\n                            maxNumRetry: 1,\n                            retryDelayMs: 1e3,\n                            maxRetryDelayMs: 8e3\n                        }\n                    }\n                },\n                maxNumAddLevelToPenaltyBox: 4,\n                firstAudioMustOverlapVideoStart: !1,\n                keyMinHoldTimeBeforeCleanup: 15e3,\n                startFragPrefetch: !1,\n                appendErrorMaxRetry: 3,\n                alwaysResetOnNewCC: !1,\n                fLoader: void 0,\n                pLoader: void 0,\n                xhrSetup: void 0,\n                iframeMaxExitSeekDuration: 2e3,\n                iframeStallMaxRetry: 5,\n                audioPrimingDelay: 0,\n                enableCEA708Captions: !0,\n                customTextTrackCueRenderer: !1,\n                enableWebVTT: !0,\n                captionsTextTrack1Label: \"English\",\n                captionsTextTrack1LanguageCode: \"en\",\n                captionsTextTrack2Label: \"Spanish\",\n                captionsTextTrack2LanguageCode: \"es\",\n                enableDualTrackSelection: !1,\n                condenseSubtitleTrack: !1,\n                nativeTextTrackChangeHandling: !0,\n                earlyFragTolerance: 7,\n                vttConcurrentLoadCount: 1,\n                trottleCheckInterval: 2e3,\n                subtitleLeadTime: 30,\n                lateTolerance: 2,\n                stretchShortVideoTrack: !1,\n                forceKeyFrameOnDiscontinuity: !0,\n                useFirstLevelAtIncompatDiscontinuity: !0,\n                abrBandwidthEstimator: \"bandwidth-history-controller\",\n                abrEwmaDefaultEstimate: 5e5,\n                abrDefaultEstimate: 5e5,\n                abrBandWidthFactor: .95,\n                abrBandWidthUpFactor: .9,\n                abrMaxWithRealBitrate: !1,\n                maxStarvationDelay: 4,\n                maxLoadingDelay: 4,\n                minAutoBitrate: 0,\n                enableRtcReporting: !1,\n                rtcIntervalTimeout: 3e5,\n                rtcSender: \"HLSJS\",\n                rtcSessionTag: \"none\",\n                useHTTPPlaybackSessionId: !1,\n                warmupCdms: !1,\n                enablePerformanceLogging: !1,\n                overridePlaybackRate: !1,\n                nativeControlsEnabled: !1,\n                useCustomMediaFunctions: !0,\n                seekEventThrottleMs: 150,\n                enableAdaptiveStartup: !0,\n                bandwidthHistoryWindowSize: 12e4,\n                bandwidthHistoryTTL: 6e5,\n                bandwidthHistoryAggregationMethod: \"quadratic-time-weighted\",\n                bandwidthHistoryGetEstimateThrottleMs: 1e3,\n                defaultTargetDuration: 10,\n                targetStartupMs: 4e3,\n                adaptiveStartupMetricsOverride: {\n                    maxValidHeight: 1080,\n                    maxValidBitrate: 1 / 0,\n                    maxPreferredBitrate: 1 / 0\n                },\n                bandwidthHistoryStorageKey: \"AppleHLS-bandwidth-estimation\",\n                storageKeyPrefix: \"AppleHLS-\",\n                storage: {\n                    get: \"undefined\" == typeof localStorage ? void 0 : localStorage.getItem.bind(localStorage),\n                    set: \"undefined\" == typeof localStorage ? void 0 : localStorage.setItem.bind(localStorage)\n                },\n                minFragmentCount: 10,\n                minPlaylistCount: 5,\n                enableCDNFallback: !0,\n                enableQueryParamsForITunes: !1,\n                gapless: !1,\n                useViewportSizeForLevelCap: !1,\n                statDefaults: {\n                    playlistLoadTimeMs: 500,\n                    playlistParseTimeMs: 50,\n                    fragParseTimeMs: 50,\n                    fragBufferCreationDelayMs: 200,\n                    dataFragAppendMs: 50,\n                    initFragAppendMs: 50\n                },\n                disableVideoCodecList: new Set([]),\n                disableAudioCodecList: new Set([fu.ALAC, fu.FLAC, fu.XHEAAC]),\n                useHighestVideoCodecPrivate: !0,\n                sessionDataAutoLoad: {\n                    \"com.apple.hls.chapters\": !0\n                }\n            },\n            Lu = Object.assign(Object.assign({}, {\n                itemId: \"Nah\",\n                mediaOptionId: \"Nah\"\n            }), {\n                mediaOptionType: void 0\n            }),\n            _u = e => {\n                var {\n                    itemId: t,\n                    mediaOptionId: e\n                } = e;\n                return \"Nah\" !== t && \"Nah\" !== e\n            };\n        (iu = gu = gu || {})[iu.Variant = 0] = \"Variant\", iu[iu.AltAudio = 1] = \"AltAudio\", iu[iu.Subtitle = 2] = \"Subtitle\";\n        const Nu = [\"variant\", \"altAudio\", \"subtitle\"],\n            Fu = [gu.Variant, gu.AltAudio, gu.Subtitle],\n            Bu = [gu.Variant, gu.AltAudio];\n        (ru = yu = yu || {})[ru.Variant = 0] = \"Variant\", ru[ru.AltAudio = 1] = \"AltAudio\";\n        const Uu = [\"variant\", \"altAudio\"];\n\n        function $u(e) {\n            switch (e) {\n                case gu.Variant:\n                    return yu.Variant;\n                case gu.AltAudio:\n                    return yu.AltAudio;\n                default:\n                    return null\n            }\n        }\n\n        function Vu(e) {\n            return e === yu.Variant ? gu.Variant : gu.AltAudio\n        }(w = vu = vu || {})[w.NO = 0] = \"NO\", w[w.YES = 1] = \"YES\", (nu = Su = Su || {}).UNKNOWN = \"unkn\", nu.VIDEO = \"vide\", nu.AUDIO = \"soun\", nu.SUBTITLE = \"sbtl\", nu.CLOSEDCAPTION = \"clcp\";\n        const Ku = {\n            search: function(e, t) {\n                let i, r, n = 0,\n                    s = (null == e ? void 0 : e.length) - 1;\n                for (; n <= s;) {\n                    var a = t(r = e[i = (n + s) / 2 | 0]);\n                    if (0 < a) n = 1 + i;\n                    else {\n                        if (!(a < 0)) return r;\n                        s = i - 1\n                    }\n                }\n                return null\n            }\n        };\n        var qu = Ku,\n            Hu = {\n                findFragmentBySNAndBuffer: function(e, t, i = 0, r = 0, n = 0) {\n                    let s;\n                    e = e ? t[e.mediaSeqNum - t[0].mediaSeqNum + 1] : null;\n                    return s = i < r ? (r - n < i && (n = 0), e && !this.fragmentWithinToleranceTest(i, n, e) ? e : Ku.search(t, this.fragmentWithinToleranceTest.bind(null, i, n))) : t[t.length - 1], s\n                },\n                fragmentWithinToleranceTest: function(e, t, i) {\n                    t = Math.min(t, i.duration);\n                    return i.start + i.duration - t <= e ? 1 : i.start - t > e && i.start ? -1 : 0\n                }\n            };\n        const ju = {\n            startFragmentInCC: function(e, t, i) {\n                let r = t - i.discoSeqNum;\n                if (0 === r) {\n                    const t = e[i.mediaSeqNum - e[0].mediaSeqNum - 1];\n                    r = t && t.discoSeqNum === i.discoSeqNum ? -1 : 0\n                }\n                return r\n            },\n            endFragmentInCC: function(e, t, i) {\n                let r = t - i.discoSeqNum;\n                if (0 === r) {\n                    const t = e[i.mediaSeqNum - e[0].mediaSeqNum + 1];\n                    r = t && t.discoSeqNum === i.discoSeqNum ? 1 : 0\n                }\n                return r\n            },\n            findStartEndFragmentsInCC: function(e, t, i) {\n                let r, n;\n                return 0 < (null == e ? void 0 : e.length) && ne(t) && (r = Ku.search(e, ju.startFragmentInCC.bind(null, e, t)), n = Ku.search(e, ju.endFragmentInCC.bind(null, e, t))), r && !ne(r.discoSeqNum) && (r = void 0), n && !ne(n.discoSeqNum) && (n = void 0), {\n                    startFrag: r,\n                    endFrag: n\n                }\n            },\n            getTimeRangeDictForCC: function(e, t, i) {\n                var {\n                    startFrag: t,\n                    endFrag: i\n                } = ju.findStartEndFragmentsInCC(e, t, i);\n                return {\n                    start: t.start,\n                    end: i.start + i.duration\n                }\n            },\n            getTimeRangeForCC: function(e, t, i) {\n                var {\n                    startFrag: t,\n                    endFrag: i\n                } = ju.findStartEndFragmentsInCC(e, t, i);\n                let r = [];\n                return t && i && (r = [t.start, i.start + i.duration]), r\n            },\n            snapToCCTimeRange: function(e, t, i, r) {\n                r = ju.getTimeRangeForCC(t, i, r);\n                return null != r && r.length ? Math.min(r[1], Math.max(r[0], e)) : e\n            },\n            getMinTimeForCC(e, t, i, r) {\n                if (null == e || !e.length) return 0;\n                let n = 0;\n                if (ne(i) && e) {\n                    e = ju.getTimeRangeForCC(e, i, r);\n                    if (e) {\n                        const s = ju.getTimeRangeForCC(t, i, r);\n                        n = null != s && s.length ? Math.max(s[0], e[0]) : e[0]\n                    }\n                }\n                return n\n            },\n            discoSeqNumForTime(e, t, i = 0) {\n                i = Ku.search(e, Hu.fragmentWithinToleranceTest.bind(null, t, i));\n                return null == i ? void 0 : i.discoSeqNum\n            }\n        };\n        var Qu = ju;\n        const Wu = $i(void 0);\n\n        function Gu(e, t, i = 1) {\n            return e.pipe(ln(t), Ds(i))\n        }\n\n        function zu(e, t) {\n            var i = e.timeline;\n            return {\n                seconds: (e.seconds - i.rootTimeSeconds) / i.rate * t.rate + t.rootTimeSeconds,\n                timeline: t\n            }\n        }\n        class Xu {\n            constructor() {\n                this._timeline = null\n            }\n            get forward() {\n                var e;\n                return 0 < (null === (e = this.timeline) || void 0 === e ? void 0 : e.rate)\n            }\n            get isStarted() {\n                return Boolean(this.hostClock)\n            }\n            start(e) {\n                this.stopTime = null, this._timeline = Object.assign({}, e);\n                const t = {\n                    rootTimeSeconds: performance.now() / 1e3,\n                    rate: 1\n                };\n                this.hostClock = {\n                    timeline: t,\n                    getCurrentTime: () => ({\n                        seconds: performance.now() / 1e3,\n                        timeline: t\n                    })\n                }\n            }\n            pause() {\n                this.isStarted && (this.stopTime = this.getCurrentTime())\n            }\n            stop() {\n                this.pause(), this.hostClock = null, this._timeline = null\n            }\n            get timeline() {\n                return this._timeline\n            }\n            getCurrentTime() {\n                return this.stopTime || zu(this.hostClock.getCurrentTime(), this.timeline)\n            }\n        }\n        class Yu {\n            constructor(e) {\n                this._timeline = e, this.mediaRootTime = this.lastTimeSeconds = e.rootTimeSeconds\n            }\n            get timeline() {\n                return Object.assign({}, this._timeline)\n            }\n            getCurrentTime() {\n                return {\n                    seconds: this.lastTimeSeconds,\n                    timeline: Object.assign({}, this._timeline)\n                }\n            }\n        }\n        const Ju = {\n            name: \"ifm\"\n        };\n        class Zu {\n            constructor(e, t) {\n                this.config = e, this.logger = t, this.scaledFragments = [], this.iframeClock = new Xu, this.hasMore$ = new yi(!0), this.logger = t.child(Ju)\n            }\n            destroy() {\n                this.stop()\n            }\n            resetScaledSegments() {\n                this.scaledFragments = []\n            }\n            get anchorFrag() {\n                return this.scaledFragments.length ? this.scaledFragments[0] : null\n            }\n            get lastFrag() {\n                return this.scaledFragments.length ? this.scaledFragments.slice(-1)[0] : null\n            }\n            get isStarted() {\n                return Boolean(this.iframeClock.isStarted)\n            }\n            get iframeRate() {\n                var e;\n                return null !== (e = null === (e = this.iframeClock.timeline) || void 0 === e ? void 0 : e.rate) && void 0 !== e ? e : 0\n            }\n            get iframeClockTimeSeconds() {\n                return Math.max(0, this.iframeClock.getCurrentTime().seconds)\n            }\n            get mediaAppendClockTimeSeconds() {\n                var e;\n                return null !== (e = null === (e = this.mediaAppendClock) || void 0 === e ? void 0 : e.getCurrentTime().seconds) && void 0 !== e ? e : 0\n            }\n            get mediaRootTime() {\n                var e;\n                return null === (e = this.mediaAppendClock) || void 0 === e ? void 0 : e.mediaRootTime\n            }\n            pause() {\n                this.iframeClock.pause()\n            }\n            stop() {\n                this.hasMore$.next(!0), this.iframeClock.stop(), this.mediaAppendClock = null, this.resetScaledSegments()\n            }\n            checkHasMore() {\n                this.hasMore$.next(!0)\n            }\n            startClocksAndGetFirstFragment(e, t, i, r, n) {\n                let s = Ku.search(e, Hu.fragmentWithinToleranceTest.bind(null, r, 1e-4));\n                if (!s && r >= e[e.length - 1].start && (s = e[e.length - 1]), !s) return this.logger.error(`startClocksAndGetFirstFragment => no anchorFrag for time ${r}`), this.hasMore$.next(!1), null;\n                var a = ne(n) ? n : s.discoSeqNum,\n                    a = Qu.getMinTimeForCC(e, t, a, this.logger),\n                    r = ne(n) && 1 < i ? a : r,\n                    a = 1 < i ? Math.ceil(r) : Math.ceil(a);\n                return this.iframeClock.start({\n                    rootTimeSeconds: r,\n                    rate: i\n                }), this.mediaAppendClock = new Yu({\n                    rootTimeSeconds: a,\n                    rate: 1\n                }), {\n                    frag: s,\n                    newMediaRootTime: a\n                }\n            }\n            getNextFragment(e, t, i) {\n                const r = this.lastFrag,\n                    {\n                        iframeClock: n,\n                        mediaAppendClock: s\n                    } = this,\n                    a = n.timeline;\n                s.lastTimeSeconds = t;\n                var o = n.forward ? 1 : -1;\n                let l, d = Math.max(0, Math.min(r.mediaSeqNum - e[0].mediaSeqNum + o, e.length - 1));\n                if (r.mediaSeqNum !== e[d].mediaSeqNum)\n                    do {\n                        l = e[d];\n                        const i = n.forward ? l.start : l.start + l.duration;\n                        if (zu({\n                                seconds: i,\n                                timeline: a\n                            }, s.timeline).seconds >= t && (n.forward && i >= this.iframeClockTimeSeconds || !n.forward && i <= this.iframeClockTimeSeconds)) break\n                    } while (d += o, 0 < d && d < e.length);\n                return l || (this.logger.error(`getNextFragment(bufferEnd: ${t}) => no more frags, but we should have found an end fragment, setting hasMore to false`), this.hasMore$.next(!1)), {\n                    frag: l\n                }\n            }\n            nextFragment(e, t, i, r) {\n                let n, s;\n                if (this.isStarted && i !== this.iframeRate && (s = this.iframeClockTimeSeconds, this.stop()), this.isStarted) {\n                    if (n = this.getNextFragment(e, r, i), !n.frag) return;\n                    if (n.frag.discoSeqNum !== this.anchorFrag.discoSeqNum) {\n                        const a = this.iframeClockTimeSeconds;\n                        this.stop();\n                        const s = this.startClocksAndGetFirstFragment(e, t, i, a, n.frag.discoSeqNum)[\"newMediaRootTime\"];\n                        n.newMediaRootTime = s\n                    }\n                } else if (n = this.startClocksAndGetFirstFragment(e, t, i, null != s ? s : r), !n) return;\n                var r = n[\"frag\"],\n                    r = this.handleNextFrag(e, r);\n                return Object.assign(Object.assign({}, n), {\n                    frag: r\n                })\n            }\n            handleNextFrag(e, t) {\n                const i = Object.assign(Object.assign({}, t), {\n                        iframeMediaStart: NaN,\n                        iframeMediaDuration: NaN\n                    }),\n                    {\n                        mediaAppendClock: r,\n                        iframeClock: n\n                    } = this;\n                this.iframeClockBounds = Qu.getTimeRangeDictForCC(e, i.discoSeqNum, this.logger);\n                var s = r.getCurrentTime().seconds,\n                    t = n.timeline.rate;\n                return ne(i.iframeOriginalStart) || (i.iframeOriginalStart = i.start), i.start = i.iframeMediaStart = s, i.iframeMediaDuration = Math.max(i.duration / Math.abs(t), 1 / this.config.minIframeDuration), this.scaledFragments.push(i), this.isEndFrag(e, i) && this.hasMore$.next(!1), i\n            }\n            get hasMore() {\n                return this.hasMore$.value\n            }\n            handleWaitForMore() {\n                return this.isStarted ? (this.iframeClock.getCurrentTime(), Gu(this.hasMore$, e => !0 === e).pipe(Za(() => {}))) : Wu\n            }\n            isEndFrag(e, t) {\n                var i = e[0],\n                    r = e[e.length - 1],\n                    e = this.iframeClock.forward;\n                return !e && (null == i ? void 0 : i.mediaSeqNum) === t.mediaSeqNum || e && (null == r ? void 0 : r.mediaSeqNum) === t.mediaSeqNum\n            }\n        }\n\n        function ec(e, t) {\n            for (var i = 0; i < t.length; i++) {\n                var r = t[i];\n                r.enumerable = r.enumerable || !1, r.configurable = !0, \"value\" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)\n            }\n        }\n\n        function tc(t) {\n            return function(e) {\n                return e.lift(new nc(t))\n            }\n        }\n        var ic, rc, nc = (ec(sc.prototype, [{\n            key: \"call\",\n            value: function(e, t) {\n                return t.subscribe(e)\n            }\n        }]), sc);\n\n        function sc(e) {\n            ! function(e) {\n                if (!(e instanceof sc)) throw new TypeError(\"Cannot call a class as a function\")\n            }(this), \"tag\" in this ? Object.defineProperty(this, \"tag\", {\n                value: void 0,\n                enumerable: !0,\n                configurable: !0,\n                writable: !0\n            }) : this.tag = void 0, this.tag = e\n        }\n\n        function ac(e) {\n            const {\n                method: t,\n                isEncrypted: i,\n                uri: r,\n                format: n,\n                formatversions: s\n            } = e, a = {\n                method: t,\n                isEncrypted: i,\n                uri: r,\n                format: n,\n                formatversions: s,\n                iv: e.ivBuf ? new Uint8Array(e.ivBuf) : null\n            };\n            return e.keyIdBuf && (a.keyId = new Uint8Array(e.keyIdBuf)), e.keyBuf && (a.key = new Uint8Array(e.keyBuf)), e.psshBuf && (a.pssh = new Uint8Array(e.psshBuf)), a\n        }(iu = ic = ic || {}).MustRequestResponse = \"MustRequestResponse\", iu.WaitingForKeyResponse = \"WaitingForKeyResponse\", iu.GotKeyResponse = \"GotKeyResponse\";\n        class oc extends Error {\n            constructor(e, t) {\n                super(e), this.code = t\n            }\n        }\n        class lc extends p {\n            constructor(e, t, i, r, n, s) {\n                super(o, e, t, i, n), this.code = r, this.isTimeout = s, this.response = n\n            }\n        }\n        class dc extends lc {\n            constructor(e, t, i, r, n) {\n                super(n ? \"manifestLoadTimeOut\" : \"manifestLoadError\", e, t, i, r, n)\n            }\n        }\n        class uc extends lc {\n            constructor(e, t, i, r, n, s, a, o) {\n                switch (super(\"\", e, t, i, r, n), this.mediaOptionType = s, this.mediaOptionId = a, this.url = o, s) {\n                    case gu.Variant:\n                        this.details = n ? \"levelLoadTimeOut\" : N;\n                        break;\n                    case gu.AltAudio:\n                        this.details = n ? \"audioTrackLoadTimeOut\" : \"audioTrackLoadError\";\n                        break;\n                    case gu.Subtitle:\n                        this.details = n ? \"subtitleTrackLoadTimeout\" : \"subtitleTrackLoadError\"\n                }\n            }\n        }\n        class cc extends lc {\n            constructor(e, t, i, r) {\n                super(\"sessionDataLoadError\", e, t, i, r, !1)\n            }\n        }\n        class hc extends lc {\n            constructor(e, t, i, r, n, s, a) {\n                super(n ? \"fragLoadTimeOut\" : \"fragLoadError\", e, t, i, r, n), this.mediaOptionId = s.mediaOptionId, this.mediaOptionType = s.mediaOptionType, this.stats = a\n            }\n        }\n        class pc extends dr {\n            constructor(e, t, i) {\n                super(), this.message = e, this.code = t, this.stats = i\n            }\n        }\n        class fc extends lc {\n            constructor(e, t, i) {\n                super(\"fragAbortError\", !1, \"Fragment abort\", 0, i, !1), this.candidateMediaOptionId = t, this.mediaOptionId = e.mediaOptionId, this.mediaOptionType = e.mediaOptionType\n            }\n        }\n        class mc extends lc {\n            constructor(e, t, i, r = []) {\n                super(\"keyLoadTimeOut\", !1, e, i.code, i, !0), this.keyuri = t, this.response = i, this.mediaOptionIds = r\n            }\n        }(ru = rc = rc || {})[ru.InvalidState = 0] = \"InvalidState\", ru[ru.Abort = 1] = \"Abort\", ru[ru.OutputRestricted = 2] = \"OutputRestricted\", ru[ru.AlreadyFailedKey = 3] = \"AlreadyFailedKey\", ru[ru.HttpError = 4] = \"HttpError\", ru[ru.InternalError = 5] = \"InternalError\", ru[ru.LicenseServerError = 6] = \"LicenseServerError\", ru[ru.InsufficientCPC = 7] = \"InsufficientCPC\";\n        class gc extends lc {\n            constructor(e, t, i, r, n, s, a = !1, o = []) {\n                super(\"keyLoadError\", a, e, i, r, !1), this.keyuri = t, this.isOkToRetry = n, this.keyErrorReason = s, this.mediaOptionIds = o\n            }\n        }\n        class yc extends p {\n            constructor(e, t, i, r, n) {\n                super(s, \"keySystemGenericError\", !0, e, r), this.keyuri = t, this.code = i, this.response = r, this.keysystemstring = n\n            }\n        }\n\n        function vc(e, t) {\n            return e instanceof gc ? new gc(e.message, e.keyuri, e.code, e.response, e.isOkToRetry, e.keyErrorReason, e.fatal, t) : e instanceof mc ? new mc(e.message, e.keyuri, $.CryptResponseReceivedSlowly, t) : e ? new V(e.fatal, e.reason, $.InternalError) : null\n        }\n        const Sc = {\n            id: \"fairplaystreaming\",\n            systemStringPrefix: \"com.apple.fps\",\n            keyFormatString: \"com.apple.streamingkeydelivery\",\n            securityLevels: {\n                AppleBaseline: 0,\n                AppleMain: 1,\n                Main: 1,\n                Baseline: 0\n            }\n        };\n        class bc extends kl {\n            constructor(e) {\n                super(e), this.store = e\n            }\n            get unresolvedUriLoading$() {\n                return this.selectEntityAction(Eo.Add).pipe(hr(e => e.map(e => this.getEntity(e))))\n            }\n        }\n        class Tc {\n            constructor(e) {\n                this.store = e\n            }\n            createUnresolvedUriLoading(e, t, i) {\n                Do(\"loader.create.unresolvedUriLoading\"), this.store.add({\n                    uri: e,\n                    responseType: t,\n                    userAgent: i\n                })\n            }\n            removeUnresolvedUriLoading(e) {\n                Do(\"loader.remove.unresolvedUriLoading\"), this.store.remove(e)\n            }\n        }\n        const Ec = new class extends fl {\n            constructor() {\n                super({}, {\n                    name: \"loader\",\n                    producerFn: su,\n                    idKey: \"uri\"\n                })\n            }\n        };\n        let Ic = null;\n        class wc extends t {\n            trigger(e, t) {\n                try {\n                    this.emit(e, e, t), \"hlsFragLoadProgress\" !== e.toString() && (\"hlsInternalError\" !== e && \"hlsError\" !== e || !t.length || JSON.stringify(t[0], [\"fatal\", \"details\", \"reason\"]), e.toString())\n                } catch (t) {\n                    Qe().warn(`error in event listener for ${e}: ${t.message}`)\n                }\n            }\n        }\n        class Ac {\n            constructor(e, t) {\n                this.target = e, this._this = t\n            }\n            eventWithOptions(e, t, i, r = this._this) {\n                let n = rn(this.target, e, t);\n                return this.target instanceof wc && (n = n.pipe(hr(([, e]) => e))), i && (r && (i = i.bind(r)), n = n.pipe(Za(i))), n\n            }\n            event(e, t, i = this._this) {\n                return this.eventWithOptions(e, void 0, t, i)\n            }\n            listen(e, t, i, r = this._this) {\n                return this.event(e, i, r).pipe(Va(t)).subscribe()\n            }\n        }\n\n        function Oc(e, t) {\n            return new Ac(e, t)\n        }\n\n        function kc(e, t, i) {\n            var r;\n            return {\n                currentTarget: null !== (r = null == i ? void 0 : i.currentTarget) && void 0 !== r ? r : e,\n                target: null !== (i = null == i ? void 0 : i.target) && void 0 !== i ? i : e,\n                type: t\n            }\n        }\n\n        function Cc(y, v) {\n            return new $t(e => {\n                const {\n                    maxTimeToFirstByteMs: t,\n                    maxLoadTimeMs: i\n                } = v, r = new XMLHttpRequest, n = {\n                    trequest: performance.now(),\n                    tfirst: NaN,\n                    tload: NaN,\n                    loaded: 0,\n                    total: NaN,\n                    complete: !1\n                }, s = Oc(r), a = s.event(\"progress\").pipe(Aa(), ao(300, Ti, {\n                    leading: !0,\n                    trailing: !0\n                }), hr(e => (isNaN(n.tfirst) && (n.tfirst = performance.now()), n.loaded = e.loaded, e.lengthComputable && (n.total = e.total), e.target)), ln(e => 3 <= e.readyState)), o = s.event(\"readystatechange\").pipe(Aa(), hr(e => e.target), ln(e => 2 <= e.readyState), Za(e => {\n                    isNaN(n.tfirst) && 3 <= e.readyState && (n.tfirst = performance.now())\n                }));\n                let l = Ii;\n                isFinite(t) && 0 < t && (l = an(a, o).pipe(Ds(1), So(0 < y.extendMaxTTFB ? y.extendMaxTTFB : t), La(() => Ii)));\n                let d = Ii;\n                isFinite(i) && 0 < i && (d = o.pipe(ln(e => 4 <= e.readyState), Ds(1), So(i), La(() => Ii)));\n                let u = Ii;\n                y.onProgress && (u = an($i(r), a).pipe(hr(e => {\n                    const {\n                        getData: t,\n                        cb: i\n                    } = y.onProgress;\n                    return i(y.url, e.status, n, t ? e.response : void 0)\n                }), Wa(e => !e, !0)).pipe($a(Ii)));\n                const c = an(a.pipe(La(() => Ii)), o, l, d, u).pipe(ln(e => 4 <= e.readyState), Ds(1), La(e => {\n                        if (n.complete = !0, 200 <= e.status && e.status < 300) {\n                            if (n.tload = performance.now(), n.contentType = e.getResponseHeader(\"Content-Type\"), v.reportCDNServer && (n.cdnServer = e.getResponseHeader(\"CDN-Server\")), n.contentLength = v.forceContentLenCheckIfNoHeader ? function(e) {\n                                    let t;\n                                    const i = e.getResponseHeader(\"Content-Encoding\"),\n                                        r = e.getResponseHeader(\"Transfer-Encoding\"),\n                                        n = !i || i && \"identity\" === i.toLowerCase(),\n                                        s = !r || r && \"identity\" === r.toLowerCase();\n                                    return n && s && (t = function(e) {\n                                        e = /([0-9]+)\\-([0-9]+)\\/([0-9]+)/.exec(e);\n                                        return e ? parseInt(e[2]) - parseInt(e[1]) + 1 : void 0\n                                    }(e.getResponseHeader(\"Content-Range\")), ne(t) || (t = parseInt(e.getResponseHeader(\"Content-Length\")))), t\n                                }(e) : null, i = e, (r = y).collectServerInstanceInfo && (r.serverInstanceInfo = {}, r.collectServerInstanceInfo.forEach(e => {\n                                    var t = i.getResponseHeader(e);\n                                    t && (r.serverInstanceInfo[e] = t)\n                                })), \"arraybuffer\" === y.responseType ? n.loaded = e.response.byteLength : n.loaded = e.responseText.length, n.total = n.loaded, y.checkContentLength && (0 === n.total || ne(n.contentLength) && n.total != n.contentLength)) throw new oc(\"Network error\", e.status);\n                            return Nr($i([e, n]), Ti)\n                        }\n                        var i, r;\n                        throw new oc(\"Network error\", e.status)\n                    }), Vn(e => {\n                        if (e instanceof dr) throw new pc(e.message, 0, n);\n                        if (!(e instanceof oc)) throw new oc(e.message, 0);\n                        throw e\n                    })).subscribe(e),\n                    {\n                        url: h,\n                        method: p,\n                        byteRangeOffset: f,\n                        responseType: m,\n                        body: g\n                    } = y;\n                y.mimeType && r.overrideMimeType(y.mimeType);\n                try {\n                    const v = y.xhrSetup;\n                    if (v) try {\n                        v(r, h)\n                    } catch (e) {\n                        r.open(p, y.url, !0), v(r, y.url)\n                    }\n                    r.readyState || r.open(p, y.url, !0)\n                } catch (e) {\n                    throw new oc(e.message, r.status)\n                }\n                if (r.responseType = m, f && ne(f.start) && ne(f.end) && 0 <= f.start && f.end > f.start) {\n                    const {\n                        start: y,\n                        end: v\n                    } = f;\n                    r.setRequestHeader(\"Range\", `bytes=${y}-${v-1}`)\n                }\n                if (y.headers)\n                    for (const [v, e] of Object.entries(y.headers)) r.setRequestHeader(v, e);\n                return \"POST\" === p && g ? r.send(g) : r.send(), () => {\n                    r.abort(), c.unsubscribe()\n                }\n            })\n        }\n        const Dc = {\n            name: \"CustomUrlLoader\"\n        };\n        class Mc {\n            constructor(e) {\n                this.loaderService = e, this.requestMap = {}, this.logger = Qe()\n            }\n            load(a, o) {\n                return new $t(e => {\n                    const t = a.url,\n                        i = o[\"maxTimeToFirstByteMs\"],\n                        r = {\n                            trequest: performance.now(),\n                            tfirst: NaN,\n                            tload: NaN,\n                            loaded: 0,\n                            total: NaN,\n                            complete: !1\n                        },\n                        n = (this.requestMap[t] = new er).pipe(So(0 < a.extendMaxTTFB ? a.extendMaxTTFB : i), La(e => (r.tfirst = performance.now(), this.handleExternalResponse(e, a, o, r))), Vn(e => {\n                            if (e instanceof dr) throw new pc(e.message, 0, r);\n                            throw e\n                        }), Vs(() => {\n                            this.requestMap[t] = void 0, this.loaderService.removeUnresolvedUriLoading(t)\n                        }));\n                    a.onProgress && a.onProgress.cb(t, 0, r, void 0);\n                    const s = n.subscribe(e);\n                    return this.loaderService.createUnresolvedUriLoading(t, a.responseType, navigator.userAgent), () => {\n                        s.unsubscribe(), this.requestMap[t] = void 0\n                    }\n                })\n            }\n            setCustomUrlResponse(e, t) {\n                const i = this.requestMap[e];\n                i && (i.next(t), i.complete(), this.requestMap[e] = void 0)\n            }\n            handleExternalResponse(e, t, i, r) {\n                r.tload = performance.now();\n                var n = e.response.status || 200;\n                return 200 <= n && n < 300 ? (\"arraybuffer\" === t.responseType && e.response.data instanceof ArrayBuffer ? r.loaded = e.response.data.byteLength : r.loaded = e.response.data.toString().length, r.total = r.loaded, r.complete = !0, Nr($i({\n                    status: n,\n                    data: e,\n                    stats: r\n                }), Ti)) : 300 === n || 302 === n || 303 === n || 305 === n ? this.redirectRequest(e.response.uri, t, i, r) : (this.logger.warn(Dc, `unable to load custom url > uri=${le(e.response.uri)}, status=${n}`), Vi(new oc(\"Unable to load custom url\", n)))\n            }\n            redirectRequest(e, t, i, n) {\n                var {\n                    maxLoadTimeMs: r,\n                    maxTimeToFirstByteMs: s\n                } = i, r = r - (performance.now() - n.trequest), s = 0 < t.extendMaxTTFB ? t.extendMaxTTFB : s - (performance.now() - n.trequest), i = Object.assign(Object.assign({}, i), {\n                    maxLoadTimeMs: r,\n                    maxTimeToFirstByteMs: s\n                }), e = Object.assign(Object.assign({}, t), {\n                    url: e\n                });\n                return r <= 0 || s <= 0 ? Vi(new dr) : Cc(e, i).pipe(hr(([e, t]) => {\n                    var {\n                        responseURL: i,\n                        status: r\n                    } = e, i = i || \"\", i = {\n                        uri: i,\n                        response: {\n                            status: r,\n                            uri: i,\n                            data: e.response\n                        }\n                    };\n                    return n.loaded = n.total = t.loaded, n.tload = performance.now(), n.complete = !0, {\n                        status: e.status,\n                        data: i,\n                        stats: n\n                    }\n                }))\n            }\n        }\n        let xc;\n\n        function Pc(e) {\n            return xc || (e = e || (Ic = Ic || new Tc(Ec), Ic), xc = new Mc(e)), xc\n        }\n\n        function Rc(e, t) {\n            const i = Object.assign(Object.assign({}, e), {\n                    method: \"GET\",\n                    responseType: \"arraybuffer\"\n                }),\n                r = Pc();\n            return Tu(i.url) ? r.load(i, t).pipe(hr(e => [e.data.response.data, e.stats, i.serverInstanceInfo])) : Cc(i, t).pipe(hr(([e, t]) => [e.response, t, i.serverInstanceInfo]))\n        }\n\n        function Lc(e, t) {\n            return !e.url || Tu(e.url) ? t.customURL : t.default\n        }\n\n        function _c(e, t) {\n            return e instanceof lc ? e.isTimeout ? t.timeoutRetry : t.errorRetry : null\n        }\n\n        function Nc(e) {\n            var t = e.type,\n                i = e.liveOrEvent;\n            let r = \"VOD\";\n            \"EVENT\" === t && i ? r = \"EVENT\" : t && 0 !== t.length && \"LIVE\" !== t || !i || (r = \"LIVE\"), e.type !== r && (e.type = r)\n        }\n        const Fc = {\n                id: \"playready\",\n                systemStringPrefix: \"com.microsoft.playready\",\n                keyFormatString: \"com.microsoft.playready\",\n                securityLevels: {\n                    SL2000: 0,\n                    SL3000: 1\n                }\n            },\n            Bc = {\n                id: \"widevine\",\n                systemStringPrefix: \"com.widevine.alpha\",\n                keyFormatString: \"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed\",\n                securityLevels: {\n                    WIDEVINE_SOFTWARE: 0,\n                    WIDEVINE_HARDWARE: 1\n                }\n            };\n\n        function Uc(e) {\n            return e.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=+$/, \"\")\n        }\n        class $c {\n            static strToBase64Encode(e) {\n                return btoa(e)\n            }\n            static base64DecodeToStr(e) {\n                return atob(e)\n            }\n            static base64Encode(e) {\n                return btoa(String.fromCharCode(...e))\n            }\n            static base64UrlEncode(e) {\n                return Uc($c.base64Encode(e))\n            }\n            static base64Decode(e) {\n                return Uint8Array.from(atob(e), e => e.charCodeAt(0))\n            }\n        }\n        class Vc {\n            static strToBase64Encode(e) {\n                return l.Buffer.from(e).toString(\"base64\")\n            }\n            static base64DecodeToStr(e) {\n                return l.Buffer.from(e, \"base64\").toString()\n            }\n            static base64Encode(e) {\n                return l.Buffer.from(e).toString(\"base64\")\n            }\n            static base64UrlEncode(e) {\n                return Uc(Vc.base64Encode(e))\n            }\n            static base64Decode(e) {\n                e = l.Buffer.from(e, \"base64\");\n                return new Uint8Array(e.buffer, e.byteOffset, e.byteLength)\n            }\n        }\n        var Kc, qc = void 0 !== l.Buffer ? Vc : $c;\n        const Hc = {\n                avc1: \"video/mp4\",\n                avc3: \"video/mp4\",\n                dvav: \"video/mp4\",\n                dva1: \"video/mp4\",\n                hev1: \"video/mp4\",\n                hvc1: \"video/mp4\",\n                dvh1: \"video/mp4\",\n                dvhe: \"video/mp4\"\n            },\n            jc = {\n                mp4a: \"audio/mp4\",\n                \"ac-3\": \"audio/mp4\",\n                \"ec-3\": \"audio/mp4\"\n            };\n\n        function Qc(e) {\n            const t = O.strToUtf8array(e).subarray(0, 16),\n                i = new Uint8Array(16);\n            return i.set(t, 16 - t.length), i\n        }\n        const Wc = {\n            getCapabilities: function(e, t) {\n                const i = {\n                    videoCapabilities: [],\n                    audioCapabilities: []\n                };\n                return e && e.forEach(e => {\n                    var t = e.split(\".\")[0].trim();\n                    t in Hc && i.videoCapabilities.push({\n                        contentType: Hc[t] + \";codecs=\" + e,\n                        robustness: \"\"\n                    })\n                }), t && t.forEach(e => {\n                    var t = e.split(\".\")[0].trim();\n                    t in jc && i.audioCapabilities.push({\n                        contentType: jc[t] + \";codecs=\" + e,\n                        robustness: \"\"\n                    })\n                }), i\n            },\n            changeEndianness: function(e) {\n                function t(e, t, i) {\n                    var r = e[t];\n                    e[t] = e[i], e[i] = r\n                }\n                t(e, 0, 3), t(e, 1, 2), t(e, 4, 5), t(e, 6, 7)\n            },\n            getKeyIdBytes: Qc,\n            convertDataUriToArrayBytes: function(e) {\n                const t = e.split(\":\");\n                let i = null;\n                if (\"data\" === t[0] && 2 === t.length) {\n                    const e = t[1].split(\";\"),\n                        r = e[e.length - 1].split(\",\");\n                    if (2 === r.length) {\n                        const t = \"base64\" === r[0],\n                            n = r[1];\n                        i = t ? (e.splice(-1, 1), qc.base64Decode(n)) : Qc(n)\n                    }\n                }\n                return i\n            },\n            makeKeyIdsInitData: function(e) {\n                e = {\n                    kids: e.map(qc.base64UrlEncode)\n                };\n                return O.strToUtf8array(JSON.stringify(e))\n            },\n            parsePSSHList: function(e) {\n                const i = new DataView(e);\n                let r = 0;\n                const n = {};\n                for (; r < i.buffer.byteLength;) {\n                    const e = r,\n                        t = i.getUint32(r);\n                    r += 4;\n                    var s = e + t;\n                    if (1886614376 === i.getUint32(r)) {\n                        switch (r += 4, i.getUint8(r)) {\n                            case 0:\n                            case 1:\n                                r += 1;\n                                break;\n                            default:\n                                r = s\n                        }\n                        r += 3;\n                        let t = \"\";\n                        for (let e = 0; e < 16; ++e, ++r) switch (t += i.getUint8(r).toString(16), e) {\n                            case 4:\n                            case 6:\n                            case 8:\n                            case 10:\n                                t += \"-\"\n                        }\n                        r += 4, n[t] = i.buffer.slice(e, s)\n                    } else r = s\n                }\n                return n\n            }\n        };\n        let Gc = {};\n        class zc {\n            constructor(e, t, i, r, n) {\n                if (this.method = e, this.uri = t, this.iv = i, this.format = r, this.formatversions = n, this.isEncrypted = this.method && \"NONE\" !== this.method, this.formatversions && 0 !== this.formatversions.length || (this.formatversions = [1]), this.key = void 0, this.keyId = void 0, this.isEncrypted) {\n                    const a = Wc.convertDataUriToArrayBytes(this.uri);\n                    if (a) switch (r) {\n                        case Fc.keyFormatString: {\n                            this.pssh = a;\n                            const e = new Uint16Array(a.buffer, a.byteOffset, a.byteLength / 2),\n                                t = String.fromCharCode.apply(null, Array.from(e)),\n                                i = t.substring(t.indexOf(\"<\"), t.length),\n                                r = (new DOMParser).parseFromString(i, \"text/xml\").getElementsByTagName(\"KID\")[0];\n                            if (r) {\n                                var s = null;\n                                if (s = r.childNodes[0] ? r.childNodes[0].nodeValue : r.getAttribute(\"VALUE\")) {\n                                    const t = qc.base64Decode(s).subarray(0, 16);\n                                    Wc.changeEndianness(t), this.keyId = t\n                                }\n                            }\n                            break\n                        }\n                        case Bc.keyFormatString:\n                            this.pssh = a, 22 <= a.length && (this.keyId = a.subarray(a.length - 22, a.length - 6));\n                            break;\n                        default: {\n                            let e = a.subarray(0, 16);\n                            if (16 !== e.length) {\n                                const t = new Uint8Array(16);\n                                t.set(e, 16 - e.length), e = t\n                            }\n                            this.keyId = e;\n                            break\n                        }\n                    }\n                    if (!this.keyId || 16 !== this.keyId.byteLength) {\n                        let e = Gc[this.uri];\n                        if (!e) {\n                            const t = Object.keys(Gc).length % Number.MAX_SAFE_INTEGER;\n                            e = new Uint8Array(16), new DataView(e.buffer, 12, 4).setUint32(0, t), Gc[this.uri] = e\n                        }\n                        this.keyId = e\n                    }\n                }\n            }\n            get keyTagInfo() {\n                var {\n                    method: e,\n                    isEncrypted: t,\n                    uri: i,\n                    iv: r,\n                    keyId: n,\n                    key: s,\n                    format: a,\n                    formatversions: o\n                } = this;\n                return {\n                    method: e,\n                    isEncrypted: t,\n                    uri: i,\n                    iv: r,\n                    keyId: n,\n                    key: s,\n                    format: a,\n                    formatversions: o\n                }\n            }\n            static clearKeyUriToKeyIdMap() {\n                Gc = {}\n            }\n        }(w = Kc = Kc || {}).NONE = \"NONE\", w.GET_REQUEST_INFO = \"GET_REQUEST_INFO\", w.GET_CHALLENGE = \"GET_CHALLENGE\", w.GET_KEY_RESPONSE = \"GET_KEY_RESPONSE\", w.PROCESS_LICENSE = \"PROCESS_LICENSE\";\n        class Xc {\n            constructor(e, t, i, r) {\n                this.session = e, this.onkeystatuseschange = t, this.onkeymessage = i, this.logger = r, this.isClosing$ = new yi(!1), this.closed$ = new yi(!1);\n                const n = Oc(this.session);\n                n.listen(\"keystatuseschange\", this.isClosing$.pipe(ln(e => !0 === e)), this.onkeystatuseschange), n.listen(\"message\", this.closed$.pipe(ln(e => !0 === e)), this.onkeymessage)\n            }\n            get isClosing() {\n                return this.isClosing$.value\n            }\n            get isClosed() {\n                return this.closed$.value\n            }\n            destroy() {\n                this.isClosing$.next(!0);\n                const e = this.session;\n                return Fr(e.remove().catch(e => {}).then(() => e.close()).catch(e => {})).pipe(Za(() => {\n                    this.isClosing$.next(!1), this.closed$.next(!0)\n                }), Vs(() => {\n                    this.isClosing$.next(!1), this.closed$.next(!0)\n                }))\n            }\n        }\n        class Yc {\n            constructor(e, t = null) {\n                this.decryptdata = e, this._requestState$ = new yi(Kc.NONE), this.destroy$ = new Xt, this.currentObservable = null, this.session = null, this.oldSessions = [], this.session = t\n            }\n            get requestState() {\n                return this._requestState$.value\n            }\n            get onKeyRequestState$() {\n                return this._requestState$\n            }\n            destroy() {\n                this.destroy$.next()\n            }\n            abort() {\n                var e;\n                this.requestState !== Kc.NONE && (e = new gc(\"Aborted\", this.decryptdata.uri, 0, $.KeySystemAbort, !0, rc.Abort), this.error(e))\n            }\n            setKeyRequestState(e) {\n                if (this.currentObservable) {\n                    const t = new gc(`Unexpected state transition ${this.requestState}->${e}`, this.decryptdata.uri, 0, $.KeySystemUnexpectedStateTransition, !0, rc.InvalidState);\n                    this.error(t)\n                }\n                this._requestState$.next(e);\n                const t = new er;\n                return e === Kc.NONE ? (t.complete(), this.currentObservable = null) : this.currentObservable = t, t\n            }\n            resolveState(e, t) {\n                if (this.currentObservable)\n                    if (e === this.requestState)\n                        if (t instanceof Error) this.error(t);\n                        else {\n                            const e = this.currentObservable;\n                            this.currentObservable = null, e.next(t), e.complete()\n                        }\n                else {\n                    const t = new gc(`Unexpected state ${this.requestState} != ${e}`, this.decryptdata.uri, 0, $.KeySystemUnexpectedState, !0, rc.InvalidState);\n                    this.error(t)\n                }\n            }\n            error(e) {\n                if (this.currentObservable) {\n                    const t = this.currentObservable;\n                    this.currentObservable = null, t.error(e)\n                }\n                this.setKeyRequestState(Kc.NONE)\n            }\n        }\n\n        function Jc(e) {\n            return `uri=${le(e.uri)} keyId=${je(e.keyId)}`\n        }\n        class Zc {\n            constructor(e, t, i, r, n, s, a) {\n                this.mediaKeys = e, this.systemString = t, this.config = i, this.eventEmitter = r, this.useSingleKeySession = n, this.sessionHandler = s, this.logger = a, this.destroy$ = new Xt, this.setCert = !1, this.certificate$ = new yi(null), this._keyStatusChange$ = new Xt, this.shouldDestroyMediaKeys = !1, this.itemId = \"\", this.sessions = [], this.keyIdToKeyInfo = {}, this.keyUriToKeyInfo = {}, this.sessionIdToKeyUri = {}, this.onkeystatuseschange = this.handleKeyStatusesChange.bind(this), this.onkeymessage = this.handleKeyMessage.bind(this)\n            }\n            get keyStatusChange$() {\n                return this._keyStatusChange$\n            }\n            destroy() {\n                this.isDestroying = !0, this.destroy$.next();\n                for (const e of Object.values(this.keyIdToKeyInfo)) this._abortKeyRequest(e);\n                const e = this.sessions.map(e => e.destroy()),\n                    t = nn(() => 0 === e.length, Wu, en(e)).pipe(Zs(void 0), Vs(() => {\n                        this.mediaKeys = void 0, this.keyIdToKeyInfo = {}, this.keyUriToKeyInfo = {}, this.sessionIdToKeyUri = {}\n                    }));\n                return zc.clearKeyUriToKeyIdMap(), t\n            }\n            setServerCertificate(e = null) {\n                return this.needsCert ? (e && this.certificate$.next(e), Gu(this.certificate$, e => null != e).pipe(So(1e4)).pipe(La(e => this.setCert ? $i(!0) : !this.setCertSubject || this.setCertSubject.isStopped ? (this.setCertSubject = new er, Fr(this.mediaKeys.setServerCertificate(e)).pipe(Za(e => {\n                    e = void 0 === e || e;\n                    this.setCert = e, this.setCertSubject.next(e), this.setCertSubject.complete()\n                }), Vn(e => (this.setCert = !1, this.setCertSubject.error(e), Wu)), La(() => this.setCertSubject))) : this.setCertSubject), Vn(e => {\n                    throw e\n                }))) : $i(!0)\n            }\n            ensureKeyContext(e) {\n                var t = e.uri;\n                this.keyUriToKeyInfo[t] || (this.keyUriToKeyInfo[t] = new Yc(e));\n                const i = this.keyUriToKeyInfo[t];\n                if (i.session) return i;\n                if (this.useSingleKeySession && 0 < this.sessions.length) return i.session = this.sessions[0].session, i;\n                t = this.mediaKeys.createSession();\n                return t && this.sessions.push(new Xc(t, this.onkeystatuseschange, this.onkeymessage, this.logger)), i.session = t, i\n            }\n            startKeyRequest(t) {\n                const i = t.uri,\n                    r = this.ensureKeyContext(t);\n                if (null == r || !r.session) return Vi(new yc(\"Could not create key session\", t.uri, 0, $.KeySystemFailedToCreateSession, this.systemString));\n                var e = O.utf8arrayToStr(t.keyId);\n                return this.keyIdToKeyInfo[e] = r, en([this.getKeyRequestInfo(r), this.setServerCertificate()]).pipe(hr(e => e[0]), La(e => {\n                    var t;\n                    return null === (t = this.sessionHandler) || void 0 === t || t.licenseChallengeSubmitted({\n                        keyuri: i,\n                        keyFormat: this.systemString\n                    }), this.generateLicenseChallenge(r, e).pipe(Vn(e => {\n                        var t;\n                        throw null === (t = this.sessionHandler) || void 0 === t || t.licenseChallengeError({\n                            keyuri: i\n                        }), e\n                    }))\n                }), La(e => {\n                    var t;\n                    return null === (t = this.sessionHandler) || void 0 === t || t.licenseChallengeCreated({\n                        keyuri: i,\n                        cdmVersion: this.cdmVersion\n                    }), this.getKeyRequestResponse(r, e)\n                }), La(e => {\n                    var t;\n                    return null === (t = this.sessionHandler) || void 0 === t || t.licenseResponseSubmitted({\n                        keyuri: i\n                    }), this.handleParsedKeyResponse(r, e).pipe(Vn(e => {\n                        var t;\n                        throw null === (t = this.sessionHandler) || void 0 === t || t.licenseResponseError({\n                            keyuri: i\n                        }), e\n                    }))\n                }), hr(() => {\n                    var e;\n                    return null === (e = this.sessionHandler) || void 0 === e || e.licenseResponseProcessed({\n                        keyuri: i\n                    }), r.setKeyRequestState(Kc.NONE), this.removeSessions(r.decryptdata, !1).subscribe(), t\n                }), Vn(e => {\n                    throw this.handleKeyExchangeError(r, e), e\n                }), Vs(() => {\n                    this._abortKeyRequest(r)\n                }))\n            }\n            _abortKeyRequest(e) {\n                var t, i;\n                e && (i = e.decryptdata.uri, O.utf8arrayToStr(e.decryptdata.keyId), e.requestState !== Kc.NONE && (null === (t = this.sessionHandler) || void 0 === t || t.keyAborted({\n                    keyuri: i\n                })), e.abort())\n            }\n            handleKeyExchangeError(e, t) {\n                e.error(t), O.utf8arrayToStr(e.decryptdata.keyId)\n            }\n            updateItemId(e) {\n                this.itemId = e\n            }\n            removeKey(e) {\n                return this.removeKeyInternal(e)\n            }\n            removeKeyInternal(e) {\n                const t = this.keyUriToKeyInfo[e.uri];\n                if (t && t.session) {\n                    var i = t.session;\n                    t.abort(), t.destroy();\n                    var r = O.utf8arrayToStr(e.keyId);\n                    return this.keyIdToKeyInfo[r] = void 0, this.keyUriToKeyInfo[e.uri] = void 0, this.removeSession(i)\n                }\n            }\n            removeSessions(e, t) {\n                const i = this.keyUriToKeyInfo[e.uri];\n                if (i) {\n                    const r = i.oldSessions.map(e => this.removeSession(e));\n                    return i.oldSessions = [], nn(() => 0 === r.length, Wu, en(r)).pipe(La(() => t ? this.removeKeyInternal(e) : Wu))\n                }\n                return Wu\n            }\n            removeSession(t) {\n                const e = this.sessions.findIndex(e => e.session === t),\n                    i = this.sessions[e];\n                return -1 < e && this.sessions.splice(e, 1), this.sessionIdToKeyUri[t.sessionId] = void 0, i ? i.destroy() : Wu\n            }\n            getKeyRequestInfo(e) {\n                var t = e.decryptdata,\n                    i = t.uri,\n                    e = e.setKeyRequestState(Kc.GET_REQUEST_INFO);\n                return this.eventEmitter.trigger(x.KEY_REQUEST_STARTED, {\n                    keyuri: i,\n                    decryptdata: t,\n                    timestamp: Date.now()\n                }), e\n            }\n            setKeyRequestInfo(e, t) {\n                const i = this.keyUriToKeyInfo[e];\n                i && i.resolveState(Kc.GET_REQUEST_INFO, t)\n            }\n            sanitizeRequest(e) {\n                return e\n            }\n            generateLicenseChallengeInternal(t, e, i) {\n                const r = t.decryptdata,\n                    n = t.session,\n                    s = r.uri,\n                    a = r.keyId;\n                let o;\n                var l = t.setKeyRequestState(Kc.GET_CHALLENGE);\n                if (n.generateRequestPromise) o = Nr(n.generateRequestPromise, Ti).pipe(La(() => this.generateRequestInitialized(t, \"usable\" === i)));\n                else {\n                    const i = this.generateInitData(a, r, e);\n                    n.generateRequestPromise = n.generateRequest(i.initDataType, i.initData), o = Nr(n.generateRequestPromise, Ti).pipe(Za(() => {\n                        this.sessionIdToKeyUri[n.sessionId] = s\n                    }), Vn(e => {\n                        throw new yc(e.message, t.decryptdata.uri, 0, $.KeySystemFailedToGenerateLicenseRequest, this.systemString)\n                    }))\n                }\n                return en([l, o]).pipe(hr(e => new Uint8Array(e[0])))\n            }\n            generateLicenseChallenge(e, t) {\n                const i = e.decryptdata,\n                    r = e.session,\n                    n = i.uri,\n                    s = i.keyId;\n                let a, o;\n                if (O.utf8arrayToStr(i.keyId), e.licenseChallenge && e.resolveState(Kc.GET_CHALLENGE, e.licenseChallenge), t = this.sanitizeRequest(t), e.requestInfo = t, this.sessionId = this.sessionId || t && t.sessionId || this.itemId, this.systemString === Fc.systemStringPrefix) {\n                    const e = new Uint8Array(s);\n                    Wc.changeEndianness(e), a = r.keyStatuses.get(e)\n                } else a = r.keyStatuses.get(s);\n                switch (a) {\n                    case \"status-pending\":\n                    case \"usable\":\n                    case \"expired\":\n                    case void 0:\n                        o = this.generateLicenseChallengeInternal(e, t, a);\n                        break;\n                    default:\n                        o = Vi(new yc(`Bad internal state state=${a}`, n, 0, $.KeySystemUnexpectedState, this.systemString))\n                }\n                return o\n            }\n            setParsedResponse(e, t) {\n                const i = this.keyUriToKeyInfo[e];\n                i && i.resolveState(Kc.GET_KEY_RESPONSE, t)\n            }\n            handleKeyStatusesChange(e) {\n                e.target.keyStatuses.forEach((e, t, i) => {\n                    t = new Uint8Array(t);\n                    this.systemString === Fc.systemStringPrefix && Wc.changeEndianness(t);\n                    t = O.utf8arrayToStr(t), t = this.keyIdToKeyInfo[t];\n                    t && this.handleKeyStatusForKey(e, t)\n                })\n            }\n            handleKeyStatusForKey(e, t) {\n                if (t) {\n                    var i = t.decryptdata,\n                        r = i.uri;\n                    switch (e) {\n                        case \"internal-error\":\n                            this.logger.error(`${this.systemString} internal-error for key ${Jc(i)}`), this._signalError(t, new gc(\"Got internal error from key system\", r, 0, $.KeySystemInternalError, !1, rc.InternalError));\n                            break;\n                        case \"usable\":\n                            t.requestState === Kc.PROCESS_LICENSE && t.resolveState(Kc.PROCESS_LICENSE, void 0);\n                            break;\n                        case \"output-restricted\":\n                            this.logger.warn(`${this.systemString} output-restricted for key ${Jc(i)}`), t.session && this.removeSession(t.session).pipe(Va(this.destroy$)).subscribe(), this._signalError(t, new gc(\"output-restricted\", r, 0, $.KeySystemOutputRestricted, !1, rc.OutputRestricted));\n                            break;\n                        case \"expired\":\n                            this.logger.warn(`${this.systemString} expired for key ${Jc(i)}. Attempting renewal`), this._signalRenewal(t)\n                    }\n                }\n            }\n            _scheduleRenewal(e, t) {\n                bn(t).pipe(Za(() => this._signalRenewal(e)), Va(fn(e.destroy$, this.destroy$, Gu(e.onKeyRequestState$, e => e === Kc.GET_REQUEST_INFO)))).subscribe()\n            }\n            _signalRenewal(e) {\n                this._keyStatusChange$.next({\n                    decryptdata: e.decryptdata,\n                    status: \"needs-renewal\"\n                })\n            }\n            _signalError(e, t) {\n                this._keyStatusChange$.next({\n                    decryptdata: e.decryptdata,\n                    status: \"error\",\n                    error: t\n                }), e.error(t)\n            }\n        }\n        const eh = \"org.w3.clearkey\",\n            th = {\n                id: \"clearkey\",\n                systemStringPrefix: eh,\n                keyFormatString: eh,\n                securityLevels: {\n                    NONE: 0\n                }\n            },\n            ih = [\"clearkey\", \"fairplaystreaming\", \"playready\", \"widevine\"],\n            rh = {\n                initDataTypes: [\"keyids\", \"cenc\"]\n            };\n        var nh, nu = class extends Zc {\n            constructor(e, t, i, r, n, s) {\n                super(e, t, i, r, !1, n, s)\n            }\n            static get requestAccessConfig() {\n                return rh\n            }\n            get needsCert() {\n                return !1\n            }\n            getKeyRequestResponse(e, t) {\n                return Rc({\n                    url: e.decryptdata.uri,\n                    xhrSetup: this.config.xhrSetup\n                }, {\n                    maxLoadTimeMs: 0,\n                    maxTimeToFirstByteMs: 0,\n                    autoRetry: !1,\n                    timeoutRetry: null,\n                    errorRetry: null\n                }).pipe(hr(([e]) => {\n                    e = new Uint8Array(e);\n                    return {\n                        response: this.parseResponse(t, e)\n                    }\n                }))\n            }\n            parseResponse(e, t) {\n                t = {\n                    kty: \"oct\",\n                    kid: qc.base64UrlEncode(e),\n                    k: qc.base64UrlEncode(t)\n                };\n                return O.strToUtf8array(JSON.stringify({\n                    keys: [t]\n                }))\n            }\n            handleParsedKeyResponse(i, e) {\n                e = e.response;\n                return en([i.setKeyRequestState(Kc.PROCESS_LICENSE), Fr(i.session.update(e)).pipe(Za(() => {\n                    var e = i.decryptdata.keyId,\n                        e = i.session.keyStatuses.get(e);\n                    this.handleKeyStatusForKey(e, i)\n                }), Vn(e => {\n                    var t = {\n                        code: e.code,\n                        text: \"Failed to update with key response\"\n                    };\n                    throw new yc(e.message, i.decryptdata.uri, e.code, t, this.systemString)\n                }))]).pipe(Zs(void 0))\n            }\n            generateInitData(e) {\n                return {\n                    initData: Wc.makeKeyIdsInitData([e]),\n                    initDataType: \"keyids\"\n                }\n            }\n            generateRequestInitialized() {\n                return Wu\n            }\n            sanitizeRequest(e) {\n                return e\n            }\n            handleKeyMessage(e) {\n                if (!this.isDestroying && \"license-request\" === e.messageType) {\n                    e = new Uint8Array(e.message), e = JSON.parse(O.utf8arrayToStr(e).trim());\n                    if (1 === e.kids.length) {\n                        const t = qc.base64Decode(e.kids[0]),\n                            i = O.utf8arrayToStr(t),\n                            r = this.keyIdToKeyInfo[i];\n                        r && r.resolveState(Kc.GET_CHALLENGE, t)\n                    }\n                }\n            }\n        };\n        const sh = {\n                initDataTypes: [\"cenc\"]\n            },\n            ah = new Uint8Array([148, 206, 134, 251, 7, 255, 79, 67, 173, 184, 147, 210, 250, 150, 140, 162]);\n        (iu = nh = nh || {})[iu.CENC = 1667591779] = \"CENC\", iu[iu.CBCS = 1667392371] = \"CBCS\";\n        class oh extends Zc {\n            constructor(e, t, i, r, n, s, a) {\n                super(e, t, i, r, n, s, a), this._hasSetRenewal = !1\n            }\n            static get systemId() {\n                return ah\n            }\n            static get requestAccessConfig() {\n                return sh\n            }\n            get needsCert() {\n                return !0\n            }\n            sanitizeRequest(e) {\n                return {\n                    assetId: e && e.assetId ? new Uint8Array(e.assetId) : void 0,\n                    ssc: e && e.ssc ? new Uint8Array(e.ssc) : void 0,\n                    sessionId: e && e.sessionId ? e.sessionId : void 0\n                }\n            }\n            _scheduleRenewal(e, t) {\n                this.useSingleKeySession ? this._hasSetRenewal || (this._hasSetRenewal = !0, bn(t).pipe(Za(() => {\n                    var e = Object.values(this.keyUriToKeyInfo)[0];\n                    e && this._signalRenewal(e)\n                }), Vs(() => {\n                    this._hasSetRenewal = !1\n                }), Va(this.destroy$)).subscribe()) : super._scheduleRenewal(e, t)\n            }\n            handleParsedKeyResponse(t, e) {\n                var i = t.decryptdata.uri,\n                    r = e.statusCode,\n                    n = e.ckc && 0 !== e.ckc.byteLength ? e.ckc : e.license && 0 !== e.license.byteLength ? e.license : void 0;\n                if (0 === r && !n) return Vi(new gc(\"License request resulted in HTTP Error\", i, r, {\n                    code: r,\n                    text: \"HTTP Error\"\n                }, !0, rc.HttpError));\n                if (0 !== r) return Vi(new gc(\"License server responded with error\", i, r, {\n                    code: r,\n                    text: \"Server Error\"\n                }, !1, rc.LicenseServerError));\n                if (!n) return Vi(new gc(\"License server responded with invalid license\", i, r, {\n                    code: r,\n                    text: \"Invalid license\"\n                }, !1, rc.LicenseServerError));\n                const s = e.renewalDate,\n                    a = new Date,\n                    o = s > a ? s.getTime() - a.getTime() : 0;\n                0 < o && this._scheduleRenewal(t, o);\n                const l = this.makeProcessLicenseRequestMessage(t, n, o),\n                    d = t.session,\n                    u = Fr(d.update(l)).pipe(Za(() => {\n                        var e = t.decryptdata.keyId,\n                            e = d.keyStatuses.get(e);\n                        this.handleKeyStatusForKey(e, t)\n                    }), Vn(e => {\n                        throw new yc(e.message, t.decryptdata.uri, 0, $.KeySystemFailedToUpdateSession, this.systemString)\n                    }));\n                return en([t.setKeyRequestState(Kc.PROCESS_LICENSE), u]).pipe(Zs(void 0))\n            }\n            makeKeyRequests(e) {\n                const t = [];\n                for (const i of e) {\n                    const e = i.decryptdata,\n                        r = i.requestInfo,\n                        n = e.keyId;\n                    t.push({\n                        keyId: n,\n                        assetId: r ? r.assetId : void 0,\n                        ssc: r ? r.ssc : void 0,\n                        versionList: e.formatversions\n                    })\n                }\n                return t\n            }\n            getSchemeAndFlags(e) {\n                return {\n                    scheme: \"ISO-23001-7\" === e.method ? nh.CENC : nh.CBCS,\n                    flags: 0\n                }\n            }\n            generateInitData(e, t, i) {\n                var {\n                    scheme: r,\n                    flags: n\n                } = this.getSchemeAndFlags(t), i = this.makeKeyRequests([{\n                    decryptdata: t,\n                    requestInfo: i\n                }]);\n                return {\n                    initData: this.makeFpsKeySystemInitData(r, n, i),\n                    initDataType: \"cenc\"\n                }\n            }\n            generateRequestInitialized(t, e) {\n                tc(`[Keys] challenge create start uri=${le(t.decryptdata.uri)} versions=${JSON.stringify(t.decryptdata.formatversions)}`);\n                e = this.makeKeyRequestMessage(t, e);\n                return e ? Fr(t.session.update(e)).pipe(Za(() => {\n                    t.requestInfo = void 0\n                }), Vn(e => {\n                    throw tc(`[Keys] ${this.systemString} FAIL: generateRequestInitialized keyuri=${le(t.decryptdata.uri)} message=${e.message}`), new yc(e.message, t.decryptdata.uri, 0, $.KeySystemFailedToGenerateLicenseRenewal, this.systemString)\n                })) : Vi(new gc(\"Unable to generate request using existing keySession\", t.decryptdata.uri, 0, $.KeySystemFailedToGenerateLicenseRequest, !0, rc.InvalidState))\n            }\n            getKeyRequestResponse(e, t) {\n                var i = e.decryptdata.uri,\n                    e = e.setKeyRequestState(Kc.GET_KEY_RESPONSE);\n                return this.eventEmitter.trigger(x.LICENSE_CHALLENGE_CREATED, {\n                    keyuri: i,\n                    licenseChallenge: t,\n                    keysystem: this.systemString\n                }), e\n            }\n            resolveSPCPromise(e, t) {\n                e.resolveState(Kc.GET_CHALLENGE, t)\n            }\n        }\n        const lh = {},\n            dh = 1919710053;\n\n        function uh(e, t, i) {\n            if (!(i + 4 > e.byteLength)) {\n                t = t.getUint32(i);\n                if (!((i += 4) + t > e.byteLength)) {\n                    e = e.slice(i, i + t);\n                    return {\n                        pos: i += t,\n                        data: e\n                    }\n                }\n            }\n        }\n\n        function ch(t) {\n            const i = {},\n                r = new DataView(t.buffer);\n            let n = 4;\n            const s = r.getUint32(n);\n            n += 4;\n            for (let e = 0; e < s && n < t.byteLength && !(n + 16 > t.byteLength); ++e) {\n                const s = t.slice(n, n + 16);\n                if (n += 16, n + 4 > t.byteLength) break;\n                var a = uh(t, r, n);\n                if (!a) break;\n                n = a.pos, i[O.utf8arrayToStr(s)] = a.data\n            }\n            return i\n        }\n\n        function hh(e, t, i, r) {\n            var n = r ? r.byteLength : 0;\n            return t.setUint32(i, n), n && e.set(r, i + 4), i + (4 + n)\n        }\n\n        function ph(e) {\n            let t = 4;\n            for (const i of e) t += 28 + (i.assetId ? i.assetId.byteLength : 0) + (i.ssc ? i.ssc.byteLength : 0) + (i.versionList ? 4 * i.versionList.length : 0);\n            return t\n        }\n\n        function fh(e, t, i, r) {\n            t.setUint32(i, r.length), i += 4;\n            for (const n of r)\n                if (e.set(n.keyId, i), i = hh(e, t, i += 16, n.assetId), i = hh(e, t, i, n.ssc), t.setUint32(i, n.versionList ? n.versionList.length : 0), i += 4, n.versionList)\n                    for (const e of n.versionList) t.setUint32(i, e), i += 4;\n            return i\n        }\n        class mh extends oh {\n            constructor(e, t, i, r, n, s) {\n                super(e, t, i, r, void 0 === i.useMultipleKeySessions || !i.useMultipleKeySessions, n, s)\n            }\n            makeProcessLicenseRequestMessage(e, t, i) {\n                t = new Uint8Array(t);\n                return function(e) {\n                    let t = 0;\n                    for (const i of e) t += 24 + i.ckc.byteLength;\n                    let i = 0;\n                    const r = new Uint8Array(8 + t),\n                        n = new DataView(r.buffer);\n                    n.setUint32(0, 1667982195), n.setUint32(4, e.length), i += 8;\n                    for (const t of e) r.set(t.keyId, i), i += 16, n.setUint32(i, t.expirySec), i += 4, i = hh(r, n, i, t.ckc);\n                    return r\n                }([{\n                    keyId: e.decryptdata.keyId,\n                    expirySec: i / 1e3,\n                    ckc: t\n                }])\n            }\n            makeFpsKeySystemInitData(e, t, i) {\n                i = function(e, t, i) {\n                    var r = ph(i);\n                    const n = new Uint8Array(8 + r),\n                        s = new DataView(n.buffer);\n                    return s.setUint32(0, e), s.setUint32(4, 1 << 24 | 16777215 & t), fh(n, s, 8, i), n\n                }(e, t, i);\n                return ge.pssh(mh.systemId, [], i)\n            }\n            makeKeyRequestMessage(e) {\n                return function(e) {\n                    var t = ph(e);\n                    const i = new Uint8Array(4 + t),\n                        r = new DataView(i.buffer);\n                    return r.setUint32(0, 1668442994), fh(i, r, 4, e), i\n                }([{\n                    keyId: e.decryptdata.keyId,\n                    assetId: e.requestInfo ? e.requestInfo.assetId : void 0,\n                    ssc: e.requestInfo ? e.requestInfo.ssc : void 0,\n                    versionList: e.decryptdata.formatversions\n                }])\n            }\n            handleKeyMessage(e) {\n                if (e.message.byteLength < 4) this.logger.warn(\"Unexpected message\");\n                else {\n                    const t = new Uint8Array(e.message),\n                        i = new DataView(e.message),\n                        r = i.getUint32(0);\n                    if (this.isDestroying && r !== dh) this.logger.warn(`In the middle of destroying, ignore command: ${r.toString(16)}`);\n                    else switch (r) {\n                        case 1667592820:\n                            this.logger.warn(\"Certificate not set!\");\n                            break;\n                        case 1919837559: {\n                            const e = ch(t);\n                            for (const t in e)\n                                if (Object.prototype.hasOwnProperty.call(e, t)) {\n                                    const e = this.keyIdToKeyInfo[t];\n                                    e && this._signalRenewal(e)\n                                } break\n                        }\n                        case 1936745331: {\n                            const e = ch(t);\n                            for (const t in e)\n                                if (Object.prototype.hasOwnProperty.call(e, t)) {\n                                    const i = this.keyIdToKeyInfo[t],\n                                        r = e[t];\n                                    i && r && this.resolveSPCPromise(i, r)\n                                } break\n                        }\n                        case dh:\n                            this._handleLicenseRelease(t);\n                            break;\n                        case 1667525993: {\n                            const e = uh(t, i, 4);\n                            e && (this.cdmVersion = O.utf8arrayToStr(e.data));\n                            break\n                        }\n                        default:\n                            this.logger.warn(`Unrecognized command:'0x${r.toString(16)}'`)\n                    }\n                }\n            }\n            _handleLicenseRelease(e) {\n                const t = {},\n                    i = new DataView(e.buffer);\n                switch (i.getUint32(4)) {\n                    case 1936946288:\n                        lh, 0, t[lh.SessionId] = this.sessionId;\n                        var r;\n                        if (e.byteLength < 12) break;\n                        t[lh.APIProvider] = i.getUint32(8) === nh.CENC ? \"EC396D13-FB13-4993-9D0D-71518ACF3D6F\" : \"F19BF03B-7470-41A4-9655-86D078307D59\", 0;\n                        var n = uh(e, i, 12);\n                        if (!n) break;\n                        if (r = n.pos, t[lh.MovieID] = O.utf8arrayToStr(n.data), !(n = uh(e, i, r))) break;\n                        if (r = n.pos, t[lh.SecureStopSPC] = n.data, !(n = uh(e, i, r))) break;\n                        n.pos, t[lh.SessionLifespanSPC] = n.data\n                }\n                this.eventEmitter.trigger(x.LICENSE_RELEASED, {\n                    keysystem: this.systemString,\n                    itemId: this.itemId,\n                    releaseRecord: t\n                })\n            }\n        }\n        ru = mh;\n        const gh = {\n            fpsd: O.strToUtf8array(\"fpsd\"),\n            fpsi: O.strToUtf8array(\"fpsi\"),\n            fpsk: O.strToUtf8array(\"fpsk\"),\n            fkri: O.strToUtf8array(\"fkri\"),\n            fkai: O.strToUtf8array(\"fkai\"),\n            fkcx: O.strToUtf8array(\"fkcx\"),\n            fkvl: O.strToUtf8array(\"fkvl\")\n        };\n        t = class extends oh {\n            constructor(e, t, i, r, n, s) {\n                super(e, t, i, r, !1, n, s), this.sessions = [], this.keyIdToKeyInfo = {}, this.keyUriToKeyInfo = {}, this.sessionIdToKeyUri = {}\n            }\n            static get needsCert() {\n                return !0\n            }\n            handleKeyExchangeError(e, t) {\n                this.removeKey(e.decryptdata).subscribe(), super.handleKeyExchangeError(e, t)\n            }\n            _abortKeyRequest(e) {\n                return !this.isDestroying && e && e.requestState !== Kc.NONE && this.removeKey(e.decryptdata).subscribe(), super._abortKeyRequest(e)\n            }\n            makeFpsKeySystemInitData(e, t, i) {\n                const r = [gh.fpsd, (n = e, e = t, t = new Uint8Array(4), ge.set32(n, t, 0), ge.box(gh.fpsi, new Uint8Array([0, e >> 16 & 255, e >> 8 & 255, 255 & e]), t))];\n                var n;\n                for (const s of i) r.push(function(t, e, i, r) {\n                    const n = [gh.fpsk],\n                        s = ge.box(gh.fkri, new Uint8Array([0, 0, 0, 0]), t);\n                    if (n.push(s), e && e.byteLength && n.push(ge.box(gh.fkai, e)), i && i.byteLength && n.push(ge.box(gh.fkcx, i)), r && r.length) {\n                        const t = new Uint8Array(4 * r.length);\n                        let e = 0;\n                        for (const i of r) ge.set32(i, t, e), e += 4;\n                        n.push(ge.box(gh.fkvl, t))\n                    }\n                    return ge.box.apply(null, n)\n                }(s.keyId, s.assetId, s.ssc, s.versionList));\n                i = ge.box.apply(null, r);\n                return ge.pssh(oh.systemId, null, i)\n            }\n            makeKeyRequestMessage(e, t) {\n                if (t) return O.strToUtf8array(\"renew\")\n            }\n            makeProcessLicenseRequestMessage(e, t, i) {\n                t = JSON.stringify([{\n                    keyID: qc.base64Encode(e.decryptdata.keyId),\n                    payload: qc.base64Encode(new Uint8Array(t))\n                }]);\n                return O.strToUtf8array(t)\n            }\n            handleKeyMessage(e) {\n                const t = e.target,\n                    i = t.sessionId,\n                    r = e.messageType,\n                    n = this.sessionIdToKeyUri[i];\n                let s;\n                if (n) s = this.keyUriToKeyInfo[n];\n                else\n                    for (const e of Object.values(this.keyUriToKeyInfo)) e && e.session === t && (s = e);\n                if (s) switch (r) {\n                    case \"license-request\": {\n                        const t = new Uint8Array(e.message),\n                            i = O.utf8arrayToStr(t);\n                        try {\n                            JSON.parse(i).forEach(e => {\n                                var t = qc.base64DecodeToStr(e.keyID),\n                                    e = qc.base64Decode(e.payload),\n                                    t = this.keyIdToKeyInfo[t];\n                                t && this.resolveSPCPromise(t, e)\n                            })\n                        } catch (e) {\n                            this.logger.warn(\"[Keys] got unexpected license-request format\"), this.resolveSPCPromise(s, t)\n                        }\n                        break\n                    }\n                    case \"license-renewal\": {\n                        const t = new Uint8Array(e.message);\n                        this.resolveSPCPromise(s, t);\n                        break\n                    }\n                    case \"license-release\":\n                        this._handleLicenseRelease(t);\n                        break;\n                    default:\n                        this.logger.warn(`[Keys] Unexpected messageType ${r}`)\n                } else this.logger.warn(\"[Keys] No key associated with session\")\n            }\n            _handleLicenseRelease(e) {\n                e.update(O.strToUtf8array(\"acknowledged\")).catch(e => {\n                    this.logger.error(`Promise error: ${e.message}`)\n                })\n            }\n        };\n        const yh = {\n                initDataTypes: [\"cenc\"]\n            },\n            vh = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);\n        class Sh extends Zc {\n            constructor(e, t, i, r, n, s) {\n                super(e, t, i, r, !1, n, s), this.shouldDestroyMediaKeys = !0\n            }\n            static get systemId() {\n                return vh\n            }\n            static get requestAccessConfig() {\n                return yh\n            }\n            get needsCert() {\n                return !1\n            }\n            generateInitData(e, t) {\n                t = t.pssh;\n                return {\n                    initData: ge.pssh(Sh.systemId, [], t),\n                    initDataType: \"cenc\"\n                }\n            }\n            removeKey(e) {\n                return super.removeSessions(e, !0)\n            }\n            ensureKeyContext(e) {\n                const t = e.uri,\n                    i = this.keyUriToKeyInfo[t];\n                return null != i && i.session && (i.oldSessions.push(i.session), i.session = null), super.ensureKeyContext(e)\n            }\n            getKeyRequestResponse(e, t) {\n                var i = e.decryptdata.uri,\n                    r = e.setKeyRequestState(Kc.GET_KEY_RESPONSE);\n                return this.eventEmitter.trigger(x.LICENSE_CHALLENGE_CREATED, {\n                    keyuri: i,\n                    licenseChallenge: t,\n                    keysystem: this.systemString,\n                    keyId: e.decryptdata.keyId\n                }), r\n            }\n            generateRequestInitialized(e) {\n                var t = e.licenseChallenge;\n                return e.requestInfo = void 0, e.resolveState(Kc.GET_CHALLENGE, t), Wu\n            }\n            handleParsedKeyResponse(t, e) {\n                const i = t.decryptdata.uri,\n                    r = e.statusCode;\n                if (0 !== r) return Vi(new gc(\"License server responded with error\", i, r, {\n                    code: r,\n                    text: \"Server error\"\n                }, !1, rc.LicenseServerError));\n                if (!e.license || !e.license.byteLength) return Vi(new gc(\"License server responded with invalid license\", i, r, {\n                    code: r,\n                    text: \"Invalid license\"\n                }, !1, rc.LicenseServerError));\n                if (e.renewalDate) {\n                    const i = e.renewalDate,\n                        r = new Date,\n                        n = i > r ? i.getTime() - r.getTime() : 0;\n                    0 < n && this._scheduleRenewal(t, n)\n                }\n                return en([t.setKeyRequestState(Kc.PROCESS_LICENSE), Fr(t.session.update(e.license)).pipe(Za(() => {\n                    t.resolveState(Kc.PROCESS_LICENSE, void 0)\n                }), Vn(e => {\n                    throw this.logger.error(`${this.systemString} FAIL: Failed to update with key response message=${e.message}`), new yc(e.message, t.decryptdata.uri, 0, $.KeySystemFailedToUpdateSession, this.systemString)\n                }))]).pipe(Zs(void 0))\n            }\n            handleKeyMessage(e) {\n                if (this.isDestroying) this.logger.warn(\"In the middle of destroying, ignore key message\");\n                else {\n                    const t = new DOMParser,\n                        i = new(\"utf16\" === this.config.playReadyMessageFormat ? Uint16Array : Uint8Array)(e.message.buffer || e.message),\n                        r = String.fromCharCode.apply(null, Array.from(i)),\n                        n = t.parseFromString(r, \"application/xml\").getElementsByTagName(\"PlayReadyKeyMessage\")[0];\n                    if (n && \"LicenseAcquisition\" === n.getAttribute(\"type\")) {\n                        const s = t.parseFromString(r, \"application/xml\").getElementsByTagName(\"Challenge\")[0];\n                        if (s && \"base64encoded\" === s.getAttribute(\"encoding\") && 0 !== s.childNodes.length) {\n                            const a = qc.base64Decode(s.childNodes[0].nodeValue),\n                                o = O.utf8arrayToStr(a),\n                                l = t.parseFromString(o, \"application/xml\").getElementsByTagName(\"KID\")[0];\n                            e = null, e = l.childNodes[0] ? l.childNodes[0].nodeValue : l.getAttribute(\"VALUE\"), e = qc.base64Decode(e).subarray(0, 16);\n                            Wc.changeEndianness(e);\n                            const d = this.keyIdToKeyInfo[O.utf8arrayToStr(e)];\n                            d && (d.licenseChallenge = a, d.resolveState(Kc.GET_CHALLENGE, a))\n                        } else this.logger.warn(`${this.systemString} wrong challenge format or empty challenge`)\n                    } else this.logger.warn(`${this.systemString} unrecognized message ignore it`)\n                }\n            }\n        }\n        w = Sh;\n        const bh = {\n                initDataTypes: [\"cenc\", \"keyids\"]\n            },\n            Th = new Uint8Array([237, 239, 139, 169, 121, 214, 74, 206, 163, 200, 39, 220, 213, 29, 33, 237]),\n            Eh = {\n                clearkey: th,\n                fairplaystreaming: Sc,\n                playready: Fc,\n                widevine: Bc\n            },\n            Ih = {\n                clearkey: [\n                    [\"org.w3.clearkey\", nu]\n                ],\n                fairplaystreaming: [\n                    [\"com.apple.fps.3_0\", t],\n                    [\"com.apple.fps\", ru]\n                ],\n                playready: [\n                    [\"com.microsoft.playready.recommendation\", w]\n                ],\n                widevine: [\n                    [\"com.widevine.alpha\", class extends Zc {\n                        constructor(e, t, i, r, n, s) {\n                            super(e, t, i, r, !1, n, s), this.shouldDestroyMediaKeys = !0\n                        }\n                        static get systemId() {\n                            return Th\n                        }\n                        static get requestAccessConfig() {\n                            return bh\n                        }\n                        get needsCert() {\n                            return !0\n                        }\n                        removeKey(e) {\n                            return super.removeSessions(e, !0)\n                        }\n                        ensureKeyContext(e) {\n                            const t = e.uri,\n                                i = this.keyUriToKeyInfo[t];\n                            return null != i && i.session && (i.oldSessions.push(i.session), i.session = null), super.ensureKeyContext(e)\n                        }\n                        getKeyRequestResponse(e, t) {\n                            var i = e.decryptdata.uri,\n                                r = e.setKeyRequestState(Kc.GET_KEY_RESPONSE);\n                            return this.eventEmitter.trigger(x.LICENSE_CHALLENGE_CREATED, {\n                                keyuri: i,\n                                licenseChallenge: t,\n                                keysystem: this.systemString,\n                                keyId: e.decryptdata.keyId\n                            }), r\n                        }\n                        handleParsedKeyResponse(t, e) {\n                            t.licenseChallenge = void 0;\n                            const i = t.decryptdata.uri,\n                                r = e.statusCode;\n                            if (0 !== r) return Vi(new gc(\"License server responded with error\", i, r, {\n                                code: r,\n                                text: \"Server error\"\n                            }, !1, rc.LicenseServerError));\n                            if (!e.license || !e.license.byteLength) return Vi(new gc(\"License server responded with invalid license\", i, r, {\n                                code: r,\n                                text: \"Invalid license\"\n                            }, !1, rc.LicenseServerError));\n                            if (e.renewalDate) {\n                                const i = e.renewalDate,\n                                    r = new Date,\n                                    n = i > r ? i.getTime() - r.getTime() : 0;\n                                0 < n && this._scheduleRenewal(t, n)\n                            }\n                            return en([t.setKeyRequestState(Kc.PROCESS_LICENSE), Fr(t.session.update(e.license)).pipe(Za(() => {\n                                var e = t.decryptdata.keyId,\n                                    e = t.session.keyStatuses.get(e);\n                                this.handleKeyStatusForKey(e, t)\n                            }), Vn(e => {\n                                throw this.logger.error(`${this.systemString} FAIL: Failed to update with key response code=${e.code} message=${e.message}`), new yc(e.message, t.decryptdata.uri, e.code, {\n                                    code: e.code,\n                                    text: \"Failed to update with key response\"\n                                }, this.systemString)\n                            }))]).pipe(Zs(void 0))\n                        }\n                        generateInitData(e, t) {\n                            return {\n                                initData: t.pssh,\n                                initDataType: \"cenc\"\n                            }\n                        }\n                        generateRequestInitialized(e) {\n                            var t = e.licenseChallenge;\n                            return e.requestInfo = void 0, e.resolveState(Kc.GET_CHALLENGE, t), Wu\n                        }\n                        handleKeyMessage(i) {\n                            if (this.isDestroying) this.logger.warn(\"In the middle of destroying, ignore key message\");\n                            else {\n                                const r = i.target;\n                                let e = null,\n                                    t = null;\n                                if (r.sessionId in this.sessionIdToKeyUri) e = this.sessionIdToKeyUri[r.sessionId], t = this.keyUriToKeyInfo[e];\n                                else\n                                    for (const [i, n] of Object.entries(this.keyUriToKeyInfo))\n                                        if (n.session === r) {\n                                            e = i, t = n;\n                                            break\n                                        } if (t) switch (i.messageType) {\n                                    case \"license-request\": {\n                                        const r = new Uint8Array(i.message);\n                                        t.resolveState(Kc.GET_CHALLENGE, r);\n                                        break\n                                    }\n                                } else this.logger.warn(`${this.systemString} empty keyuri and keyInfo`)\n                            }\n                        }\n                    }]\n                ]\n            },\n            wh = th.id;\n        class Ah {\n            createMediaKeys(t, e, i, r, n) {\n                let s = Ah.idToMediaKeysInfoMap[t];\n                if (!s) {\n                    const a = Wc.getCapabilities(e, i),\n                        o = new er;\n                    Ah.requestKeySystemAccess(t, a, n, r).pipe(La(function(e) {\n                        return Fr((Ah.idToMediaKeysInfoMap[t].keySystemAccess = e).createMediaKeys())\n                    }), Za(e => {\n                        o.next(e), o.complete()\n                    }), Vn(e => (o.error(new yc(`could not initialize key system: ${e.message}`, void 0, 0, $.KeySystemFailedToInitialize, t)), Ii)), Va(Ah.destroy$)).subscribe(), s = Ah.idToMediaKeysInfoMap[t] = {\n                        mediaKeys$: o,\n                        keySystemAccess: null\n                    }\n                }\n                return s.mediaKeys$\n            }\n            destroyMediaKeys() {\n                Ah.destroy$.next(), Ah.idToMediaKeysInfoMap = {}\n            }\n            static getKeySystemIdForDecryptData(e) {\n                let t;\n                if (e) {\n                    t = wh;\n                    var i = e.format;\n                    for (const e of ih) {\n                        var r = Eh[e];\n                        if ((null == r ? void 0 : r.keyFormatString) === i) {\n                            t = e;\n                            break\n                        }\n                    }\n                }\n                if (!t) throw Error(\"No matching key system\");\n                return t\n            }\n            static requestKeySystemAccess(e, t, i, r) {\n                if (\"undefined\" == typeof navigator || void 0 === navigator.requestMediaKeySystemAccess) return Vi(new yc(\"navigator undefined\", void 0, 0, $.KeySystemUndefinedNavigator, e));\n                const n = Ih[e];\n                let s = Vi(new yc(\"no key systems to try\", void 0, 0, $.KeySystemNoKeySystemsToTry, e));\n                for (const e of n) {\n                    const n = e[0],\n                        o = e[1],\n                        l = (a = i) && \"object\" == typeof a ? i : o.requestAccessConfig,\n                        d = [Object.assign({}, l, t)];\n                    s = s.pipe(Vn(() => Ah.requestKeySystemInternal(n, d, r)))\n                }\n                var a;\n                return s\n            }\n            static requestKeySystemInternal(e, t, i) {\n                return Zr(() => Fr(navigator.requestMediaKeySystemAccess(e, t)))\n            }\n            make(e, t, i, r, n, s) {\n                var a = null === (l = Ah.idToMediaKeysInfoMap[e]) || void 0 === l ? void 0 : l.keySystemAccess;\n                if (!a) throw new yc(`No keySystemAccess for ${e}`, void 0, 0, $.KeySystemNoKeySystemAccess, e);\n                let o;\n                var l = Eh[e].systemStringPrefix;\n                for (const t of Ih[e])\n                    if (t[0] === a.keySystem) {\n                        o = t[1];\n                        break\n                    } if (!o) throw new yc(`No constructor associated with ${e}`, void 0, 0, $.KeySystemNoConstructor, l);\n                return new o(t, l, i, r, n, s)\n            }\n            static get availableKeySystems() {\n                return Object.keys(Eh)\n            }\n            static getKeySystemFormat(e) {\n                e = Eh[e];\n                return e ? e.keyFormatString : \"\"\n            }\n            static getKeySystemSecurityLevel(e) {\n                e = Eh[e];\n                return e ? e.securityLevels : void 0\n            }\n        }\n        Ah.idToMediaKeysInfoMap = {}, Ah.destroy$ = new Xt;\n        const Oh = [\"avc1.42E01E\"],\n            kh = [\"mp4a.40.2\"];\n\n        function Ch(e, t, i) {\n            if (t) {\n                if (t instanceof dr) t = new mc(\"Key request timed out\", e, $.KeySystemRequestTimedOut);\n                else if (t instanceof yc) {\n                    const i = (null == t ? void 0 : t.response) || $.InternalError;\n                    t = new gc(t.message, e, 0, i, !1, rc.InternalError, !0)\n                }\n            } else t = new gc(\"Unknown error from CDM\", e, 0, $.KeySystemCDMUnknownError, !1, rc.InternalError);\n            return (t instanceof gc || t instanceof mc) && (t.mediaOptionIds = [...i]), t\n        }\n        class Dh {\n            constructor(e, t, i, r, n, s, a, o = new Ah) {\n                this.ksService = e, this.mediaSink = t, this.config = i, this.platformQuery = r, this.eventEmitter = n, this.sessionHandler = s, this.keySystemFactory = o, this.reset$ = new Xt, this.keyRequest$ = new Xt, this.abort$ = new Xt, this.keySystem$ = new yi(null), this._keyStatusChange$ = new Xt, this.protectionData = {}, this.keySystemId = null, this.keyUriToRequest = {}, this.ksQuery = e.getQuery(), this.logger = a.child({\n                    name: \"eme\"\n                }), this.config.warmupCdms && this.keySystemFactory.createMediaKeys(Sc.id, Oh, kh, this.logger, void 0).subscribe(), an(r.platformInfo$.pipe(Is((e, t) => e && t && e.requiresCDMAttachOnStart === t.requiresCDMAttachOnStart), La(e => null != e && e.requiresCDMAttachOnStart ? this.attachMediaKeys().pipe(Vn(e => (this.handleKeySystemError(e), Ii))) : Wu), $a(Ii)), this.keyRequest$.pipe(jr(e => e.pipe(Vn(() => Ii)))), this.keySystem$.pipe(La(e => e ? e.keyStatusChange$.pipe(Za(e => {\n                    var t = e.decryptdata.uri,\n                        i = this.ksQuery.getKeyInfo(t);\n                    \"needs-renewal\" === e.status ? this.ksService.updateKeyRequestState(t, ic.MustRequestResponse, e => e === ic.GotKeyResponse) : (i = Ch(t, e.error, null !== (i = null == i ? void 0 : i.mediaOptionIds) && void 0 !== i ? i : []), this.ksService.setError(t, i)), this._keyStatusChange$.next(e)\n                })) : Ii)), this.isKeyCleanupSupported() ? this.mediaSink.mediaQuery.bufferedSegmentsTuple$.pipe(jr(e => {\n                    const [t, i] = e, r = new Set;\n                    return t.forEach(e => {\n                        e = null === (e = null === (e = e.frag) || void 0 === e ? void 0 : e.keyTagInfo) || void 0 === e ? void 0 : e.uri;\n                        e && r.add(e)\n                    }), i.forEach(e => {\n                        e = null === (e = null === (e = e.frag) || void 0 === e ? void 0 : e.keyTagInfo) || void 0 === e ? void 0 : e.uri;\n                        e && r.add(e)\n                    }), this.handleKeyCleanup(r)\n                })) : Wu).pipe(Va(this.reset$)).subscribe()\n            }\n            get keyStatusChange$() {\n                return this._keyStatusChange$\n            }\n            get keySystem() {\n                return this.keySystem$.value\n            }\n            destroy() {\n                this.reset$.next(), this.ksService.removeAll(), this.keySystemId = null;\n                const e = this.keySystem;\n                let t = Wu;\n                return e && (this.keySystem$.next(null), e.shouldDestroyMediaKeys && this.keySystemFactory.destroyMediaKeys(), t = e.destroy()), Mr([t, this.mediaSink.clearMediaKeys()]).pipe(Zs(void 0))\n            }\n            attachMediaKeys() {\n                if (this.keySystem) return Wu;\n                var e = this.config.keySystemPreference ? Ah.getKeySystemFormat(this.config.keySystemPreference) : Sc.keyFormatString;\n                return this.makeKeySystem(new zc(\"NONE\", null, null, e, [1])).pipe(Zs(void 0))\n            }\n            isKeyCleanupSupported() {\n                return !0 === this.config.useMultipleKeySessions || \"widevine\" === this.config.keySystemPreference || \"playready\" === this.config.keySystemPreference\n            }\n            handleKeyCleanup(i) {\n                if (this.ksQuery.getCount() < 6) return Wu;\n                const r = performance.now(),\n                    e = this.ksQuery.getAll().map(e => {\n                        var t = e.keyUri;\n                        if (!i.has(t)) {\n                            const i = ac(e.decryptdata);\n                            if (\"AES-128\" !== i.method && r > e.minHoldTime) return this._removeKey(t, i)\n                        }\n                        return Wu\n                    });\n                return e.length ? en(e).pipe($a(Wu)) : Wu\n            }\n            _removeKey(e, t) {\n                return this.abort$.next(e), this.ksService.removeKey(e), this.keySystem.removeKey(t)\n            }\n            removeKeysForItems(i) {\n                const r = [];\n                return al(() => {\n                    for (const e of i) {\n                        this.ksService.removeAllKeysForItem(e);\n                        const i = this.ksQuery.getAll({\n                            filterBy: e => 0 === e.itemIds.length\n                        });\n                        for (const t of i) r.push(this._removeKey(t.keyUri, ac(t.decryptdata)))\n                    }\n                }), r.length ? en(r).pipe(La(() => Wu)) : Wu\n            }\n            get availableKeySystems() {\n                return Ah.availableKeySystems\n            }\n            initialize(e) {\n                var t = this.protectionData;\n                this.protectionData = {};\n                var i = this.config.keySystemPreference;\n                for (const a of Ah.availableKeySystems) {\n                    var r = e[a];\n                    if (r)\n                        if (i === a) {\n                            var n, s = r.certificate,\n                                r = r.serverCertUrl ? bu.buildAbsoluteURL(window.location.href, r.serverCertUrl) : void 0;\n                            let e;\n                            this.protectionData[a] = {\n                                serverCertUrl: r,\n                                certificate: s\n                            }, s ? e = $i({\n                                keysystem: a,\n                                certificate: s\n                            }) : r && (null === (n = null == t ? void 0 : t[a]) || void 0 === n ? void 0 : n.serverCertUrl) !== r && (n = Tu(r) ? this.config.certLoadPolicy.customURL : this.config.certLoadPolicy.default, e = Rc({\n                                url: r,\n                                xhrSetup: this.config.xhrSetup\n                            }, n).pipe(hr(([e]) => ({\n                                keysystem: a,\n                                certificate: new Uint8Array(e)\n                            })))), e && e.pipe(La(e => this.onServerCertificateLoaded(e)), Vn(e => {\n                                throw this.logger.error(`Error loading cert: ${e.message}`), this.eventEmitter.trigger(x.INTERNAL_ERROR, {\n                                    type: o,\n                                    details: \"certificateLoadError\",\n                                    fatal: !1,\n                                    handled: !0,\n                                    reason: \"Error handling cert\",\n                                    response: $.KeySystemCertificateLoadError,\n                                    message: e.message,\n                                    name: \"certificateLoadError\"\n                                }), e\n                            }), Va(this.reset$)).subscribe()\n                        } else this.logger.warn(`Key system ${a} does not match preference ${i}, ignoring`)\n                }\n            }\n            generateRequest(e, t) {\n                this.keySystem && this.keySystem.setKeyRequestInfo(e, t)\n            }\n            setLicenseResponse(e, t) {\n                this.keySystem && this.keySystem.setParsedResponse(e, t)\n            }\n            getKeyFromDecryptData(e, t) {\n                if (!e || !e.isEncrypted) return $i(e);\n                let i;\n                return al(() => {\n                    i = this._getKeyFromDecryptData(e, t)\n                }), i\n            }\n            _getKeyFromDecryptData(t, i) {\n                let r = null,\n                    n = null;\n                i && (r = i.itemId, n = i.mediaOptionId);\n                const s = t.uri,\n                    e = this.ksQuery.getKeyInfo(s);\n                if (e && null != i && this.ksService.addMediaOption(s, i), (null == e ? void 0 : e.error) instanceof gc && !1 === e.error.isOkToRetry) return Vi(e.error);\n                if (e && e.requestState !== ic.MustRequestResponse) return e.requestState === ic.GotKeyResponse ? $i(ac(e.decryptdata)) : this.keyUriToRequest[s]; {\n                    const o = performance.now() + this.config.keyMinHoldTimeBeforeCleanup;\n                    let e;\n                    this.abort$.next(s), this.ksService.upsertKey({\n                        keyUri: s,\n                        decryptdata: function(e) {\n                            var {\n                                method: t,\n                                isEncrypted: i,\n                                uri: r,\n                                format: n,\n                                formatversions: s\n                            } = e;\n                            return {\n                                method: t,\n                                isEncrypted: i,\n                                uri: r,\n                                format: n,\n                                formatversions: s,\n                                ivBuf: null !== (s = null === (s = e.iv) || void 0 === s ? void 0 : s.buffer) && void 0 !== s ? s : null,\n                                keyIdBuf: null === (s = e.keyId) || void 0 === s ? void 0 : s.buffer,\n                                keyBuf: null === (s = e.key) || void 0 === s ? void 0 : s.buffer,\n                                psshBuf: null === (e = e.key) || void 0 === e ? void 0 : e.buffer\n                            }\n                        }(t),\n                        minHoldTime: o,\n                        mediaOptionIds: [n],\n                        requestState: ic.WaitingForKeyResponse,\n                        itemIds: [r]\n                    });\n                    var a = t.method;\n                    switch (a) {\n                        case \"SAMPLE-AES\":\n                        case \"ISO-23001-7\":\n                        case \"SAMPLE-AES-CTR\": {\n                            const o = this.config.keyLoadPolicy.customURL;\n                            e = this.fetchKeyEME(t).pipe(So(o.maxLoadTimeMs));\n                            break\n                        }\n                        case \"AES-128\":\n                            e = this.fetchKeyHTTP(t.uri, t, this.config.keyLoadPolicy);\n                            break;\n                        default:\n                            return Vi(new V(!1, `Unexpected METHOD attribute ${a}`, $.KeySystemUnexpectedMETHOD))\n                    }\n                    i = this.keyUriToRequest[s] = e.pipe(hr(e => {\n                        var t = e.decryptdata;\n                        return this.ksService.updateKeyValue(s, t.key), this.eventEmitter.trigger(x.KEY_LOADED, e), e.decryptdata\n                    }), Vn(e => {\n                        var t = this.ksQuery.getKeyInfo(s);\n                        return e = Ch(s, e, null !== (t = null == t ? void 0 : t.mediaOptionIds) && void 0 !== t ? t : []), this.ksService.setError(s, e), Vi(e)\n                    }), Vs(() => {\n                        this.ksService.updateKeyRequestState(s, ic.MustRequestResponse, e => e === ic.WaitingForKeyResponse), this.keyUriToRequest[s] = null\n                    }), Aa(), Va(fn(this.abort$.pipe(ln(e => e === s)), this.reset$).pipe(Za(e => this.logger.warn(e ? `aborted ${le(e)}` : \"got reset\")))));\n                    return this.keyRequest$.next(i), i\n                }\n            }\n            fetchKeyEME(e) {\n                return this.requestKey(e).pipe(hr(e => ({\n                    timestamp: performance.now(),\n                    keyuri: e.uri,\n                    decryptdata: e\n                })))\n            }\n            fetchKeyHTTP(e, t, i) {\n                return Dh.fetchKeyHTTP(e, this.config, t, i)\n            }\n            static fetchKeyHTTP(t, e, i, r) {\n                e = {\n                    url: t,\n                    xhrSetup: e.xhrSetup\n                };\n                return Rc(e, Lc(e, r)).pipe(hr(([e]) => (i.key = new Uint8Array(e), {\n                    decryptdata: i,\n                    keyuri: t,\n                    timestamp: performance.now()\n                })))\n            }\n            requestKey(t) {\n                return this.makeKeySystem(t).pipe(La(e => e.startKeyRequest(t)))\n            }\n            ensureKeySystem(t) {\n                return Zr(() => {\n                    if (!this.keySystem && this.keySystemId) {\n                        this.keySystem$.next(this.keySystemFactory.make(this.keySystemId, t, this.config, this.eventEmitter, this.sessionHandler, this.logger));\n                        var e = this.protectionData && this.protectionData[this.keySystemId];\n                        if (e) return this.keySystem.setServerCertificate(e.certificate).pipe(Zs(this.keySystem))\n                    }\n                    return $i(this.keySystem)\n                })\n            }\n            makeKeySystem(e) {\n                return this.ensureMediaKeys(e).pipe(La(e => this.mediaSink.setMediaKeys(e).pipe(La(() => this.ensureKeySystem(e)))))\n            }\n            ensureMediaKeys(e) {\n                var t = Ah.getKeySystemIdForDecryptData(e);\n                if (null == this.keySystemId) this.keySystemId = t;\n                else if (this.keySystemId !== t) return Vi(new gc(`New key system string does not match existing ${t} !== ${this.keySystemId}`, e.uri, 0, $.KeySystemUnmatchedString, !1, rc.InternalError));\n                return this.keySystemFactory.createMediaKeys(this.keySystemId, Oh, kh, this.logger, null === (e = this.platformQuery.platformInfo) || void 0 === e ? void 0 : e.keySystemConfig)\n            }\n            onServerCertificateLoaded(e) {\n                var t = e.keysystem,\n                    e = e.certificate;\n                return this.protectionData[t].certificate = e, this.keySystem && this.keySystemId === t ? this.keySystem.setServerCertificate(e).pipe(Zs(void 0)) : Wu\n            }\n            handleKeySystemError(e) {\n                e = new yc(e.message, void 0, void 0, $.KeySystemSetupError, void 0);\n                this.eventEmitter.trigger(x.INTERNAL_ERROR, e)\n            }\n        }\n        class Mh extends kl {\n            constructor(e) {\n                super(e)\n            }\n            getKeyInfo(e) {\n                e = this.getEntity(e);\n                return e ? Object.assign(Object.assign({}, e), {\n                    error: vc(e.error, e.mediaOptionIds)\n                }) : null\n            }\n            getKeyInfo$(e) {\n                return this.selectEntity(e).pipe(hr(e => e ? Object.assign(Object.assign({}, e), {\n                    error: vc(e.error, e.mediaOptionIds)\n                }) : null))\n            }\n            getKeyRequestState$(e) {\n                return this.selectEntity(e, e => null == e ? void 0 : e.requestState)\n            }\n            getKeyStatus$(e) {\n                return this.selectEntity(e, e => null == e ? void 0 : e.status)\n            }\n            getKeyError$(e) {\n                return this.selectEntity(e, e => vc(null == e ? void 0 : e.error, null == e ? void 0 : e.mediaOptionIds)).pipe(wl)\n            }\n        }\n        class xh {\n            constructor(e) {\n                this.store = e\n            }\n            getQuery() {\n                return new Mh(this.store)\n            }\n            upsertKey(i) {\n                Do(\"keys.upsert\", i.keyUri);\n                const r = new Set(i.itemIds.filter(e => null != e)),\n                    n = new Set(i.mediaOptionIds.filter(e => null != e));\n                this.store.upsert(i.keyUri, e => {\n                    const t = Object.assign(Object.assign({}, e), i);\n                    if (\"itemIds\" in e)\n                        for (const i of e.itemIds) r.add(i);\n                    if (t.itemIds = Array.from(r), \"mediaOptionIds\" in e)\n                        for (const i of e.mediaOptionIds) n.add(i);\n                    return t.mediaOptionIds = Array.from(n), t\n                }, () => Object.assign(Object.assign({}, i), {\n                    itemIds: Array.from(r),\n                    mediaOptionIds: Array.from(n)\n                }))\n            }\n            removeKey(e) {\n                Do(\"keys.removeKey\", e), this.store.remove(e)\n            }\n            removeAllKeysForItem(i) {\n                Do(`keys.removeAllKeysForItem ${i}`), this.store.update(null, e => {\n                    var t = e.itemIds.findIndex(e => e === i);\n                    0 <= t && e.itemIds.splice(t, 1)\n                })\n            }\n            removeAll() {\n                Do(\"keys.remove\"), this.store.remove()\n            }\n            updateKeyValue(e, t) {\n                Do(\"keys.updateKeyValue\", e), this.store.update(e, e => {\n                    null == e.decryptdata.keyBuf && null != t && (e.decryptdata.keyBuf = t.buffer), e.requestState = ic.GotKeyResponse\n                })\n            }\n            updateKeyStatus(e, t) {\n                Do(`keys.updateKeyStatus ${t}`, e), this.store.update(e, e => {\n                    e.status = t\n                })\n            }\n            updateKeyRequestState(e, t, i) {\n                Do(`keys.updateKeyRequestState ${t}`, e), this.store.update(e, e => {\n                    i && !i(e.requestState) || (e.requestState = t)\n                })\n            }\n            addMediaOption(e, t) {\n                const {\n                    itemId: i,\n                    mediaOptionId: r\n                } = t;\n                Do(`keys.addMediaOption itemId: ${i}, mediaOptionId: ${r}`, e), this.store.update(e, e => {\n                    null != r && e.mediaOptionIds.every(e => e !== r) && e.mediaOptionIds.push(r), null != i && e.itemIds.every(e => e !== i) && e.itemIds.push(i)\n                })\n            }\n            setError(e, t) {\n                var i;\n                Do(`keys.setError ${null===(i=null==t?void 0:t.constructor)||void 0===i?void 0:i.name}`, e), this.store.update(e, e => {\n                    e.error = vc(t), e.requestState = ic.MustRequestResponse\n                })\n            }\n        }\n        const Ph = new class extends fl {\n            constructor() {\n                super({}, {\n                    name: \"key-system-store\",\n                    idKey: \"keyUri\",\n                    producerFn: su\n                })\n            }\n        };\n        let Rh = null;\n\n        function Lh(e) {\n            let t = e;\n            return Nh.hasOwnProperty(e) && (t = Nh[e]), String.fromCharCode(t)\n        }\n\n        function _h(t) {\n            const i = [];\n            for (let e = 0; e < t.length; e++) i.push(t[e].toString(16));\n            return i\n        }\n        const Nh = {\n                42: 225,\n                92: 233,\n                94: 237,\n                95: 243,\n                96: 250,\n                123: 231,\n                124: 247,\n                125: 209,\n                126: 241,\n                127: 9608,\n                128: 174,\n                129: 176,\n                130: 189,\n                131: 191,\n                132: 8482,\n                133: 162,\n                134: 163,\n                135: 9834,\n                136: 224,\n                137: 32,\n                138: 232,\n                139: 226,\n                140: 234,\n                141: 238,\n                142: 244,\n                143: 251,\n                144: 193,\n                145: 201,\n                146: 211,\n                147: 218,\n                148: 220,\n                149: 252,\n                150: 8216,\n                151: 161,\n                152: 42,\n                153: 8217,\n                154: 9473,\n                155: 169,\n                156: 8480,\n                157: 8226,\n                158: 8220,\n                159: 8221,\n                160: 192,\n                161: 194,\n                162: 199,\n                163: 200,\n                164: 202,\n                165: 203,\n                166: 235,\n                167: 206,\n                168: 207,\n                169: 239,\n                170: 212,\n                171: 217,\n                172: 249,\n                173: 219,\n                174: 171,\n                175: 187,\n                176: 195,\n                177: 227,\n                178: 205,\n                179: 204,\n                180: 236,\n                181: 210,\n                182: 242,\n                183: 213,\n                184: 245,\n                185: 123,\n                186: 125,\n                187: 92,\n                188: 94,\n                189: 95,\n                190: 124,\n                191: 8764,\n                192: 196,\n                193: 228,\n                194: 214,\n                195: 246,\n                196: 223,\n                197: 165,\n                198: 164,\n                199: 9475,\n                200: 197,\n                201: 229,\n                202: 216,\n                203: 248,\n                204: 9487,\n                205: 9491,\n                206: 9495,\n                207: 9499\n            },\n            Fh = 100,\n            Bh = {\n                17: 1,\n                18: 3,\n                21: 5,\n                22: 7,\n                23: 9,\n                16: 11,\n                19: 12,\n                20: 14\n            },\n            Uh = {\n                17: 2,\n                18: 4,\n                21: 6,\n                22: 8,\n                23: 10,\n                19: 13,\n                20: 15\n            },\n            $h = {\n                25: 1,\n                26: 3,\n                29: 5,\n                30: 7,\n                31: 9,\n                24: 11,\n                27: 12,\n                28: 14\n            },\n            Vh = {\n                25: 2,\n                26: 4,\n                29: 6,\n                30: 8,\n                31: 10,\n                27: 13,\n                28: 15\n            },\n            Kh = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\", \"black\", \"transparent\"],\n            qh = {\n                verboseFilter: {\n                    DATA: 3,\n                    DEBUG: 3,\n                    INFO: 2,\n                    WARNING: 2,\n                    TEXT: 1,\n                    ERROR: 0\n                },\n                time: null,\n                verboseLevel: 0,\n                setTime: function(e) {\n                    this.time = e\n                },\n                log: function(e, t) {\n                    var i = this.verboseFilter[e];\n                    this.verboseLevel >= i && console.log(this.time + \" [\" + e + \"] \" + t)\n                }\n            };\n        class Hh {\n            constructor(e, t, i, r, n) {\n                this.foreground = e || \"white\", this.underline = t || !1, this.italics = i || !1, this.background = r || \"black\", this.flash = n || !1\n            }\n            reset() {\n                this.foreground = \"white\", this.underline = !1, this.italics = !1, this.background = \"black\", this.flash = !1\n            }\n            setStyles(e) {\n                Object.assign(this, e)\n            }\n            isDefault() {\n                return \"white\" === this.foreground && !this.underline && !this.italics && \"black\" === this.background && !this.flash\n            }\n            equals(e) {\n                return this.foreground === e.foreground && this.underline === e.underline && this.italics === e.italics && this.background === e.background && this.flash === e.flash\n            }\n            copy(e) {\n                this.foreground = e.foreground, this.underline = e.underline, this.italics = e.italics, this.background = e.background, this.flash = e.flash\n            }\n            toString() {\n                return \"color=\" + this.foreground + \", underline=\" + this.underline + \", italics=\" + this.italics + \", background=\" + this.background + \", flash=\" + this.flash\n            }\n        }\n        class jh {\n            constructor(e, t, i, r, n, s) {\n                this.uchar = e || \" \", this.penState = new Hh(t, i, r, n, s)\n            }\n            reset() {\n                this.uchar = \" \", this.penState.reset()\n            }\n            setChar(e, t) {\n                this.uchar = e, this.penState.copy(t)\n            }\n            setPenState(e) {\n                this.penState.copy(e)\n            }\n            equals(e) {\n                return this.uchar === e.uchar && this.penState.equals(e.penState)\n            }\n            copy(e) {\n                this.uchar = e.uchar, this.penState.copy(e.penState)\n            }\n            isEmpty() {\n                return \" \" === this.uchar && this.penState.isDefault()\n            }\n        }\n        class Qh {\n            constructor() {\n                this.chars = [];\n                for (let e = 0; e < Fh; e++) this.chars.push(new jh);\n                this.pos = 0, this.currPenState = new Hh\n            }\n            equals(t) {\n                let i = !0;\n                for (let e = 0; e < Fh; e++)\n                    if (!this.chars[e].equals(t.chars[e])) {\n                        i = !1;\n                        break\n                    } return i\n            }\n            copy(t) {\n                for (let e = 0; e < Fh; e++) this.chars[e].copy(t.chars[e])\n            }\n            isEmpty() {\n                let t = !0;\n                for (let e = 0; e < Fh; e++)\n                    if (!this.chars[e].isEmpty()) {\n                        t = !1;\n                        break\n                    } return t\n            }\n            setCursor(e) {\n                this.pos !== e && (this.pos = e), this.pos < 0 ? (qh.log(\"ERROR\", \"Negative cursor position \" + this.pos), this.pos = 0) : this.pos > Fh && (qh.log(\"ERROR\", \"Too large cursor position \" + this.pos), this.pos = Fh)\n            }\n            moveCursor(e) {\n                var t = this.pos + e;\n                if (1 < e)\n                    for (let e = this.pos + 1; e < t + 1; e++) this.chars[e].setPenState(this.currPenState);\n                this.setCursor(t)\n            }\n            backSpace() {\n                this.moveCursor(-1), this.chars[this.pos].setChar(\" \", this.currPenState)\n            }\n            insertChar(e) {\n                144 <= e && this.backSpace();\n                var t = Lh(e);\n                this.pos >= Fh ? qh.log(\"ERROR\", \"Cannot insert \" + e.toString(16) + \" (\" + t + \") at position \" + this.pos + \". Skipping it!\") : (this.chars[this.pos].setChar(t, this.currPenState), this.moveCursor(1))\n            }\n            clearFromPos(e) {\n                let t;\n                for (t = e; t < Fh; t++) this.chars[t].reset()\n            }\n            clear() {\n                this.clearFromPos(0), this.pos = 0, this.currPenState.reset()\n            }\n            clearToEndOfRow() {\n                this.clearFromPos(this.pos)\n            }\n            getTextString() {\n                const t = [];\n                let i = !0;\n                for (let e = 0; e < Fh; e++) {\n                    var r = this.chars[e].uchar;\n                    \" \" !== r && (i = !1), t.push(r)\n                }\n                return i ? \"\" : t.join(\"\")\n            }\n            setPenStyles(e) {\n                this.currPenState.setStyles(e), this.chars[this.pos].setPenState(this.currPenState)\n            }\n        }\n        class Wh {\n            constructor() {\n                this.rows = [];\n                for (let e = 0; e < 15; e++) this.rows.push(new Qh);\n                this.currRow = 14, this.nrRollUpRows = null, this.reset()\n            }\n            reset() {\n                for (let e = 0; e < 15; e++) this.rows[e].clear();\n                this.currRow = 14\n            }\n            equals(t) {\n                let i = !0;\n                for (let e = 0; e < 15; e++)\n                    if (!this.rows[e].equals(t.rows[e])) {\n                        i = !1;\n                        break\n                    } return i\n            }\n            copy(t) {\n                for (let e = 0; e < 15; e++) this.rows[e].copy(t.rows[e])\n            }\n            isEmpty() {\n                let t = !0;\n                for (let e = 0; e < 15; e++)\n                    if (!this.rows[e].isEmpty()) {\n                        t = !1;\n                        break\n                    } return t\n            }\n            backSpace() {\n                this.rows[this.currRow].backSpace()\n            }\n            clearToEndOfRow() {\n                this.rows[this.currRow].clearToEndOfRow()\n            }\n            insertChar(e) {\n                this.rows[this.currRow].insertChar(e)\n            }\n            setPen(e) {\n                this.rows[this.currRow].setPenStyles(e)\n            }\n            moveCursor(e) {\n                this.rows[this.currRow].moveCursor(e)\n            }\n            setCursor(e) {\n                qh.log(\"INFO\", \"setCursor: \" + e), this.rows[this.currRow].setCursor(e)\n            }\n            setPAC(t) {\n                qh.log(\"INFO\", \"pacData = \" + JSON.stringify(t));\n                let i = t.row - 1;\n                if (this.nrRollUpRows && i < this.nrRollUpRows - 1 && (i = this.nrRollUpRows - 1), this.nrRollUpRows && this.currRow !== i) {\n                    for (let e = 0; e < 15; e++) this.rows[e].clear();\n                    const t = this.currRow + 1 - this.nrRollUpRows,\n                        r = this.lastOutputScreen;\n                    if (r) {\n                        const e = r.rows[t].cueStartTime;\n                        if (e && e < qh.time)\n                            for (let e = 0; e < this.nrRollUpRows; e++) this.rows[i - this.nrRollUpRows + e + 1].copy(r.rows[t + e])\n                    }\n                }\n                this.currRow = i;\n                const r = this.rows[this.currRow];\n                if (null !== t.indent) {\n                    const i = t.indent,\n                        e = Math.max(i - 1, 0);\n                    r.setCursor(t.indent), t.color = r.chars[e].penState.foreground\n                }\n                const e = {\n                    foreground: t.color,\n                    underline: t.underline,\n                    italics: t.italics,\n                    background: \"black\",\n                    flash: !1\n                };\n                this.setPen(e)\n            }\n            setBkgData(e) {\n                qh.log(\"INFO\", \"bkgData = \" + JSON.stringify(e)), this.backSpace(), this.setPen(e), this.insertChar(32)\n            }\n            setRollUpRows(e) {\n                this.nrRollUpRows = e\n            }\n            rollUp() {\n                if (null !== this.nrRollUpRows) {\n                    qh.log(\"INFO\", \"TEXT \" + this.getDisplayText());\n                    const e = this.currRow + 1 - this.nrRollUpRows,\n                        t = this.rows.splice(e, 1)[0];\n                    t.clear(), this.rows.splice(this.currRow, 0, t), qh.log(\"INFO\", \"Rolling up\")\n                } else qh.log(\"DEBUG\", \"roll_up but nrRollUpRows not set yet\")\n            }\n            getDisplayText(t) {\n                t = t || !1;\n                const i = [];\n                let e = \"\",\n                    r;\n                for (let e = 0; e < 15; e++) {\n                    const n = this.rows[e].getTextString();\n                    n && (r = e + 1, t ? i.push(\"Row \" + r + \": '\" + n + \"'\") : i.push(n.trim()))\n                }\n                return 0 < i.length && (e = t ? \"[\" + i.join(\" | \") + \"]\" : i.join(\"\\n\")), e\n            }\n            getTextAndFormat() {\n                return this.rows\n            }\n        }\n        class Gh {\n            constructor(e, t) {\n                this.chNr = e, this.outputFilter = t, this.mode = null, this.verbose = 0, this.displayedMemory = new Wh, this.nonDisplayedMemory = new Wh, this.lastOutputScreen = new Wh, this.currRollUpRow = this.displayedMemory.rows[14], this.writeScreen = this.displayedMemory, this.mode = null, this.cueStartTime = null\n            }\n            reset() {\n                this.mode = null, this.displayedMemory.reset(), this.nonDisplayedMemory.reset(), this.lastOutputScreen.reset(), this.currRollUpRow = this.displayedMemory.rows[14], this.writeScreen = this.displayedMemory, this.mode = null, this.cueStartTime = null, this.lastCueEndTime = null\n            }\n            getHandler() {\n                return this.outputFilter\n            }\n            setHandler(e) {\n                this.outputFilter = e\n            }\n            setPAC(e) {\n                this.writeScreen.setPAC(e)\n            }\n            setBkgData(e) {\n                this.writeScreen.setBkgData(e)\n            }\n            setMode(e) {\n                e !== this.mode && (this.mode = e, qh.log(\"INFO\", \"MODE=\" + e), \"MODE_POP-ON\" === this.mode ? this.writeScreen = this.nonDisplayedMemory : (this.writeScreen = this.displayedMemory, this.writeScreen.reset()), \"MODE_ROLL-UP\" !== this.mode && (this.displayedMemory.nrRollUpRows = null, this.nonDisplayedMemory.nrRollUpRows = null), this.mode = e)\n            }\n            insertChars(t) {\n                for (let e = 0; e < t.length; e++) this.writeScreen.insertChar(t[e]);\n                var e = this.writeScreen === this.displayedMemory ? \"DISP\" : \"NON_DISP\";\n                qh.log(\"INFO\", e + \": \" + this.writeScreen.getDisplayText(!0)), \"MODE_PAINT-ON\" !== this.mode && \"MODE_ROLL-UP\" !== this.mode || (qh.log(\"TEXT\", \"DISPLAYED: \" + this.displayedMemory.getDisplayText(!0)), this.outputDataUpdate())\n            }\n            ccRCL() {\n                qh.log(\"INFO\", \"RCL - Resume Caption Loading\"), this.setMode(\"MODE_POP-ON\")\n            }\n            ccBS() {\n                qh.log(\"INFO\", \"BS - BackSpace\"), \"MODE_TEXT\" !== this.mode && (this.writeScreen.backSpace(), this.writeScreen === this.displayedMemory && this.outputDataUpdate())\n            }\n            ccAOF() {}\n            ccAON() {}\n            ccDER() {\n                qh.log(\"INFO\", \"DER- Delete to End of Row\"), this.writeScreen.clearToEndOfRow(), this.outputDataUpdate()\n            }\n            ccRU(e) {\n                qh.log(\"INFO\", \"RU(\" + e + \") - Roll Up\"), this.writeScreen = this.displayedMemory, this.setMode(\"MODE_ROLL-UP\"), this.writeScreen.setRollUpRows(e)\n            }\n            ccFON() {\n                qh.log(\"INFO\", \"FON - Flash On\"), this.writeScreen.setPen({\n                    flash: !0\n                })\n            }\n            ccRDC() {\n                qh.log(\"INFO\", \"RDC - Resume Direct Captioning\"), this.setMode(\"MODE_PAINT-ON\")\n            }\n            ccTR() {\n                qh.log(\"INFO\", \"TR\"), this.setMode(\"MODE_TEXT\")\n            }\n            ccRTD() {\n                qh.log(\"INFO\", \"RTD\"), this.setMode(\"MODE_TEXT\")\n            }\n            ccEDM() {\n                qh.log(\"INFO\", \"EDM - Erase Displayed Memory\"), this.displayedMemory.reset(), this.outputDataUpdate(!0)\n            }\n            ccCR() {\n                qh.log(\"INFO\", \"CR - Carriage Return\"), this.writeScreen.rollUp(), this.outputDataUpdate(!0)\n            }\n            ccENM() {\n                qh.log(\"INFO\", \"ENM - Erase Non-displayed Memory\"), this.nonDisplayedMemory.reset()\n            }\n            ccEOC() {\n                var e;\n                qh.log(\"INFO\", \"EOC - End Of Caption\"), \"MODE_POP-ON\" === this.mode && (e = this.displayedMemory, this.displayedMemory = this.nonDisplayedMemory, this.nonDisplayedMemory = e, this.writeScreen = this.nonDisplayedMemory, qh.log(\"TEXT\", \"DISP: \" + this.displayedMemory.getDisplayText())), this.outputDataUpdate(!0)\n            }\n            ccTO(e) {\n                qh.log(\"INFO\", \"TO(\" + e + \") - Tab Offset\"), this.writeScreen.moveCursor(e)\n            }\n            ccMIDROW(e) {\n                const t = {\n                    flash: !1,\n                    underline: !1,\n                    italics: !1\n                };\n                t.underline = e % 2 == 1, t.italics = 46 <= e, t.italics ? t.foreground = \"white\" : (e = Math.floor(e / 2) - 16, t.foreground = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\"][e]), qh.log(\"INFO\", \"MIDROW: \" + JSON.stringify(t)), this.writeScreen.setPen(t)\n            }\n            outputDataUpdate(e = !1) {\n                var t = qh.time;\n                null !== t && this.outputFilter && (this.outputFilter.updateData && this.outputFilter.updateData(t, this.displayedMemory), null !== this.cueStartTime || this.displayedMemory.isEmpty() ? this.displayedMemory.equals(this.lastOutputScreen) || (this.outputFilter.newCue && (this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen), !0 === e && this.outputFilter.dispatchCue && this.outputFilter.dispatchCue()), this.cueStartTime = this.displayedMemory.isEmpty() ? null : t) : this.cueStartTime = t, this.lastOutputScreen.copy(this.displayedMemory))\n            }\n            cueSplitAtTime(e) {\n                this.outputFilter && (this.displayedMemory.isEmpty() || (this.outputFilter.newCue && this.outputFilter.newCue(this.cueStartTime, e, this.displayedMemory), this.cueStartTime = e))\n            }\n        }\n        var zh = class {\n            constructor(e = 1, t, i) {\n                this.field = e, this.currChNr = -1, this.lastCmdA = null, this.lastCmdB = null, this.channels = [new Gh(1, t), new Gh(2, i)], this.dataCounters = {\n                    padding: 0,\n                    char: 0,\n                    cmd: 0,\n                    other: 0\n                }\n            }\n            getHandler(e) {\n                return this.channels[e].getHandler()\n            }\n            setHandler(e, t) {\n                this.channels[e].setHandler(t)\n            }\n            addData(e, t) {\n                let i, r, n, s = null;\n                qh.setTime(e);\n                for (let e = 0; e < t.length; e += 2) r = 127 & t[e], n = 127 & t[e + 1], 16 <= r && r <= 31 && r === this.lastCmdA && n === this.lastCmdB ? (this.lastCmdA = null, this.lastCmdB = null, qh.log(\"DEBUG\", \"Repeated command (\" + _h([r, n]) + \") is dropped\")) : 0 != r || 0 != n ? (qh.log(\"DATA\", \"[\" + _h([t[e], t[e + 1]]) + \"] -> (\" + _h([r, n]) + \")\"), i = this.parseCmd(r, n), i = i || this.parseMidrow(r, n), i = i || this.parsePAC(r, n), i = i || this.parseBackgroundAttributes(r, n), !i && (s = this.parseChars(r, n), s) && (this.currChNr && 0 <= this.currChNr ? this.channels[this.currChNr - 1].insertChars(s) : qh.log(\"WARNING\", \"No channel found yet. TEXT-MODE?\")), i ? this.dataCounters.cmd += 2 : s ? this.dataCounters.char += 2 : (this.dataCounters.other += 2, qh.log(\"WARNING\", \"Couldn't parse cleaned data \" + _h([r, n]) + \" orig: \" + _h([t[e], t[e + 1]])))) : this.dataCounters.padding += 2\n            }\n            parseCmd(e, t) {\n                var i;\n                if (!((20 === e || 21 === e || 28 === e || 29 === e) && 32 <= t && t <= 47 || (23 === e || 31 === e) && 33 <= t && t <= 35)) return !1;\n                const r = this.channels[(i = 20 === e || 23 === e ? 1 : 2) - 1];\n                return 20 === e || 21 === e || 28 === e || 29 === e ? 32 === t ? r.ccRCL() : 33 === t ? r.ccBS() : 34 === t ? r.ccAOF() : 35 === t ? r.ccAON() : 36 === t ? r.ccDER() : 37 === t ? r.ccRU(2) : 38 === t ? r.ccRU(3) : 39 === t ? r.ccRU(4) : 40 === t ? r.ccFON() : 41 === t ? r.ccRDC() : 42 === t ? r.ccTR() : 43 === t ? r.ccRTD() : 44 === t ? r.ccEDM() : 45 === t ? r.ccCR() : 46 === t ? r.ccENM() : 47 === t && r.ccEOC() : r.ccTO(t - 32), this.lastCmdA = e, this.lastCmdB = t, this.currChNr = i, !0\n            }\n            parseMidrow(e, t) {\n                var i;\n                if ((17 === e || 25 === e) && 32 <= t && t <= 47) {\n                    if ((i = 17 === e ? 1 : 2) !== this.currChNr) return qh.log(\"ERROR\", \"Mismatch channel in midrow parsing\"), !1;\n                    const r = this.channels[i - 1];\n                    return r.insertChars([32]), r.ccMIDROW(t), qh.log(\"DEBUG\", \"MIDROW (\" + _h([e, t]) + \")\"), this.lastCmdA = e, this.lastCmdB = t, !0\n                }\n                return !1\n            }\n            parsePAC(e, t) {\n                if (!((17 <= e && e <= 23 || 25 <= e && e <= 31) && 64 <= t && t <= 127 || (16 === e || 24 === e) && 64 <= t && t <= 95)) return !1;\n                var i = e <= 23 ? 1 : 2,\n                    r = (64 <= t && t <= 95 ? 1 == i ? Bh : $h : 1 == i ? Uh : Vh)[e],\n                    r = this.interpretPAC(r, t);\n                return this.channels[i - 1].setPAC(r), this.lastCmdA = e, this.lastCmdB = t, this.currChNr = i, !0\n            }\n            interpretPAC(e, t) {\n                var i;\n                const r = {\n                    color: null,\n                    italics: !1,\n                    indent: null,\n                    underline: !1,\n                    row: e\n                };\n                return i = 95 < t ? t - 96 : t - 64, r.underline = 1 == (1 & i), i <= 13 ? r.color = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\", \"white\"][Math.floor(i / 2)] : i <= 15 ? (r.italics = !0, r.color = \"white\") : r.indent = 4 * Math.floor((i - 16) / 2), r\n            }\n            parseChars(e, t) {\n                let i = null,\n                    r = null,\n                    n = null;\n                var s;\n                if (n = 25 <= e ? (i = 2, e - 8) : (i = 1, e), 17 <= n && n <= 19 ? (s = t, s = 17 === n ? t + 80 : 18 === n ? t + 112 : t + 144, qh.log(\"INFO\", \"Special char '\" + Lh(s) + \"' in channel \" + i), r = [s], this.lastCmdA = e, this.lastCmdB = t) : 32 <= e && e <= 127 && (r = 0 === t ? [e] : [e, t], this.lastCmdA = null, this.lastCmdB = null), r) {\n                    const e = _h(r);\n                    qh.log(\"DEBUG\", `Char codes =  ${e.join(\",\")}`)\n                }\n                return r\n            }\n            parseBackgroundAttributes(e, t) {\n                let i, r, n;\n                return ((16 === e || 24 === e) && 32 <= t && t <= 47 || (23 === e || 31 === e) && 45 <= t && t <= 47) && (i = {\n                    underline: !1\n                }, 16 === e || 24 === e ? (r = Math.floor((t - 32) / 2), i.background = Kh[r], t % 2 == 1 && (i.background = i.background + \"_semi\")) : 45 === t ? i.background = \"transparent\" : (i.foreground = \"black\", 47 === t && (i.underline = !0)), n = this.channels[(e < 24 ? 1 : 2) - 1], n.setBkgData(i), this.lastCmdA = null, !(this.lastCmdB = null))\n            }\n            reset() {\n                for (let e = 0; e < this.channels.length; e++) this.channels[e] && this.channels[e].reset();\n                this.lastCmdA = null, this.lastCmdB = null\n            }\n            cueSplitAtTime(t) {\n                for (let e = 0; e < this.channels.length; e++) this.channels[e] && this.channels[e].cueSplitAtTime(t)\n            }\n        };\n        class Xh {\n            constructor(e, t) {\n                this.handler = e, this.track = t, this.startTime = null, this.endTime = null, this.screen = null\n            }\n            dispatchCue() {\n                null !== this.startTime && (this.handler.addCues(\"cc\" + this.track, this.startTime, this.endTime, this.screen), this.startTime = null)\n            }\n            newCue(e, t, i) {\n                (null === this.startTime || this.startTime > e) && (this.startTime = e), this.endTime = t, this.screen = i, this.handler.createHTMLCaptionsTrack(this.track)\n            }\n        }\n        var Yh = {},\n            iu = {},\n            nu = {},\n            t = {};\n        Object.defineProperty(t, \"__esModule\", {\n            value: !0\n        }), t.isValidPercentValue = function(e) {\n            return \"number\" == typeof e && 0 <= e && e <= 100\n        }, t.isValidAlignSetting = function(e) {\n            return \"string\" == typeof e && [\"start\", \"center\", \"end\", \"left\", \"right\", \"middle\"].includes(e)\n        }, t.isValidDirectionSetting = function(e) {\n            return \"string\" == typeof e && [\"\", \"rl\", \"lr\"].includes(e)\n        }, t.isValidLineAndPositionSetting = function(e) {\n            return \"number\" == typeof e || \"auto\" === e\n        }, t.isValidLineAlignSetting = function(e) {\n            return \"string\" == typeof e && [\"start\", \"center\", \"end\"].includes(e)\n        }, t.isValidPositionAlignSetting = function(e) {\n            return \"string\" == typeof e && [\"line-left\", \"center\", \"line-right\", \"auto\", \"left\", \"start\", \"middle\", \"end\", \"right\"].includes(e)\n        }, t.isValidScrollSetting = function(e) {\n            return [\"\", \"up\"].includes(e)\n        };\n        ru = {};\n        Object.defineProperty(ru, \"__esModule\", {\n            value: !0\n        });\n        const Jh = {\n                \"&amp;\": \"&\",\n                \"&lt;\": \"<\",\n                \"&gt;\": \">\",\n                \"&lrm;\": \"â€Ž\",\n                \"&rlm;\": \"â€\",\n                \"&nbsp;\": \"Â \"\n            },\n            Zh = {\n                c: \"span\",\n                i: \"i\",\n                b: \"b\",\n                u: \"u\",\n                ruby: \"ruby\",\n                rt: \"rt\",\n                v: \"span\",\n                lang: \"span\"\n            },\n            ep = {\n                v: \"title\",\n                lang: \"lang\"\n            },\n            tp = {\n                rt: \"ruby\"\n            },\n            ip = {\n                \"text-combine-upright\": \"-webkit-text-combine:horizontal; text-orientation: mixed;\"\n            };\n        class rp {\n            static parseTimeStamp(e) {\n                function t(e) {\n                    var [t, i, r, e] = e.map(e => e ? parseInt(\"\" + e) : 0);\n                    return 3600 * t + 60 * i + r + e / 1e3\n                }\n                const i = /^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/.exec(e);\n                return i ? i[3] ? t([i[1], i[2], i[3].substring(1), i[4]]) : 59 < parseInt(i[1]) ? t([i[1], i[2], null, i[4]]) : t([null, i[1], i[2], i[4]]) : null\n            }\n            static parseContent(s, t, a) {\n                let i = t.text;\n\n                function e(e) {\n                    return Jh[e]\n                }\n                const r = s.document.createElement(\"div\"),\n                    n = [];\n                let o, l, d = r;\n                for (; null !== (o = function() {\n                        if (!i) return null;\n                        var e = (e = /^([^<]*)(<[^>]+>?)?/.exec(i))[1] || e[2];\n                        return i = i.substr(e.length), e\n                    }());)\n                    if (\"<\" !== o[0]) d.appendChild(s.document.createTextNode(o.replace(/&(amp|lt|gt|lrm|rlm|nbsp);/g, e)));\n                    else {\n                        if (\"/\" === o[1]) {\n                            n.length && n[n.length - 1] === o.substr(2).replace(\">\", \"\") && (n.pop(), d = d.parentNode);\n                            continue\n                        }\n                        const t = rp.parseTimeStamp(o.substr(1, o.length - 2));\n                        let e;\n                        if (t) {\n                            e = s.document.createProcessingInstruction(\"timestamp\", t.toString()), d.appendChild(e);\n                            continue\n                        }\n                        if (!(l = /^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/.exec(o))) continue;\n                        if (e = function(e, t, i) {\n                                var r = Zh[e];\n                                if (!r) return null;\n                                const n = s.document.createElement(r);\n                                if (n.dataset.localName = r, (e = ep[e]) && i && (n[e] = i.trim()), t)\n                                    if (a[t]) {\n                                        const s = function(e) {\n                                            let t = \"\";\n                                            for (const i in e) t += ip[i] || i + \":\" + e[i] + \";\";\n                                            return t\n                                        }(a[t]);\n                                        n.setAttribute(\"style\", s)\n                                    } else console.info(`WebVTT: parseContent: Style referenced, but no style defined for '${t}'!`);\n                                return n\n                            }(l[1], l[2], l[3]), !e) continue;\n                        if (u = d, c = e, tp[c.dataset.localName] && tp[c.dataset.localName] !== u.dataset.localName) continue;\n                        n.push(l[1]), d.appendChild(e), d = e\n                    } var u, c;\n                return r\n            }\n        }\n        ru.default = rp;\n        w = e && e.__decorate || function(e, t, i, r) {\n            var n, s = arguments.length,\n                a = s < 3 ? t : null === r ? r = Object.getOwnPropertyDescriptor(t, i) : r;\n            if (\"object\" == typeof Reflect && \"function\" == typeof Reflect.decorate) a = Reflect.decorate(e, t, i, r);\n            else\n                for (var o = e.length - 1; 0 <= o; o--)(n = e[o]) && (a = (s < 3 ? n(a) : 3 < s ? n(t, i, a) : n(t, i)) || a);\n            return 3 < s && a && Object.defineProperty(t, i, a), a\n        };\n        Object.defineProperty(nu, \"__esModule\", {\n            value: !0\n        });\n        const np = t,\n            sp = ru;\n        w = w([function(e) {\n            let t = e;\n            return \"undefined\" != typeof window && null != window.VTTCue && (t = window.VTTCue, t.create = e.create, t.fromJSON = e.fromJSON, t.prototype.toJSON = e.prototype.toJSON), t\n        }], w = class {\n            constructor(e, t, i) {\n                this._id = \"\", this._pauseOnExit = !1, this._region = null, this._vertical = \"\", this._snapToLines = !0, this._line = \"auto\", this._lineAlign = \"start\", this._position = \"auto\", this._positionAlign = \"auto\", this._size = 100, this._align = \"center\", this.hasBeenReset = !1, this._startTime = e, this._endTime = t, this._text = i\n            }\n            get id() {\n                return this._id\n            }\n            set id(e) {\n                this._id = \"\" + e\n            }\n            get pauseOnExit() {\n                return this._pauseOnExit\n            }\n            set pauseOnExit(e) {\n                this._pauseOnExit = !!e\n            }\n            get startTime() {\n                return this._startTime\n            }\n            set startTime(e) {\n                if (\"number\" != typeof e) throw new TypeError(`Start time must be set to a number: ${e}`);\n                this._startTime = e, this.hasBeenReset = !0\n            }\n            get endTime() {\n                return this._endTime\n            }\n            set endTime(e) {\n                if (\"number\" != typeof e) throw new TypeError(`End time must be set to a number: ${e}`);\n                this._endTime = e, this.hasBeenReset = !0\n            }\n            get text() {\n                return this._text\n            }\n            set text(e) {\n                this._text = \"\" + e, this.hasBeenReset = !0\n            }\n            get region() {\n                return this._region\n            }\n            set region(e) {\n                this._region = e, this.hasBeenReset = !0\n            }\n            get vertical() {\n                return this._vertical\n            }\n            set vertical(e) {\n                if (!np.isValidDirectionSetting(e)) throw new SyntaxError(`An invalid or illegal string was specified for vertical: ${e}`);\n                this._vertical = e, this.hasBeenReset = !0\n            }\n            get snapToLines() {\n                return this._snapToLines\n            }\n            set snapToLines(e) {\n                this._snapToLines = !!e, this.hasBeenReset = !0\n            }\n            get line() {\n                return this._line\n            }\n            set line(e) {\n                if (!np.isValidLineAndPositionSetting(e)) throw new SyntaxError(`An invalid number or illegal string was specified for line: ${e}`);\n                this._line = e, this.hasBeenReset = !0\n            }\n            get lineAlign() {\n                return this._lineAlign\n            }\n            set lineAlign(e) {\n                if (!np.isValidLineAlignSetting(e)) throw new SyntaxError(`An invalid or illegal string was specified for lineAlign: ${e}`);\n                this._lineAlign = e, this.hasBeenReset = !0\n            }\n            get position() {\n                return this._position\n            }\n            set position(e) {\n                if (!np.isValidLineAndPositionSetting(e)) throw new Error(`Position must be between 0 and 100 or auto: ${e}`);\n                this._position = e, this.hasBeenReset = !0\n            }\n            get positionAlign() {\n                return this._positionAlign\n            }\n            set positionAlign(e) {\n                if (!np.isValidPositionAlignSetting(e)) throw new SyntaxError(`An invalid or illegal string was specified for positionAlign: ${e}`);\n                this._positionAlign = e, this.hasBeenReset = !0\n            }\n            get size() {\n                return this._size\n            }\n            set size(e) {\n                if (e < 0 || 100 < e) throw new Error(`Size must be between 0 and 100: ${e}`);\n                this._size = e, this.hasBeenReset = !0\n            }\n            get align() {\n                return this._align\n            }\n            set align(e) {\n                if (!np.isValidAlignSetting(e)) throw new SyntaxError(`An invalid or illegal string was specified for align: ${e}`);\n                this._align = e, this.hasBeenReset = !0\n            }\n            getCueAsHTML() {\n                return sp.default.parseContent(window, this, {})\n            }\n            static create(t) {\n                if (!t.hasOwnProperty(\"startTime\") || !t.hasOwnProperty(\"endTime\") || !t.hasOwnProperty(\"text\")) throw new Error(\"You must at least have start time, end time, and text.\");\n                const i = new this(t.startTime, t.endTime, t.text);\n                return Object.keys(t).forEach(e => {\n                    i.hasOwnProperty(e) && (i[e] = t[e])\n                }), i\n            }\n            static fromJSON(e) {\n                return this.create(JSON.parse(e))\n            }\n            toJSON() {\n                const t = {};\n                return Object.keys(this).forEach(e => {\n                    this.hasOwnProperty(e) && \"getCueAsHTML\" !== e && \"hasBeenReset\" !== e && \"displayState\" !== e && (t[e] = this[e])\n                }), t\n            }\n        });\n        nu.VTTCue = w;\n        w = {}, e = e && e.__decorate || function(e, t, i, r) {\n            var n, s = arguments.length,\n                a = s < 3 ? t : null === r ? r = Object.getOwnPropertyDescriptor(t, i) : r;\n            if (\"object\" == typeof Reflect && \"function\" == typeof Reflect.decorate) a = Reflect.decorate(e, t, i, r);\n            else\n                for (var o = e.length - 1; 0 <= o; o--)(n = e[o]) && (a = (s < 3 ? n(a) : 3 < s ? n(t, i, a) : n(t, i)) || a);\n            return 3 < s && a && Object.defineProperty(t, i, a), a\n        };\n        Object.defineProperty(w, \"__esModule\", {\n            value: !0\n        });\n        const ap = t;\n        e = e([function(e) {\n            let t = e;\n            return \"undefined\" != typeof window && null != window.VTTRegion && (t = window.VTTRegion, t.create = e.create, t.fromJSON = e.fromJSON, t.prototype.toJSON = e.prototype.toJSON), t\n        }], e = class {\n            constructor() {\n                this._id = \"\", this._lines = 3, this._regionAnchorX = 0, this._regionAnchorY = 100, this._scroll = \"\", this._viewportAnchorX = 0, this._viewportAnchorY = 100, this._width = 100\n            }\n            get id() {\n                return this._id\n            }\n            set id(e) {\n                if (\"string\" != typeof e) throw new Error(\"ID must be a string.\");\n                this._id = e\n            }\n            get lines() {\n                return this._lines\n            }\n            set lines(e) {\n                if (\"number\" != typeof e) throw new TypeError(\"Lines must be set to a number.\");\n                this._lines = e\n            }\n            get regionAnchorX() {\n                return this._regionAnchorX\n            }\n            set regionAnchorX(e) {\n                if (!ap.isValidPercentValue(e)) throw new TypeError(\"RegionAnchorX must be between 0 and 100.\");\n                this._regionAnchorX = e\n            }\n            get regionAnchorY() {\n                return this._regionAnchorY\n            }\n            set regionAnchorY(e) {\n                if (!ap.isValidPercentValue(e)) throw new TypeError(\"RegionAnchorY must be between 0 and 100.\");\n                this._regionAnchorY = e\n            }\n            get scroll() {\n                return this._scroll\n            }\n            set scroll(e) {\n                if (\"string\" == typeof e) {\n                    e = e.toLowerCase();\n                    if (ap.isValidScrollSetting(e)) return void(this._scroll = e)\n                }\n                throw new SyntaxError(\"An invalid or illegal string was specified.\")\n            }\n            get viewportAnchorX() {\n                return this._viewportAnchorX\n            }\n            set viewportAnchorX(e) {\n                if (!ap.isValidPercentValue(e)) throw new TypeError(\"ViewportAnchorX must be between 0 and 100.\");\n                this._viewportAnchorX = e\n            }\n            get viewportAnchorY() {\n                return this._viewportAnchorY\n            }\n            set viewportAnchorY(e) {\n                if (!ap.isValidPercentValue(e)) throw new TypeError(\"ViewportAnchorY must be between 0 and 100.\");\n                this._viewportAnchorY = e\n            }\n            get width() {\n                return this._width\n            }\n            set width(e) {\n                if (!ap.isValidPercentValue(e)) throw new TypeError(\"Width must be between 0 and 100.\");\n                this._lines = e\n            }\n            toJSON() {\n                const t = {};\n                return Object.keys(this).forEach(e => {\n                    this.hasOwnProperty(e) && (t[e] = this[e])\n                }), t\n            }\n            static create(t) {\n                const i = new this;\n                return Object.keys(t).forEach(e => {\n                    i.hasOwnProperty(e) && (i[e] = t[e])\n                }), i\n            }\n            static fromJSON(e) {\n                return this.create(JSON.parse(e))\n            }\n        });\n        w.VTTRegion = e, Object.defineProperty(iu, \"__esModule\", {\n            value: !0\n        });\n        const op = nu;\n        iu.VTTCue = op.VTTCue;\n        const lp = w;\n        iu.VTTRegion = lp.VTTRegion;\n        const dp = ru;\n        class up extends Error {\n            constructor(e, t) {\n                super(), this.name = \"ParsingError\", this.code = \"number\" == typeof e ? e : e.code, t ? this.message = t : e instanceof up && (this.message = e.message)\n            }\n        }(iu.ParsingError = up).Errors = {\n            BadSignature: new up(0, \"Malformed WebVTT signature.\"),\n            BadTimeStamp: new up(1, \"Malformed time stamp.\")\n        };\n        class cp {\n            constructor() {\n                this.values = {}\n            }\n            set(e, t) {\n                this.get(e) || \"\" === t || (this.values[e] = t)\n            }\n            get(e, t, i) {\n                return \"object\" == typeof t && \"string\" == typeof i ? this.has(e) ? this.values[e] : t[i] : this.has(e) ? this.values[e] : t\n            }\n            has(e) {\n                return e in this.values\n            }\n            alt(t, i, r) {\n                for (let e = 0; e < r.length; ++e)\n                    if (i === r[e]) {\n                        this.set(t, i);\n                        break\n                    }\n            }\n            integer(e, t) {\n                /^-?\\d+$/.test(t) && this.set(e, parseInt(t, 10))\n            }\n            percent(e, t) {\n                if (t.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/)) try {\n                    var i = parseFloat(t);\n                    if (0 <= i && i <= 100) return this.set(e, i), !0\n                } catch (e) {\n                    return !1\n                }\n                return !1\n            }\n        }\n        class hp {\n            constructor(e, t, i) {\n                this.window = e, this.state = \"INITIAL\", this.styleCollector = \"\", this.buffer = \"\", this.decoder = t || new TextDecoder(\"utf8\"), this.regionList = [], this.onStylesParsedCallback = i, this._styles = {}\n            }\n            static StringDecoder() {\n                return {\n                    decode: e => {\n                        if (!e) return \"\";\n                        if (\"string\" != typeof e) throw new Error(\"Error - expected string data.\");\n                        return decodeURIComponent(encodeURIComponent(e))\n                    }\n                }\n            }\n            reportOrThrowError(e) {\n                if (!(e instanceof up && \"function\" == typeof this.onparsingerror)) throw e;\n                this.onparsingerror(e)\n            }\n            parseOptions(e, t, i, r) {\n                e = r ? e.split(r) : [e];\n                for (const n of e)\n                    if (\"string\" == typeof n) {\n                        const r = n.split(i);\n                        2 === r.length && t(r[0], r[1])\n                    }\n            }\n            parseCue(t, e, a) {\n                const i = t,\n                    r = () => {\n                        var e = dp.default.parseTimeStamp(t);\n                        if (null === e) throw new up(up.Errors.BadTimeStamp, \"Malformed timestamp: \" + i);\n                        return t = t.replace(/^[^\\sa-zA-Z-]+/, \"\"), e\n                    },\n                    n = () => {\n                        t = t.replace(/^\\s+/, \"\")\n                    };\n                if (n(), e.startTime = r(), n(), \"--\\x3e\" !== t.substr(0, 3)) throw new up(up.Errors.BadTimeStamp, `Malformed time stamp (time stamps must be separated by '--\\x3e'): ${i}`);\n                t = t.substr(3), n(), e.endTime = r(), n(), ((e, t) => {\n                    const s = new cp;\n                    this.parseOptions(e, (t, i) => {\n                        let e, r;\n                        switch (t) {\n                            case \"region\":\n                                for (let e = a.length - 1; 0 <= e; e--)\n                                    if (a[e].id === i) {\n                                        s.set(t, a[e].region);\n                                        break\n                                    } break;\n                            case \"vertical\":\n                                s.alt(t, i, [\"rl\", \"lr\"]);\n                                break;\n                            case \"line\":\n                                e = i.split(\",\"), r = e[0], s.integer(t, r), s.percent(t, r) && s.set(\"snapToLines\", !1), s.alt(t, r, [\"auto\"]), 2 === e.length && s.alt(\"lineAlign\", e[1], [\"start\", \"center\", \"end\"]);\n                                break;\n                            case \"position\":\n                                e = i.split(\",\"), s.percent(t, e[0]), 2 === e.length && (n = [\"line-left\", \"line-right\", \"center\", \"auto\", \"left\", \"start\", \"middle\", \"end\", \"right\"], s.alt(\"positionAlign\", e[1], n));\n                                break;\n                            case \"size\":\n                                s.percent(t, i);\n                                break;\n                            case \"align\":\n                                var n = [\"start\", \"center\", \"end\", \"left\", \"right\", \"middle\"];\n                                s.alt(t, i, n)\n                        }\n                    }, /:/, /\\s/), t.region = s.get(\"region\", null), t.vertical = s.get(\"vertical\", \"\"), t.line = s.get(\"line\", void 0 === t.line ? \"auto\" : t.line), t.lineAlign = s.get(\"lineAlign\", \"start\"), t.snapToLines = s.get(\"snapToLines\", !0), t.size = s.get(\"size\", 100);\n                    e = s.get(\"align\", \"center\");\n                    t.align = \"middle\" === e ? \"center\" : e, t.position = s.get(\"position\", \"auto\");\n                    e = s.get(\"positionAlign\", {\n                        start: \"start\",\n                        left: \"start\",\n                        center: \"center\",\n                        right: \"end\",\n                        end: \"end\"\n                    }, t.align);\n                    t.positionAlign = {\n                        start: \"start\",\n                        \"line-left\": \"start\",\n                        left: \"start\",\n                        center: \"center\",\n                        middle: \"center\",\n                        \"line-right\": \"end\",\n                        right: \"end\",\n                        end: \"end\"\n                    } [e]\n                })(t, e)\n            }\n            parseRegion(e) {\n                const n = new cp;\n                if (this.parseOptions(e, (e, t) => {\n                        switch (e) {\n                            case \"id\":\n                                n.set(e, t);\n                                break;\n                            case \"width\":\n                                n.percent(e, t);\n                                break;\n                            case \"lines\":\n                                n.integer(e, t);\n                                break;\n                            case \"regionanchor\":\n                            case \"viewportanchor\": {\n                                var i = t.split(\",\");\n                                if (2 !== i.length) break;\n                                const r = new cp;\n                                if (r.percent(\"x\", i[0]), r.percent(\"y\", i[1]), !r.has(\"x\") || !r.has(\"y\")) break;\n                                n.set(e + \"X\", r.get(\"x\")), n.set(e + \"Y\", r.get(\"y\"));\n                                break\n                            }\n                            case \"scroll\":\n                                n.alt(e, t, [\"up\"])\n                        }\n                    }, /=/, /\\s/), n.has(\"id\")) {\n                    const e = new lp.VTTRegion;\n                    e.width = n.get(\"width\", 100), e.lines = n.get(\"lines\", 3), e.regionAnchorX = n.get(\"regionanchorX\", 0), e.regionAnchorY = n.get(\"regionanchorY\", 100), e.viewportAnchorX = n.get(\"viewportanchorX\", 0), e.viewportAnchorY = n.get(\"viewportanchorY\", 100), e.scroll = n.get(\"scroll\", \"\"), this.onregion && this.onregion(e), this.regionList.push({\n                        id: n.get(\"id\"),\n                        region: e\n                    })\n                }\n            }\n            parseStyle(i) {\n                const e = i.split(\"}\");\n                e.pop();\n                for (const i of e) {\n                    let e = null,\n                        t = null;\n                    const r = i.split(\"{\");\n                    r[0] && (e = r[0].trim()), r[1] && (t = (e => {\n                        const t = {},\n                            i = e.split(\";\");\n                        for (let e = 0; e < i.length; e++)\n                            if (i[e].includes(\":\")) {\n                                const r = i[e].split(\":\", 2),\n                                    n = r[0].trim(),\n                                    s = r[1].trim();\n                                \"\" !== n && \"\" !== s && (t[n] = s)\n                            } return t\n                    })(r[1])), e && t && (this._styles[e] = t)\n                }\n                this.onStylesParsedCallback && this.onStylesParsedCallback(this._styles)\n            }\n            parseHeader(e) {\n                this.parseOptions(e, function(e, t) {\n                    \"Region\" === e && this.parseRegion(t)\n                }, /:/)\n            }\n            parse(i) {\n                i && (this.buffer += this.decoder.decode(i, {\n                    stream: !0\n                }));\n                const r = () => {\n                    const e = this.buffer;\n                    let t = 0;\n                    let i = {\n                        start: e.length,\n                        length: 0\n                    };\n                    for (; t < e.length;) {\n                        const r = ((t, i) => {\n                            const r = {\n                                start: -1,\n                                length: -1\n                            };\n                            if (\"\\r\" === t[i]) r.start = i, r.length = 1;\n                            else if (\"\\n\" === t[i]) r.start = i, r.length = 1;\n                            else if (\"<\" === t[i] && i + 1 < t.length && \"b\" === t[i + 1] && i + 2 < t.length && \"r\" === t[i + 2]) {\n                                let e = i + 2;\n                                for (; e < t.length && \">\" !== t[e++];);\n                                r.start = i, r.length = e - i\n                            }\n                            return r\n                        })(e, t);\n                        if (0 < r.length) {\n                            i = r;\n                            break\n                        }++t\n                    }\n                    const r = e.substr(0, i.start);\n                    return this.buffer = e.substr(i.start + i.length), r\n                };\n                try {\n                    let e;\n                    if (\"INITIAL\" === this.state) {\n                        if (!/\\r\\n|\\n/.test(this.buffer)) return this;\n                        e = r();\n                        var n = /^(Ã¯Â»Â¿)?WEBVTT([ \\t].*)?$/.exec(e);\n                        if (!n || !n[0]) throw new up(up.Errors.BadSignature);\n                        this.state = \"HEADER\"\n                    }\n                    let t = !1;\n                    for (; this.buffer;) {\n                        if (!/\\r\\n|\\n/.test(this.buffer)) return this;\n                        switch (t ? t = !1 : e = r(), this.state) {\n                            case \"HEADER\":\n                                e.includes(\":\") ? this.parseHeader(e) : e || (this.state = \"ID\");\n                                continue;\n                            case \"NOTE\":\n                                e || (this.state = \"ID\");\n                                continue;\n                            case \"STYLE\":\n                                e ? this.styleCollector += e : (this.parseStyle(this.styleCollector), this.state = \"ID\", this.styleCollector = \"\");\n                                continue;\n                            case \"ID\":\n                                if (/^NOTE($|[ \\t])/.test(e)) {\n                                    this.state = \"NOTE\";\n                                    break\n                                }\n                                if (/^STYLE($|[ \\t])/.test(e)) {\n                                    this.state = \"STYLE\";\n                                    break\n                                }\n                                if (!e) continue;\n                                if (this.cue = new op.VTTCue(0, 0, \"\"), this.state = \"CUE\", !e.includes(\"--\\x3e\")) {\n                                    this.cue.id = e;\n                                    continue\n                                }\n                            case \"CUE\":\n                                try {\n                                    this.parseCue(e, this.cue, this.regionList)\n                                } catch (i) {\n                                    this.reportOrThrowError(i), this.cue = null, this.state = \"BADCUE\";\n                                    continue\n                                }\n                                this.state = \"CUETEXT\";\n                                continue;\n                            case \"CUETEXT\": {\n                                const r = e.includes(\"--\\x3e\");\n                                if (!e || r) {\n                                    t = !0, this.oncue && this.oncue(this.cue), this.cue = null, this.state = \"ID\";\n                                    continue\n                                }\n                                this.cue.text && (this.cue.text += \"\\n\"), this.cue.text += e;\n                                continue\n                            }\n                            case \"BADCUE\":\n                                e || (this.state = \"ID\");\n                                continue\n                        }\n                    }\n                } catch (i) {\n                    this.reportOrThrowError(i), \"CUETEXT\" === this.state && this.cue && this.oncue && this.oncue(this.cue), this.cue = null, this.state = \"INITIAL\" === this.state ? \"BADWEBVTT\" : \"BADCUE\"\n                }\n                return this\n            }\n            flush() {\n                try {\n                    if (this.buffer += this.decoder.decode(), !this.cue && \"HEADER\" !== this.state || (this.buffer += \"\\n\\n\", this.parse()), \"INITIAL\" === this.state) throw new up(up.Errors.BadSignature)\n                } catch (e) {\n                    this.reportOrThrowError(e)\n                }\n                return this.onflush && this.onflush(), this\n            }\n            styles() {\n                return this._styles\n            }\n        }\n        iu.default = hp, iu.WebVTTParser = hp;\n        var pp, w = {};\n        Object.defineProperty(w, \"__esModule\", {\n            value: !0\n        });\n        const fp = nu;\n        w.VTTCue = fp.VTTCue;\n        const mp = ru,\n            gp = [/^(::cue\\()(\\..*)(\\))/, /^(::cue\\()(#.*)(\\))/, /^(::cue\\()(c|i|b|u|ruby|rt|v|lang)(\\))/],\n            yp = [\n                [1470, 1470],\n                [1472, 1472],\n                [1475, 1475],\n                [1478, 1478],\n                [1488, 1514],\n                [1520, 1524],\n                [1544, 1544],\n                [1547, 1547],\n                [1549, 1549],\n                [1563, 1563],\n                [1566, 1610],\n                [1645, 1647],\n                [1649, 1749],\n                [1765, 1766],\n                [1774, 1775],\n                [1786, 1805],\n                [1807, 1808],\n                [1810, 1839],\n                [1869, 1957],\n                [1969, 1969],\n                [1984, 2026],\n                [2036, 2037],\n                [2042, 2042],\n                [2048, 2069],\n                [2074, 2074],\n                [2084, 2084],\n                [2088, 2088],\n                [2096, 2110],\n                [2112, 2136],\n                [2142, 2142],\n                [2208, 2208],\n                [2210, 2220],\n                [8207, 8207],\n                [64285, 64285],\n                [64287, 64296],\n                [64298, 64310],\n                [64312, 64316],\n                [64318, 64318],\n                [64320, 64321],\n                [64323, 64324],\n                [64326, 64449],\n                [64467, 64829],\n                [64848, 64911],\n                [64914, 64967],\n                [65008, 65020],\n                [65136, 65140],\n                [65142, 65276],\n                [67584, 67589],\n                [67592, 67592],\n                [67594, 67637],\n                [67639, 67640],\n                [67644, 67644],\n                [67647, 67669],\n                [67671, 67679],\n                [67840, 67867],\n                [67872, 67897],\n                [67903, 67903],\n                [67968, 68023],\n                [68030, 68031],\n                [68096, 68096],\n                [68112, 68115],\n                [68117, 68119],\n                [68121, 68147],\n                [68160, 68167],\n                [68176, 68184],\n                [68192, 68223],\n                [68352, 68405],\n                [68416, 68437],\n                [68440, 68466],\n                [68472, 68479],\n                [68608, 68680],\n                [126464, 126467],\n                [126469, 126495],\n                [126497, 126498],\n                [126500, 126500],\n                [126503, 126503],\n                [126505, 126514],\n                [126516, 126519],\n                [126521, 126521],\n                [126523, 126523],\n                [126530, 126530],\n                [126535, 126535],\n                [126537, 126537],\n                [126539, 126539],\n                [126541, 126543],\n                [126545, 126546],\n                [126548, 126548],\n                [126551, 126551],\n                [126553, 126553],\n                [126555, 126555],\n                [126557, 126557],\n                [126559, 126559],\n                [126561, 126562],\n                [126564, 126564],\n                [126567, 126570],\n                [126572, 126578],\n                [126580, 126583],\n                [126585, 126588],\n                [126590, 126590],\n                [126592, 126601],\n                [126603, 126619],\n                [126625, 126627],\n                [126629, 126633],\n                [126635, 126651],\n                [1114109, 1114109]\n            ];\n        class vp {\n            applyStyles(e, t) {\n                t = t || this.div;\n                for (const i in e) e.hasOwnProperty(i) && (t.style[i] = e[i])\n            }\n            formatStyle(e, t) {\n                return 0 === e ? \"0\" : e + t\n            }\n        }\n        w.StyleBox = vp;\n        class Sp extends vp {\n            constructor(e, t, i, r, n) {\n                super();\n                let s = {\n                    textAlign: {\n                        start: \"left\",\n                        \"line-left\": \"left\",\n                        left: \"left\",\n                        center: \"center\",\n                        middle: \"center\",\n                        \"line-right\": \"right\",\n                        right: \"right\",\n                        end: \"right\"\n                    } [(this.cue = t).positionAlign] || t.align,\n                    whiteSpace: \"pre-line\",\n                    position: \"absolute\"\n                };\n                s.direction = this.determineBidi(this.cueDiv), s.writingMode = this.directionSettingToWritingMode(t.vertical), s.unicodeBidi = \"plaintext\", this.div = e.document.createElement(\"div\"), this.applyStyles(s), s = {\n                    backgroundColor: r.backgroundColor,\n                    display: \"inline-block\"\n                }, this.parseOpacity(s.backgroundColor) && (s.padding = \"5px\", s.borderRadius = \"5px\"), this.backgroundDiv = e.document.createElement(\"div\"), this.applyStyles(s, this.backgroundDiv), s = {\n                    color: i.color,\n                    backgroundColor: i.backgroundColor,\n                    textShadow: i.textShadow,\n                    fontSize: i.fontSize,\n                    fontFamily: i.fontFamily,\n                    position: \"relative\",\n                    left: \"0\",\n                    right: \"0\",\n                    top: \"0\",\n                    bottom: \"0\",\n                    display: \"inline-block\",\n                    textOrientation: \"upright\"\n                }, s.writingMode = this.directionSettingToWritingMode(t.vertical), s.unicodeBidi = \"plaintext\", this.cueDiv = mp.default.parseContent(e, t, n), this.applyStyles(s, this.cueDiv), this.backgroundDiv.appendChild(this.cueDiv), this.div.appendChild(this.backgroundDiv);\n                let a = 0;\n                if (\"number\" == typeof t.position) {\n                    n = t.positionAlign || t.align;\n                    if (n) switch (n) {\n                        case \"start\":\n                        case \"left\":\n                            a = t.position;\n                            break;\n                        case \"center\":\n                        case \"middle\":\n                            a = t.position - t.size / 2;\n                            break;\n                        case \"end\":\n                        case \"right\":\n                            a = t.position - t.size\n                    }\n                }\n                \"\" === t.vertical ? this.applyStyles({\n                    left: this.formatStyle(a, \"%\"),\n                    width: this.formatStyle(t.size, \"%\")\n                }) : this.applyStyles({\n                    top: this.formatStyle(a, \"%\"),\n                    height: this.formatStyle(t.size, \"%\")\n                })\n            }\n            determineBidi(e) {\n                let t = [],\n                    i = \"\";\n                if (!e || !e.childNodes) return \"ltr\";\n\n                function n(t, i) {\n                    for (let e = i.childNodes.length - 1; 0 <= e; e--) t.push(i.childNodes[e])\n                }\n                for (n(t, e); i = function e(t) {\n                        if (!t || !t.length) return null;\n                        let i = t.pop(),\n                            r = i.textContent || i.innerText;\n                        if (r) {\n                            const i = /^.*(\\n|\\r)/.exec(r);\n                            return i ? i[t.length = 0] : r\n                        }\n                        return \"ruby\" === i.tagName ? e(t) : i.childNodes ? (n(t, i), e(t)) : void 0\n                    }(t);)\n                    for (let e = 0; e < i.length; e++)\n                        if (function(e, t) {\n                                for (const i of t)\n                                    if (e >= i[0] && e <= i[1]) return 1\n                            }(i.charCodeAt(e), yp)) return \"rtl\";\n                return \"ltr\"\n            }\n            parseOpacity(e) {\n                if (!e || \"string\" != typeof e) return null;\n                e = (e = e.replace(/ /g, \"\").replace(\"rgba(\", \"\").replace(\")\", \"\")).split(\",\");\n                return e && 4 <= e.length ? e[3] : null\n            }\n            directionSettingToWritingMode(e) {\n                return \"\" === e ? \"horizontal-tb\" : \"lr\" === e ? \"vertical-lr\" : \"vertical-rl\"\n            }\n            move(e) {\n                this.applyStyles({\n                    top: this.formatStyle(e.top, \"px\"),\n                    bottom: this.formatStyle(e.bottom, \"px\"),\n                    left: this.formatStyle(e.left, \"px\"),\n                    right: this.formatStyle(e.right, \"px\"),\n                    height: this.formatStyle(e.height, \"px\"),\n                    width: this.formatStyle(e.width, \"px\")\n                })\n            }\n        }\n        w.CueStyleBox = Sp;\n        class bp {\n            constructor(e) {\n                var t;\n                let i, r, n, s, a, o;\n                if (e instanceof Sp && e.cue ? (t = e.cue) && \"\" !== t.vertical ? this.property = \"width\" : this.property = \"height\" : e instanceof bp && (this.property = e.property || \"height\"), e instanceof Sp && e.div) {\n                    n = e.div.offsetHeight, s = e.div.offsetWidth, a = e.div.offsetTop;\n                    const t = e.div.firstChild;\n                    if (o = (t || e.div).getBoundingClientRect(), i = o && o[this.property] || null, t && t.firstChild) {\n                        const e = t.firstChild;\n                        e && \"string\" == typeof e.textContent && (r = i / this.calculateNewLines(e.textContent))\n                    }\n                } else e instanceof bp && (o = e);\n                this.left = o.left, this.right = o.right, this.top = o.top || a, this.height = o.height || n, this.bottom = o.bottom || a + (o.height || n), this.width = o.width || s, this.lineHeight = null !== i ? i : o.lineHeight, this.singleLineHeight = null !== r ? r : o.singleLineHeight, this.singleLineHeight || (this.singleLineHeight = 41)\n            }\n            calculateNewLines(t) {\n                let i = 1;\n                for (let e = 0; e < t.length; e++) \"\\n\" === t[e] && i++;\n                return i\n            }\n            move(e, t) {\n                switch (t = void 0 !== t ? t : this.singleLineHeight, e) {\n                    case \"+x\":\n                        this.left += t, this.right += t;\n                        break;\n                    case \"-x\":\n                        this.left -= t, this.right -= t;\n                        break;\n                    case \"+y\":\n                        this.top += t, this.bottom += t;\n                        break;\n                    case \"-y\":\n                        this.top -= t, this.bottom -= t\n                }\n            }\n            overlaps(e) {\n                return this.left < e.right && this.right > e.left && this.top < e.bottom && this.bottom > e.top\n            }\n            overlapsAny(e) {\n                for (const t of e)\n                    if (this.overlaps(t)) return !0;\n                return !1\n            }\n            within(e) {\n                return this.top >= e.top && this.bottom <= e.bottom && this.left >= e.left && this.right <= e.right\n            }\n            moveIfOutOfBounds(e, t) {\n                switch (t) {\n                    case \"+x\":\n                        this.left < e.left && (this.left = e.left, this.right = this.left + this.width);\n                        break;\n                    case \"-x\":\n                        this.right > e.right && (this.right = e.right, this.left = this.right - this.width);\n                        break;\n                    case \"+y\":\n                        this.top < e.top && (this.top = e.top, this.bottom = this.top + this.height);\n                        break;\n                    case \"-y\":\n                        this.bottom > e.bottom && (this.bottom = e.bottom, this.top = this.bottom - this.height)\n                }\n            }\n            toCSSCompatValues(e) {\n                return {\n                    top: this.top - e.top,\n                    bottom: e.bottom - this.bottom,\n                    left: this.left - e.left,\n                    right: e.right - this.right,\n                    height: this.height,\n                    width: this.width\n                }\n            }\n            static getSimpleBoxPosition(e) {\n                let t = null;\n                e instanceof vp && e.div ? t = e.div : e instanceof HTMLElement && (t = e);\n                let i = t.offsetHeight || 0,\n                    r = t.offsetWidth || 0,\n                    n = t.offsetTop || 0,\n                    s = n + i,\n                    a = t.getBoundingClientRect();\n                var {\n                    left: o,\n                    right: e\n                } = a;\n                return a.top && (n = a.top), a.height && (i = a.height), a.width && (r = a.width), a.bottom && (s = a.bottom), {\n                    left: o,\n                    right: e,\n                    top: n,\n                    height: i,\n                    bottom: s,\n                    width: r\n                }\n            }\n            static getBoxPosition(r, n) {\n                if (r && 0 < r.length) {\n                    let t = 0,\n                        i = r[0][n];\n                    for (let e = 0; e < r.length; e++) n in [\"top\", \"right\"] ? r[e][n] > i && (t = e, i = r[e][n]) : n in [\"bottom\", \"left\"] && r[e][n] < i && (t = e, i = r[e][n]);\n                    return r[t]\n                }\n                return null\n            }\n            static moveToMinimumDistancePlacement(e, t, i) {\n                \"height\" === e.property ? \"+y\" === t ? (e.top = i.topMostBoxPosition.bottom + 0, e.bottom = e.top + e.height) : \"-y\" === t && (e.bottom = +i.bottomMostBoxPosition.top, e.top = e.bottom - e.height) : \"width\" === e.property && (\"+x\" === t ? (e.left = i.rightMostBoxPosition.right + 0, e.right = e.left + e.width) : \"-x\" === t && (e.right = +i.leftMostBoxPosition.left, e.left = e.right - e.width))\n            }\n            static moveBoxToLinePosition(e, a, o) {\n                var n = e.cue;\n                let i, r = new bp(e),\n                    s = function() {\n                        if (\"number\" == typeof n.line && (n.snapToLines || 0 <= n.line && n.line <= 100)) return n.line;\n                        if (!n.track || !n.track.textTrackList || !n.track.textTrackList.mediaElement) return -1;\n                        let t = 0;\n                        var i = n.track,\n                            r = i.textTrackList;\n                        for (let e = 0; e < r.length && r[e] !== i; e++) \"showing\" === r[e].mode && t++;\n                        return -1 * ++t\n                    }(),\n                    l = [];\n                if (n.snapToLines) {\n                    let t = 0;\n                    switch (n.vertical) {\n                        case \"\":\n                            l = [\"+y\", \"-y\"], i = \"height\";\n                            break;\n                        case \"rl\":\n                            l = [\"+x\", \"-x\"], i = \"width\";\n                            break;\n                        case \"lr\":\n                            l = [\"-x\", \"+x\"], i = \"width\"\n                    }\n                    const o = r.lineHeight,\n                        d = a[i] + o,\n                        u = l[0];\n                    if (s < 0) {\n                        let e = 0;\n                        switch (n.vertical) {\n                            case \"\":\n                                e = a.height - o - .05 * a.height;\n                                break;\n                            case \"rl\":\n                            case \"lr\":\n                                e = -a.width + o + .05 * a.width\n                        }\n                        t = e, l = l.reverse()\n                    } else {\n                        switch (n.vertical) {\n                            case \"\":\n                                t = o * Math.round(s);\n                                break;\n                            case \"rl\":\n                                t = a.width - o * Math.round(s);\n                                break;\n                            case \"lr\":\n                                t = o * Math.round(s)\n                        }\n                        Math.abs(t) > d && (t = t < 0 ? -1 : 1, t *= Math.ceil(d / o) * o)\n                    }\n                    r.move(u, t)\n                } else {\n                    const o = \"\" === n.vertical ? a.height : a.width,\n                        i = r.lineHeight / o * 100;\n                    switch (n.lineAlign) {\n                        case \"center\":\n                            s -= i / 2;\n                            break;\n                        case \"end\":\n                            s -= i\n                    }\n                    switch (n.vertical) {\n                        case \"\":\n                            e.applyStyles({\n                                top: e.formatStyle(s, \"%\")\n                            });\n                            break;\n                        case \"rl\":\n                            e.applyStyles({\n                                right: e.formatStyle(s, \"%\")\n                            });\n                            break;\n                        case \"lr\":\n                            e.applyStyles({\n                                left: e.formatStyle(s, \"%\")\n                            })\n                    }\n                    l = [\"+y\", \"-y\", \"+x\", \"-x\"], \"+y\" === n.axis ? l = [\"+y\", \"-y\", \"+x\", \"-x\"] : \"-y\" === n.axis && (l = [\"-y\", \"+y\", \"+x\", \"-x\"]), r = new bp(e)\n                }\n                const d = function(r, n) {\n                    let s;\n                    for (let i = 0; i < n.length; i++) {\n                        r.moveIfOutOfBounds(a, n[i]);\n                        let e = 0,\n                            t = !1;\n                        for (; r.overlapsAny(o) && !(9 < e);) t ? r.move(n[i]) : (o && 0 < o.length && (s = s || {\n                            topMostBoxPosition: bp.getBoxPosition(o, \"top\"),\n                            bottomMostBoxPosition: bp.getBoxPosition(o, \"bottom\"),\n                            leftMostBoxPosition: bp.getBoxPosition(o, \"left\"),\n                            rightMostBoxPosition: bp.getBoxPosition(o, \"right\")\n                        }, bp.moveToMinimumDistancePlacement(r, n[i], s)), t = !0), e++\n                    }\n                    return r\n                }(r, l);\n                e.move(d.toCSSCompatValues(a))\n            }\n        }\n        w.BoxPosition = bp;\n        class Tp {\n            constructor(e, t, i = !0) {\n                if (!e) return null;\n                this.window = e, this.overlay = t, this.loggingEnabled = i, this.foregroundStyleOptions = {\n                    fontFamily: \"Helvetica\",\n                    fontSize: \"36px\",\n                    color: \"rgba(255, 255, 255, 1)\",\n                    textShadow: \"\",\n                    backgroundColor: \"rgba(0, 0, 0, 0)\"\n                }, this.backgroundStyleOptions = {\n                    backgroundColor: \"rgba(0, 0, 0, 0.5)\"\n                }, this.globalStyleCollection = {};\n                const r = e.document.createElement(\"div\");\n                r.style.position = \"absolute\", r.style.left = \"0\", r.style.right = \"0\", r.style.top = \"0\", r.style.bottom = \"0\", r.style.margin = \"1.5%\", this.paddedOverlay = r, t.appendChild(this.paddedOverlay), this.initSubtitleCSS()\n            }\n            initSubtitleCSS() {\n                var e = [new fp.VTTCue(0, 0, \"String to init CSS - Won't be visible to user\")];\n                this.paddedOverlay.style.opacity = \"0\", this.processCues(e), this.processCues([]), this.paddedOverlay.style.opacity = \"1\"\n            }\n            convertCueToDOMTree(e) {\n                return e ? mp.default.parseContent(this.window, e, this.globalStyleCollection) : null\n            }\n            setStyles(i) {\n                function r(e, t, i) {\n                    for (const r in t) t.hasOwnProperty(r) && (!0 === i && void 0 !== e[r] || !1 === i) && (e[r] = t[r])\n                }\n                for (const a in i) {\n                    let t = !1,\n                        e = null;\n                    \"::cue\" === a ? (e = this.foregroundStyleOptions, t = !0) : \"::-webkit-media-text-track-display\" === a && (e = this.backgroundStyleOptions, t = !0);\n                    var n = i[a];\n                    if (!0 === t) r(e, n, t);\n                    else\n                        for (let e = 0; e < gp.length; e++) {\n                            var s = gp[e].exec(a);\n                            if (s && 4 === s.length) {\n                                const i = s[2],\n                                    o = {};\n                                r(o, n, t), this.globalStyleCollection[i] = o\n                            }\n                        }\n                }\n                this.initSubtitleCSS(), this.loggingEnabled && (console.log(\"WebVTTRenderer setStyles foregroundStyleOptions: \" + JSON.stringify(this.foregroundStyleOptions)), console.log(\"WebVTTRenderer setStyles backgroundStyleOptions: \" + JSON.stringify(this.backgroundStyleOptions)), console.log(\"WebVTTRenderer setStyles globalStyleCollection: \" + JSON.stringify(this.globalStyleCollection)))\n            }\n            processCues(r) {\n                if (r) {\n                    for (; this.paddedOverlay.firstChild;) this.paddedOverlay.removeChild(this.paddedOverlay.firstChild);\n                    if (function(t) {\n                            for (let e = 0; e < t.length; e++)\n                                if (t[e].hasBeenReset || !t[e].displayState) return 1\n                        }(r)) {\n                        const n = [],\n                            s = bp.getSimpleBoxPosition(this.paddedOverlay);\n                        1 < r.length && (r = function(t) {\n                            const i = [];\n                            let r = 0;\n                            for (let e = 0; e < t.length; e++) {\n                                var n = t[e];\n                                if (\"number\" != typeof n.line) return t;\n                                r += n.line, i.push(n)\n                            }\n                            return r /= t.length, 50 < r ? (i.forEach(function(e) {\n                                e.axis = \"-y\"\n                            }), i.sort((e, t) => t.line - e.line)) : (i.forEach(function(e) {\n                                e.axis = \"+y\"\n                            }), i.sort((e, t) => e.line - t.line)), i\n                        }(r));\n                        for (let i = 0; i < r.length; i++) {\n                            let e = r[i],\n                                t = new Sp(this.window, e, this.foregroundStyleOptions, this.backgroundStyleOptions, this.globalStyleCollection);\n                            this.paddedOverlay.appendChild(t.div), bp.moveBoxToLinePosition(t, s, n), e.displayState = t.div, n.push(bp.getSimpleBoxPosition(t))\n                        }\n                    } else\n                        for (let e = 0; e < r.length; e++) this.paddedOverlay.appendChild(r[e].displayState)\n                }\n            }\n            setSize(e, t) {\n                e && (this.overlay.style.width = e + \"px\"), t && (this.overlay.style.height = t + \"px\")\n            }\n            getOverlay() {\n                return this.overlay\n            }\n        }\n\n        function Ep(e) {\n            for (var t in e) pp.hasOwnProperty(t) || (pp[t] = e[t])\n        }\n        w.default = Tp, w.WebVTTRenderer = Tp, pp = Yh, Object.defineProperty(pp, \"__esModule\", {\n            value: !0\n        }), Ep(iu), Ep(w);\n\n        function Ip(e, t, i) {\n            return e.substr(i || 0, t.length) === t\n        }\n\n        function wp(e) {\n            let t = 5381,\n                i = e.length;\n            for (; i;) t = 33 * t ^ e.charCodeAt(--i);\n            return (t >>> 0).toString()\n        }\n\n        function Ap(e) {\n            var t = Math.floor(e),\n                i = t + .5,\n                r = t + 1;\n            return i <= e ? r - e <= e - i ? r : i : i - e <= e - t ? i : t\n        }\n\n        function Op(e, t = 0, i = 8589934592) {\n            if (!Number.isFinite(t)) return e;\n            var r = i / 2,\n                n = Math.abs(e - t) % i;\n            return t + (t < e ? -1 : 1) * (r < n ? i - n : -n)\n        }\n        var kp, Cp, Dp, Mp = function(e, t, i, r, n, s, a, o) {\n                const l = O.utf8arrayToStr(new Uint8Array(e)).trim().replace(/\\r\\n|\\n\\r|\\n|\\r/g, \"\\n\").split(\"\\n\"),\n                    d = {\n                        baseTime: Math.floor(9e4 * t.baseTime / t.timescale),\n                        timescale: 9e4\n                    };\n                let u = 0,\n                    c = 0;\n                const h = [];\n                let p = null,\n                    f = !0;\n                const m = new Yh.WebVTTParser(window, Yh.WebVTTParser.StringDecoder(), a);\n                m.oncue = function(e) {\n                    var t = S({\n                        baseTime: Op(Op(u) - d.baseTime, 9e4 * i),\n                        timescale: 9e4\n                    });\n                    e.startTime = Op(e.startTime + t - c, 0, 95443.7176888889), e.endTime = Op(e.endTime + t - c, 0, 95443.7176888889), e.id = wp(Ap(e.startTime).toString()) + wp(Ap(e.endTime - e.startTime).toString()) + wp(e.text), e.text = decodeURIComponent(encodeURIComponent(e.text)), 0 < e.endTime && h.push(e)\n                }, m.onparsingerror = function(e) {\n                    p = e\n                }, m.onflush = function() {\n                    p && s ? s(p) : n(h)\n                }, l.forEach(a => f && Ip(a, \"X-TIMESTAMP-MAP=\") ? (f = !1, void a.substr(16).split(\",\").forEach(e => {\n                    if (Ip(e, \"LOCAL:\")) {\n                        let t;\n                        try {\n                            t = (i = e.substr(6), r = parseInt(i.substr(-3)), n = parseInt(i.substr(-6, 2)), s = parseInt(i.substr(-9, 2)), i = 9 < i.length ? parseInt(i.substr(0, i.indexOf(\":\"))) : 0, ne(r) && ne(n) && ne(s) && ne(i) ? (r += 1e3 * n, r += 6e4 * s, r += 36e5 * i) : -1)\n                        } catch (e) {\n                            t = -1\n                        } - 1 !== t ? c = t / 1e3 : p = new Error(`Malformed X-TIMESTAMP-MAP: ${a}`)\n                    } else Ip(e, \"MPEGTS:\") && (u = parseInt(e.substr(7)));\n                    var i, r, n, s\n                })) : void m.parse(a + \"\\n\")), m.flush()\n            },\n            xp = {\n                newCue: function(e, t, i, r, n) {\n                    let s, a, o, l, d;\n                    var u, c, h = {\n                        foreground: !1,\n                        background: !1,\n                        italics: !1,\n                        underline: !1,\n                        flash: !1,\n                        styleStack: []\n                    };\n                    for ([u, c] of r.rows.entries())\n                        if (a = !0, o = 0, l = \"\", !c.isEmpty()) {\n                            for (let e = 0; e < c.chars.length; e++) c.chars[e].uchar.match(/\\s/) && a ? o++ : (l += this.getFormattedChar(c.chars[e], h), a = !1);\n                            (c.cueStartTime = t) === i && (i += 1e-4), l = l.trim().replace(/<br(?: \\/)?>/gi, \"\\n\"), l += this.closeStyles(h), s = new Yh.VTTCue(t, i, l), 16 <= o ? o-- : o++, d = !navigator.userAgent.match(/Firefox\\//) && 7 < u ? u : u + 1, s.snapToLines = !1, s.line = 10 + 5.33 * d, s.align = \"left\", s.position = this.getPosition(o, n), e.addCue(s)\n                        }\n                },\n                getPosition: function(e, t) {\n                    let i = 1.3333333333333333;\n                    t && t.offsetWidth && t.offsetHeight && 1.6 <= t.offsetWidth / t.offsetHeight && (i = 1.7777777777777777);\n                    let r = 10 + e / 32 * 80,\n                        n = 10,\n                        s = 90;\n                    return 1.7777777777777777 === i && (r = 12.5 + .75 * r, n = 20, s = 80), Math.max(n, Math.min(s, r + (navigator.userAgent.match(/Firefox\\//) ? 50 : 0)))\n                },\n                getRootStyleTag: function(e) {\n                    var t = e[0];\n                    return \"c\" === t ? t : e\n                },\n                closeStyles: function(t) {\n                    let i = \"\";\n                    for (let e = t.styleStack.length - 1; 0 <= e; --e) i += \"</\" + this.getRootStyleTag(t.styleStack[e]) + \">\", t.styleStack.pop();\n                    return i\n                },\n                beginStyleAndBalance: function(e, t) {\n                    let i = \"\";\n                    return \"c\" === t[0] && (i += this.closeStyleAndBalance(e, \"c\")), i += \"<\" + t + \">\", e.styleStack.push(t), i\n                },\n                closeStyleAndBalance: function(t, i) {\n                    var r = t.styleStack.length;\n                    let n = 0,\n                        s = \"\";\n                    for (let e = r - 1; 0 <= e; --e) {\n                        var a = t.styleStack[e],\n                            o = this.getRootStyleTag(a);\n                        if (i[0] === a[0]) {\n                            s += \"</\" + o + \">\", t.styleStack.splice(r - 1 - n);\n                            break\n                        }\n                        \"c\" === o[0] ? (t.background = \"\", t.foreground = \"\", t.flash = !1, s += \"</c>\") : \"u\" === o[0] ? (t.underline = !1, s += \"</u>\") : \"i\" === o[0] && (t.italics = !1, s += \"</i>\"), n++\n                    }\n                    return s\n                },\n                getFormattedChar: function(e, t) {\n                    let i = \"\",\n                        r = e.uchar,\n                        n = \"\";\n                    var s = e.penState.foreground !== t.foreground,\n                        a = e.penState.background !== t.background,\n                        o = e.penState.flash !== t.flash;\n                    return (s || a || o) && (n = \".\" + e.penState.foreground, n += \".bg_\" + e.penState.background, e.penState.flash && o && (n += \".blink\"), e.penState.foreground || e.penState.background || e.penState.blink ? i += this.beginStyleAndBalance(t, \"c\" + n) : i += this.closeStyleAndBalance(t, \"c\"), s && (t.foreground = e.penState.foreground), a && (t.background = e.penState.background), o && (t.flash = e.penState.flash)), e.penState.underline !== t.underline && (i += e.penState.underline ? this.beginStyleAndBalance(t, \"u\") : this.closeStyleAndBalance(t, \"u\"), t.underline = e.penState.underline), e.penState.italics !== t.italics && (i += e.penState.italics ? this.beginStyleAndBalance(t, \"i\") : this.closeStyleAndBalance(t, \"i\"), t.italics = e.penState.italics), i + r\n                }\n            };\n        (w = kp = kp || {}).CloseEnough = \"CloseEnough\", w.TooFar = \"TooFar\", w.Unknown = \"Unknown\";\n        const Pp = e => \"cc1\" === e || \"cc2\" === e;\n\n        function Rp(t) {\n            const i = [];\n            for (let e = 0; e < t.length; e++) {\n                var r = t[e];\n                (\"captions\" === r.kind || \"subtitles\" === r.kind || \"metadata\" === r.kind && r.customTextTrackCueRenderer) && i.push(r)\n            }\n            return i\n        }\n\n        function Lp(e) {\n            if (e && e.cues)\n                for (; 0 < e.cues.length;) e.removeCue(e.cues[0])\n        }\n        class _p extends $t {\n            constructor(e, t, i, r) {\n                super(e => {\n                    const t = Oc(this.hls, this);\n                    if (e.add(t.event(x.INLINE_STYLES_PARSED, this.onInlineStylesParsed).pipe(Vs(() => this.destroy())).subscribe()), e.add(bn(0, this.config.trottleCheckInterval).pipe(La(() => (this.checkReadyToLoadNextSubtitleFragment(), Wu))).subscribe()), this.config.nativeTextTrackChangeHandling)\n                        if (this.mediaSink.textTracks && \"onchange\" in this.mediaSink.textTracks) {\n                            const t = Oc(this.mediaSink.textTracks, this);\n                            e.add(t.event(\"change\", this._onTextTracksChanged).subscribe())\n                        } else e.add(bn(0, 500).pipe(La(() => (this._onTextTracksChanged(), Wu))).subscribe())\n                }), this.config = t, this.hls = i, this.logger = r.child({\n                    name: \"legible\"\n                }), this.mediaSink = e, this.id3Track = e.id3TextTrack, this.enableCaption = !0, this.Cues = xp, this.tracks = [], this.cueRanges = [], this.channelToTrackMap = {}, this.htmlTextTrackMap = new Map, this.lastCueEndTime = 0, this.gotTracks = !1, this.tryAgain$ = new yi(!0), this.needNextSubtitle$ = new yi(!0)\n            }\n            destroy() {\n                Lp(this.textTrack1), Lp(this.textTrack2), this.mediaSink = void 0, this.nativeSubtitleTrackChange$ = void 0\n            }\n            convertCuesIntoSubtitleFragInfo(t) {\n                const i = {};\n                if (null != t && 0 < t.length)\n                    for (let e = 0; e < t.length; e++) {\n                        var r = t[e];\n                        if (ne(r.fragSN)) {\n                            const n = i[r.fragSN];\n                            n ? (n.count++, n.startTime = Math.min(r.startTime, n.startTime), n.endTime = Math.max(r.endTime, n.endTime)) : i[r.fragSN] = {\n                                count: 1,\n                                startTime: r.startTime,\n                                endTime: r.endTime\n                            }\n                        }\n                    }\n                return i\n            }\n            checkReadyToLoadNextSubtitleFragment() {\n                let e = !1;\n                this.mediaSink.mediaQuery.currentTime >= this.lastCueEndTime - this.config.subtitleLeadTime && (e = !0), this.needNextSubtitle$.next(e)\n            }\n            checkReadyToLoadNextSubtitleFragment$(e, t) {\n                return e.mediaSeqNum === (null === (t = t[0]) || void 0 === t ? void 0 : t.mediaSeqNum) ? $i(!0) : (this.checkReadyToLoadNextSubtitleFragment(), this.needNextSubtitle$)\n            }\n            getNextFragment(e, t) {\n                t = t.mediaSeqNum + 1;\n                return t < e.fragments.length ? e.fragments[t - e.startSN] : null\n            }\n            calculateFragInfoMap(e, t, i, r) {\n                var n = this.convertCuesIntoSubtitleFragInfo(t);\n                let s = {\n                        len: 0,\n                        start: e,\n                        end: e\n                    },\n                    a = e,\n                    o = e,\n                    l = null,\n                    d = null;\n                for (const t in n)\n                    if (Object.prototype.hasOwnProperty.call(n, t)) {\n                        var u = Number(t);\n                        if (ne(u)) {\n                            var c = n[u];\n                            if (this.isFragmentCompleteOrEmpty(u, c.count, i))\n                                if (u === r.startSN && e < c.startTime && (a = o = s.start = s.end = e = c.startTime), e >= c.startTime && (a === e || ne(l) && 1 < u - l) && (a = o = c.startTime), e >= c.startTime) o = c.endTime, l = u;\n                                else {\n                                    if (!ne(l) || u - l != 1) {\n                                        d = u;\n                                        break\n                                    }\n                                    o = c.endTime, l = u\n                                }\n                        } else this.logger.warn(`$fragInfoMap has invalid key ${u}`)\n                    } return s = {\n                    len: o - a,\n                    start: a,\n                    end: o\n                }, {\n                    fragInfoMap: n,\n                    bufferInfo: s,\n                    prevFragSN: l,\n                    nextFragSN: d\n                }\n            }\n            findFrags$(t, i) {\n                return this.tryAgain$.pipe(ji(tr), La(() => {\n                    var e = this.findFragmentsForPosition(this.mediaSink.mediaQuery.currentTime, i, t);\n                    return e.foundFrags ? (this.lastCueEndTime = 0, this.needNextSubtitle$.next(!0), $i(e)) : Ii\n                }))\n            }\n            reviewParsedFrag(e, i, r) {\n                var n = e.frag,\n                    s = e.cueRange,\n                    t = i.subtitleBufferInfo,\n                    a = i.subtitleParsedInfo,\n                    o = this.mediaSink.mediaQuery.currentTime,\n                    e = i.foundFrags;\n                let l = !0;\n                if (n.mediaSeqNum === e[0].mediaSeqNum) {\n                    if (!i.timelineEstablished) return kp.TooFar;\n                    if (!s) return this.logger.warn(`[subtitle] 1st frag sn ${n.mediaSeqNum} has no cue; details ${r.fragments.length} frags`), kp.Unknown;\n                    if (s.startTime < o) {\n                        const d = r.fragments,\n                            i = n.mediaSeqNum - r.startSN;\n                        let e = i,\n                            t = s.startTime;\n                        for (; e < d.length && (t += d[e].duration, !(t >= o)); ++e);\n                        l = e - i + 1 <= this.config.earlyFragTolerance\n                    } else if (s.startTime > o && n.mediaSeqNum !== r.startSN) {\n                        const d = s.startTime - o,\n                            i = t.prevFragSN;\n                        l = n.mediaSeqNum === i + 1 && (null === (t = t.fragInfoMap[i]) || void 0 === t ? void 0 : t.count) === (null === (a = a[i]) || void 0 === a ? void 0 : a.count) || d <= this.config.lateTolerance\n                    }\n                }\n                return l ? kp.CloseEnough : kp.TooFar\n            }\n            isFragmentEmpty(e) {\n                return e && !ne(e.startTime) && 0 === e.count\n            }\n            isFragmentCompleteOrEmpty(e, t, i) {\n                e = i ? i[e] : null;\n                return (null == e ? void 0 : e.count) === t || this.isFragmentEmpty(e)\n            }\n            getEarlierFragmentInSameDisco(e, t, i) {\n                var r = t.mediaSeqNum - e.startSN - 1;\n                if (r < 0 || r > e.fragments.length - 1) return this.logger.error(`[subtitle] getEarlierFragmentInSameDisco index ${r} out of range`), t;\n                r = e.fragments[r];\n                return r && r.discoSeqNum === t.discoSeqNum && !i[t.mediaSeqNum] ? r : t\n            }\n            inferSubtitleFragmentForPosition(i, r, t, n, s) {\n                let a, o, e, l, d;\n                if (ne(n.prevFragSN) && (o = n.prevFragSN - s.startSN, e = t[n.prevFragSN]), ne(n.nextFragSN) && (l = n.nextFragSN - s.startSN, d = t[n.nextFragSN]), ne(o) && 0 <= o && o < s.fragments.length && e) {\n                    let t = e.startTime;\n                    const n = ne(l) ? l : s.fragments.length;\n                    for (let e = o; e < n; ++e) {\n                        const l = s.fragments[e];\n                        if (!ne(r) || l.discoSeqNum === r) {\n                            if (e === n - 1) {\n                                a = {\n                                    foundFrag: l,\n                                    timelineEstablished: !0\n                                };\n                                break\n                            }\n                            if (t + l.duration > i && e > o) {\n                                a = {\n                                    foundFrag: l,\n                                    timelineEstablished: !0\n                                };\n                                break\n                            }\n                            t += l.duration\n                        }\n                    }\n                } else if (ne(l) && 0 <= l && l < s.fragments.length && d) {\n                    let t = d.startTime;\n                    for (let e = l - 1; 0 <= e; --e) {\n                        const o = s.fragments[e];\n                        if (!ne(r) || o.discoSeqNum === r) {\n                            if (t <= i) {\n                                a = {\n                                    foundFrag: o,\n                                    timelineEstablished: !0\n                                };\n                                break\n                            }\n                            t -= o.duration\n                        }\n                    }\n                } else\n                    for (let e = 0; e < s.fragments.length; ++e) {\n                        const t = s.fragments[e];\n                        if (ne(r) && t.discoSeqNum === r) {\n                            a = {\n                                foundFrag: t,\n                                timelineEstablished: !1\n                            };\n                            break\n                        }\n                    }\n                return a\n            }\n            generateFragmentBatch(t, i, e, r, n, s) {\n                var a;\n                const o = [],\n                    l = null == e ? void 0 : e.foundFrag;\n                if (!l) return {\n                    foundFrags: void 0,\n                    subtitleParsedInfo: void 0,\n                    subtitleBufferInfo: void 0,\n                    timelineEstablished: null == e ? void 0 : e.timelineEstablished\n                };\n                for (let e = l ? l.mediaSeqNum - s.startSN : s.fragments.length; e < s.fragments.length && o.length < t; ++e) {\n                    const t = s.fragments[e];\n                    if (t.discoSeqNum === i) {\n                        const l = null === (a = n.fragInfoMap[t.mediaSeqNum]) || void 0 === a ? void 0 : a.count;\n                        this.isFragmentCompleteOrEmpty(t.mediaSeqNum, null != l ? l : 0, r) || o.push(t)\n                    }\n                }\n                return {\n                    foundFrags: o,\n                    subtitleParsedInfo: r,\n                    subtitleBufferInfo: n,\n                    timelineEstablished: null == e ? void 0 : e.timelineEstablished\n                }\n            }\n            findFragmentsForPosition(e, t, i) {\n                var r = this.mediaSink.mediaQuery.getParsedSubtitleRecordsForMediaOption(this.selectedTrack.persistentID),\n                    n = this.getCuesOfEnabledTrack(this.selectedMediaOption.mediaOptionId, !1),\n                    s = this.calculateFragInfoMap(e, n, r, i),\n                    n = s.bufferInfo,\n                    n = Math.max(e, n.end),\n                    n = this.inferSubtitleFragmentForPosition(n, t, r, s, i);\n                return this.generateFragmentBatch(1 / 0, t, n, r, s, i)\n            }\n            get selectedMediaOption() {\n                return this.selectedTrack || this._disabledMediaOption\n            }\n            set selectedMediaOption(e) {\n                this.selectedTrack = \"groupId\" in e ? e : void 0\n            }\n            get selectedTrack() {\n                return this._selectedMediaOption\n            }\n            set selectedTrack(e) {\n                e !== this._selectedMediaOption && (this._selectedMediaOption = e, this.updateTextTrackState())\n            }\n            getTrack(t) {\n                return this._availableMediaOptions.find(e => e.mediaOptionId === t)\n            }\n            updateTextTrackState() {\n                if (this.mediaSink.textTracks) {\n                    const i = this.selectedTrack ? this.getExistingHTMLTextTrack(this.selectedTrack) : void 0,\n                        r = Rp(this.mediaSink.textTracks);\n                    for (let e = 0; e < r.length; e++) {\n                        var t = r[e];\n                        t === i && \"showing\" !== r[e].mode ? r[e].mode = \"showing\" : t !== i && \"hidden\" !== r[e].mode && (r[e].mode = \"hidden\")\n                    }\n                }\n            }\n            mapHTMLTextTrackIndexToMediaOptionId(e) {\n                const i = this.mediaSink.textTracks[e];\n                let r;\n                return this.htmlTextTrackMap.forEach((e, t) => {\n                    i === e && (r = t)\n                }), r\n            }\n            get mediaSelectionOptions() {\n                return this._availableMediaOptions\n            }\n            _makeDisableOption(e) {\n                return {\n                    itemId: e.itemId,\n                    mediaOptionType: e.mediaOptionType,\n                    mediaOptionId: \"Nah\"\n                }\n            }\n            _onTextTracksChanged() {\n                if (this.mediaSink) {\n                    let t, i = !1;\n                    const r = Rp(this.mediaSink.textTracks);\n                    for (let e = 0; e < r.length; e++) r[e].seen ? \"showing\" === r[e].mode && (t = r[e].persistentId) : (r[e].seen = !0, i = !0);\n                    if (!i) {\n                        const e = this.selectedTrack;\n                        if ((null == e ? void 0 : e.persistentID) !== t) {\n                            const e = this.mediaSelectionOptions.find(function(e) {\n                                return e.persistentID === t\n                            });\n                            this.nativeSubtitleTrackChange$.next(e || this._disabledMediaOption)\n                        }\n                    }\n                }\n            }\n            addCues(e, t, i, r) {\n                const n = this.cueRanges;\n                let s = !1;\n                for (let e = n.length; e--;) {\n                    const r = n[e],\n                        d = (a = r[0], o = r[1], l = t, Math.min(o, i) - Math.max(a, l));\n                    if (0 <= d && (r[0] = Math.min(r[0], t), r[1] = Math.max(r[1], i), s = !0, .5 < d / (i - t))) return\n                }\n                var a, o, l;\n                s || n.push([t, i]), this.Cues.newCue(this.channelToTrackMap[e], t, i, r, this.mediaSink)\n            }\n            getExistingHTMLTextTrackWithChannelNumber(t) {\n                var i = this.mediaSink;\n                if (i)\n                    for (let e = 0; e < i.textTracks.length; e++) {\n                        var r = i.textTracks[e],\n                            n = \"cc\" + t;\n                        if (Pp(n) && !0 === r[n]) return r\n                    }\n                return null\n            }\n            sendAddTrackEvent(e, t) {\n                let i = null;\n                try {\n                    i = new window.Event(\"addtrack\")\n                } catch (e) {\n                    i = document.createEvent(\"Event\"), i.initEvent(\"addtrack\", !1, !1)\n                }\n                i.track = e, t.dispatchEvent(i)\n            }\n            createHTMLCaptionsTrackGuts(e, t, i, r) {\n                var n = \"cc\" + e;\n                if (!this.channelToTrackMap[n]) {\n                    e = this.getExistingHTMLTextTrackWithChannelNumber(e);\n                    if (e) this.channelToTrackMap[n] = e, Lp(this.channelToTrackMap[n]), this.sendAddTrackEvent(this.channelToTrackMap[n], this.mediaSink);\n                    else {\n                        const s = this.createHTMLTextTrackGuts(\"captions\", t, i, r);\n                        s && Pp(n) && (s[n] = !0, this.channelToTrackMap[n] = s)\n                    }\n                }\n                return this.channelToTrackMap[n]\n            }\n            createHTMLCaptionsTrack(e) {\n                return this.createHTMLCaptionsTrackGuts(e, this.config[1 === e ? \"captionsTextTrack1Label\" : \"captionsTextTrack2Label\"], this.config.captionsTextTrack1LanguageCode, !1)\n            }\n            getExistingHTMLTextTrack(e) {\n                return this.config.condenseSubtitleTrack ? this.htmlTextTrackMap.get(e.persistentID) : this.htmlTextTrackMap.get(e.id)\n            }\n            getExistingHTMLTextTrackWithSubtitleTrackId(t) {\n                var e = this._availableMediaOptions.find(e => e.id === t);\n                return e ? this.getExistingHTMLTextTrack(e) : void 0\n            }\n            getExistingHTMLTextTrackIndex(e) {\n                var t = this.getExistingHTMLTextTrack(e),\n                    i = this.mediaSink.textTracks;\n                let r = -1;\n                for (let e = 0; e < i.length; ++e)\n                    if (i[e] === t) {\n                        r = e;\n                        break\n                    } return r\n            }\n            setExistingHTMLTextTrack(e, t) {\n                return t.persistentId = e.persistentID, this.config.condenseSubtitleTrack ? this.htmlTextTrackMap.set(e.persistentID, t) : this.htmlTextTrackMap.set(e.id, t)\n            }\n            createHTMLTextTrack(t) {\n                let i = this.getExistingHTMLTextTrack(t);\n                if (i) this.tracksReused += 1;\n                else {\n                    if (\"sbtl\" === t.mediaType) this.subtitleTracksCreated += 1, i = this.createHTMLTextTrackGuts(\"subtitles\", t.name, t.lang, t.forced);\n                    else {\n                        let e = 1;\n                        t.inStreamID && (e = Number(t.inStreamID.substring(2))), this.captionTracksCreated += 1, i = this.createHTMLCaptionsTrackGuts(e, t.name, t.lang, !1)\n                    }\n                    i ? this.setExistingHTMLTextTrack(t, i) : (this.logger.error(`failed to create HTML text track for track ${t.id}: persistent id ${t.persistentID} name ${t.name} lang ${t.lang} inStreamID ${t.inStreamID}`), this.tracksFailed += 1)\n                }\n                return i\n            }\n            createHTMLTextTrackGuts(t, i, r, e) {\n                const n = this.mediaSink;\n                if (n) {\n                    let e = !1;\n                    \"metadata\" !== t && this.config.customTextTrackCueRenderer && (e = !0, t = \"metadata\");\n                    const s = n.addTextTrack(t, i, r);\n                    return e && (s.customTextTrackCueRenderer = !0), s\n                }\n            }\n            resetLoadSource() {\n                this.resetTracks()\n            }\n            resetTracks() {\n                this._cleanTracks(), this.cueRanges = []\n            }\n            _cleanTracks() {\n                var e = this.mediaSink;\n                if (e) {\n                    var t = e.textTracks;\n                    if (t)\n                        for (let e = 0; e < t.length; e++) Lp(t[e])\n                }\n            }\n            getCuesOfEnabledTrack(e, t = !1) {\n                let i = [];\n                if (t) {\n                    const t = this._getCuesOfEnabledTrack(e);\n                    for (let e = 0; e < t.length; e++) {\n                        var r = t[e];\n                        Boolean(r.webVTTCue) && i.push(r)\n                    }\n                } else i = this._getCuesOfEnabledTrack(e);\n                return i\n            }\n            _getCuesOfEnabledTrack(e) {\n                e = this.getTrack(e), e = this.config.condenseSubtitleTrack ? null == e ? void 0 : e.persistentID : null == e ? void 0 : e.id, e = this.htmlTextTrackMap.get(e);\n                return e && e.cues ? Array.from(e.cues) : []\n            }\n            attachSubtitleTracks() {\n                this.gotTracks && (this.subtitleTracksCreated = 0, this.captionTracksCreated = 0, this.tracksReused = 0, this.tracksFailed = 0, this.tracks.forEach(e => {\n                    this.createHTMLTextTrack(e)\n                }))\n            }\n            setTracks(e, t, i) {\n                this._cleanTracks(), this.htmlTextTrackMap = new Map, this.cueRanges = [], this.config.enableWebVTT && (this.tracks = e || []), this.gotTracks = !0, this._availableMediaOptions = e, this._disabledMediaOption = i, this.attachSubtitleTracks(), this.selectedTrack = t, this.nativeSubtitleTrackChange$ = new Xt, this.mediaSink.textTracksCreated = !0\n            }\n            onInlineStylesParsed(e) {}\n            processSubtitleFrag(e, t, i, r) {\n                var n = new Uint8Array(r),\n                    e = this.getExistingHTMLTextTrackIndex(e);\n                if (t && r.byteLength) {\n                    const s = this._parseVTTs(e, t, i, n);\n                    return s && ne(s.startTime) && (this.lastCueEndTime = Math.max(this.lastCueEndTime, s.endTime)), s\n                }\n            }\n            _parseVTTs(r, n, e, t) {\n                let s;\n                return Mp(t, e, n.start, n.discoSeqNum, e => {\n                    const t = this.mediaSink.textTracks[r],\n                        i = {\n                            count: 0,\n                            startTime: Number.POSITIVE_INFINITY,\n                            endTime: 0\n                        };\n                    e.map(e => {\n                        !t || t.cues && t.cues.getCueById(e.id) || (e.fragSN = n.mediaSeqNum, e.webVTTCue = !0, t.addCue(e), i.count++), i.startTime = Math.min(e.startTime, i.startTime), i.endTime = Math.max(e.endTime, i.endTime)\n                    }), s = i, this.mediaSink.archiveParsedSubtitleFragmentRecord(this.selectedTrack.persistentID, n.mediaSeqNum, i)\n                }, e => {}, e => {\n                    this.hls.trigger(x.INLINE_STYLES_PARSED, {\n                        styles: e\n                    })\n                }, this.logger), s\n            }\n            _ensureParser() {\n                var e, t;\n                this.cea608Parser || (e = new Xh(this, 1), t = new Xh(this, 2), this.cea608Parser = new zh(0, e, t))\n            }\n            setupForFrag(e) {\n                e && e.mediaOptionType === gu.Variant && !e.iframe && ((e = e.mediaSeqNum) !== this.lastVariantSeqNum + 1 && this.resetClosedCaptionParser(), this.lastVariantSeqNum = e)\n            }\n            resetClosedCaptionParser() {\n                var e;\n                null === (e = this.cea608Parser) || void 0 === e || e.reset()\n            }\n            addLegibleSamples(e, t, i, r) {\n                t && this.addClosedCaptionSamples(e, t), i && 0 < i.length && this.addId3Samples(e, i, S(r))\n            }\n            addClosedCaptionSamples(e, t) {\n                t.mp4 ? this.addMP4CaptionSamples(e, t.mp4) : t.ts && this.addTSCaptionSamples(e, t.ts)\n            }\n            addMP4CaptionSamples(e, i) {\n                if (this.enableCaption && this.config.enableCEA708Captions) {\n                    var r = S(e);\n                    this._ensureParser();\n                    for (let e = 0; e < i.length; e++) {\n                        let t = i[e].pts - r;\n                        var n = i[e].bytes;\n                        for (let e = 0; e < n.length; e += 2) {\n                            const i = [];\n                            i.push(n[e]), e + 1 < n.length ? i.push(n[e + 1]) : i.push(80), this.cea608Parser.addData(t, i), t += .03336666666666667\n                        }\n                    }\n                }\n            }\n            addTSCaptionSamples(e, t) {\n                if (this.enableCaption && this.config.enableCEA708Captions) {\n                    var i = S(e);\n                    this._ensureParser();\n                    for (let e = 0; e < t.length; e++) {\n                        var r = t[e].pts - i,\n                            n = _p.extractCea608Data(t[e].bytes);\n                        this.cea608Parser.addData(r, n)\n                    }\n                }\n            }\n            addId3Samples(e, t, r) {\n                if (this.config.enableID3Cues) {\n                    const n = window.WebKitDataCue || window.VTTCue || window.TextTrackCue,\n                        s = S(e);\n                    for (let e = 0; e < t.length; e++) {\n                        const a = t[e].pts - s;\n                        let i = (e < t.length - 1 ? t[e + 1].pts : r) - s;\n                        a === i && (i += 1e-4), t[e].frames && t[e].frames.forEach(e => {\n                            if (e && !this.id3shouldIgnore(e)) {\n                                const t = new n(a, i, \"\");\n                                t.value = e, this.id3Track.addCue(t)\n                            }\n                        })\n                    }\n                }\n            }\n            id3shouldIgnore(e) {\n                return \"PRIV\" === e.key && (\"com.apple.streaming.transportStreamTimestamp\" === e.info || \"com.apple.streaming.audioDescription\" === e.info)\n            }\n            static extractCea608Data(t) {\n                var i = 31 & t[0];\n                let r, n, s, a = 2;\n                const o = [];\n                for (let e = 0; e < i; e++) r = t[a++], n = 127 & t[a++], s = 127 & t[a++], 0 == n && 0 == s || 0 != (4 & r) && 0 == (3 & r) && (o.push(n), o.push(s));\n                return o\n            }\n        }\n        const Np = {\n            name: \"plist\"\n        };\n        class Fp {\n            constructor(e, t, i, r) {\n                this.config = e, this.xhrLoader = t, this.customUrlLoader = i, this.sessionDataCheckForCompleteness = e => {\n                    const t = this.config[\"sessionDataAutoLoad\"],\n                        i = Object.assign({}, e);\n                    return e.complete || (e.itemList ? i.complete = e.itemList.every(e => t[e[\"DATA-ID\"]] && !e.VALUE && !e._STATUS && e.URI ? (this.logger.warn(`Incomplete because ${e[\"DATA-ID\"]} was autoloaded but no response yet`), !1) : (t[e[\"DATA-ID\"]] && !e.URI && this.logger.warn(`id=${e[\"DATA-ID\"]} missing uri`), !0)) : this.logger.warn(\"Uninitialized SessionData\")), i\n                }, this.logger = r.child({\n                    name: \"SessionDataLoader\"\n                })\n            }\n            loadSessionData(r) {\n                const n = this.config[\"sessionDataAutoLoad\"],\n                    t = r.itemList || [];\n                let s = $i(r);\n                return t.forEach(e => {\n                    const i = e[\"DATA-ID\"],\n                        t = e.URI;\n                    if (t && n[i]) {\n                        const n = bu.buildAbsoluteURL(r.baseUrl, t, {\n                                alwaysNormalize: !0\n                            }),\n                            e = \"\";\n                        s = s.pipe(La(t => this.loadSessionDataItemWithUrl(n, i, \"\", this.config, t, this.xhrLoader, this.customUrlLoader).pipe(Vn(e => (this.logger.error(`Error loading SessionData > url=${n}, id=${i}, err=${e}`), $i(t))))))\n                    }\n                }), s.pipe(hr(e => {\n                    if (t.length < 1) return e;\n                    e = this.sessionDataCheckForCompleteness(e);\n                    if (e.complete) return e;\n                    throw new V(!1, \"Session data not complete after loading all items\", $.IncompleteSessionData)\n                }), Vs(() => {}))\n            }\n            loadSessionDataItemWithUrl(e, t, i, r, n, s, a) {\n                const o = Qe(),\n                    l = {\n                        url: e,\n                        method: \"GET\",\n                        responseType: i,\n                        xhrSetup: r.xhrSetup,\n                        mimeType: \"application/xml\"\n                    },\n                    d = Lc({\n                        url: e\n                    }, r.fragLoadPolicy);\n                let u;\n                return u = Tu(e) ? a(l, d).pipe(hr(e => this.onLoadSuccess(n, t, e.data.response.data.toString(), e.data.response.data))) : s(l, d).pipe(hr(([e]) => this.onLoadSuccess(n, t, e.response, e.responseXML))), u.pipe(Vn(e => (e instanceof dr ? e = new cc(!1, e.message, 0, $.SessionDataLoadTimeout) : e instanceof oc && (e = new cc(!1, e.message, e.code, {\n                    code: e.code,\n                    text: \"Failed to load SessionData\"\n                })), o.error(`Unable to load SessionData > err=${e}`), $i(this.onLoadError(n, t, e)))))\n            }\n            onLoadSuccess(e, t, i, r) {\n                let n = null,\n                    s = e;\n                if (function(e) {\n                        const t = /[\\s]*<\\?xml/i;\n                        t.lastIndex = 0;\n                        var i = t.exec(e);\n                        return i || /[\\s]*<plist/i.exec(e)\n                    }(i) && (n = r)) {\n                    const i = function n(e) {\n                        if (!e) return null;\n                        const t = Qe();\n                        let s = null;\n                        var a = e.childNodes;\n                        if (a)\n                            if (e.tagName) {\n                                var i = null === (i = e.tagName) || void 0 === i ? void 0 : i.toLowerCase();\n                                if (\"plist\" === i) {\n                                    s = [];\n                                    for (let e = 0; e < a.length; ++e) {\n                                        const r = a[e];\n                                        r.tagName && s.push(n(r))\n                                    }\n                                    1 === s.length && (s = s[0])\n                                }\n                                if (\"array\" === i) {\n                                    s = [];\n                                    for (let e = 0; e < a.length; ++e) {\n                                        const r = a[e];\n                                        r.tagName && s.push(n(r))\n                                    }\n                                }\n                                if (\"dict\" === i) {\n                                    let t, i, r = 0;\n                                    s = {};\n                                    for (let e = 0; e < a.length; e++) {\n                                        var o = a[e],\n                                            l = null === (l = o.tagName) || void 0 === l ? void 0 : l.toLowerCase();\n                                        l && (r % 2 == 0 ? \"key\" === l && (t = n(o), r++) : (i = n(o), s[t] = i, t = null, i = null, r++))\n                                    }\n                                    t && (s[t] = i, t = null, i = null)\n                                } else if (\"key\" === i) {\n                                    const e = a[0];\n                                    s = e ? e.nodeValue : (t.warn(Np, \"Invalid dict key: Key is null, probably like this: <key/>\"), null)\n                                } else if (\"string\" === i) {\n                                    const e = a[0];\n                                    s = e ? e.nodeValue : null\n                                } else if (\"integer\" === i) {\n                                    const e = a[0];\n                                    s = e ? parseInt(e.nodeValue) : 0\n                                } else if (\"float\" === i) {\n                                    const e = a[0];\n                                    s = e ? parseFloat(e.nodeValue) : 0\n                                } else if (\"date\" === i) {\n                                    const e = a[0];\n                                    s = e ? new Date(e.nodeValue) : null\n                                } else if (\"data\" === i) {\n                                    const e = a[0];\n                                    s = e ? atob(e.nodeValue) : null\n                                } else \"true\" === i ? s = !0 : \"false\" === i && (s = !1)\n                            } else if (a.length < 1) t.warn(Np, `unknown node with unknown value > nodeType=${e.nodeType} tagName=${e.tagName} nodeName=${e.nodeName} value=${e.nodeValue}`);\n                        else {\n                            s = [];\n                            for (let e = 0; e < a.length; ++e) {\n                                const r = a[e];\n                                r.tagName && s.push(n(r))\n                            }\n                            1 === s.length && (s = s[0])\n                        }\n                        return s\n                    }(n);\n                    s = this.setSessionData(e, t, \"VALUE\", i)\n                } else if (function(e) {\n                        const t = /[\\s]*[\\{\\[]/;\n                        return t.lastIndex = 0, t.exec(e)\n                    }(i)) try {\n                    const r = JSON.parse(i);\n                    s = this.setSessionData(e, t, \"VALUE\", r)\n                } catch (r) {\n                    this.logger.error(`JSON parser error: ${r}`), s = this.setSessionData(e, t, \"VALUE\", i), s = this.setSessionData(s, t, \"_STATUS\", -1)\n                } else s = this.setSessionData(e, t, \"VALUE\", i);\n                return s\n            }\n            setSessionData(t, i, r, n) {\n                let s = t;\n                if (t.itemList) {\n                    let e;\n                    const a = [...t.itemList];\n                    for (e = 0; e < t.itemList.length; ++e) {\n                        const t = Object.assign({}, a[e]);\n                        if (t[\"DATA-ID\"] === i) {\n                            t[r] = n, a[e] = t;\n                            break\n                        }\n                    }\n                    e === t.itemList.length && this.logger.error(`Can't set ${r} of session data ${i}`), s = Object.assign(Object.assign({}, t), {\n                        itemList: a\n                    })\n                } else this.logger.error(`Can't set ${r} on uninitialized session data`);\n                return s\n            }\n            onLoadError(e, t, i) {\n                return this.setSessionData(e, t, \"_STATUS\", null === (i = i.response) || void 0 === i ? void 0 : i.code)\n            }\n        }\n\n        function Bp(e, t) {\n            let i, r = 0;\n            for (const a of e)\n                if (a.start <= t.endPTS && a.end > t.startPTS) {\n                    const e = (n = t, s = a, Math.min(n.endPTS, s.end) - Math.max(n.startPTS, s.start));\n                    e > r && (i = a, r = e)\n                } else if (0 < r) break;\n            var n, s;\n            return i\n        }\n\n        function Up(e) {\n            return null != e && \"iframeMediaDuration\" in e && \"iframeMediaStart\" in e\n        }\n\n        function $p(e, t) {\n            return e === t || e && t && e.itemId === t.itemId && e.mediaOptionId === t.mediaOptionId && e.mediaSeqNum === t.mediaSeqNum && e.discoSeqNum === t.discoSeqNum\n        }\n\n        function Vp(e) {\n            return JSON.stringify(e, [\"mediaOptionId\", \"mediaSeqNum\", \"discoSeqNum\", \"start\", \"duration\"])\n        }\n\n        function Kp() {\n            return e => e.pipe(ln(e => null != e), hr(e => e))\n        }\n\n        function qp(e) {\n            return be.isDolby(e) ? hu.DOVI : be.isHEVC(e) ? hu.HEVC : be.isVP09(e) ? hu.VP09 : be.isAVC(e) ? hu.AVC : hu.UNKNOWN\n        }\n\n        function Hp(e) {\n            return null == e ? void 0 : e.split(\".\")[0]\n        }\n\n        function jp(e) {\n            return be.isALAC(e) ? fu.ALAC : be.isFLAC(e) ? fu.FLAC : be.isEC3(e) ? fu.EC3 : be.isAC3(e) ? fu.AC3 : be.isXHEAAC(e) ? fu.XHEAAC : be.isAAC(e) ? fu.AAC : be.isMP3(e) ? fu.MP3 : fu.UNKNOWN\n        }\n        class Qp {\n            constructor(...e) {\n                this.identifier = e\n            }\n            ensureSameIdentifierLength(e) {\n                if (this.identifier.length !== e.identifier.length) throw new Error(`Identifiers have non-matching lengths! (${this.identifier.length} vs ${e.identifier.length})`)\n            }\n            isGreaterThan(t) {\n                this.ensureSameIdentifierLength(t);\n                for (let e = 0; e < this.identifier.length; ++e) {\n                    if (this.identifier[e] < t.identifier[e]) return !1;\n                    if (this.identifier[e] > t.identifier[e]) return !0\n                }\n                return !1\n            }\n            isEqualTo(i) {\n                return this.ensureSameIdentifierLength(i), this.identifier.every((e, t) => e === i.identifier[t])\n            }\n        }\n\n        function Wp(e) {\n            return ne(e) && 0 !== e && 1 !== e\n        }\n        class Gp extends Error {}\n        class zp {\n            constructor(e) {\n                this.value = e, this.waiters = [], this.wcounter = 0, this.rcounter = 0\n            }\n            lock(e, t = !1) {\n                return this._lock(!0, e, t)\n            }\n            unlock() {\n                this._unlock(!0)\n            }\n            readLock(e, t = !1) {\n                return this._lock(!1, e, t)\n            }\n            readUnlock() {\n                this._unlock(!1)\n            }\n            _schedule() {\n                const t = [];\n                this.waiters = this.waiters.filter(e => !this._canLock(e.rw) || (e.rw ? ++this.wcounter : ++this.rcounter, t.push(e), !1));\n                for (const e of t) e.observer.next(this.value), e.observer.complete()\n            }\n            _canLock(e) {\n                return e && 0 === this.wcounter && 0 === this.rcounter || !e && 0 === this.wcounter\n            }\n            _lock(i, e, r = !1) {\n                \"boolean\" == typeof e && ([r, e] = [e, void 0]);\n                const t = new $t(e => {\n                    var t = this._canLock(i);\n                    if (r && !t) throw new Gp;\n                    t ? (i ? ++this.wcounter : ++this.rcounter, e.next(), e.complete()) : this.waiters.push({\n                        rw: i,\n                        observer: e\n                    })\n                });\n                return e ? t.pipe(jr(() => ((e, t, i, r) => {\n                    if (!r) return $i(e);\n                    let n, s;\n                    try {\n                        n = r(e, t)\n                    } catch (e) {\n                        s = Vi(() => e)\n                    }\n                    return s = s || (void 0 === n ? $i(e) : Fr(n)), s.pipe(Vs(i))\n                })(this.value, e => {\n                    this.value = e\n                }, () => this._unlock(i), e))) : t\n            }\n            _unlock(e) {\n                e ? this.wcounter = Math.max(this.wcounter - 1, 0) : this.rcounter = Math.max(this.rcounter - 1, 0), this._schedule()\n            }\n        }\n        class Xp extends $t {\n            constructor() {\n                super(e => this._count$.pipe(ln(e => 0 === e), Ds(1), Zs(void 0)).subscribe(e)), this._count$ = new yi(0)\n            }\n            wrap(e) {\n                return Zr(() => (this.add(), Fr(e))).pipe(Za({\n                    error: e => this._count$.error(e)\n                }), Vs(() => this.done()))\n            }\n            add(e = 1) {\n                this._count$.next(this._count$.value + e)\n            }\n            done(e = 1) {\n                this._count$.next(this._count$.value - e)\n            }\n        }\n        const Yp = {\n            isBuffered(t, i) {\n                for (let e = 0; t && e < t.length; e++)\n                    if (i >= t.start(e) && i <= t.end(e)) return !0;\n                return !1\n            },\n            timeRangesToBufferedRange(t) {\n                const i = [];\n                for (let e = 0; t && e < t.length; e++) i.push({\n                    start: t.start(e),\n                    end: t.end(e)\n                });\n                return i\n            },\n            subtitleBufferInfo(e, t, i) {\n                if (e) {\n                    e = this.bufferedCues(e);\n                    return this.getBufferedInfo(e, t, i)\n                }\n                return {\n                    len: 0,\n                    start: t,\n                    end: t,\n                    nextStart: void 0\n                }\n            },\n            fragmentsBufferedInfo(e, t, i) {\n                const r = [];\n                for (const t of e) r.push({\n                    start: t.start,\n                    end: t.start + t.duration\n                });\n                return this.getBufferedInfo(r, t, i)\n            },\n            bufferedCues(t) {\n                const i = [];\n                if (t)\n                    for (let e = 0; e < t.length; e++) i.push({\n                        start: t[e].startTime,\n                        end: t[e].endTime\n                    });\n                return i\n            },\n            bufferedInfoFromMedia: (e, t, i) => Yp.getBufferedInfo(Yp.timeRangesToBufferedRange(e.buffered), t, i),\n            getBufferedInfo(e, t, i) {\n                const r = [];\n                let n, s, a, o, l;\n                const d = e.map(({\n                    start: e,\n                    end: t\n                }) => ({\n                    start: e,\n                    end: t\n                }));\n                for (d.sort((e, t) => {\n                        return e.start - t.start || t.end - e.end\n                    }), l = 0; l < d.length; l++) {\n                    const e = r.length;\n                    if (e) {\n                        const t = r[e - 1].end;\n                        d[l].start - t < i ? d[l].end > t && (r[e - 1].end = d[l].end) : r.push(d[l])\n                    } else r.push(d[l])\n                }\n                for (l = 0, n = 0, s = a = t; l < r.length; l++) {\n                    const e = r[l][\"start\"],\n                        d = r[l][\"end\"];\n                    if (t + i >= e && t < d) s = e, a = d, n = a - t;\n                    else if (t + i < e) {\n                        o = e;\n                        break\n                    }\n                }\n                return {\n                    len: n,\n                    start: s,\n                    end: a,\n                    nextStart: o\n                }\n            },\n            toRangeString: e => `[${e.start.toFixed(3)},${e.end.toFixed(3)}]`\n        };\n        (w = Cp = Cp || {}).Seek = \"Seek\", w.HighBuffer = \"HighBuffer\", w.LowBuffer = \"LowBuffer\", (w = Dp = Dp || {}).AlmostDry = \"AlmostDry\", w.LowWater = \"LowWater\", w.HighWater = \"HighWater\", w.AboveHighWater = \"AboveHighWater\";\n        const Jp = {\n            [Dp.AlmostDry]: 0,\n            [Dp.LowWater]: 1,\n            [Dp.HighWater]: 2,\n            [Dp.AboveHighWater]: 3\n        };\n\n        function Zp(t, e) {\n            return [{\n                threshold: e.highWaterLevelSeconds,\n                level: Dp.HighWater\n            }, {\n                threshold: e.lowWaterLevelSeconds,\n                level: Dp.LowWater\n            }, {\n                threshold: e.almostDryWaterLevelSeconds,\n                level: Dp.AlmostDry\n            }].find(({\n                threshold: e\n            }) => e < t)\n        }\n\n        function ef(t, e) {\n            return [{\n                threshold: e.almostDryWaterLevelSeconds,\n                level: Dp.AlmostDry\n            }, {\n                threshold: e.lowWaterLevelSeconds,\n                level: Dp.LowWater\n            }, {\n                threshold: e.highWaterLevelSeconds,\n                level: Dp.HighWater\n            }, {\n                threshold: 1 / 0,\n                level: Dp.AboveHighWater\n            }].find(({\n                threshold: e\n            }) => t <= e)\n        }\n\n        function tf(t, i) {\n            const e = ef(t.getCurrentWaterLevel(i), t.bufferMonitorInfo).level,\n                r = [null, null];\n            return [yu.Variant, yu.AltAudio].forEach(e => {\n                null != t.sourceBufferEntityByType(e) && (r[e] = ef(t.getCurrentWaterLevelByType(e, i), t.bufferMonitorInfo).level)\n            }), {\n                combined: e,\n                sbTuple: r\n            }\n        }\n\n        function rf(s, a) {\n            return ed([s.combinedBuffer$, s.gotPlaying$, s.seeking$, s.waterLevelChangedForType$(null), s.stallInfo$]).pipe(La(([e, t, i, r, n]) => 0 === e.length || !t || i || null == r || null != n ? Ii : function t(i, r, e) {\n                const n = i.getCurrentWaterLevel(r),\n                    s = Zp(n, i.bufferMonitorInfo);\n                if (s) {\n                    const e = s[\"threshold\"];\n                    return bn(Math.ceil(1e3 * (n - e))).pipe(La(() => {\n                        const e = Zp(i.getCurrentWaterLevel(r), i.bufferMonitorInfo);\n                        return (null == e ? void 0 : e.level) === s.level ? t(i, r) : Wu\n                    }), hr(() => tf(i, r)))\n                }\n                return Ii\n            }(s, a)))\n        }\n        class nf extends kl {\n            constructor(e, t) {\n                super(t), this.mediaElement = e\n            }\n            get mediaElementDuration$() {\n                return this.selectActive(({\n                    mediaElementDuration: e\n                }) => e)\n            }\n            get mediaElementDuration() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.mediaElementDuration) && void 0 !== e ? e : 1 / 0\n            }\n            get msDuration() {\n                var e;\n                return null !== (e = null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.duration) && void 0 !== e ? e : 1 / 0\n            }\n            get minSBDuration() {\n                var e;\n                let i = Number.POSITIVE_INFINITY;\n                return null === (e = null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e || e.forEach((e, t) => {\n                    e && (i = ne(e.totalDuration) ? Math.min(i, e.totalDuration) : Number.NEGATIVE_INFINITY)\n                }), ne(i) ? i : 1 / 0\n            }\n            get currentTime() {\n                return this.mediaElement.currentTime\n            }\n            get clientWidth() {\n                return this.mediaElement.clientWidth\n            }\n            get clientHeight() {\n                return this.mediaElement.clientHeight\n            }\n            getBufferedDuration(e = .5) {\n                var t = Yp.timeRangesToBufferedRange(this.mediaElement.buffered),\n                    e = Yp.getBufferedInfo(t, this.currentTime, e);\n                return e.end - e.start\n            }\n            get mediaSourceEntity() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.mediaSourceEntity\n            }\n            get msReadyState() {\n                var e;\n                return null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.readyState\n            }\n            get sourceBufferEntities() {\n                var e;\n                return null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities\n            }\n            sourceBufferEntityByType(e) {\n                var t;\n                return null === (t = this.sourceBufferEntities) || void 0 === t ? void 0 : t[e]\n            }\n            initSegmentEntityByType(e) {\n                return null === (e = this.sourceBufferEntityByType(e)) || void 0 === e ? void 0 : e.initSegmentInfo\n            }\n            get maxBufferSize() {\n                var e = null === (e = this.sourceBufferEntities) || void 0 === e ? void 0 : e[yu.Variant];\n                let t = 1 / 0;\n                return null != e && e.gotQuotaExceeded && (t = null !== (e = e.maxTotalBytes) && void 0 !== e ? e : 1 / 0), t\n            }\n            get postFlushSeek() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.postFlushSeek\n            }\n            get seekable() {\n                return this.mediaElement.seekable\n            }\n            get desiredRate() {\n                var e;\n                return (null === (e = this.getActive()) || void 0 === e ? void 0 : e.desiredRate) || 0\n            }\n            get desiredRate$() {\n                return this.selectActive(({\n                    desiredRate: e\n                }) => null != e ? e : 0)\n            }\n            get effectiveRate() {\n                return this.isIframeRate ? this.desiredRate : this.paused ? 0 : 1\n            }\n            get playbackRate() {\n                return this.mediaElement.playbackRate\n            }\n            get isIframeRate() {\n                return Wp(this.desiredRate)\n            }\n            get isIframeRate$() {\n                return this.desiredRate$.pipe(hr(Wp))\n            }\n            get msObjectUrl$() {\n                return this.selectActive(({\n                    mediaSourceEntity: e\n                }) => null == e ? void 0 : e.objectUrl).pipe(Is())\n            }\n            get msReadyState$() {\n                return this.selectActive(({\n                    mediaSourceEntity: e\n                }) => {\n                    return null !== (e = null == e ? void 0 : e.readyState) && void 0 !== e ? e : null\n                })\n            }\n            get readyState() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.readyState) && void 0 !== e ? e : 0\n            }\n            get readyState$() {\n                return this.selectActive(({\n                    readyState: e\n                }) => null != e ? e : 0)\n            }\n            get mediaSourceEntity$() {\n                return this.selectActive(({\n                    mediaSourceEntity: e\n                }) => e)\n            }\n            get expectedSbCount$() {\n                return this.selectActive(({\n                    expectedSbCount: e\n                }) => e)\n            }\n            get expectedSbCount() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.expectedSbCount\n            }\n            get paused$() {\n                return this.selectActive(({\n                    paused: e\n                }) => e)\n            }\n            get paused() {\n                var e;\n                return null === (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.paused) || void 0 === e || e\n            }\n            get playbackStarted() {\n                var e;\n                return ne(null === (e = this.getActive()) || void 0 === e ? void 0 : e.firstPlayTime)\n            }\n            get flushing$() {\n                return this.selectActive(({\n                    flushing: e\n                }) => e)\n            }\n            get flushing() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.flushing) && void 0 !== e && e\n            }\n            get waitingForDisco$() {\n                return this.selectActive(({\n                    waitingForDisco: e\n                }) => e)\n            }\n            get waitingForDisco() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.waitingForDisco) && void 0 !== e && e\n            }\n            get gotPlaying() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.gotPlaying) && void 0 !== e && e\n            }\n            get gotPlaying$() {\n                return this.selectActive(({\n                    gotPlaying: e\n                }) => e)\n            }\n            get gotLoadStart$() {\n                return this.selectActive(({\n                    gotLoadStart: e\n                }) => e)\n            }\n            get seekTo() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.seekTo\n            }\n            get seekTo$() {\n                return this.selectActive(({\n                    seekTo: e\n                }) => e)\n            }\n            get seeking() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.seeking) && void 0 !== e && e\n            }\n            get seeking$() {\n                return this.selectActive(({\n                    seeking: e\n                }) => e)\n            }\n            get nudgeTarget$() {\n                return this.selectActive(({\n                    nudgeInfo: e\n                }) => null == e ? void 0 : e.nudgeTarget)\n            }\n            get nudgeCount() {\n                var e;\n                return null !== (e = null === (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.nudgeInfo) || void 0 === e ? void 0 : e.nudgeCount) && void 0 !== e ? e : 0\n            }\n            get sourceBufferEntities$() {\n                return this.selectActive(({\n                    mediaSourceEntity: e\n                }) => null == e ? void 0 : e.sourceBufferEntities)\n            }\n            sourceBufferEntityByType$(t) {\n                return this.selectActive(({\n                    mediaSourceEntity: e\n                }) => {\n                    return null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]\n                })\n            }\n            bufferedSegmentsByType$(t) {\n                return this.selectActive(({\n                    mediaSourceEntity: e\n                }) => {\n                    return null !== (e = null === (e = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]) || void 0 === e ? void 0 : e.bufferedSegments) && void 0 !== e ? e : []\n                })\n            }\n            getBufferedSegmentsByType(e) {\n                return null !== (e = null === (e = this.sourceBufferEntityByType(e)) || void 0 === e ? void 0 : e.bufferedSegments) && void 0 !== e ? e : []\n            }\n            get bufferedSegmentsTuple$() {\n                return ed([this.bufferedSegmentsByType$(yu.Variant), this.bufferedSegmentsByType$(yu.AltAudio)]).pipe(Gn(10))\n            }\n            get timeupdate$() {\n                return Oc(this.mediaElement).event(\"timeupdate\").pipe(ji(tr), Aa(), ao(125, void 0, {\n                    leading: !0,\n                    trailing: !0\n                }), hr(e => this.currentTime), ln(e => ne(e)))\n            }\n            get playingEvent$() {\n                return Oc(this.mediaElement).event(\"playing\").pipe(hr(() => {}))\n            }\n            get mediaElementEntity$() {\n                return this.selectActive(e => Boolean(e))\n            }\n            get ended$() {\n                return this.selectActive(e => {\n                    return null !== (e = null == e ? void 0 : e.ended) && void 0 !== e && e\n                })\n            }\n            sbUpdating$(t) {\n                return this.selectActive(e => {\n                    return null !== (e = null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]) || void 0 === e ? void 0 : e.updating) && void 0 !== e && e\n                })\n            }\n            sbUpdating(e) {\n                var t;\n                return null !== (e = null === (e = null === (t = null === (t = null === (t = this.getActive()) || void 0 === t ? void 0 : t.mediaSourceEntity) || void 0 === t ? void 0 : t.sourceBufferEntities) || void 0 === t ? void 0 : t[e]) || void 0 === e ? void 0 : e.updating) && void 0 !== e && e\n            }\n            sbError$(t) {\n                return this.selectActive(e => {\n                    return null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]) || void 0 === e ? void 0 : e.error\n                })\n            }\n            get updating$() {\n                return ed([this.sbUpdating$(yu.Variant), this.sbUpdating$(yu.AltAudio)]).pipe(hr(e => e.some(e => e)))\n            }\n            get bufferedRangeTuple$() {\n                return ed([this.selectActive(e => {\n                    return null !== (e = null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[gu.Variant]) || void 0 === e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : null\n                }), this.selectActive(e => {\n                    return null !== (e = null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[gu.AltAudio]) || void 0 === e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : null\n                })])\n            }\n            getBufferedRangeByType(e) {\n                return null !== (e = null === (e = this.sourceBufferEntities[e]) || void 0 === e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : []\n            }\n            get combinedBuffer$() {\n                return this.selectActive(e => {\n                    return null !== (e = null == e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : []\n                })\n            }\n            getBufferInfo(n, s) {\n                var e;\n                const t = null === (e = this.sourceBufferEntities) || void 0 === e ? void 0 : e.map(e => null == e ? void 0 : e.bufferedRanges),\n                    i = {\n                        buffered: {\n                            start: n,\n                            end: n,\n                            len: 0\n                        },\n                        bufferedSegments: []\n                    },\n                    a = [i, i];\n                return t && t.forEach((e, t) => {\n                    if (e) {\n                        const i = Yp.getBufferedInfo(e, n, s),\n                            r = (null !== (e = this.sourceBufferEntities[t].bufferedSegments) && void 0 !== e ? e : []).filter(e => !(e.endPTS < i.start || e.startPTS > i.end));\n                        a[t] = {\n                            buffered: i,\n                            bufferedSegments: r\n                        }\n                    }\n                }), a\n            }\n            getCombinedBufferInfo(e, t) {\n                var i = this.getActive();\n                return i ? Yp.getBufferedInfo(i.bufferedRanges, e, t) : null\n            }\n            get bufferMonitorInfo() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.bufferMonitorInfo) && void 0 !== e ? e : null\n            }\n            get bufferMonitorThresholds$() {\n                return this.selectActive(e => {\n                    var t = null == e ? void 0 : e.bufferMonitorInfo;\n                    if (!t) return null;\n                    var {\n                        almostDryWaterLevelSeconds: i,\n                        lowWaterLevelSeconds: r,\n                        highWaterLevelSeconds: e,\n                        maxBufferSeconds: t\n                    } = t;\n                    return {\n                        almostDryWaterLevelSeconds: i,\n                        lowWaterLevelSeconds: r,\n                        highWaterLevelSeconds: e,\n                        maxBufferSeconds: t\n                    }\n                }).pipe(Is((e, t) => (null == e ? void 0 : e.lowWaterLevelSeconds) === (null == t ? void 0 : t.lowWaterLevelSeconds)))\n            }\n            get waterLevelType$() {\n                return this.selectActive(e => {\n                    return null !== (e = null == e ? void 0 : e.bufferMonitorInfo.waterLevelType) && void 0 !== e ? e : null\n                })\n            }\n            waterLevelForType(e) {\n                var t;\n                return null !== (e = null === (t = null === (t = this.getActive()) || void 0 === t ? void 0 : t.bufferMonitorInfo.waterLevelType) || void 0 === t ? void 0 : t.sbTuple[e]) && void 0 !== e ? e : null\n            }\n            waterLevelChangedForType$(t) {\n                return this.waterLevelType$.pipe(hr(e => null == e ? null : null == t ? e.combined : e.sbTuple[t]))\n            }\n            get fellBelowLowWater$() {\n                return this.waterLevelChangedForType$(yu.Variant).pipe(ha(), hr(([e, t]) => function(e, t) {\n                    return Jp[e] > Jp[t]\n                }(e, t) && (t === Dp.LowWater || t === Dp.AlmostDry)), bo(this.seekTo$, this.waitingForDisco$), hr(([e, t, i]) => e && !ne(null == t ? void 0 : t.pos) && !i), Ra(!1))\n            }\n            isBufferedToEnd$(s, a = !0) {\n                return ed([this.combinedBuffer$, this.selectActive(e => e.bufferMonitorInfo).pipe(Kp(), hr(e => a ? e.almostDryWaterLevelSeconds : Math.max(e.almostDryWaterLevelSeconds, e.lowWaterLevelSeconds / 2))), this.seeking$]).pipe(hr(([e, t]) => {\n                    var i = this.minSBDuration;\n                    if (!e || !ne(i) && a) return !1;\n                    e = Yp.getBufferedInfo(e, this.currentTime, s).end;\n                    let r, n;\n                    return n = a ? (r = i, Math.abs(r - e) <= t) : (r = this.mediaElementDuration, r - e <= t), n\n                }), Is())\n            }\n            needData$(e, n = !1) {\n                var t = !n;\n                return ed([this.msReadyState$, this.waterLevelChangedForType$(null), this.isBufferedToEnd$(e, t), this.bufferedRangeTuple$, this.seekTo$, this.mediaElementDuration$]).pipe(Gn(10), hr(([e, t, i, , r]) => {\n                    if (\"closed\" === e) return !1;\n                    if (n) return !0;\n                    i = null == t || !i && t !== Dp.AboveHighWater, r = this.isIframeRate || !!r;\n                    return i || t !== Dp.AboveHighWater && r\n                }), tc(\"needData\"))\n            }\n            getSourceBufferInfoAction(e, t, i, r) {\n                var {\n                    currentTime: n,\n                    sourceBufferEntities: s,\n                    msReadyState: a\n                } = this;\n                let o = [null, null];\n                return !e && i.every(e => !(null != e && e.userInitiated)) ? null : \"open\" === a && s && null != s[0] ? (o = this.getBufferInfo(n, r), {\n                    position: n,\n                    discoSeqNum: null == t ? void 0 : t.discoSeqNum,\n                    bufferInfoTuple: o,\n                    switchContexts: i\n                }) : {\n                    position: null == t ? void 0 : t.pos,\n                    discoSeqNum: null == t ? void 0 : t.discoSeqNum,\n                    bufferInfoTuple: o,\n                    switchContexts: i\n                }\n            }\n            get haveEnough() {\n                var e;\n                return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.haveEnough) && void 0 !== e && e\n            }\n            get haveEnough$() {\n                return this.selectActive(({\n                    haveEnough: e\n                }) => e)\n            }\n            static likelyToKeepUp(e, t, i) {\n                return t && i >= e.HAVE_FUTURE_DATA\n            }\n            get playbackLikelyToKeepUp() {\n                return nf.likelyToKeepUp(this.mediaElement, this.haveEnough, this.readyState)\n            }\n            get playbackLikelyToKeepUp$() {\n                return ed([this.haveEnough$, this.readyState$]).pipe(hr(([e, t]) => nf.likelyToKeepUp(this.mediaElement, e, t)))\n            }\n            getCurrentWaterLevel(e) {\n                var t = this.currentTime,\n                    i = null !== (i = null === (i = this.getActive()) || void 0 === i ? void 0 : i.bufferedRanges) && void 0 !== i ? i : [];\n                return Yp.getBufferedInfo(i, t, e).len\n            }\n            getCombinedMediaSourceBufferInfo(e) {\n                var t = this.currentTime,\n                    [i, r] = null === (r = null === (i = this.getActive()) || void 0 === i ? void 0 : i.mediaSourceEntity) || void 0 === r ? void 0 : r.sourceBufferEntities;\n                return [Yp.getBufferedInfo(null !== (i = null == i ? void 0 : i.bufferedRanges) && void 0 !== i ? i : [], t, e), Yp.getBufferedInfo(null !== (r = null == r ? void 0 : r.bufferedRanges) && void 0 !== r ? r : [], t, e)]\n            }\n            getCurrentWaterLevelByType(e, t) {\n                var i = this.currentTime,\n                    e = this.sourceBufferEntityByType(e),\n                    e = null !== (e = null == e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : [];\n                return Yp.getBufferedInfo(e, i, t).len\n            }\n            canContinuePlaybackWithoutGap(e, t, i, r) {\n                if (\"LIVE\" !== e.type) return !0;\n                if (!e.ptsKnown) return !1;\n                var n = this.currentTime,\n                    i = performance.now() + i.avgPlaylistLoadTimeMs + 1e3 * e.targetduration,\n                    t = e.fragments[0].start + (i - t) / 1e3;\n                let s = this.getCombinedBufferInfo(n, r).end;\n                return s >= e.fragments[0].start - r && s <= e.fragments[0].start + e.totalduration && (s = e.fragments[0].start + e.totalduration), t <= s\n            }\n            get stallInfo$() {\n                return this.selectActive(e => {\n                    return null !== (e = null == e ? void 0 : e.stallInfo) && void 0 !== e ? e : null\n                })\n            }\n            get textTracks() {\n                return this.mediaElement.textTracks\n            }\n            get textTracksCreated$() {\n                return this.selectActive(e => null == e ? void 0 : e.textTracksCreated)\n            }\n            get mediaOptionParsedSubtitleRecord() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.mediaOptionParsedSubtitleRecord\n            }\n            getParsedSubtitleRecordsForMediaOption(e) {\n                return this.mediaOptionParsedSubtitleRecord ? this.mediaOptionParsedSubtitleRecord[e] || {} : null\n            }\n        }\n        class sf {\n            constructor(e, t, i, r) {\n                this.mediaSink = e, this.media = t, this.logger = r, this.useCustomMediaFunctions = i.useCustomMediaFunctions, this.overridePlaybackRate = i.overridePlaybackRate\n            }\n            install() {\n                const e = this.media;\n                e && (this.useCustomMediaFunctions && e && e.play && e.pause && (e.originalPlay || (e.originalPlay = e.play.bind(e)), e.originalPause || (e.originalPause = e.pause.bind(e)), e.play = () => (this.mediaSink.checkForReplay(), this.mediaSink.desiredRate = 1, 0 < e.currentTime && !e.paused && !e.ended && 2 < e.readyState ? Promise.resolve() : new Promise((e, t) => {\n                    this.pendingPlayPromises || (this.pendingPlayPromises = []), this.pendingPlayPromises.push({\n                        resolve: e,\n                        reject: t\n                    })\n                })), e.pause = () => {\n                    this.mediaSink.desiredRate = 0\n                }), \"function\" == typeof HTMLMediaElement && this.overridePlaybackRate && Object.defineProperty(e, \"playbackRate\", {\n                    enumerable: !0,\n                    configurable: !0,\n                    get: function() {\n                        return 1\n                    },\n                    set: function(e) {\n                        Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, \"playbackRate\").set.call(this, e)\n                    }\n                }), this.playPromise = null, this.expectPauseEvent = this.expectPlayEvent = !1)\n            }\n            uninstall() {\n                const e = this.media;\n                e && (e.originalPlay && (e.play = e.originalPlay, delete e.originalPlay), e.originalPause && (e.pause = e.originalPause, delete e.originalPause), this.overridePlaybackRate && (e.playbackRate = 1, delete e.playbackRate)), this.playPromise = null, this.expectPauseEvent = this.expectPlayEvent = !1\n            }\n            play() {\n                var e;\n                this.media && (e = this.mediaSink.flushing, this.playPromise || e ? this.logger.warn(`Ignoring play command playPromise/flushing ${Boolean(this.playPromise)}/${e}`) : (this.expectPlayEvent = this.expectPlayEvent || this.media.paused, this.playPromise = this._mediaPlayInternal(), this.playPromise && this.playPromise.then(function() {\n                    this.playPromise = null, this._handlePendingPlayPromises(null)\n                }.bind(this)).catch(function(e) {\n                    this.playPromise = null, this.expectPlayEvent = !1, this._handlePendingPlayPromises(e || new Error(\"Play rejected for unknown reason\")), \"NotAllowedError\" === (null == e ? void 0 : e.name) ? (this.logger.warn(\"play() not allowed, going back to rate 0\"), this.mediaSink.desiredRate = 0) : this.logger.error(`play() error: ${null==e?void 0:e.message}`)\n                }.bind(this))))\n            }\n            pause() {\n                this.media && (this.playPromise ? this.playPromise.then(() => {\n                    var e = this.mediaSink.mediaQuery;\n                    (0 === this.mediaSink.desiredRate || e.seeking && !e.playbackLikelyToKeepUp) && this._mediaPauseInternal()\n                }).catch(e => {\n                    this.logger.error(`Promise error in pause(): ${e.message}`)\n                }) : this._mediaPauseInternal())\n            }\n            _handlePendingPlayPromises(t) {\n                var e, i = null === (e = this.pendingPlayPromises) || void 0 === e ? void 0 : e.length;\n                if (t)\n                    for (let e = 0; e < i; e++) this.pendingPlayPromises[e].reject(t);\n                else\n                    for (let e = 0; e < i; e++) this.pendingPlayPromises[e].resolve();\n                this.pendingPlayPromises = []\n            }\n            _mediaPlayInternal() {\n                return (this.media.originalPlay || this.media.play.bind(this.media))()\n            }\n            _mediaPauseInternal() {\n                return this.expectPauseEvent = this.expectPauseEvent || !this.media.paused, (this.media.originalPause || this.media.pause.bind(this.media))()\n            }\n        }\n        class af extends Error {}\n        class of extends p {\n            constructor(e, t, i, r, n) {\n                super(L, e, t, i, r), this.sbType = n, this.response = r\n            }\n        }\n        class lf extends of {\n            constructor(e, t, i, r) {\n                super(\"bufferAddCodecError\", !1, e, t, i), this.mediaOptionId = r, this.mediaOptionType = Vu(this.sbType)\n            }\n        }\n        class df extends of {\n            constructor(e, t, i, r, n, s) {\n                super(e, t, i, r, n), this.isTimeout = s, this.mediaOptionType = Vu(this.sbType)\n            }\n        }\n        class uf extends df {\n            constructor(e, t, i, r) {\n                super(\"bufferFullError\", !1, e, t, i, !1), this.maxTotalBytes = r\n            }\n        }\n        class cf extends df {\n            constructor(e, t, i) {\n                super(n, !1, e, t, i, !0)\n            }\n        }\n        class hf extends df {\n            constructor(e, t, i, r) {\n                super(n, !1, e, t, i, !1), this.mediaOptionId = r, this.mediaOptionType = Vu(this.sbType)\n            }\n        }\n        class pf extends p {\n            constructor(e, t, i, r, n, s, a = NaN) {\n                super(L, e, t, i, r), this.stallType = n, this.bufferLen = s, this.nudgePosition = a, this.response = r\n            }\n        }\n        class ff extends $t {\n            constructor(n, e, s, a, o, l, d, u, c) {\n                super(e => {\n                    const t = Oc(l),\n                        i = u.child({\n                            sb: o\n                        });\n                    n.setSourceBufferEntity(o, d), d.mimeType.includes(\"audio/mpeg\") && (this.updateMp3Timestamps = !0);\n                    const r = an(t.event(\"updatestart\").pipe(Za(() => {\n                        n.setSourceBufferUpdating(o)\n                    })), t.event(\"updateend\").pipe(ji(tr), Za(() => {\n                        var e = Yp.timeRangesToBufferedRange(l.buffered),\n                            t = Yp.timeRangesToBufferedRange(s.buffered);\n                        n.setBufferedRangesUpdated(o, e, t, !1, c)\n                    })), t.event(\"error\").pipe(Za(() => {\n                        n.setSourceBufferError(o, \"Got source buffer error\")\n                    }))).pipe(La(() => Ii)).subscribe(e);\n                    return () => {\n                        r.unsubscribe();\n                        try {\n                            \"open\" === a.readyState && l.abort(), a.removeSourceBuffer(l)\n                        } catch (e) {\n                            i.error(`Error aborting SourceBuffer on unsubscribe: ${e.message}`)\n                        }\n                    }\n                }), this.mediaElementStore = n, this.mediaElementQuery = e, this.mediaElement = s, this.type = o, this.sourceBuffer = l, this.config = c, this.updateMp3Timestamps = !1\n            }\n            get buffered() {\n                return this.sourceBuffer.buffered\n            }\n            appendBuffer(e, t) {\n                return Zr(() => this.sourceBuffer.updating ? this._waitForUpdateEndOrError().pipe(La(() => this.appendBuffer(e, t))) : this._appendBufferAsync(e, t))\n            }\n            _appendBufferAsync(e, t) {\n                let i = NaN,\n                    r = null;\n                const n = (\"startPTS\" in t ? t.frag : t).mediaOptionId;\n                try {\n                    \"startPTS\" in t && (r = {\n                        startPTS: t.startPTS,\n                        endPTS: t.endPTS,\n                        bytes: t.bytes,\n                        frag: Object.assign({}, t.frag)\n                    }), this.mediaElementStore.setInflightSegment(this.type, r), i = performance.now(), this.sourceBuffer.appendBuffer(e)\n                } catch (e) {\n                    return 22 !== e.code ? (this.mediaElementStore.setInflightSegment(this.type, null), this.mediaElement.error ? Vi(new hf(e.message, $.VideoDecoderBadDataErr, this.type, n)) : Vi(e)) : (this.mediaElementStore.setBufferedRangesUpdated(this.type, Yp.timeRangesToBufferedRange(this.sourceBuffer.buffered), Yp.timeRangesToBufferedRange(this.mediaElement.buffered), !0, this.config), Vi(new uf(e.message, $.AllocationFailed, this.type, this.maxTotalBytes)))\n                }\n                return this._waitForUpdateEndOrError().pipe(hr(() => ({\n                    startAppend: i,\n                    endAppend: performance.now(),\n                    bytesAppend: e.byteLength\n                })), So(1e4), Vn(e => {\n                    throw e instanceof dr ? (this.sourceBuffer.abort(), e = new cf(\"Append took longer than 10000ms\", $.InternalError, this.type)) : e instanceof of && (e = new hf(\"Decode error\", $.VideoDecoderBadDataErr, this.type, n)), e\n                }))\n            }\n            remove(e, t) {\n                return this._waitForUpdateEndOrError().pipe(La(this._removeAsync.bind(this, e, t)))\n            }\n            _removeAsync(e, t) {\n                try {\n                    this.sourceBuffer.remove(e, t)\n                } catch (e) {\n                    return Vi(new of (r, !1, e.message, $.InternalError, this.type))\n                }\n                return this._waitForUpdateEndOrError()\n            }\n            abort() {\n                try {\n                    this.sourceBuffer.abort()\n                } catch (e) {\n                    return Vi(new of (r, !1, e.message, $.InternalError, this.type))\n                }\n                return this._waitForUpdateEndOrError()\n            }\n            get updating() {\n                return this.sourceBuffer.updating\n            }\n            get timestampOffset() {\n                return this.sourceBuffer.timestampOffset\n            }\n            set timestampOffset(e) {\n                this.sourceBuffer.timestampOffset = e\n            }\n            get gotQuotaExceeded() {\n                var e;\n                return null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.gotQuotaExceeded) && void 0 !== e && e\n            }\n            get bufferedSegments() {\n                var e;\n                return null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.bufferedSegments) && void 0 !== e ? e : []\n            }\n            get totalBytes() {\n                var e;\n                return null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.totalBytes) && void 0 !== e ? e : 0\n            }\n            get maxTotalBytes() {\n                var e = null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.maxTotalBytes) && void 0 !== e ? e : 1 / 0;\n                return this.gotQuotaExceeded ? e : 1 / 0\n            }\n            _waitForUpdateEndOrError() {\n                return this.sourceBuffer.updating && this.mediaElementStore.setSourceBufferUpdating(this.type), this.mediaElementQuery.sbUpdating$(this.type).pipe(ln(e => !1 === e), bo(this.mediaElementQuery.sbError$(this.type)), hr(([, e]) => {\n                    if (e) throw new of (r, !1, \"Got error during sourceBuffer operation\", $.InternalError, this.type)\n                }), Ds(1))\n            }\n        }\n        class mf extends $t {\n            constructor(a, o, e, l, t) {\n                super(e => {\n                    const t = Oc(l),\n                        i = an(t.event(\"sourceopen\"), t.event(\"sourceclose\"), t.event(\"sourceended\")).pipe(Za(e => {\n                            e = (null !== (e = null == e ? void 0 : e.target) && void 0 !== e ? e : l).readyState;\n                            o.msReadyState = e\n                        })),\n                        r = this.sourceBuffers$.pipe(La(e => e ? an(...e.filter(e => null != e)) : Ii)),\n                        n = an(i, r).pipe(La(() => Ii)).subscribe(e),\n                        s = URL.createObjectURL(l);\n                    return a.src = s, o.setMediaSourceEntity(s, l.readyState), () => {\n                        n.unsubscribe(), URL.revokeObjectURL(s), a.src === s && (a.removeAttribute(\"src\"), a.load(), o.setMediaSourceEntity(null)), this.sourceBuffers$.next(null)\n                    }\n                }), this.mediaElement = a, this.mediaElementStore = o, this.mediaElementQuery = e, this.mediaSource = l, this.logger = t, this.sourceBuffers$ = new yi(null)\n            }\n            get readyState() {\n                return this.mediaSource.readyState\n            }\n            set duration(e) {\n                this.mediaSource.duration = e\n            }\n            get duration() {\n                return this.mediaSource.duration\n            }\n            endOfStream(e) {\n                this.mediaSource.endOfStream(e)\n            }\n            createSourceBuffers(e, a) {\n                const o = this.mediaSource;\n                al(() => {\n                    try {\n                        const s = [null, null];\n                        e.forEach((t, i) => {\n                            if (t) {\n                                var {\n                                    mimeType: r,\n                                    mediaOptionId: n\n                                } = t;\n                                let e;\n                                try {\n                                    e = o.addSourceBuffer(r)\n                                } catch (t) {\n                                    throw new lf(t.message, $.IncompatibleAsset, i, n)\n                                }\n                                s[i] = new ff(this.mediaElementStore, this.mediaElementQuery, this.mediaElement, this.mediaSource, i, e, t, this.logger, a)\n                            }\n                        }), this.sourceBuffers$.next(s)\n                    } catch (e) {\n                        if (!(e instanceof p)) throw new af(`error initializing sourcebuffers ${e.message} readyState=${o.readyState}`);\n                        throw e\n                    }\n                })\n            }\n            get needSourceBuffers() {\n                return null == this.sourceBuffers$.value || null == this.sourceBuffers$.value[0]\n            }\n            get sourceBuffers() {\n                return this.sourceBuffers$.value\n            }\n            getSourceBufferByType(e) {\n                var t = this.sourceBuffers$.value;\n                return t ? t[e] : null\n            }\n            updateLiveSeekableRange(e, t) {\n                const i = this.mediaSource;\n                null != i && i.setLiveSeekableRange && \"open\" === (null == i ? void 0 : i.readyState) && i.setLiveSeekableRange(e, t)\n            }\n            clearLiveSeekableRange() {\n                const e = this.mediaSource;\n                null != e && e.clearLiveSeekableRange && \"open\" === (null == e ? void 0 : e.readyState) && e.clearLiveSeekableRange()\n            }\n        }\n\n        function gf(e, c, t) {\n            const {\n                lowBufferThreshold: h,\n                lowBufferWatchdogPeriod: p,\n                highBufferWatchdogPeriod: f,\n                seekWatchdogPeriod: m\n            } = t, i = ed([c.desiredRate$, c.ended$, c.combinedBuffer$, c.seekTo$]).pipe(hr(e => {\n                var t, [i, r, n, s] = e;\n                return t = c.currentTime, e = i, i = r, r = n, n = isFinite(null == s ? void 0 : s.pos), s = r.some(e => e.start <= t && e.end > t), !(1 !== e || i || 0 === r.length || n && !s)\n            }), Is()), r = c.combinedBuffer$.pipe(hr(() => c.getCurrentWaterLevel(0) <= t.lowBufferThreshold || !c.haveEnough ? Cp.LowBuffer : Cp.HighBuffer), Is()), n = ed([i, c.seekTo$, c.gotPlaying$, r]).pipe(La(e => {\n                var [t, i, r] = e;\n                if (!t) return $i(null);\n                var n, s, a, o, l, d, u, e = c.nudgeCount,\n                    t = m + +e;\n                return isFinite(null == i ? void 0 : i.pos) || !r ? (n = c, s = performance.now(), t = t, a = h, bn(1e3 * t).pipe(hr(() => {\n                    var e = n.currentTime,\n                        t = n.getCombinedBufferInfo(e, 0);\n                    return yf(Cp.Seek, e, s, t, a, n.haveEnough)\n                }))) : (o = c, l = p, d = f + +e, u = h, an($i(o.currentTime), o.timeupdate$).pipe(La(e => {\n                    const t = performance.now(),\n                        i = o.getCombinedBufferInfo(e, 0);\n                    let r, n;\n                    return r = i.len <= u || !o.haveEnough ? (n = l, Cp.LowBuffer) : (n = d, Cp.HighBuffer), bn(Math.max(100, 1e3 * n)).pipe(hr(() => e < o.currentTime ? null : yf(r, e, t, i, u, o.haveEnough)))\n                })))\n            })), s = n.pipe(Kp(), bo(c.combinedBuffer$), La(([]) => ed([c.seeking$, c.paused$])), La(([e, t]) => e || t ? Ii : c.timeupdate$.pipe(ha(), ln(([e, t]) => ne(e) && ne(t) && e < t), Ds(1))), hr(() => null));\n            return an(n, s)\n        }\n\n        function yf(e, t, i, r, n, s) {\n            var a = performance.now() - i;\n            return {\n                type: e,\n                isLowBufferStall: r.len <= n || !s,\n                tstalled: i,\n                stallDurationMs: a,\n                currentTime: t\n            }\n        }\n        class vf extends $t {\n            constructor(w, A, e, t, i, r, n) {\n                super(e => {\n                    const t = this.config,\n                        i = A.startMediaSession(w, t.maxBufferLength, t.almostDryBufferSec, t.defaultTargetDuration),\n                        r = Sf(w, A, this._mediaQuery, this, this.hlsGapless, t, this.logger, this.rtcService),\n                        n = this.mediaSource$.pipe(La(e => e || Ii)),\n                        s = this._mediaQuery.seekTo$.pipe((u = w, c = this._mediaQuery, p = (h = this).config, f = (f = this.logger).child({\n                            name: \"seek\"\n                        }), e => e.pipe(Za(e => {}), ln(e => e && ne(e.pos)), La(e => c.readyState$.pipe(ln(e => e >= u.HAVE_METADATA), Ds(1), Zs(e), La(({\n                            pos: e,\n                            fromEvent: t\n                        }) => (h.checkForInconsistentStoreBufferRangesAndUpdate(), u.paused || h.pause(), t || (u.currentTime = e), Gu(c.haveEnough$, e => e).pipe(Zs({\n                            pos: e,\n                            fromEvent: t\n                        })))), La(({\n                            pos: e,\n                            fromEvent: t\n                        }) => {\n                            var i = c.getCombinedBufferInfo(e, 0),\n                                r = i.nextStart;\n                            return (!t || p.nudgeFromEventSeek) && 0 === i.len && ne(r) && e < r && r - e <= p.maxSeekHole ? (h.seekTo = r, Ii) : $i(e)\n                        }), bo(c.desiredRate$), hr(([, e]) => {\n                            u.paused && 0 !== e && h.play()\n                        }), $a(Ii), Vn(e => (f.error(`error during seek ${e.message}`), Ii))))))),\n                        a = this._mediaQuery.desiredRate$.pipe((o = w, l = this._mediaQuery, d = this, e => e.pipe(bo(l.seekTo$), La(([e, t]) => ne(null == t ? void 0 : t.pos) ? Ii : 0 === e ? (o.paused || d.pause(), Ii) : Gu(l.haveEnough$, e => e).pipe(Za(() => {\n                            o.paused && d.play()\n                        }))), $a(Ii))));\n                    var o, l, d, u, c, h, p, f;\n                    this.liveSeekableWindow = {\n                        start: NaN,\n                        end: NaN\n                    }, this.mediaFunctions = this.mediaFunctions || new sf(this, w, t, this.logger), this.mediaFunctions.install();\n                    var m, g, y, v, S, b, T, E, I = an(gf(this.logger, this._mediaQuery, this.config).pipe(Za(e => {\n                        A.setStallInfo(e)\n                    })), this.mediaQuery.stallInfo$.pipe((g = A, y = (m = this).config, v = this.logger, e => e.pipe(_s(e => e ? function(i, e, r, n) {\n                        const s = i.mediaQuery;\n                        return an(ed([s.seekTo$, s.nudgeTarget$]).pipe(ln(([e, t]) => e && ne(e.pos) && ne(t) && (e.pos < t || e.pos - t > r.maxSeekHole)), Zs(null)), s.stallInfo$).pipe(bo(s.desiredRate$), ji(tr), hr(([c, e], t) => {\n                            if (!c) return NaN;\n                            var h = s.getCombinedBufferInfo(c.currentTime, 0),\n                                e = Wp(e);\n                            return function(e, t, i, r, n) {\n                                var {\n                                    type: s,\n                                    isLowBufferStall: a,\n                                    currentTime: o\n                                } = c, l = h.len, d = t.maxSeekHole;\n                                let u = NaN;\n                                if (a) {\n                                    const t = h.nextStart - o <= d ? h.nextStart : 1 / 0;\n                                    ne(t) ? u = t : e.mediaQuery.msDuration - o < .1 && (u = o + .1)\n                                } else if (n < t.nudgeMaxRetry) u = o + t.nudgeOffset;\n                                else {\n                                    if (!r) throw i.error(`still stuck in high buffer @${o} after ${t.nudgeMaxRetry}, raise fatal error`), new pf(\"bufferStalledError\", !0, \"got fatal buffer error\", $.VideoDecoderBadDataErr, s, l);\n                                    i.error(`still stuck in high buffer @${o} after ${t.nudgeMaxRetry}, non fatal in iframeMode`)\n                                }\n                                return ne(u) && e.nudgeSeek(u, n + 1), u\n                            }(i, r, n, e, t)\n                        }), Wa(e => ne(e)), Vs(() => {\n                            e.setNudgeInfo(null)\n                        }))\n                    }(m, g, y, v) : $i(NaN))))));\n                    an(r, n, s, a, I, (S = this.mediaQuery, b = A, I = t.maxBufferHole, an((E = I, ed([(T = S).bufferMonitorThresholds$, T.combinedBuffer$, T.seeking$]).pipe(hr(([e]) => null == e ? null : tf(T, E)))), rf(S, I)).pipe(ji(tr), Za(({\n                        combined: e,\n                        sbTuple: t\n                    }) => {\n                        b.updateWaterLevels(e, t)\n                    })))).pipe($a(Ii), Vs(() => {\n                        A.remove(i), this.mediaFunctions.uninstall(), this.mediaFunctions = void 0\n                    })).subscribe(e)\n                }), this.mediaElement = w, this.mediaElementStore = A, this.config = e, this.hlsGapless = t, this.logger = i, this.teardownWG$ = r, this.rtcService = n, this.mediaSource$ = new yi(null), this.mediaKeysMutex = new zp, this._mediaQuery = new nf(w, A), this.logger = i.child({\n                    name: \"mse\"\n                }), this.createId3Track(w), this.mediaFunctions = new sf(this, w, e, this.logger)\n            }\n            get mediaSourceAdapter() {\n                return this.mediaSource$.value\n            }\n            get sourceBuffers() {\n                var e;\n                return null !== (e = null === (e = this.mediaSourceAdapter) || void 0 === e ? void 0 : e.sourceBuffers) && void 0 !== e ? e : []\n            }\n            get needSourceBuffers() {\n                return !this.sourceBuffers[0]\n            }\n            get mediaQuery() {\n                return this._mediaQuery\n            }\n            sourceBuffersBufferedRangeByType(e) {\n                var t, e = null === (t = null === (t = this.mediaSourceAdapter) || void 0 === t ? void 0 : t.sourceBuffers) || void 0 === t ? void 0 : t[e];\n                return e ? Yp.timeRangesToBufferedRange(e.sourceBuffer.buffered) : null\n            }\n            createId3Track(e) {\n                this.id3Track = e.addTextTrack(\"metadata\", \"id3\"), this.id3Track.mode = \"hidden\"\n            }\n            checkForInconsistentStoreBufferRangesAndUpdate() {\n                var e = Yp.timeRangesToBufferedRange(this.mediaElement.buffered),\n                    t = this.sourceBuffersBufferedRangeByType(yu.Variant),\n                    i = this.sourceBuffersBufferedRangeByType(yu.AltAudio),\n                    r = null !== (n = null === (r = this.mediaQuery.sourceBufferEntityByType(yu.Variant)) || void 0 === r ? void 0 : r.bufferedRanges) && void 0 !== n ? n : null,\n                    n = null !== (n = null === (n = this.mediaQuery.sourceBufferEntityByType(yu.AltAudio)) || void 0 === n ? void 0 : n.bufferedRanges) && void 0 !== n ? n : null;\n                this.shouldUpdateStoreValues(t, r) && (this.logger.warn(`[${Uu[yu.Variant]}] SourceBuffer's loaded bufferedRanges ${JSON.stringify(t)} & mediaElementStore's bufferedRanges ${JSON.stringify(r)} are out of sync!`), this.updateMediaElementStoreBufferedRanges(e, yu.Variant)), this.shouldUpdateStoreValues(i, n) && (this.logger.warn(`[${Uu[yu.AltAudio]}] SourceBuffer's loaded bufferedRanges ${JSON.stringify(i)} & mediaElementStore's bufferedRanges ${JSON.stringify(n)} are out of sync!`), this.updateMediaElementStoreBufferedRanges(e, yu.AltAudio))\n            }\n            shouldUpdateStoreValues(e, i) {\n                return !(null == e && null == i || (null == e ? void 0 : e.length) == (null == i ? void 0 : i.length) && !e.find(t => {\n                    var e = Ku.search(i, e => t.start >= e.start && t.end <= e.end ? 0 : t.end < e.start ? -1 : 1);\n                    return null == e || e.start != t.start || e.end != t.end || void 0\n                }))\n            }\n            updateMediaElementStoreBufferedRanges(e, t) {\n                var i = this.sourceBuffersBufferedRangeByType(t);\n                i && !this.mediaQuery.sbUpdating(t) && this.mediaElementStore.setBufferedRangesUpdated(t, i, e, !1, this.config)\n            }\n            destroyMediaSource() {\n                this.mediaSource$.next(null)\n            }\n            makeMediaSource() {\n                return new MediaSource\n            }\n            openMediaSource(t) {\n                al(() => {\n                    var e;\n                    t ? (e = new mf(this.mediaElement, this.mediaElementStore, this.mediaQuery, t, this.logger), this.mediaSource$.next(e)) : this.mediaSource$.next(null)\n                })\n            }\n            createSourceBuffers(e) {\n                const t = this.mediaSource$.value;\n                if (!t) throw new Error(\"createSourceBuffers empty mediaSource\");\n                t.createSourceBuffers(e, this.config)\n            }\n            _waitForMediaSourceOpen(i) {\n                const r = this.mediaQuery.mediaSourceEntity.objectUrl;\n                return ed([this.mediaQuery.msReadyState$, this.mediaQuery.msObjectUrl$]).pipe(La(([e, t]) => t !== r ? $i(null) : \"open\" === e || \"ended\" === e ? $i(i) : Ii))\n            }\n            get appendOrder() {\n                return this.mediaQuery.isIframeRate ? [yu.Variant, yu.AltAudio] : [yu.AltAudio, yu.Variant]\n            }\n            clearFlush(e) {\n                e.forEach(e => {\n                    e && (e.dataSeg.flushBeforeAppend = {\n                        start: 0,\n                        end: 0\n                    })\n                })\n            }\n            getSwitchPosition(e) {\n                return e.reduce((e, t) => {\n                    t = t ? t.dataSeg.switchPosition : void 0;\n                    return ne(t) ? ne(e) ? Math.min(e, t) : t : e\n                }, void 0)\n            }\n            checkForReplay() {\n                var e = this.mediaElement;\n                e.paused && !e.seeking && e.duration && e.currentTime && e.currentTime >= e.duration - this.config.maxTotalDurationTolerance && (this.seekTo = 0)\n            }\n            resetMediaSourceIfNeeded(r) {\n                const n = this[\"mediaQuery\"],\n                    e = n[\"sourceBufferEntities\"],\n                    t = n.getActive()[\"expectedSbCount\"];\n                if (!e || this.needSourceBuffers) return this._waitForMediaSourceOpen(r);\n                const s = function(e, s, t, i) {\n                    const r = s.filter(e => Boolean(e)).length,\n                        n = e.filter(e => Boolean(e)).length,\n                        l = [null, null];\n                    e.forEach((e, t) => {\n                        var i, r, n, s, a, o;\n                        e && (s = e[\"offsetTimestamp\"], a = S(s), i = e.initSeg.mimeType, {\n                            audioCodec: r,\n                            videoCodec: n\n                        } = e.initSeg.initParsedData, o = e[\"dataSeg\"], s = S(o.startPts) - a, a = S(o.endPts) - a, o = o.discoSeqNum, l[t] = {\n                            audioCodec: r,\n                            videoCodec: n,\n                            mimeType: i,\n                            startPTSSec: s,\n                            endPTSSec: a,\n                            discoSeqNum: o,\n                            mediaOptionId: e.initSeg.mediaOptionId\n                        })\n                    });\n                    let a = r === t,\n                        o = n === t;\n                    if (1 === n && n < t && 0 !== r) {\n                        const t = e[gu.Variant] ? gu.Variant : gu.AltAudio,\n                            h = 1 - t,\n                            r = l[t],\n                            n = l[h] = function(e, i, r, n, t, s) {\n                                const a = null == e ? void 0 : e.bufferedSegments;\n                                if (!a) return s.warn(\"getMatchingInfo trying to query null sbEntity\"), null;\n                                s = a.find(e => {\n                                    var t = e.frag.discoSeqNum === n,\n                                        e = Math.max(i, e.startPTS) < Math.min(r, e.endPTS);\n                                    return t && e\n                                });\n                                if (null == s) return null; {\n                                    const {\n                                        audioCodec: i,\n                                        videoCodec: r,\n                                        mimeType: o\n                                    } = e;\n                                    return {\n                                        mimeType: o,\n                                        audioCodec: i,\n                                        videoCodec: r,\n                                        startPTSSec: s.startPTS,\n                                        endPTSSec: s.endPTS,\n                                        discoSeqNum: n,\n                                        mediaOptionId: t\n                                    }\n                                }\n                            }(s[h], r.startPTSSec, r.endPTSSec, r.discoSeqNum, r.mediaOptionId, i);\n                        if (!n)\n                            if (null !== (e = null === (e = e[gu.Variant]) || void 0 === e ? void 0 : e.dataSeg) && void 0 !== e && e.iframe && t === gu.Variant && l[t]) {\n                                const p = s[t].videoCodec,\n                                    h = l[t].videoCodec;\n                                if (a = a && (p === h || be.isCompatibleVideoCodec(p, h)), a) return {\n                                    compatible: a,\n                                    boundary: NaN,\n                                    allowance: NaN,\n                                    discoSeqNum: l[t].discoSeqNum\n                                }\n                            } else i.warn(`${Nu[t]} No matching frag found ${ae(r)} buffered=${ae(s[h].bufferedSegments.map(e=>{var{mediaSeqNum:t,discoSeqNum:i}=e.frag;return{mediaSeqNum:t,discoSeqNum:i,startPTS:e.startPTS,endPTS:e.endPTS}}))}`);\n                        o = null != n\n                    }\n                    let d = NaN,\n                        u = NaN,\n                        c = NaN;\n                    return o && l.forEach((e, t) => {\n                        if (!e) return null;\n                        ne(c) ? c !== e.discoSeqNum && (c = NaN) : c = e.discoSeqNum;\n                        t = s[t];\n                        if (t) {\n                            const s = t.audioCodec,\n                                i = t.videoCodec,\n                                {\n                                    audioCodec: r,\n                                    videoCodec: n\n                                } = e;\n                            a = a && (i === n || be.isCompatibleVideoCodec(i, n)), a = a && (s === r || be.isCompatibleAudioCodec(s, r))\n                        } else a = !1;\n                        d = ne(d) ? (u = Math.abs(e.startPTSSec - d), Math.max(e.startPTSSec, d)) : (u = 0, e.startPTSSec)\n                    }), {\n                        compatible: a && o,\n                        boundary: d,\n                        allowance: u,\n                        discoSeqNum: c\n                    }\n                }(r, e, t, (this.config.maxBufferHole, this.logger));\n                if (s.compatible) return this._waitForMediaSourceOpen(r);\n                let i = s.boundary;\n                const a = s.allowance,\n                    o = this.getSwitchPosition(r);\n                if (ne(o) && (i = o), !ne(i)) return this.logger.warn(\"not enough info #disco\"), $i(null);\n                const l = fn(Gu(an($i(n.currentTime), n.timeupdate$), e => e >= i), Gu(n.stallInfo$.pipe(hr(e => {\n                    return null !== (e = null == e ? void 0 : e.currentTime) && void 0 !== e ? e : NaN\n                })), e => e >= i - a - this.config.discontinuitySeekTolerance));\n                return this.mediaElementStore.waitingForDisco = !0, l.pipe(Zs(i), La(e => {\n                    performance.now();\n                    const t = n.currentTime,\n                        i = this.msDuration;\n                    return this.resetMediaSource(Math.max(t, e), s.discoSeqNum), this._waitForMediaSourceOpen(r).pipe(Za(() => {\n                        performance.now(), this.msDuration = i\n                    }))\n                }), Vs(() => {\n                    this.mediaElementStore.waitingForDisco = !1\n                }))\n            }\n            resetMediaSource(e = NaN, t) {\n                var i;\n                ne(e) || (e = null !== (i = null === (i = this.mediaQuery.seekTo) || void 0 === i ? void 0 : i.pos) && void 0 !== i ? i : this.mediaQuery.currentTime), ne(t) || (t = null === (i = this.mediaQuery.seekTo) || void 0 === i ? void 0 : i.discoSeqNum), 0 < this.sourceBuffers.length && (this.openMediaSource(this.makeMediaSource()), this.setSeekToWithDiscontinuity(e, t))\n            }\n            setExpectedSbCount(e) {\n                this.mediaElementStore.expectedSbCount = e\n            }\n            appendInitSegments(l, d) {\n                const {\n                    mediaQuery: e,\n                    mediaElementStore: u,\n                    sourceBuffers: c\n                } = this, h = e[\"sourceBufferEntities\"];\n                if (!c) throw new Error(\"appendInitSegments: null sourceBuffers\");\n                if (!h) throw new Error(\"appendInitSegments: null sourceBufferEntities\");\n                var t = this.appendOrder.map(t => {\n                    if (l[t]) {\n                        const i = c[t],\n                            r = l[t],\n                            n = h[t],\n                            s = r[\"initSeg\"];\n                        if (!n) throw new Error(`appendInitSegments: sb[${Uu[t]}] null currentSbEntity`);\n                        if (!i) throw new Error(`appendInitSegments: sb[${Uu[t]}] null source buffer`);\n                        const a = n.initSegmentInfo,\n                            o = function() {\n                                var {\n                                    itemId: e,\n                                    mediaOptionId: t,\n                                    discoSeqNum: i,\n                                    keyTagInfo: r\n                                } = s;\n                                return {\n                                    itemId: e,\n                                    mediaOptionId: t,\n                                    discoSeqNum: i,\n                                    keyId: je(null == r ? void 0 : r.keyId)\n                                }\n                            }();\n                        if ((e = o) && a && e.itemId === a.itemId && e.mediaOptionId === a.mediaOptionId && e.discoSeqNum === a.discoSeqNum && e.keyId === a.keyId) return $i(null);\n                        var e = Vu(t);\n                        return i.appendBuffer(s.data, s).pipe(Za(e => {\n                            u.setInitSegmentEntity(t, o)\n                        }), d(i, e, s.mediaOptionId, this.config, this.mediaQuery))\n                    }\n                }).filter(e => Boolean(e));\n                return 0 === t.length ? $i(null) : en(t)\n            }\n            appendDataSegments(m, g) {\n                var e = this.appendOrder.map(e => {\n                    const t = m[e],\n                        {\n                            mediaQuery: i,\n                            sourceBuffers: r\n                        } = this,\n                        n = i[\"sourceBufferEntities\"];\n                    if (!r) throw new Error(\"appendDataSegments: null sourceBuffers\");\n                    if (!n) throw new Error(\"appendDataSegments: null sourceBufferEntities\");\n                    if (!t) return null;\n                    const s = r[e],\n                        a = m[e],\n                        o = n[e];\n                    if (!o) throw new Error(\"appendDataSegments: null currentSbEntity\");\n                    const l = o.initSegmentInfo,\n                        d = a[\"dataSeg\"];\n                    if (!l) throw new Error(`appendDataSegments: sb[${Uu[e]}] null currentInitSegmentInfo`);\n                    if (!o) throw new Error(`appendDataSegments: sb[${Uu[e]}] null currentSbEntity`);\n                    if (!s) throw new Error(`appendDataSegments: sb[${Uu[e]}] null source buffer`);\n                    const u = s.timestampOffset,\n                        c = {\n                            startPTS: S(d.startPts) + u,\n                            endPTS: S(d.endPts) + u,\n                            firstKeyframePts: d.firstKeyframePts ? S(d.firstKeyframePts) + u : void 0,\n                            bytes: d.data2 ? d.data1.byteLength + d.data2.byteLength : d.data1.byteLength,\n                            frag: {\n                                itemId: d.itemId,\n                                mediaOptionId: d.mediaOptionId,\n                                mediaSeqNum: d.mediaSeqNum,\n                                discoSeqNum: d.discoSeqNum,\n                                keyTagInfo: d.keyTagInfo,\n                                isLastFragment: d.isLastFragment,\n                                iframe: d.iframe,\n                                framesWithoutIDR: d.framesWithoutIDR,\n                                dropped: d.dropped\n                            }\n                        },\n                        h = Vu(e);\n                    let p = Wu;\n                    var f = t.dataSeg.flushBeforeAppend;\n                    return f && f.start !== f.end && (p = this.flushData(e, f.start, f.end)), p.pipe(La(() => $i(d.data1, d.data2).pipe(Kp()).pipe(Wn(e => s.appendBuffer(e, c).pipe(g(s, h, d.mediaOptionId, this.config, this.mediaQuery))))), Za(() => {\n                        i.getBufferedRangeByType(e)\n                    }))\n                }).filter(e => Boolean(e));\n                return 0 === e.length ? $i(null) : en(e)\n            }\n            setStoreSbTimeoffsets(s) {\n                const {\n                    mediaElementStore: a,\n                    sourceBuffers: e\n                } = this;\n                e.forEach((t, i) => {\n                    if (t && s[i]) {\n                        var {\n                            offsetTimestamp: r,\n                            dataSeg: n\n                        } = s[i], n = S(n.startPts);\n                        let e = -1 * S(r);\n                        t.updateMp3Timestamps && .1 < Math.abs(t.timestampOffset - n) && (e = n + e), t.timestampOffset !== e && (t.timestampOffset = e, a.setTimestampOffset(i, t.timestampOffset))\n                    }\n                })\n            }\n            adjustJaggedStart(e) {\n                const {\n                    mediaQuery: t,\n                    logger: n\n                } = this, {\n                    sourceBufferEntities: i,\n                    currentTime: r,\n                    seekTo: s\n                } = t, a = e.reduce((e, t) => null != t && t.dataSeg.endPts ? Math.min(b(t.dataSeg.endPts, t.offsetTimestamp), e) : e, Number.POSITIVE_INFINITY);\n                if (!i) throw new Error(\"appendSourceBufferData null currentSbEntity\");\n                const o = (null == s ? void 0 : s.pos) || r;\n                let l = NaN;\n                i.forEach((e, t) => {\n                    if (e) {\n                        e = Yp.getBufferedInfo(e.bufferedRanges, o, 0);\n                        if (0 === e.len) {\n                            const i = e[\"nextStart\"],\n                                r = ne(this.config.jaggedSeekTolerance) ? this.config.jaggedSeekTolerance : 0;\n                            n.warn(`sb[${Uu[t]}] jagged start: ${i} appendEndTime=${a} current=${l} tolerance=${r}`), ne(i) && (!ne(l) || i - l > r) && (l = i)\n                        }\n                    }\n                }), ne(l) && a > l && (n.warn(`[seek] jagged start, adjusting currentTime:${r.toFixed(3)} seekTo=${null===(e=null==s?void 0:s.pos)||void 0===e?void 0:e.toFixed(3)}->${l} appendEndTime=${a}`), this.seekTo = l)\n            }\n            addCues(e, t) {\n                const i = this.mediaElement.textTracks[e];\n                i && t.forEach(e => {\n                    i.addCue(e)\n                })\n            }\n            _flushInternal(e, t, i) {\n                return Zr(() => e.remove(t, i)).pipe(Za(() => {}))\n            }\n            flushAll(i, r, n = !1) {\n                return 0 === this.sourceBuffers.length ? Wu : en(this.sourceBuffers.map((e, t) => e ? this.flushData(t, i, r, n) : Wu)).pipe(Zs(void 0))\n            }\n            flushData(o, l, d, u = !1) {\n                const {\n                    mediaQuery: t,\n                    logger: c\n                } = this;\n                return Gu(t.updating$, e => !1 === e).pipe(La(() => {\n                    var e = t[\"sourceBufferEntities\"],\n                        e = e[o];\n                    null != e && e.updating && this.logger.warn(`trying to flush while updating ${o}`);\n                    const r = this.sourceBuffers[o];\n                    if (!r) return Wu;\n                    let n, s, a = Wu;\n                    e = -1 === navigator.userAgent.toLowerCase().indexOf(\"firefox\");\n                    if (this.flushing = !0, e) return this._flushInternal(r, l, d);\n                    for (let i = 0; i < r.buffered.length; i++) {\n                        let e, t;\n                        n = r.buffered.start(i), s = r.buffered.end(i), t = d === 1 / 0 ? (e = l, d) : (e = Math.max(n, l), Math.min(s, d)), Math.min(t, s) > e && (u || .5 < Math.min(t, s) - e) ? a = a.pipe($a(this._flushInternal(r, e, t))) : c.warn(`ignoring sb[${Uu[o]}] flush ${e},${t}`)\n                    }\n                    return a\n                }), Vs(() => {\n                    this.flushing = !1\n                }))\n            }\n            static convertInitSegToCompatInfo(e) {\n                return {\n                    mimeType: e.mimeType,\n                    audioCodec: e.initParsedData.audioCodec,\n                    videoCodec: e.initParsedData.videoCodec,\n                    startPTSSec: void 0,\n                    endPTSSec: void 0,\n                    discoSeqNum: e.discoSeqNum,\n                    mediaOptionId: e.mediaOptionId\n                }\n            }\n            static combineAppendDataInfoWithCompatInfo(e, t, i, r = 0) {\n                const n = [...t];\n                e.forEach((e, t) => null != e && e.initSeg ? n[t] = vf.convertInitSegToCompatInfo(e.initSeg) : null);\n                t = n[yu.Variant].videoCodec, e = Hp(t);\n                if (i && i.has(e)) {\n                    const s = i.get(e);\n                    n[yu.Variant].mimeType = n[yu.Variant].mimeType.replace(t, s), n[yu.Variant].videoCodec = s\n                }\n                return n\n            }\n            convertSourceBufferEntitiesToCompatInfo(e) {\n                const t = e.sourceBufferEntities,\n                    i = [null, null];\n                return t.forEach((e, t) => {\n                    e && (i[t] = {\n                        mimeType: e.mimeType,\n                        audioCodec: e.audioCodec,\n                        videoCodec: e.videoCodec,\n                        startPTSSec: void 0,\n                        endPTSSec: void 0,\n                        discoSeqNum: void 0,\n                        mediaOptionId: null === (e = e.initSegmentInfo) || void 0 === e ? void 0 : e.mediaOptionId\n                    })\n                }), i\n            }\n            appendData(e, i, r) {\n                const {\n                    mediaQuery: t,\n                    logger: n\n                } = this, o = this.convertSourceBufferEntitiesToCompatInfo(t);\n                return e.every(e => null == e) ? $i([]) : this.resetMediaSourceIfNeeded(e).pipe(La(e => e ? t.updating$.pipe(ln(e => !1 === e), Ds(1), Zs(e)) : $i(null)), La(t => {\n                    if (!t) return $i([]);\n                    let s = NaN,\n                        a = NaN;\n                    if (this.needSourceBuffers) {\n                        s = performance.now();\n                        const i = vf.combineAppendDataInfoWithCompatInfo(t, o, r, n);\n                        this.createSourceBuffers(i), a = performance.now(), this.clearFlush(t)\n                    }\n                    return t.forEach(e => {\n                        e = null == e ? void 0 : e.dataSeg;\n                        null != e && e.cues && ne(null == e ? void 0 : e.texttrackIdx) && this.addCues(e.texttrackIdx, e.cues)\n                    }), this.setStoreSbTimeoffsets(t), Jr(Zr(() => this.appendInitSegments(t, i)), Zr(() => this.appendDataSegments(t, i))).pipe(function(r, i) {\n                        return 2 <= arguments.length ? function(e) {\n                            return Bt(sa(r, i), Ws(1), (void 0 === (t = i) && (t = null), function(e) {\n                                return e.lift(new is(t))\n                            }))(e);\n                            var t\n                        } : function(e) {\n                            return Bt(sa(function(e, t, i) {\n                                return r(e, t)\n                            }), Ws(1))(e)\n                        }\n                    }((e, t) => (e.push(t), e), new Array), hr(([i, r]) => {\n                        const n = [null, null];\n                        return [yu.Variant, yu.AltAudio].forEach(e => {\n                            var t;\n                            null != (null == i ? void 0 : i[e]) && (t = {\n                                fragmentType: Vu(e),\n                                bufferCreationStart: s,\n                                bufferCreationEnd: a,\n                                startInitAppend: i[e].startAppend,\n                                endInitAppend: i[e].endAppend,\n                                initBytesAppend: i[e].bytesAppend,\n                                startDataAppend: r[e].startAppend,\n                                endDataAppend: r[e].endAppend,\n                                dataBytesAppend: r[e].bytesAppend\n                            }, n[e] = t)\n                        }), n\n                    }), Za(e => {\n                        this.adjustJaggedStart(t)\n                    }))\n                }), Ds(1))\n            }\n            endStream() {\n                try {\n                    this.mediaSourceAdapter.endOfStream()\n                } catch (e) {\n                    this.logger.warn(`endOfStream failed: ${e.message}`)\n                }\n            }\n            setMediaKeys(e) {\n                return this.teardownWG$.wrap(this.mediaKeysMutex.lock(() => Fr(this.mediaElement.setMediaKeys(e))).pipe(Za(() => {}), va(e => e.pipe(jr((e, t) => {\n                    if (t < 3) return bn(100 * t);\n                    throw e\n                })))))\n            }\n            clearMediaKeys() {\n                return Zr(() => {\n                    if (!this.mediaElement) return Wu;\n                    const e = -1 < navigator.userAgent.toLowerCase().indexOf(\"chrome\"),\n                        t = this.mediaElement.src;\n                    return e && (this.mediaElement.src = \"\"), this.setMediaKeys(null).pipe(Za(() => this.mediaElement.src = t))\n                })\n            }\n            set postFlushSeek(e) {\n                this.mediaElementStore.postFlushSeek = e\n            }\n            schedulePostFlushSeek(e) {\n                al(() => {\n                    this.mediaQuery.seekTo && (this.seekTo = null), this.postFlushSeek = e\n                })\n            }\n            set seekTo(e) {\n                this.mediaElementStore.setSeekToPos(e, !1)\n            }\n            setSeekToWithDiscontinuity(e, t) {\n                this.mediaElementStore.setSeekToPos(e, !1, t)\n            }\n            nudgeSeek(e, t) {\n                al(() => {\n                    this.mediaElementStore.setSeekToPos(e, !1), this.mediaElementStore.setNudgeInfo({\n                        nudgeTarget: e,\n                        nudgeCount: t\n                    })\n                })\n            }\n            set desiredRate(e) {\n                this.mediaElementStore.desiredRate = e\n            }\n            toggleTrickPlaybackMode(e) {\n                if (this.config.overridePlaybackRate) {\n                    const t = e ? 2 : 1;\n                    try {\n                        this.mediaElement.playbackRate = t\n                    } catch (e) {\n                        this.logger.error({\n                            name: \"iframes\"\n                        }, `Exception when setting playbackRate=${t}: ${e.message}`)\n                    }\n                }\n                const t = this.muteValueOnTrickPlaybackToggle;\n                e && void 0 === t ? (this.muteValueOnTrickPlaybackToggle = this.mediaElement.muted, this.mediaElement.muted = e) : e || void 0 === t || (this.mediaElement.muted = t, this.muteValueOnTrickPlaybackToggle = void 0)\n            }\n            play() {\n                this.mediaFunctions.play()\n            }\n            pause() {\n                this.mediaFunctions.pause()\n            }\n            get expectPlayEvent() {\n                return this.mediaFunctions.expectPlayEvent\n            }\n            set expectPlayEvent(e) {\n                this.mediaFunctions.expectPlayEvent = e\n            }\n            get expectPauseEvent() {\n                return this.mediaFunctions.expectPauseEvent\n            }\n            set expectPauseEvent(e) {\n                this.mediaFunctions.expectPauseEvent = e\n            }\n            set textTracksCreated(e) {\n                const t = this[\"mediaElementStore\"];\n                t.textTracksCreated = e\n            }\n            get msDuration() {\n                return this._mediaQuery.msDuration\n            }\n            set msDuration(e) {\n                try {\n                    const t = this[\"mediaElementStore\"],\n                        i = this.mediaSource$.value;\n                    i.duration !== e && (i.duration = e, t.msDuration = e)\n                } catch (e) {\n                    this.logger.warn(`Error setting duration ${e.message}`)\n                }\n            }\n            set haveEnough(e) {\n                this.mediaElementStore.haveEnough = e\n            }\n            set flushing(e) {\n                this.mediaElementStore.flushing = e\n            }\n            set bufferMonitorTargetDuration(e) {\n                this.mediaElementStore.bufferMonitorTargetDuration = e\n            }\n            get textTracks() {\n                return this.mediaElement.textTracks\n            }\n            get id3TextTrack() {\n                return this.id3Track\n            }\n            addTextTrack(e, t, i) {\n                return this.mediaElement.addTextTrack(e, t, i)\n            }\n            dispatchEvent(e) {\n                return this.mediaElement.dispatchEvent(e)\n            }\n            get offsetWidth() {\n                return this.mediaElement.offsetWidth\n            }\n            get offsetHeight() {\n                return this.mediaElement.offsetHeight\n            }\n            getliveSeekableWindow() {\n                return this.liveSeekableWindow\n            }\n            archiveParsedSubtitleFragmentRecord(e, t, i) {\n                return this.mediaElementStore.archiveParsedSubtitleFragmentRecord(e, t, i)\n            }\n            updateLiveSeekableRange(e) {\n                var t = e.fragments,\n                    e = t.length;\n                if (1 < e) {\n                    const i = Math.max(t[0].start, 0),\n                        r = t[e - 1].start + t[e - 1].duration;\n                    this.mediaSource$.value.updateLiveSeekableRange(i, r), this.liveSeekableWindow.start = i, this.liveSeekableWindow.end = r\n                }\n            }\n            clearLiveSeekableRange() {\n                this.mediaSource$.value.clearLiveSeekableRange(), this.liveSeekableWindow.start = NaN, this.liveSeekableWindow.end = NaN\n            }\n        }\n        const Sf = (t, r, n, s, a, o, l, i) => {\n                if (!t) return Ii;\n                const e = Oc(t);\n                return an(e.event(\"durationchange\").pipe(hr(e => kc(t, \"durationchange\", e)), Za(e => {\n                    e = e.currentTarget;\n                    r.mediaElementDuration = e.duration\n                })), e.event(\"seeking\").pipe(ao(o.seekEventThrottleMs), hr(e => kc(t, \"seeking\", e)), Za(e => {\n                    var t = e.currentTarget,\n                        e = t.currentTime;\n                    if (t.readyState >= t.HAVE_METADATA) {\n                        const i = n.seekTo;\n                        !i || !i.fromEvent && 1e-5 < Math.abs(i.pos - e) ? a.inGaplessMode ? function(e, t, i, r, n) {\n                            let s = !1;\n                            e < t.playingItem.itemStartOffset && (n.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${t.playingItem.itemStartOffset}`), e = t.playingItem.itemStartOffset, s = !0), t.isPreloading && (e > t.loadingItem.itemStartOffset && (n.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${t.loadingItem.itemStartOffset}`), e = t.loadingItem.itemStartOffset, s = !0), t.dequeueSource(\"SeekToUnbufferedTimeRanges\")), s ? i.resetMediaSource(e) : r.setSeekToPos(e, !0)\n                        }(e, a, s, r, l) : s && s.hasOwnProperty(\"liveSeekableWindow\") && ne(s.getliveSeekableWindow().start) && ne(s.getliveSeekableWindow().end) && (e < s.getliveSeekableWindow().start || e > s.getliveSeekableWindow().end) ? function(e, t, i, r, n, s) {\n                            let a = e;\n                            if (e < t) a = t;\n                            else if (i < e) {\n                                let e = r.defaultTargetDuration;\n                                ne(r.liveSyncDuration) ? e = r.liveSyncDuration : ne(r.liveSyncDurationCount) && (e = r.liveSyncDurationCount * r.defaultTargetDuration), a = Math.max(0, i - e)\n                            }\n                            s.warn(`[live] liveAdjustedSeek seekTo:${se(e,3)}, adjustedSeek:${se(a,3)}, liveWindowStart:${se(t,3)}, liveWindowEnd:${se(i,3)}`), n.setSeekToPos(a, !0)\n                        }(e, s.getliveSeekableWindow().start, s.getliveSeekableWindow().end, o, r, l) : r.setSeekToPos(e, !0) : r.seeking = !0\n                    }\n                })), e.event(\"seeked\").pipe(hr(e => kc(t, \"seeked\", e)), Za(() => {\n                    r.setSeekToPos(null, !0)\n                })), e.event(\"play\").pipe(hr(e => kc(t, \"play\", e)), bo(n.desiredRate$), hr(([e]) => {\n                    var t = e.currentTarget;\n                    r.paused = t.paused;\n                    var i = s.expectPlayEvent,\n                        t = t.controls || o.nativeControlsEnabled;\n                    return !i && t && (s.checkForReplay(), r.desiredRate = 1), s.expectPlayEvent = !1, e\n                })), e.event(\"playing\").pipe(hr(e => kc(t, \"playing\", e)), Za(e => {\n                    e = e.currentTarget;\n                    r.paused = e.paused, r.gotPlayingEvent()\n                })), e.event(\"loadstart\").pipe(hr(e => kc(t, \"loadstart\", e)), Za(() => {\n                    r.gotLoadStartEvent()\n                })), e.event(\"pause\").pipe(hr(e => kc(t, \"pause\", e)), Za(e => {\n                    var t = e.currentTarget;\n                    r.paused = t.paused;\n                    e = s.expectPauseEvent, t = t.controls || o.nativeControlsEnabled;\n                    !e && t && (r.desiredRate = 0), s.expectPauseEvent = !1\n                })), e.event(\"loadedmetadata\").pipe(hr(e => kc(t, \"loadedmetadata\", e))), e.event(\"loadeddata\").pipe(hr(e => kc(t, \"loadeddata\", e))), e.event(\"canplay\").pipe(hr(e => kc(t, \"canplay\", e))), e.event(\"canplaythrough\").pipe(hr(e => kc(t, \"canplaythrough\", e))), e.event(\"waiting\").pipe(hr(e => kc(t, \"waiting\", e))), e.event(\"emptied\").pipe(hr(e => kc(t, \"emptied\", e))), e.event(\"error\").pipe(hr(e => kc(t, \"error\", e)), Wn(e => Vi(t.error))), e.event(\"ended\").pipe(hr(e => kc(t, \"ended\", e)))).pipe(bo(n.bufferedRangeTuple$), ll(([e]) => {\n                    var t = e.currentTarget,\n                        e = t.readyState;\n                    r.readyState = e, r.ended = t.ended\n                }), Vn(e => (e instanceof MediaError ? (l.warn(`mediaElementError, code: ${e.code}, message: ${e.message}`), null == i || i.handleMediaElementError(e)) : l.error(`media event error: ${e.message}`), Ii)), $a(on), Vn(e => e instanceof MediaError ? (l.warn(`mediaElementError, code: ${e.code}, message: ${e.message}`), Vi(e)) : (l.error(`media event error: ${e.message}`), Ii)))\n            },\n            bf = new class extends fl {\n                constructor() {\n                    super({}, {\n                        name: \"media-element-store\",\n                        producerFn: su\n                    }), this._activeId = \"\"\n                }\n                get activeId() {\n                    return this._activeId\n                }\n                startMediaSession(i, r, n, s) {\n                    return Do(\"playback.session.start\"), this._activeId = `media session: ${(new Date).toISOString()}`, al(() => {\n                        var e = s,\n                            t = Math.max(e, r - e),\n                            t = {\n                                id: this.activeId,\n                                desiredRate: !i.autoplay && i.paused ? 0 : 1,\n                                paused: i.paused,\n                                gotPlaying: !1,\n                                gotLoadStart: !1,\n                                firstPlayTime: void 0,\n                                seeking: i.seeking,\n                                flushing: !1,\n                                readyState: i.readyState,\n                                ended: i.ended,\n                                bufferedRanges: [],\n                                haveEnough: !1,\n                                mediaSourceEntity: null,\n                                expectedSbCount: NaN,\n                                bufferMonitorInfo: {\n                                    waterLevelType: null,\n                                    almostDryWaterLevelSeconds: n,\n                                    lowWaterLevelSeconds: e,\n                                    highWaterLevelSeconds: t,\n                                    maxBufferSeconds: r\n                                },\n                                mediaOptionParsedSubtitleRecord: [],\n                                textTracksCreated: !1,\n                                waitingForDisco: !1\n                            };\n                        this.add(t), this.setActive(this.activeId)\n                    }), this.logger = Qe().child({\n                        name: \"UpdateBufferedSegments\"\n                    }), this.activeId\n                }\n                setMediaSourceEntity(t, i) {\n                    Do(\"playback.set.msObjectUrl\"), this.updateActive(e => {\n                        e.mediaSourceEntity = null != t && null != i ? {\n                            objectUrl: t,\n                            readyState: i,\n                            duration: NaN,\n                            sourceBufferEntities: [null, null]\n                        } : null, e.bufferedRanges = [], e.haveEnough = !1, e.readyState = 0, e.bufferMonitorInfo.waterLevelType = null\n                    })\n                }\n                set mediaElementDuration(t) {\n                    Do(\"playback.set.mediaElementDuration\"), this.updateActive(e => {\n                        e && (e.mediaElementDuration = t)\n                    })\n                }\n                set msReadyState(t) {\n                    Do(\"playback.set.msReadyState\"), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        e && (e.readyState = t)\n                    })\n                }\n                set readyState(t) {\n                    Do(`playback.set.readyState ${t}`), this.updateActive(e => {\n                        e.readyState = t\n                    })\n                }\n                set ended(t) {\n                    Do(`playback.set.ended ${t}`), this.updateActive(e => {\n                        e.ended = t\n                    })\n                }\n                set msDuration(t) {\n                    Do(\"playback.set.msDuration\"), this.updateActive(e => {\n                        e.mediaSourceEntity.duration = t\n                    })\n                }\n                set textTracksCreated(t) {\n                    Do(\"playback.set.textTracksCreated ${created}\"), this.updateActive(e => {\n                        e.textTracksCreated = t\n                    })\n                }\n                set expectedSbCount(t) {\n                    Do(\"playback.set.expectedSbCount\"), this.updateActive(e => {\n                        e.expectedSbCount = t\n                    })\n                }\n                set postFlushSeek(e) {\n                    this.updateActive({\n                        postFlushSeek: e\n                    })\n                }\n                setSeekToPos(t, i, r) {\n                    Do(`playback.set.seekToPos: ${null==t?void 0:t.toFixed(3)} cc: ${r}`), this.updateActive(e => {\n                        ne(t) ? (e.seekTo = {\n                            pos: t,\n                            fromEvent: i,\n                            discoSeqNum: r\n                        }, e.gotPlaying = !1, e.haveEnough = !1) : (e.seekTo = null, e.postFlushSeek = void 0), i && (e.seeking = ne(t))\n                    })\n                }\n                set seeking(t) {\n                    Do(`playback.set.seeking: ${t}`), this.updateActive(e => {\n                        e.seeking = t\n                    })\n                }\n                set paused(t) {\n                    Do(`playback.set.paused: ${t}`), this.updateActive(e => {\n                        (e.paused = t) && (e.gotPlaying = !1)\n                    })\n                }\n                gotPlayingEvent() {\n                    Do(\"playback.set.playing\"), this.updateActive(e => {\n                        e.paused || (e.gotPlaying = !0, e.firstPlayTime = e.firstPlayTime || performance.now())\n                    })\n                }\n                gotLoadStartEvent() {\n                    Do(\"playback.set.loadstart\"), this.updateActive(e => {\n                        e.gotLoadStart = !0\n                    })\n                }\n                set desiredRate(t) {\n                    Do(`playback.set.desiredRate: ${t}`), this.updateActive(e => {\n                        e.desiredRate = t\n                    })\n                }\n                set haveEnough(t) {\n                    Do(`playback.set.haveEnough: ${t}`), this.updateActive(e => {\n                        e.haveEnough = t\n                    })\n                }\n                set flushing(e) {\n                    Do(`playback.set.flushing: ${e}`), this.updateActive({\n                        flushing: e\n                    })\n                }\n                set waitingForDisco(t) {\n                    Do(`playback.set.waitingForDisco: ${t}`), this.updateActive(e => {\n                        e && (e.waitingForDisco = t)\n                    })\n                }\n                setSourceBufferUpdating(i) {\n                    Do(`playback.set.sourcebuffers[${Uu[i]}].updating`), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i];\n                        t && (t.updating = !0, t.error = void 0)\n                    })\n                }\n                setTimestampOffset(i, r) {\n                    Do(`playback.set.sourcebuffers[${Uu[i]}].timestampOffset`), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i];\n                        t && (t.timestampOffset = r)\n                    })\n                }\n                setBufferedRangesUpdated(a, o, l, d, u) {\n                    Do(`playback.set.sourcebuffers[${Uu[a]}].bufferupdated`), this.updateActive(e => {\n                        var t, i, r;\n                        const n = null == e ? void 0 : e.mediaSourceEntity,\n                            s = null === (r = null == n ? void 0 : n.sourceBufferEntities) || void 0 === r ? void 0 : r[a];\n                        if (s) {\n                            const a = null == n ? void 0 : n.duration;\n                            s.updating = !1, s.bufferedRanges = [...o], t = s, i = t.inFlight, r = t.bufferedSegments, i && ne(i.startPTS) && ne(i.endPTS) && function(t, i) {\n                                    let r = !1;\n                                    for (let e = t.length - 1; - 1 < e; e--) {\n                                        const s = t[e],\n                                            a = Math.max(i.startPTS, s.startPTS),\n                                            o = Math.min(i.endPTS, s.endPTS);\n                                        var n;\n                                        o <= a || ((n = (1 - (o - a) / (s.endPTS - s.startPTS)) * s.bytes) <= 0 ? t.splice(e, 1) : (s.bytes = n, s.startPTS < i.startPTS ? s.endPTS = a : (s.startPTS = o, r || (t.splice(e, 0, i), r = !0))))\n                                    }\n                                    r || t.push(i)\n                                }(r, i), t.inFlight = null,\n                                function(e, t, i, r, n) {\n                                    const {\n                                        maxBufferHole: s,\n                                        bufferedSegmentEjectionToleranceMs: a\n                                    } = r, o = e.bufferedSegments, l = e.bufferedRanges;\n                                    let d, u = 0,\n                                        c = !1;\n                                    if (l.length)\n                                        for (let e = o.length - 1; - 1 < e; e--) {\n                                            const t = o[e],\n                                                r = !t.frag.iframe;\n                                            r && t.frag.isLastFragment && (d = t.frag);\n                                            var h = t.endPTS - t.startPTS;\n                                            if (h <= 0) o.splice(e, 1), null == n || n.warn(`Ejecting segment from bufferedSegments due to segmentDuration <= 0 > segment=${ae(t)}`), c = t.frag === d;\n                                            else {\n                                                var p = Bp(l, t);\n                                                if (p) {\n                                                    var f = Math.max(p.start, t.startPTS),\n                                                        p = Math.min(p.end, t.endPTS),\n                                                        f = p - f;\n                                                    if (u += t.bytes * f / h, r)\n                                                        if (f < Math.min(h, s)) o.splice(e, 1), null == n || n.warn(`Ejecting segment from bufferedSegments due to tiny overlaps > segment=${ae(t)}, bufferedRanges=${ae(l)}`), c = t.frag === d;\n                                                        else {\n                                                            const r = t.appendedDuration,\n                                                                u = (r || 0) - f,\n                                                                m = Math.min(.001 * a, h);\n                                                            r ? !(u > m && f != h) || t.frag.isLastFragment && p === i || (o.splice(e, 1), null == n || n.warn(`Ejecting segment from bufferedSegments due to change in current overlap > segment=${ae(t)}, delta=${u}, bufferedRanges=${ae(l)}`), c = t.frag === d) : t.appendedDuration = f\n                                                        }\n                                                } else null == n || n.warn(`Ejecting segment from bufferedSegments due to no overlap > segment=${ae(t)}, bufferedRanges=${ae(l)}`), o.splice(e, 1), c = t.frag === d\n                                            }\n                                        } else o.length && o.splice(0, o.length);\n                                    e.totalDuration = d && !c && 0 < l.length ? l[l.length - 1].end : 1 / 0, e.gotQuotaExceeded = e.gotQuotaExceeded || t, e.totalBytes = u, e.maxTotalBytes = Math.max(e.totalBytes, e.maxTotalBytes)\n                                }(s, d, a, u, this.logger)\n                        }\n                        e.bufferedRanges = [...l]\n                    })\n                }\n                setSourceBufferEntity(n, s) {\n                    Do(`playback.set.sourcebuffers[${Uu[n]}].setSourceBufferEntity`), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        var t, i, r;\n                        e && ({\n                            mimeType: t,\n                            audioCodec: i,\n                            videoCodec: r\n                        } = s, e.sourceBufferEntities[n] = {\n                            mimeType: t,\n                            audioCodec: i,\n                            videoCodec: r,\n                            updating: !1,\n                            bufferedRanges: [],\n                            timestampOffset: 0,\n                            inFlight: null,\n                            bufferedSegments: [],\n                            totalBytes: 0,\n                            maxTotalBytes: 0,\n                            gotQuotaExceeded: !1,\n                            totalDuration: 1 / 0\n                        })\n                    })\n                }\n                setInflightSegment(i, r) {\n                    Do(`playback.set.sourcebuffers[${Uu[i]}].setInflightSegment`), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i];\n                        t && (t.inFlight = r)\n                    })\n                }\n                setInitSegmentEntity(i, r) {\n                    Do(`playback.set.sourcebuffers[${Uu[i]}].setInitSegmentEntity`), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i];\n                        t && (t.initSegmentInfo = r)\n                    })\n                }\n                setSourceBufferError(i, r) {\n                    Do(`playback.set.sourcebuffers[${i}].error: ${r}`), this.updateActive(({\n                        mediaSourceEntity: e\n                    }) => {\n                        const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i];\n                        t && (t.inFlight = null, t.updating = !1, t.error = r)\n                    })\n                }\n                setStallInfo(t) {\n                    Do(`playback.set.stallInfo stalled=${null!=t}`), this.updateActive(e => {\n                        e.stallInfo = t\n                    })\n                }\n                setNudgeInfo(t) {\n                    Do(`playback.set.nudgeInfo ${ae(t)}`), this.updateActive(e => {\n                        e.nudgeInfo = t\n                    })\n                }\n                updateWaterLevels(t, i) {\n                    Do(\"playback.set.updateWaterLevels\"), this.updateActive(e => {\n                        e.bufferMonitorInfo.waterLevelType = {\n                            combined: t,\n                            sbTuple: [...i]\n                        }\n                    })\n                }\n                set bufferMonitorTargetDuration(i) {\n                    Do(`playback.set.targetDuration: ${i}`), this.updateActive(e => {\n                        if (ne(i) && 0 < i) {\n                            const t = e.bufferMonitorInfo;\n                            t.lowWaterLevelSeconds = Math.min(i, t.maxBufferSeconds), t.highWaterLevelSeconds = Math.max(t.lowWaterLevelSeconds, t.maxBufferSeconds - i)\n                        }\n                    })\n                }\n                archiveParsedSubtitleFragmentRecord(i, r, n) {\n                    Do(`playback.cues.set persistentId ${i} mediaSeqNum ${r}: parsed ${n.count} time-range ${n.startTime}:${n.endTime}`), this.updateActive(e => {\n                        let t = e.mediaOptionParsedSubtitleRecord[i];\n                        t || (t = {}, e.mediaOptionParsedSubtitleRecord[i] = t), t[r] = n\n                    })\n                }\n            };\n        class Tf extends bi {\n            constructor(e) {\n                super(e), this.store = e, this.displaySupportsHdr$ = this.select(\"supportsHdr\"), this.platformInfo$ = this.select(\"platformInfo\"), this.viewportInfo$ = this.select(\"viewportInfo\")\n            }\n            get platformInfo() {\n                return this.getValue().platformInfo\n            }\n            get displaySupportsHdr() {\n                return this.getValue().supportsHdr\n            }\n            get viewportInfo() {\n                return this.getValue().viewportInfo\n            }\n        }\n        class Ef {\n            constructor(e) {\n                this.store = e\n            }\n            getQuery() {\n                return new Tf(this.store)\n            }\n            updateSupportsHdr(t) {\n                this.store.update(e => {\n                    e.supportsHdr = t\n                })\n            }\n            updatePlatformInfo(e) {\n                this.store.update({\n                    platformInfo: e\n                })\n            }\n            updateViewportInfo(t) {\n                this.store.update(e => {\n                    e.viewportInfo = t\n                })\n            }\n        }\n        const If = new class extends dl {\n            constructor() {\n                super({\n                    supportsHdr: !0\n                }, {\n                    name: \"platform\",\n                    producerFn: su\n                })\n            }\n        };\n        let wf = null;\n\n        function Af() {\n            return wf = wf || new Ef(If), wf\n        }\n        class Of extends $t {\n            constructor(e, t) {\n                super(e => {\n                    null == t || t.add(), e.add(this._handler$.pipe(jr(([e, t, i]) => e(...t).pipe(Za({\n                        next(e) {\n                            i(e, null)\n                        },\n                        error(e) {\n                            i(null, e)\n                        }\n                    })))).subscribe())\n                }), this._vanillaRPC = e, this.teardownWG$ = t, this._handler$ = new Xt\n            }\n            register(e, i) {\n                return this._vanillaRPC.register(e, (...t) => e => {\n                    this._handler$.next([i, t, e])\n                })\n            }\n            invoke(e, t, r) {\n                return new $t(i => {\n                    this._vanillaRPC.invoke(e, t, r)((e, t) => {\n                        null != t ? i.error(t) : (i.next(e), i.complete())\n                    })\n                })\n            }\n        }\n        class kf extends Of {\n            constructor(e) {\n                super(e)\n            }\n            decrypt(e, t, i, r, n) {\n                return this.invoke(\"decrypt\", [e, t, i, r, n], [e, t, r])\n            }\n        }\n        class Cf extends Of {\n            constructor(e) {\n                super(e), this.rpcService = e, this.sessions = {}, this._onEvent = (e, t, i) => () => {\n                    null != this.sessions[e] && this.sessions[e].observer.trigger(t, i)\n                }, this.rpcService.register(\"demuxer.event\", this._onEvent)\n            }\n            init(e, t, i) {\n                return [{\n                    maxSeekHole: r,\n                    maxBufferHole: n,\n                    audioPrimingDelay: s,\n                    stretchShortVideoTrack: a,\n                    forceKeyFrameOnDiscontinuity: o\n                }] = [t], this.invoke(\"demuxer.init\", [e, t = {\n                    maxSeekHole: r,\n                    maxBufferHole: n,\n                    audioPrimingDelay: s,\n                    stretchShortVideoTrack: a,\n                    forceKeyFrameOnDiscontinuity: o\n                }, i], []).pipe(hr(e => {\n                    var t = new Df(this, e);\n                    return this.sessions[e] = t\n                }));\n                var r, n, s, a, o\n            }\n        }\n        class Df {\n            constructor(e, t) {\n                this.rpc = e, this.demuxSessionID = t, this.observer = new a\n            }\n            push(e, t, i, r, n, s, a, o, l, d, u, c, h) {\n                return this.rpc.invoke(\"demuxer.push\", [this.demuxSessionID, e, t, i, r, n, s, a, o, l, d, u, c], null != h ? h : [e])\n            }\n            pushWithoutTransfer(e, t, i, r, n, s, a, o, l, d, u, c) {\n                return this.push(e, t, i, r, n, s, a, o, l, d, u, c, [])\n            }\n            destroy() {\n                this.observer.removeAllListeners(), this.rpc.invoke(\"demuxer.destroy\", [this.demuxSessionID], []).subscribe()\n            }\n        }\n        class Mf {\n            constructor() {\n                this.handlers = {}\n            }\n            register(e, t) {\n                if (null != this.handlers[e]) return !1;\n                this.handlers[e] = t\n            }\n            unregister(e) {\n                if (null != this.handlers[e]) return !1;\n                delete this.handlers[e]\n            }\n            invoke(e, i) {\n                return (t = Mf._fallbackCallback) => {\n                    try {\n                        if (null == this.handlers[e]) throw new Error(`command ${e} not found`);\n                        this.handlers[e](...i)(t)\n                    } catch (e) {\n                        t(void 0, e)\n                    }\n                }\n            }\n            teardown(e) {\n                this.handlers = null, e()\n            }\n        }\n        Mf._fallbackCallback = (e, t) => {\n            if (null != t) throw t\n        };\n        const xf = e => {\n            e = e.child({\n                name: \"InlineRPCService\"\n            });\n            var t = new Mf;\n            return new i(t, e), new ot(t, e), t\n        };\n        let Pf;\n        const Rf = e => {\n                try {\n                    if (null == Pf) {\n                        const e = new Blob([\"var exports = {};var module = { exports: exports };function define(f){f()};define.amd = true;(\" + Xy.toString() + \")(true);\"], {\n                                type: \"text/javascript\"\n                            }),\n                            r = URL.createObjectURL(e);\n                        Pf = new Worker(r)\n                    }\n                    var t = new lt(Pf);\n                    return i = t, n = e.child({\n                        name: \"WorkerRPCService\"\n                    }), i.register(\"logger.log\", (e, i, ...r) => t => {\n                        try {\n                            for (const i of e) n = n.child(i);\n                            \"function\" == typeof n[i] && n[i](...r), t()\n                        } catch (e) {\n                            t(void 0, e)\n                        }\n                    }), t\n                } catch (e) {\n                    throw new Error(\"Failed to create WebWorker\")\n                }\n                var i, n\n            },\n            Lf = (...r) => i => {\n                for (let t = 0; t < r.length; t++) {\n                    const e = r[t];\n                    try {\n                        return e(i)\n                    } catch (e) {\n                        if (t === r.length - 1) throw e;\n                        i.warn(e)\n                    }\n                }\n            },\n            _f = e => Lf(Rf, xf)(e);\n        class Nf {}\n        Nf.PlayEnded = 6101, Nf.Periodic = 6110, Nf.PlayStalled = 6103, Nf.KeySessionComplete = 6104, Nf.PlayLikelyToKeepUp = 6105, Nf.PlayRateChanged = 6106, Nf.PlayError = 6107, Nf.MediaEngineStalled = 6108, Nf.SwitchComplete = 6109, Nf.VariantEnded = 6111, Nf.NwError = 6202;\n        const Ff = {\n            avc1: 1,\n            avc3: 1,\n            hvc1: {\n                SDR: 2,\n                HLG: 10,\n                PQ: 11\n            },\n            hev1: {\n                SDR: 2,\n                HLG: 10,\n                PQ: 11\n            },\n            vp09: {\n                SDR: 3,\n                HLG: 14,\n                PQ: 13\n            },\n            dvh1: {\n                PQ: 12\n            }\n        };\n        class Bf {\n            constructor(e, t) {\n                this.query = e, this.logger = t\n            }\n            setReportingAgent(e) {\n                this.reportingAgent = e\n            }\n            sendPlayEnded(e) {\n                var t = Nf.PlayEnded;\n                this.fillAndFire(t, this.query.playEnded(e))\n            }\n            sendPlayStalled(e) {\n                var t = Nf.PlayStalled;\n                this.fillAndFire(t, this.query.playStalled(e))\n            }\n            sendMediaEngineStalled(e) {\n                var t = Nf.MediaEngineStalled;\n                this.fillAndFire(t, this.query.mediaEngineStalled(e))\n            }\n            sendKeySessionComplete(e) {\n                var t = Nf.KeySessionComplete;\n                this.fillAndFire(t, this.query.keySessionComplete(e))\n            }\n            sendPlayLikelyToKeepUp(e) {\n                var t = Nf.PlayLikelyToKeepUp;\n                this.fillAndFire(t, this.query.playLikelyToKeepUp(e))\n            }\n            sendPlayRateChange(e) {\n                var t = Nf.PlayRateChanged;\n                this.fillAndFire(t, this.query.playRateChanged(e))\n            }\n            sendSwitchComplete(e) {\n                var t = Nf.SwitchComplete;\n                this.fillAndFire(t, this.query.switchComplete(e))\n            }\n            sendVariantEnded(e) {\n                var t = Nf.VariantEnded;\n                this.fillAndFire(t, this.query.variantEnded(e))\n            }\n            sendPlayError(e) {\n                var t = Nf.PlayError;\n                this.fillAndFire(t, this.query.playError(e))\n            }\n            sendNwError(e) {\n                var t = Nf.NwError;\n                this.fillAndFire(t, this.query.nwError(e))\n            }\n            sendPeriodic(e) {\n                var t = Nf.Periodic;\n                this.fillAndFire(t, this.query.periodic(e))\n            }\n            fillAndFire(e, t) {\n                if (e !== Nf.Periodic || t.PlayTimeWC || t.ADT) {\n                    var r = e === Nf.PlayEnded || e === Nf.Periodic ? 1 : 0;\n                    if (this.reportingAgent) {\n                        let i = {};\n                        Object.entries(t).forEach(([e, t]) => {\n                            \"object\" == typeof(t = ne(t) ? Number(Number(t).toFixed(2)) : t) ? \"ServerInfo\" === e && Object.entries(t).forEach(([e, t]) => {\n                                i[e] = t\n                            }): i[e] = t\n                        }), i = JSON.parse(JSON.stringify(i));\n                        try {\n                            this.reportingAgent.issueReportingEvent(e, i, r)\n                        } catch (e) {}\n                    }\n                }\n            }\n        }\n        class Uf extends kl {\n            constructor(e, t) {\n                super(e), this.logger = t\n            }\n            get activeEntity() {\n                return this.getActive()\n            }\n            entity(e) {\n                return this.getEntity(e)\n            }\n            playEnded(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playEndedRecord\n            }\n            periodic(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.periodicRecord\n            }\n            playStalled(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playStalledRecord\n            }\n            mediaEngineStalled(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.mediaEngineStalledRecord\n            }\n            keySessionComplete(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.keySessionCompleteRecord\n            }\n            playLikelyToKeepUp(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playLikelyToKeepUpRecord\n            }\n            playRateChanged(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playRateChangedRecord\n            }\n            switchComplete(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.switchCompleteRecord\n            }\n            variantEnded(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.variantEndedRecord\n            }\n            playError(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playErrorRecord\n            }\n            nwError(e) {\n                return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.nwErrorRecord\n            }\n        }\n        class $f extends fl {\n            constructor(e) {\n                super({}, {\n                    name: \"rtc-store\",\n                    idKey: \"itemId\",\n                    producerFn: su,\n                    resettable: !0\n                }), this.logger = e\n            }\n            createEntity(e) {\n                e = {\n                    itemId: e,\n                    sessionControlRecord: {\n                        state: \"RTC_STATE_INIT\",\n                        rate: 0,\n                        oldRate: 0,\n                        eventStartTime: Date.now(),\n                        sessionStartTime: Date.now(),\n                        lastLikelyToKeepUpTime: Date.now(),\n                        lastPeriodicTime: Date.now(),\n                        playLikelyToKeepUpEventCounter: 1,\n                        periodicEventCounter: 1,\n                        activeKeySessions: {},\n                        intervalVariantList: {},\n                        sessionVariantList: {}\n                    },\n                    playEndedRecord: {},\n                    periodicRecord: {},\n                    playStalledRecord: {},\n                    keySessionCompleteRecord: {},\n                    playLikelyToKeepUpRecord: {},\n                    playRateChangedRecord: {},\n                    playErrorRecord: {},\n                    mediaEngineStalledRecord: {},\n                    switchCompleteRecord: {},\n                    variantEndedRecord: {},\n                    nwErrorRecord: {}\n                };\n                this.add(e)\n            }\n            updateEnded(e) {\n                this._prepareEventPlayEnded(e)\n            }\n            updatePeriodic(e, t) {\n                this._prepareEventPeriodic(e, {\n                    isFinal: t\n                })\n            }\n            updateBufferStalled(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    variantEndedRecord: t,\n                    periodicRecord: i,\n                    playEndedRecord: r\n                }) => {\n                    e.rate = 0, t.StallCount = (t.StallCount || 0) + 1, i.StallCount = (i.StallCount || 0) + 1, r.StallCount = (r.StallCount || 0) + 1\n                }), this._prepareEventPlayStalled(e, t)\n            }\n            updateSegmentKeyLoaded(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = {},\n                        i = r.timestamp;\n                    t.keyFormat = \"identity\", t.keyDeliveryTime = r.adt, t.currentMediaTime = r.currentTime, \"RTC_STATE_INIT\" === e.state && (t.keyInitTime = i - e.sessionStartTime), e.activeKeySessions[r.keyuri] = t\n                }), this._prepareEventKeySessionComplete(e, r)\n            }\n            updateLicenseResponseProcessed(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    t.licenseResponseProcessTime = i.timestamp - t.licenseResponseSubmitTime, e.lastKeyDeliveryTime = t.keyDeliveryTime = i.timestamp - t.licenseChallengeStartTime, t.currentMediaTime = i.currentTime, e.finishedKeyUri = i.keyuri\n                }), this._prepareEventKeySessionComplete(e, i)\n            }\n            updateLicenseChallengeError(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    e.lastKeyErrorType = t.keyErrorType = \"licenseChallengeError\", e.finishedKeyUri = i.keyuri\n                }), this._prepareEventKeySessionComplete(e, i)\n            }\n            updateLicenseResponseError(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    e.lastKeyErrorType = t.keyErrorType = \"licenseResponseError\", e.finishedKeyUri = i.keyuri\n                }), this._prepareEventKeySessionComplete(e, i)\n            }\n            updateKeyAborted(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.activeKeySessions[t.keyuri].keyErrorType = \"keyAborted\", e.finishedKeyUri = t.keyuri\n                }), this._prepareEventKeySessionComplete(e, t)\n            }\n            updateCanPlay(e, t) {\n                this.update(e, ({}) => {}), this._prepareEventPlayLikelyToKeepUp(e, t)\n            }\n            updateRateChanged(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.rate = 100 * t.rate, 0 < t.rate && 0 === e.oldRate && (e.playInfo || (e.playInfo = []), e.playInfo.push({\n                        latency: t.latency\n                    }), e.curLevelUrl || (e.curLevelUrl = t.url))\n                }), this._prepareEventPlayRateChanged(e, t)\n            }\n            updateMediaError(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    periodicRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    t.PlayerErrCount = (t.PlayerErrCount || 0) + 1, i.PlayerErrCount = (i.PlayerErrCount || 0) + 1, r.fatal && (e.rate = 0, t.FatalPlayerErrCount = (t.FatalPlayerErrCount || 0) + 1, i.FatalPlayerErrCount = (i.FatalPlayerErrCount || 0) + 1, i.ErrCode = r.details, i.ErrReason = r.code, i.ErrIsFatal = !0, i.ErrDomain = \"mediaError\")\n                }), r.fatal ? this._prepareEventPlayError(e, r) : this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    var t = r.details + \"/\" + r.code;\n                    e.nonFatalPlayErrList[t] = (e.nonFatalPlayErrList[t] || 0) + 1\n                })\n            }\n            updateMediaElementError(e, t) {\n                let i;\n                try {\n                    i = JSON.parse(t.message)\n                } catch (e) {\n                    this.logger.warn(`message is not JSON, ignoring; ${t.message}`)\n                }\n                var r = i ? parseInt(i.ErrReason) : null,\n                    n = i ? parseInt(i.ErrDetail) : null;\n                this._prepareEventPlayError(e, {\n                    domain: \"mediaElementError\",\n                    mediaElemCode: t.code,\n                    mediaElemReason: r,\n                    mediaElemDetail: n,\n                    code: null,\n                    details: null,\n                    fatal: null\n                })\n            }\n            updateMediaEngineStalled(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    variantEndedRecord: t,\n                    periodicRecord: i,\n                    playEndedRecord: r\n                }) => {\n                    e.rate = 0, t.MediaEngineStallCount = (t.MediaEngineStallCount || 0) + 1, i.MediaEngineStallCount = (i.MediaEngineStallCount || 0) + 1, r.MediaEngineStallCount = (r.MediaEngineStallCount || 0) + 1\n                }), this._prepareEventMediaEngineStalled(e, t)\n            }\n            updateLevelSwitched(e, d) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    switchCompleteRecord: t,\n                    periodicRecord: i,\n                    playEndedRecord: r\n                }) => {\n                    i.SwCnt = (i.SwCnt || 0) + 1, r.SwCnt = (r.SwCnt || 0) + 1;\n                    var n = Date.now(),\n                        s = e.curLevelUrl,\n                        a = d.url,\n                        i = this._getVariantInfo(s, e),\n                        r = this._getVariantInfo(a, e);\n                    let o, l = !1;\n                    s && (o = r.bandwidth < i.bandwidth ? \"Down\" : \"Up\", l = r.iframes), t.BadSw = this._isBadSw(o, e.lastSwitchDir || o, l, e.lastLevelIsIframe || l, n, e.lastSwitchTime || n, d.isSeeking), e.lastSwitchDir = o, e.lastSwitchTime = n, e.lastLevelIsIframe = l, e.curLevelUrl = a, e.variantStartTimeMedia = d.currentTime\n                }), this._prepareEventSwitchComplete(e, d)\n            }\n            updateLevelLoadError(e, o) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    switchCompleteRecord: t,\n                    periodicRecord: i,\n                    playEndedRecord: r\n                }) => {\n                    var n = Date.now();\n                    let s, a = !1;\n                    if (e.curLevelUrl) {\n                        const t = this._getVariantInfo(e.curLevelUrl, e),\n                            i = this._getVariantInfo(o.url, e);\n                        s = i.bandwidth < t.bandwidth ? \"Down\" : \"Up\", a = i.iframes\n                    }\n                    i.SwCnt = (i.SwCnt || 0) + 1, r.SwCnt = (r.SwCnt || 0) + 1, t.BadSw = this._isBadSw(s, e.lastSwitchDir || s, a, e.lastLevelIsIframe || a, n, e.lastSwitchTime || n, o.isSeeking), t.SwFail = !0\n                }), this._prepareEventSwitchComplete(e, o)\n            }\n            updateVariantEnd(e, t) {\n                this._prepareEventVariantEnded(e, t)\n            }\n            updateNwError(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    periodicRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    t.NwErrCount = (t.NwErrCount || 0) + 1, i.NwErrCount = (i.NwErrCount || 0) + 1, r.fatal && (e.rate = 0, t.FatalNwErrCount = (t.FatalNwErrCount || 0) + 1, i.FatalNwErrCount = (i.FatalNwErrCount || 0) + 1, i.ErrCode = r.details, i.ErrReason = r.code, i.ErrIsFatal = !0, i.ErrDomain = \"networkError\")\n                }), r.fatal ? this._prepareEventNwError(e, r) : this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    var t = r.details + \"/\" + r.code;\n                    e.nonFatalNwErrList[t] = (e.nonFatalNwErrList[t] || 0) + 1\n                })\n            }\n            finalize(e, t) {\n                switch (t) {\n                    case Nf.PlayEnded:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            e.state = \"RTC_STATE_STOP\", e.oldRate = 0\n                        }), this.update(e, e => {\n                            e.playEndedRecord = {}\n                        });\n                        break;\n                    case Nf.Periodic:\n                        this.update(e, ({\n                            sessionControlRecord: t\n                        }) => {\n                            t.lastPeriodicTime = Date.now(), t.periodicEventCounter += 1, Object.keys(t.intervalVariantList).forEach(e => {\n                                t.intervalVariantList[e].playTime = 0\n                            })\n                        }), this.update(e, e => {\n                            e.periodicRecord = {}\n                        });\n                        break;\n                    case Nf.PlayStalled:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            e.state = \"RTC_STATE_STALL\", e.oldRate = 0\n                        }), this.update(e, e => {\n                            e.playStalledRecord = {}\n                        });\n                        break;\n                    case Nf.KeySessionComplete:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            delete e.activeKeySessions[e.finishedKeyUri]\n                        }), this.update(e, e => {\n                            e.keySessionCompleteRecord = {}\n                        });\n                        break;\n                    case Nf.PlayLikelyToKeepUp:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            \"RTC_STATE_PLAY\" !== e.state && (e.state = \"RTC_STATE_CANPLAY\", e.lastLikelyToKeepUpTime = Date.now(), e.playLikelyToKeepUpEventCounter += 1)\n                        }), this.update(e, e => {\n                            e.playLikelyToKeepUpRecord = {}\n                        });\n                        break;\n                    case Nf.PlayRateChanged:\n                        this.update(e, ({\n                            sessionControlRecord: e,\n                            playEndedRecord: t,\n                            playStalledRecord: i,\n                            mediaEngineStalledRecord: r,\n                            playErrorRecord: n,\n                            nwErrorRecord: s\n                        }) => {\n                            0 !== e.rate ? (e.state = \"RTC_STATE_PLAY\", delete t.LastStall, delete t.LastMediaEngineStall, delete t.LastPause, delete n.LastPause, delete s.LastPause) : (e.state = \"RTC_STATE_PAUSE\", delete i.LastResume, delete r.LastResume, delete n.LastResume, delete s.LastResume), e.oldRate = e.rate\n                        }), this.update(e, e => {\n                            e.playRateChangedRecord = {}\n                        });\n                        break;\n                    case Nf.PlayError:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            e.state = \"RTC_STATE_PLAYERROR\"\n                        }), this.update(e, e => {\n                            e.playErrorRecord = {}\n                        });\n                        break;\n                    case Nf.MediaEngineStalled:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            e.state = \"RTC_STATE_MEDIAENGINESTALL\", e.oldRate = 0\n                        }), this.update(e, e => {\n                            e.mediaEngineStalledRecord = {}\n                        });\n                        break;\n                    case Nf.SwitchComplete:\n                        this.update(e, e => {\n                            e.switchCompleteRecord = {}, e.sessionControlRecord.prevLevelUrl = e.sessionControlRecord.curLevelUrl\n                        });\n                        break;\n                    case Nf.VariantEnded:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            e.decodedFramesForVariant = 0, e.decodedFramesForVariantSampleCount = 0\n                        }), this.update(e, e => {\n                            e.variantEndedRecord = {}\n                        });\n                        break;\n                    case Nf.NwError:\n                        this.update(e, ({\n                            sessionControlRecord: e\n                        }) => {\n                            e.state = \"RTC_STATE_NWERROR\"\n                        }), this.update(e, e => {\n                            e.nwErrorRecord = {}\n                        })\n                }\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.eventStartTime = Date.now()\n                })\n            }\n            updatePlaybackInfo(e, s) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    periodicRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    s.droppedVideoFrames < e.droppedVideoFrames && (e.droppedVideoFrames = 0), s.decodedFrameCount < e.decodedFrameCount && (e.decodedFrameCount = 0);\n                    var r = s.droppedVideoFrames - (e.droppedVideoFrames || 0),\n                        n = s.decodedFrameCount - (e.decodedFrameCount || 0);\n                    e.droppedVideoFrames = s.droppedVideoFrames, e.decodedFrameCount = s.decodedFrameCount, e.decodedFramesForVariant += n, e.decodedFramesForVariantSampleCount += 1, r && (3 <= r ? (t.GroupViFrDr = (t.GroupViFrDr || 0) + r, t.GroupViFrDrEvtCount = (t.GroupViFrDrEvtCount || 0) + 1, i.GroupViFrDr = (i.GroupViFrDr || 0) + r, i.GroupViFrDrEvtCount = (i.GroupViFrDrEvtCount || 0) + 1) : (t.SparseViFrDr = (t.SparseViFrDr || 0) + r, t.SparseViFrDrEvtCount = (t.SparseViFrDrEvtCount || 0) + 1, i.SparseViFrDr = (i.SparseViFrDr || 0) + r, i.SparseViFrDrEvtCount = (i.SparseViFrDrEvtCount || 0) + 1))\n                })\n            }\n            updateBufferAppended(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.bufferAppendInfo || (e.bufferAppendInfo = []), e.bufferAppendInfo.push(t)\n                })\n            }\n            updateSeeked(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.seekInfo || (e.seekInfo = []), e.seekInfo.push(t)\n                })\n            }\n            updateManifestParsed(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    periodicRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    t.MasterPlaylistADT = (t.MasterPlaylistADT || 0) + r.adt, i.MasterPlaylistADT = (i.MasterPlaylistADT || 0) + r.adt;\n                    t = this._computeVariantInfo(r.levels);\n                    i.IsAudioOnly = r.isAudioOnly, i.IsGapless = r.isGapless, i.IsFirstItem = r.isFirstItem, i.ItemID = r.itemID, i.MaxVideoQltyIndex = t.maxVideoQltyIndex, i.MaxReWd = t.maxWidth, i.MaxReHt = t.maxHeight, e.manifestData = {\n                        variantList: t.variantList,\n                        varListString: t.varListString\n                    }\n                })\n            }\n            updateFragLoaded(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    periodicRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    if (t.MediaRequestsSent = (t.MediaRequestsSent || 0) + 1, i.MediaRequestsSent = (i.MediaRequestsSent || 0) + 1, r.cdnServer) {\n                        const e = r.cdnServer.toLowerCase();\n                        \"aapl\" !== e && \"akam\" !== e && \"llnw\" !== e || (i.LastMediaCDNServer = e)\n                    }\n                    r.serverInfo && (i.ServerInfo = r.serverInfo), e.segmentMimeTypes || (e.segmentMimeTypes = []), void 0 === e.segmentMimeTypes.find(e => e == r.contentType) && e.segmentMimeTypes.push(r.contentType), r.fragType === gu.Variant ? (e.variantVideoBytes = (e.variantVideoBytes || 0) + r.bytes, e.variantVideoDuration = (e.variantVideoDuration || 0) + r.duration, e.intervalVideoBytes = (e.intervalVideoBytes || 0) + r.bytes, e.intervalVideoDuration = (e.intervalVideoDuration || 0) + r.duration, e.sessionVideoBytes = (e.sessionVideoBytes || 0) + r.bytes, e.sessionVideoDuration = (e.sessionVideoDuration || 0) + r.duration, e.obrLast = 8 * r.bytes / (r.duration / 1e3), t.NetBytes = (t.NetBytes || 0) + r.bytes, t.ADT = (t.ADT || 0) + r.adt, t.SegmentProcessTime = (t.SegmentProcessTime || 0) + r.processTime, i.ADT = (i.ADT || 0) + r.adt, i.NetBytes = (i.NetBytes || 0) + r.bytes, i.SegmentProcessTime = (i.SegmentProcessTime || 0) + r.processTime) : r.fragType === gu.AltAudio && (e.variantAudioBytes = (e.variantAudioBytes || 0) + r.bytes, e.variantAudioDuration = (e.variantAudioDuration || 0) + r.duration, e.intervalAudioBytes = (e.intervalAudioBytes || 0) + r.bytes, e.intervalAudioDuration = (e.intervalAudioDuration || 0) + r.duration, e.sessionAudioBytes = (e.sessionAudioBytes || 0) + r.bytes, e.sessionAudioDuration = (e.sessionAudioDuration || 0) + r.duration)\n                })\n            }\n            updateFragBuffered(e, i) {\n                this.update(e, ({\n                    periodicRecord: e,\n                    playEndedRecord: t\n                }) => {\n                    i.fragType === gu.Variant && (e.SegmentParseTime = (e.SegmentParseTime || 0) + i.parseTime, t.SegmentParseTime = (t.SegmentParseTime || 0) + i.parseTime)\n                })\n            }\n            updateLevelLoaded(e, n) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    playLikelyToKeepUpRecord: t,\n                    periodicRecord: i,\n                    playEndedRecord: r\n                }) => {\n                    t.PlaylistADT = (t.PlaylistADT || 0) + n.adt, i.PlaylistADT = (i.PlaylistADT || 0) + n.adt, r.PlaylistADT = (r.PlaylistADT || 0) + n.adt, i.MaxPlaylistDT = n.adt > i.MaxPlaylistDT ? n.adt : i.MaxPlaylistDT, r.MaxPlaylistDT = n.adt > r.MaxPlaylistDT ? n.adt : r.MaxPlaylistDT, r.PlayType = n.playType, this._setTargetDuration(n.url, n.targetduration, e), e.playlistMimeTypes || (e.playlistMimeTypes = []), void 0 === e.playlistMimeTypes.find(e => e == n.contentType) && e.playlistMimeTypes.push(n.contentType);\n                    i = n.url, r = this._getVariantInfo(i, e);\n                    e.intervalVariantList[i] || (e.intervalVariantList[i] = Object.assign({}, r)), e.sessionVariantList[i] || (e.sessionVariantList[i] = Object.assign({}, r))\n                })\n            }\n            updateLevelsChanged(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: t,\n                    playEndedRecord: e\n                }) => {\n                    const i = this._computeVariantInfo(r.levels);\n                    e.MaxVideoQltyIndex = i.maxVideoQltyIndex, e.MaxReWd = i.maxWidth, e.MaxReHt = i.maxHeight, t.manifestData = {\n                        variantList: i.variantList,\n                        varListString: i.varListString\n                    }, Object.keys(i.variantList).forEach(e => {\n                        t.intervalVariantList[e] && (t.intervalVariantList[e].brRnk = i.variantList[e].brRnk), t.sessionVariantList[e] && (t.sessionVariantList[e].brRnk = i.variantList[e].brRnk)\n                    })\n                })\n            }\n            updateLicenseChallengeRequested(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = {},\n                        i = r.timestamp;\n                    t.licenseChallengeStartTime = i, \"RTC_STATE_INIT\" === e.state && (t.keyInitTime = i - e.sessionStartTime), e.activeKeySessions[r.keyuri] = t\n                })\n            }\n            updateLicenseChallengeReceived(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    t.licenseChallengeRequestTime = i.timestamp - t.licenseChallengeStartTime\n                })\n            }\n            updateLicenseChallengeSubmitted(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    t.keyFormat = i.keyFormat, t.licenseChallengeSubmitTime = i.timestamp\n                })\n            }\n            updateLicenseChallengeCreated(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    t.cdmVersion = i.cdmVersion, t.licenseChallengeCreationTime = i.timestamp - t.licenseChallengeSubmitTime\n                })\n            }\n            updateLicenseResponseRequested(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.activeKeySessions[t.keyuri].licenseResponseRequestTime = t.timestamp\n                })\n            }\n            updateLicenseResponseReceived(e, i) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    const t = e.activeKeySessions[i.keyuri];\n                    t.licenseResponseReceiveTime = i.timestamp - t.licenseResponseRequestTime\n                })\n            }\n            updateLicenseResponseSubmitted(e, t) {\n                this.update(e, ({\n                    sessionControlRecord: e\n                }) => {\n                    e.activeKeySessions[t.keyuri].licenseResponseSubmitTime = t.timestamp\n                })\n            }\n            _prepareEventPlayEnded(e) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    playEndedRecord: t\n                }) => {\n                    t.AvgVideoBitrate = 8 * (e.sessionVideoBytes || 0) / (e.sessionVideoDuration || 1), t.AvgAudioBitrate = 8 * (e.sessionAudioBytes || 0) / (e.sessionAudioDuration || 1);\n                    var i = 1e3 * Math.round((t.NetBytes || 0) / 1e3);\n                    t.NetBytes = i;\n                    var r = t.ADT || 1,\n                        n = t.ADT + t.SegmentProcessTime || 1,\n                        s = t.ADT + t.SegmentProcessTime + t.SegmentParseTime || 1;\n                    t.TWOBR = 8 * i / (r / 1e3), t.PerceivedTWOBR = 8 * i / (n / 1e3), t.NetTWOBR = 8 * i / (s / 1e3);\n                    var s = this._findTimeWeightedValues(\"RTC_STATE_PLAY\" === e.state ? Date.now() - e.eventStartTime : 0, e.sessionVariantList, e.curLevelUrl);\n                    t.PlayerTWIBR = s.twIBR, t.PlayerTWIABR = s.twIABR, t.TWBitRk = s.twBRnk;\n                    s = this._getVariantInfo(e.curLevelUrl, e);\n                    t.TargetDur = s.targetduration, t.ReWd = s.width, t.ReHt = s.height, t.VariantList = null === (s = e.manifestData) || void 0 === s ? void 0 : s.varListString;\n                    let a = \"\";\n                    e.playlistMimeTypes && (e.playlistMimeTypes.forEach(e => {\n                        a += e + \",\"\n                    }), a = a.slice(0, -1));\n                    let o = \"\";\n                    e.segmentMimeTypes && (e.segmentMimeTypes.forEach(e => {\n                        o += e + \",\"\n                    }), o = o.slice(0, -1)), t.PlaylistMimeType = a, t.SegmentMimeType = o, t.Rate = e.rate\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventPeriodic(e, o) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    periodicRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    t.EventCounter = e.periodicEventCounter, t.PInterval = Date.now() - e.lastPeriodicTime, t.AvgVideoBitrate = 8 * (e.intervalVideoBytes || 0) / (e.intervalVideoDuration || 1), t.AvgAudioBitrate = 8 * (e.intervalAudioBytes || 0) / (e.intervalAudioDuration || 1);\n                    let r = t.NetBytes || 0;\n                    o.isFinal && (t.NetBytes = r = 1e3 * Math.round(r / 1e3));\n                    var n = t.ADT || 1,\n                        s = t.ADT + t.SegmentProcessTime || 1,\n                        a = t.ADT + t.SegmentProcessTime + t.SegmentParseTime || 1;\n                    t.TWOBR = 8 * r / (n / 1e3), t.PerceivedTWOBR = 8 * r / (s / 1e3), t.NetTWOBR = 8 * r / (a / 1e3);\n                    var a = this._findTimeWeightedValues(\"RTC_STATE_PLAY\" === e.state ? Date.now() - e.eventStartTime : 0, e.intervalVariantList, e.curLevelUrl);\n                    t.PlayerTWIBR = a.twIBR, t.PlayerTWIABR = a.twIABR, t.TWBitRk = a.twBRnk;\n                    a = this._getVariantInfo(e.curLevelUrl, e);\n                    t.TargetDur = a.targetduration, t.ReWd = a.width, t.ReHt = a.height, t.VariantList = null === (a = e.manifestData) || void 0 === a ? void 0 : a.varListString, t.Rate = e.rate;\n                    e = this._computeMediaStats(e);\n                    e && (t.MedianBufferAppendLatency = e.bufLatencyInfo.median, t.MaxBufferAppendLatency = e.bufLatencyInfo.max, t.MedianBufferAppendSize = e.bufSizeInfo.median, t.MaxBufferAppendSize = e.bufSizeInfo.max, t.MedianSeekLatency = e.seekLatencyInfo.median, t.MaxSeekLatency = e.seekLatencyInfo.max, t.MedianPlayLatency = e.playLatencyInfo.median, t.MaxPlayLatency = e.playLatencyInfo.max), this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventPlayStalled(e, s) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    playStalledRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.curLevelUrl, e),\n                        n = Date.now();\n                    t.MediaDur = s.mediaDur, t.BitRnk = r.brRnk, t.Codecs = r.codecs, t.LastLikelyToKeepUp = n - e.lastLikelyToKeepUpTime, t.LastSwitch = n - e.lastSwitchTime, t.StallDetectionTime = s.stallDurationMs, t.StallType = s.type, t.BufferLength = s.bufferLen, \"networkError\" === i.ErrDomain && (t.NwErrTime = i.NwErrTime, t.NwErrCode = i.ErrCode), t.LaSwDir = e.lastSwitchDir, t.TargetDur = r.targetduration, t.PlayerIABR = r.avgBandwidth, t.PlayerIBR = r.bandwidth, t.Rate = e.rate, t.OBRLast = e.obrLast, t.OBRMean = 8 * i.NetBytes / (i.ADT / 1e3), this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventKeySessionComplete(e, r) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    keySessionCompleteRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    e = e.activeKeySessions[r.keyuri];\n                    e ? (t.KeyFormat = e.keyFormat, t.CDMVersion = e.cdmVersion, t.LicenseChallengeRequestTime = e.licenseChallengeRequestTime, t.LicenseChallengeCreationTime = e.licenseChallengeCreationTime, t.LicenseResponseReceiveTime = e.licenseResponseReceiveTime, t.LicenseResponseProcessTime = e.licenseResponseProcessTime, t.KeyDeliveryTime = e.keyDeliveryTime, t.CurrentMediaTime = 1e3 * e.currentMediaTime, t.KeyInitTime = e.keyInitTime, t.KeyErrorType = e.keyErrorType, this._copyCommonKeys(t, i)) : this.logger.warn(`_prepareEventKeySessionComplete no keySessionInfo for ${le(r.keyuri)}`)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventPlayLikelyToKeepUp(e, n) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    playLikelyToKeepUpRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.curLevelUrl, e);\n                    t.EventCounter = e.playLikelyToKeepUpEventCounter, t.PlayerIABR = r.avgBandwidth, t.PlayerIBR = r.bandwidth, t.MediaDur = n.mediaDur, t.BitRnk = r.brRnk, t.Codecs = r.codecs, t.TargetDur = r.targetduration, this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventPlayRateChanged(e, n) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    playRateChangedRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.curLevelUrl, e);\n                    t.Rate = e.rate, t.StNPT = n.currentTime, t.PlayerIABR = r.avgBandwidth, t.PlayerIBR = r.bandwidth, t.BitRnk = r.brRnk, t.MediaDur = n.mediaDur, t.Codecs = r.codecs, this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventPlayError(e, s) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    playErrorRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.curLevelUrl, e),\n                        n = Date.now();\n                    \"mediaElementError\" == s.domain ? (t.ErrDomain = t.ErrCode = \"mediaElementError\", t.ErrIsFatal = !0, t.ErrCodeMediaElement = s.mediaElemCode, t.ErrReason = s.mediaElemReason, t.ErrDetail = s.mediaElemDetail) : (t.ErrCode = s.details, t.ErrReason = s.code, t.ErrIsFatal = s.fatal, t.ErrDomain = \"mediaError\"), t.PlayerErrCount = s.count || 1, t.BitRnk = r.brRnk, t.MediaDur = s.mediaDur, t.PlayTime = i.PlayTime, t.PlayTimeWC = i.PlayTimeWC, t.PlayerIABR = r.avgBandwidth, t.PlayerIBR = r.bandwidth, t.LastLikelyToKeepUp = n - e.lastLikelyToKeepUpTime, t.LastSwitch = n - e.lastSwitchTime, t.VideoQltyIndex = r.qltyIndex, t.Rate = e.rate, t.KeyErrorType = e.lastKeyErrorType, t.KeyDeliveryTime = e.lastKeyDeliveryTime, this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventMediaEngineStalled(e, s) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    mediaEngineStalledRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = Date.now(),\n                        n = this._getVariantInfo(e.curLevelUrl, e);\n                    t.MediaDur = s.mediaDur, t.BitRnk = n.brRnk, t.Codecs = n.codecs, t.LastLikelyToKeepUp = r - e.lastLikelyToKeepUpTime, t.LastSwitch = r - e.lastSwitchTime, t.StallDetectionTime = s.stallDurationMs, t.StallType = s.type, t.BufferLength = s.bufferLen, t.LaSwDir = e.lastSwitchDir, t.TargetDur = n.targetduration, t.PlayerIABR = n.avgBandwidth, t.PlayerIBR = n.bandwidth, t.Rate = e.rate, t.OBRLast = e.obrLast, t.OBRMean = 8 * i.NetBytes / (i.ADT / 1e3), this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventSwitchComplete(e, s) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    switchCompleteRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.prevLevelUrl, e),\n                        n = this._getVariantInfo(e.curLevelUrl, e);\n                    t.FrBitRnk = r.brRnk, t.ToBitRnk = n.brRnk, t.TimeToBitrate = Date.now() - e.sessionStartTime, t.MediaDur = s.mediaDur, t.Rate = e.rate, t.PlayerIBR = n.bandwidth, t.PlayerIABR = n.avgBandwidth, t.LastPlayerIBR = r.bandwidth, t.LastPlayerIABR = r.avgBandwidth, t.ReWd = n.width, t.ReHt = n.height, this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventVariantEnded(e, n) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    variantEndedRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.curLevelUrl, e);\n                    t.Rate = e.rate, t.VarAvgBitrate = r.avgBandwidth, t.VarPeakBitrate = r.bandwidth, t.VarBitRk = r.brRnk, t.VarSTTime = e.variantStartTimeMedia, t.VarEndTime = 1e3 * n.currentTime, t.IFR = r.framerate, t.ODR = e.decodedFramesForVariant / e.decodedFramesForVariantSampleCount, t.ReWd = r.width, t.ReHt = r.height, t.Codecs = r.codecs, t.AvgVideoBitrate = 8 * (e.variantVideoBytes || 0) / (e.variantVideoDuration || 1), t.AvgAudioBitrate = 8 * (e.variantAudioBytes || 0) / (e.variantAudioDuration || 1), this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _prepareEventNwError(e, n) {\n                this.update(e, ({\n                    sessionControlRecord: e,\n                    nwErrorRecord: t,\n                    playEndedRecord: i\n                }) => {\n                    var r = this._getVariantInfo(e.curLevelUrl, e);\n                    t.ErrCode = n.details, t.ErrReason = n.code, t.ErrIsFatal = n.fatal, t.NwErrCount = n.count || 1, t.ErrDomain = \"networkError\", t.PlayTime = i.PlayTime, t.PlayTimeWC = i.PlayTimeWC, t.BitRnk = r.brRnk, t.Rate = e.rate, t.KeyErrorType = e.lastKeyErrorType, t.KeyDeliveryTime = e.lastKeyDeliveryTime, this._copyCommonKeys(t, i)\n                }), this._aggregateTimes(e)\n            }\n            _copyCommonKeys(e, t) {\n                e.PlayType = t.PlayType, e.LastMediaCDNServer = t.LastMediaCDNServer, e.MaxVideoQltyIndex = t.MaxVideoQltyIndex, e.MaxReWd = t.MaxReWd, e.MaxReHt = t.MaxReHt, e.IsGapless = t.IsGapless, e.IsAudioOnly = t.IsAudioOnly, e.IsFirstItem = t.IsFirstItem, e.ItemID = t.ItemID, e.ServerInfo = t.ServerInfo\n            }\n            _computeVariantInfo(e) {\n                const i = {};\n                let r = 0,\n                    n = 0,\n                    s = 0,\n                    a = 0;\n                const o = this._getMaxNormalizedPeak(e);\n                e.forEach(e => {\n                    if (e.attrs) {\n                        const r = this._getVideoFourCC(e.attrs.CODECS),\n                            n = this._getVideoQualityIndex(r, e.attrs[\"VIDEO-RANGE\"]) || 0,\n                            s = {\n                                codecs: e.attrs.CODECS,\n                                width: e.width,\n                                height: e.height,\n                                bandwidth: e.attrs.BANDWIDTH,\n                                avgBandwidth: e.attrs[\"AVERAGE-BANDWIDTH\"],\n                                framerate: e.attrs[\"FRAME-RATE\"],\n                                iframes: e.iframes,\n                                brRnk: this._getBitrateRank(e.attrs.BANDWIDTH, r, o),\n                                qltyIndex: n,\n                                targetduration: 0,\n                                playTime: 0\n                            };\n                        a = n > a ? n : a, i[e.url] = s\n                    }\n                    var t = e.width * e.height;\n                    t > s && (s = t, r = e.width, n = e.height)\n                });\n                e = 0 < Object.keys(i).length ? Object.values(i).map(e => e.bandwidth + \":\" + e.avgBandwidth).join(\",\") : void 0;\n                return {\n                    variantList: i,\n                    varListString: e,\n                    maxVideoQltyIndex: a,\n                    maxWidth: r,\n                    maxHeight: n\n                }\n            }\n            _getMaxNormalizedPeak(e) {\n                let n = 0;\n                return e.forEach(e => {\n                    e = e.attrs;\n                    if (e) {\n                        const t = e.BANDWIDTH || 0,\n                            i = this._getNormalizedPeak(t, this._getVideoFourCC(e.CODECS)),\n                            r = Math.max(t, i);\n                        n = r > n ? r : n\n                    }\n                }), n\n            }\n            _getNormalizedPeak(e, t) {\n                return \"object\" == typeof Ff[t] ? 1.5 * e : +e\n            }\n            _getVideoFourCC(e) {\n                return e && e.split(\",\").map(e => e.split(\".\")[0].trim()).find(e => !!Ff[e])\n            }\n            _getVideoQualityIndex(e, t) {\n                return \"object\" == typeof Ff[e] ? Ff[e][t] : Ff[e]\n            }\n            _getBitrateRank(e, t, i) {\n                t = Math.max(1, this._getNormalizedPeak(e, t));\n                return Math.ceil(100 * t / i)\n            }\n            _findTimeWeightedValues(o, l, d) {\n                const e = {\n                    twBRnk: 0,\n                    twIBR: 0,\n                    twIABR: 0\n                };\n                if (l) {\n                    let i = 0,\n                        r = 0,\n                        n = 0,\n                        s = 0,\n                        a = 0;\n                    Object.values(l).forEach(e => {\n                        let t = e.playTime;\n                        e === l[d] && (t += o || 0), t && (r += e.bandwidth * t, i += e.brRnk * t, n += t, e.avgBandwidth && (s += e.avgBandwidth * t, a += t))\n                    }), n && (e.twBRnk = i / n, e.twIBR = r / n), s && a && (e.twIABR = s / a)\n                }\n                return e\n            }\n            _computeMediaStats(e) {\n                const t = e.bufferAppendInfo;\n                let i = [];\n                const r = [];\n                t && t.forEach && t.forEach(e => {\n                    i.push(e.latency), r.push(e.size)\n                });\n                var n = this._computeStats(i),\n                    s = this._computeStats(r),\n                    a = e.seekInfo;\n                i = [], a && a.forEach && e.seekInfo.forEach(e => i.push(e.latency));\n                var o = this._computeStats(i),\n                    a = e.playInfo;\n                return i = [], a && a.forEach && e.playInfo.forEach(e => i.push(e.latency)), {\n                    bufLatencyInfo: n,\n                    bufSizeInfo: s,\n                    seekLatencyInfo: o,\n                    playLatencyInfo: this._computeStats(i)\n                }\n            }\n            _computeStats(e) {\n                let t, i;\n                if (e) {\n                    const r = e.filter(e => 0 < e);\n                    if (0 < r.length) {\n                        t = r.reduce((e, t) => Math.max(e, t));\n                        const e = r.length,\n                            n = r.sort((e, t) => e - t),\n                            s = Math.ceil(e / 2);\n                        i = e % 2 == 0 ? (n[s] + n[s - 1]) / 2 : n[s - 1]\n                    }\n                }\n                return {\n                    max: t,\n                    median: i\n                }\n            }\n            _getVariantInfo(e, t) {\n                return e && t.manifestData && t.manifestData.variantList && t.manifestData.variantList[e] ? t.manifestData.variantList[e] : {}\n            }\n            _setTargetDuration(e, t, i) {\n                e && i.manifestData && i.manifestData.variantList && i.manifestData.variantList[e] && (i.manifestData.variantList[e].targetduration = t)\n            }\n            _isBadSw(e, t, i, r, n, s, a) {\n                let o = n - s < 1e4 && t !== e && r === i && !a ? !0 : !1;\n                return o\n            }\n            _aggregateTimes(e) {\n                this.update(e, ({\n                    sessionControlRecord: t,\n                    playLikelyToKeepUpRecord: i,\n                    playStalledRecord: r,\n                    mediaEngineStalledRecord: n,\n                    switchCompleteRecord: s,\n                    playRateChangedRecord: a,\n                    variantEndedRecord: o,\n                    playErrorRecord: l,\n                    nwErrorRecord: d,\n                    periodicRecord: u,\n                    playEndedRecord: c\n                }) => {\n                    var h = Date.now() - t.eventStartTime;\n                    switch (t.state) {\n                        case \"RTC_STATE_INIT\":\n                            i.StartupTime = (i.StartupTime || 0) + h, u.InitTime = (u.InitTime || 0) + h, c.InitTime = (c.InitTime || 0) + h;\n                            break;\n                        case \"RTC_STATE_CANPLAY\":\n                            a.StartupTime = (a.StartupTime || 0) + h, u.InitTime = (u.InitTime || 0) + h, c.InitTime = (c.InitTime || 0) + h;\n                            break;\n                        case \"RTC_STATE_PAUSE\":\n                            u.PauseTime = (u.PauseTime || 0) + h, c.PauseTime = (c.PauseTime || 0) + h, a.LastPause = (a.LastPause || 0) + h, c.LastPause = (c.LastPause || 0) + h, l.LastPause = (l.LastPause || 0) + h, d.LastPause = (d.LastPause || 0) + h;\n                            break;\n                        case \"RTC_STATE_STALL\":\n                            o.StallTime = (o.StallTime || 0) + h, u.StallTime = (u.StallTime || 0) + h, c.StallTime = (c.StallTime || 0) + h, a.LastStall = (a.LastStall || 0) + h, l.LastStall = (l.LastStall || 0) + h, c.LastStall = (c.LastStall || 0) + h;\n                            break;\n                        case \"RTC_STATE_MEDIAENGINESTALL\":\n                            o.MediaEngineStallTime = (o.MediaEngineStallTime || 0) + h, u.MediaEngineStallTime = (u.MediaEngineStallTime || 0) + h, c.MediaEngineStallTime = (c.MediaEngineStallTime || 0) + h, a.LastMediaEngineStall = (a.LastMediaEngineStall || 0) + h, l.LastMediaEngineStall = (l.LastMediaEngineStall || 0) + h, c.LastMediaEngineStall = (c.LastMediaEngineStall || 0) + h;\n                            break;\n                        case \"RTC_STATE_NWERROR\":\n                            c.NwErrTime = (c.NwErrTime || 0) + h, u.NwErrTime = (u.NwErrTime || 0) + h;\n                            break;\n                        case \"RTC_STATE_PLAYERROR\":\n                            u.PlayErrTime = (u.PlayErrTime || 0) + h, c.PlayErrTime = (c.PlayErrTime || 0) + h;\n                            break;\n                        case \"RTC_STATE_PLAY\": {\n                            a.RateChangePlayTime = (a.RateChangePlayTime || 0) + h, s.PlayTime = (s.PlayTime || 0) + h, s.PlayTimeLastSW = (s.PlayTimeLastSW || 0) + h * (t.oldRate / 100), r.LastResume = (r.LastResume || 0) + h, n.LastResume = (n.LastResume || 0) + h, l.LastResume = (l.LastResume || 0) + h, d.LastResume = (d.LastResume || 0) + h, o.VarPlayTimeWC = (o.VarPlayTimeWC || 0) + h, o.VarPlayTime = (o.VarPlayTime || 0) + h * (t.oldRate / 100), u.PlayTimeWC = (u.PlayTimeWC || 0) + h, u.PlayTime = (u.PlayTime || 0) + h * (t.oldRate / 100), c.PlayTimeWC = (c.PlayTimeWC || 0) + h, c.PlayTime = (c.PlayTime || 0) + h * (t.oldRate / 100), n.PlayTime = c.PlayTime, r.PlayTime = c.PlayTime;\n                            const i = t.curLevelUrl;\n                            let e = t.intervalVariantList[i];\n                            e.playTime = (e.playTime || 0) + h, e = t.sessionVariantList[i], e.playTime = (e.playTime || 0) + h;\n                            break\n                        }\n                    }\n                })\n            }\n        }\n        const Vf = {\n            name: \"rtc-service\"\n        };\n        class Kf {\n            constructor(e, t, i, r) {\n                this.hls = e, this.config = t, this.accessLog = i, this.logger = r, this.destroy$ = new Xt, this.isSeeking = !1, this.seekStart = null, this.periodicInterval = t.rtcIntervalTimeout || 3e5, this.intervalFunc = null, this.rtcStore = new $f(this.logger), this.rtcQuery = new Uf(this.rtcStore, this.logger), this.rtcComponent = new Bf(this.rtcQuery, this.logger), i.setRTCQuery(this.rtcQuery), this.subscribeAndUpdateStore(), this.registerForEvents()\n            }\n            destroy() {\n                this.destroy$.next(), this.clearPeriodic(), this.rtcStore.reset()\n            }\n            detachMedia() {\n                this.clearPeriodic();\n                var e;\n                try {\n                    e = this.hls.realCurrentTime, this.rtcStore.updateVariantEnd(this.rtcEventItemId(!0), {\n                        currentTime: e\n                    }), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.VariantEnded), this.rtcStore.updatePeriodic(this.rtcEventItemId(!0), !0), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.Periodic), this.rtcStore.updateEnded(this.rtcEventItemId(!0)), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.PlayEnded)\n                } catch (e) {\n                    this.logger.warn(Vf, e)\n                }\n            }\n            handleError(e) {\n                var t = e instanceof p ? e : new V(!0, e.message, $.InternalError);\n                t instanceof uc && !t.fatal ? (this.rtcStore.updateLevelLoadError(this.rtcEventItemId(), {\n                    url: t.url,\n                    mediaDur: this.hls.bufferedDuration,\n                    isSeeking: this.isSeeking\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.SwitchComplete)) : t.type === o ? (this.rtcStore.updateNwError(this.rtcEventItemId(), {\n                    fatal: t.fatal,\n                    details: t.details,\n                    code: null === (e = t.response) || void 0 === e ? void 0 : e.code\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.NwError)) : (this.rtcStore.updateMediaError(this.rtcEventItemId(), {\n                    fatal: t.fatal,\n                    details: t.details,\n                    code: null === (t = t.response) || void 0 === t ? void 0 : t.code\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.PlayError))\n            }\n            handleMediaElementError(e) {\n                this.rtcStore.updateMediaElementError(this.rtcEventItemId(), e), this.sendAndFinalize(this.rtcEventItemId(), Nf.PlayError)\n            }\n            handleFragLoaded(e, t) {\n                var i, r, n;\n                this.checkMediaOptionType(e.mediaOptionType) && (e.itemId !== this.rtcEventItemId() && this.logger.warn(Vf, `Frag id does not match current item id. Frag Id=${e.itemId}, playing id=${this.rtcEventItemId(!0)}, loading id=${null===(n=this.hls.loadingItem)||void 0===n?void 0:n.itemId}`), i = t.tload - t.trequest, r = t.tload - t.tfirst, n = this.serverInfoInstance || {}, this.rtcStore.updateFragLoaded(e.itemId, {\n                    fragType: e.mediaOptionType,\n                    bytes: t.loaded,\n                    duration: e.duration,\n                    adt: i,\n                    processTime: r,\n                    contentType: t.contentType,\n                    cdnServer: t.cdnServer,\n                    serverInfo: n\n                }), this.accessLog.updateFragLoaded(e.itemId, this.isSeeking, {\n                    fragType: e.mediaOptionType,\n                    bytes: t.loaded,\n                    duration: e.duration,\n                    adt: i,\n                    processTime: r,\n                    startPTS: e.start,\n                    endPTS: e.start + e.duration\n                }))\n            }\n            handleFragBuffered(e) {\n                var t;\n                this.checkMediaOptionType(e.fragmentType) && (t = e.endDataAppend - e.startDataAppend, this.rtcStore.updateFragBuffered(this.rtcEventItemId(), {\n                    fragType: e.fragmentType,\n                    bytes: e.dataBytesAppend,\n                    parseTime: t\n                }))\n            }\n            handleLevelLoaded(e, t) {\n                var i;\n                e ? (e.itemId !== this.rtcEventItemId() && this.logger.warn(Vf, `media option id does not match current item id. media Id=${e.itemId}, current id=${this.rtcEventItemId}`), e.mediaOptionType === gu.Variant && (i = t.tload - t.trequest, this.rtcStore.updateLevelLoaded(this.rtcEventItemId(), {\n                    url: e.url,\n                    targetduration: e.targetduration,\n                    adt: i,\n                    contentType: t.contentType,\n                    playType: e.type\n                }))) : this.logger.warn(`handleLevelLoaded called with mediaOptionDetails as ${e}`)\n            }\n            handleLevelSwitched(e) {\n                var t = {\n                    url: e.url,\n                    isSeeking: this.isSeeking,\n                    mediaDur: this.hls.bufferedDuration,\n                    currentTime: this.hls.realCurrentTime\n                };\n                e.oldVariant && (this.rtcStore.updateVariantEnd(this.rtcEventItemId(), {\n                    currentTime: this.hls.realCurrentTime\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.VariantEnded)), this.rtcStore.updateLevelSwitched(this.rtcEventItemId(), t), this.sendAndFinalize(this.rtcEventItemId(), Nf.SwitchComplete)\n            }\n            handleLevelSwitching(e) {\n                this.levelSwitchingUrl = e\n            }\n            handleLevelsChanged(e) {\n                this.rtcStore.updateLevelsChanged(this.rtcEventItemId(), {\n                    levels: e\n                })\n            }\n            handleManifestParsed(e) {\n                var t = e.stats.tload - e.stats.trequest;\n                this.rtcStore.updateManifestParsed(this.rtcEventItemId(), {\n                    levels: e.levels,\n                    adt: t,\n                    contentType: e.stats.contentType,\n                    isAudioOnly: this.hls.inGaplessMode,\n                    isGapless: this.hls.inGaplessMode,\n                    isFirstItem: this.hls.isFirstItem,\n                    itemID: ((null === (e = this.hls.reportingAgent) || void 0 === e ? void 0 : e.SessionID) || Zl()) + \"-\" + this.rtcEventItemId()\n                })\n            }\n            handleSeek(e) {\n                if (\"SEEKING\" === e) this.isSeeking = !0, this.seekStart = Date.now();\n                else if (\"SEEKED\" === e) {\n                    this.isSeeking = !1;\n                    let e = 0;\n                    this.seekStart && (e = Date.now() - this.seekStart), this.seekStart = null, this.rtcStore.updateSeeked(this.rtcEventItemId(!0), {\n                        latency: e\n                    })\n                }\n            }\n            handleDesiredRateChanged(e, t) {\n                0 === t || 1 < Math.abs(e) && 1 < Math.abs(t) ? (this.rtcStore.updateRateChanged(this.rtcEventItemId(!0), {\n                    rate: t,\n                    latency: 0,\n                    mediaDur: this.hls.bufferedDuration,\n                    currentTime: this.hls.realCurrentTime,\n                    url: this.levelSwitchingUrl\n                }), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.PlayRateChanged)) : 1 !== e && 1 === t && (this.playStart = Date.now()), this.oldRate = e, this.newRate = t\n            }\n            handleVariantBufferAppended(e, t) {\n                let i = 0;\n                e && (i = Date.now() - e), this.rtcStore.updateBufferAppended(this.rtcEventItemId(), {\n                    latency: i,\n                    size: t\n                })\n            }\n            handleStalled(e, t) {\n                var i = {\n                        type: e.type,\n                        stallDurationMs: e.stallDurationMs,\n                        bufferLen: t,\n                        mediaDur: this.hls.bufferedDuration\n                    },\n                    t = this.rtcQuery.getEntity(this.rtcEventItemId(!0)).sessionControlRecord.state;\n                e.type === Cp.LowBuffer || e.type === Cp.Seek && e.isLowBufferStall ? \"RTC_STATE_PLAY\" === t && (this.rtcStore.updateBufferStalled(this.rtcEventItemId(!0), i), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.PlayStalled)) : \"RTC_STATE_PLAY\" === t && (this.rtcStore.updateMediaEngineStalled(this.rtcEventItemId(!0), i), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.MediaEngineStalled))\n            }\n            handlePlaybackInfo(e, t) {\n                this.rtcStore.updatePlaybackInfo(this.rtcEventItemId(!0), {\n                    droppedVideoFrames: e,\n                    decodedFrameCount: t\n                }), this.accessLog.updatePlaybackInfo(this.rtcEventItemId(!0), {\n                    droppedVideoFrames: e,\n                    decodedFrameCount: t\n                })\n            }\n            checkMediaOptionType(e) {\n                return e === gu.Variant || e === gu.AltAudio || (this.logger.error(Vf, 'Should not have media option type = \"%s\" in RTC', Nu[e]), !1)\n            }\n            rtcEventItemId(e = !1) {\n                return (this.hls.isPreloading ? e ? this.hls.playingItem : this.hls.loadingItem : this.hls.currentItem).itemId\n            }\n            subscribeAndUpdateStore() {\n                this.hls.publicQueries$.pipe(La(([, e]) => this.mediaElementQueryListener(e)), Va(this.destroy$)).subscribe(), this.hls.itemQueue.activeItemById$.pipe(Za(t => {\n                    if (t) {\n                        let e = !1;\n                        if (this.hls.userInfo ? this.hls.userInfo.internalBuild ? e = !0 : this.hls.userInfo.diagnosticsAndUsage && (e = this.config.enableRtcReporting) : e = this.config.enableRtcReporting, e) {\n                            const i = this.hls.reportingAgent;\n                            i ? this.rtcComponent.setReportingAgent(i) : this.logger.warn(Vf, \"[RTCA] - Reporting is enabled but reportingAgent is null\")\n                        } else this.rtcComponent.setReportingAgent(null);\n                        this.serverInfoInstance = null;\n                        t = t.itemId;\n                        this.rtcStore.createEntity(t), !this.hls.isFirstItem && this.hls.inGaplessMode || this.setPeriodic(t)\n                    }\n                }), Va(this.destroy$)).subscribe()\n            }\n            itemTransitioned(e, t) {\n                this.rtcStore.updateVariantEnd(e, {\n                    currentTime: this.hls.realCurrentTime\n                }), this.sendAndFinalize(e, Nf.VariantEnded), this.rtcStore.updatePeriodic(e, !0), this.sendAndFinalize(e, Nf.Periodic), this.rtcStore.updateEnded(e), this.sendAndFinalize(e, Nf.PlayEnded), this.setPeriodic(t)\n            }\n            mediaElementQueryListener(e) {\n                return e.gotPlaying$.pipe(Za(e => {\n                    if (e) {\n                        const e = this.oldRate,\n                            t = this.newRate || 1;\n                        1 < Math.abs(e) && 1 < Math.abs(t) || (this.rtcStore.updateCanPlay(this.rtcEventItemId(!0), {\n                            mediaDur: this.hls.bufferedDuration\n                        }), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.PlayLikelyToKeepUp), this.rtcStore.updateRateChanged(this.rtcEventItemId(!0), {\n                            rate: t,\n                            latency: ne(this.playStart) ? Date.now() - this.playStart : 0,\n                            mediaDur: this.hls.bufferedDuration,\n                            currentTime: this.hls.realCurrentTime,\n                            url: this.levelSwitchingUrl\n                        }), this.sendAndFinalize(this.rtcEventItemId(!0), Nf.PlayRateChanged))\n                    }\n                }))\n            }\n            registerForEvents() {\n                const e = Oc(this.hls, this);\n                an(e.event(P.KEY_REQUEST_STARTED, this.keyRequestStarted, this), e.event(P.KEY_LOADED, this.keyLoaded, this)).pipe(Va(this.destroy$)).subscribe()\n            }\n            keyRequestStarted(e) {\n                e.timestamp = Date.now(), this.rtcStore.updateLicenseChallengeRequested(this.rtcEventItemId(), e)\n            }\n            keyLoaded(e) {\n                e.timestamp = Date.now(), e.currentTime = this.hls.realCurrentTime, this.rtcStore.updateSegmentKeyLoaded(this.rtcEventItemId(), e)\n            }\n            licenseChallengeReceived(e) {\n                this.rtcStore.updateLicenseChallengeReceived(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                })\n            }\n            licenseChallengeSubmitted(e) {\n                this.rtcStore.updateLicenseChallengeSubmitted(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyFormat: e.keyFormat,\n                    keyuri: e.keyuri\n                })\n            }\n            licenseChallengeCreated(e) {\n                this.rtcStore.updateLicenseChallengeCreated(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    cdmVersion: e.cdmVersion,\n                    keyuri: e.keyuri\n                }), this.rtcStore.updateLicenseResponseRequested(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                })\n            }\n            licenseResponseSubmitted(e) {\n                this.rtcStore.updateLicenseResponseReceived(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                }), this.rtcStore.updateLicenseResponseSubmitted(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                })\n            }\n            licenseResponseProcessed(e) {\n                this.rtcStore.updateLicenseResponseProcessed(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri,\n                    currentTime: this.hls.realCurrentTime\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.KeySessionComplete)\n            }\n            licenseChallengeError(e) {\n                this.rtcStore.updateLicenseChallengeError(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.KeySessionComplete)\n            }\n            licenseResponseError(e) {\n                this.rtcStore.updateLicenseResponseError(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.KeySessionComplete)\n            }\n            keyAborted(e) {\n                var t;\n                null != (null === (t = this.rtcQuery.getEntity(this.rtcEventItemId())) || void 0 === t ? void 0 : t.sessionControlRecord.activeKeySessions[e.keyuri]) ? (this.rtcStore.updateKeyAborted(this.rtcEventItemId(), {\n                    timestamp: Date.now(),\n                    keyuri: e.keyuri\n                }), this.sendAndFinalize(this.rtcEventItemId(), Nf.KeySessionComplete)) : this.logger.warn(`keyAbort called without active key session ${le(e.keyuri)}`)\n            }\n            setPeriodic(e) {\n                this.clearPeriodic(), this.intervalFunc = setInterval(this.handlePeriodic.bind(this, e), this.periodicInterval)\n            }\n            handlePeriodic(e) {\n                this.rtcStore.updatePeriodic(e, !1), this.sendAndFinalize(e, Nf.Periodic)\n            }\n            clearPeriodic() {\n                this.intervalFunc && clearInterval(this.intervalFunc), this.intervalFunc = null\n            }\n            sendAndFinalize(e, t) {\n                switch (this.accessLog.addPlayTime(e), t) {\n                    case Nf.PlayEnded:\n                        this.rtcComponent.sendPlayEnded(e);\n                        break;\n                    case Nf.Periodic:\n                        this.rtcComponent.sendPeriodic(e);\n                        break;\n                    case Nf.PlayStalled:\n                        this.accessLog.updateStallCount(e), this.rtcComponent.sendPlayStalled(e);\n                        break;\n                    case Nf.KeySessionComplete:\n                        this.rtcComponent.sendKeySessionComplete(e);\n                        break;\n                    case Nf.PlayLikelyToKeepUp:\n                        this.accessLog.updateCanPlay(e), this.rtcComponent.sendPlayLikelyToKeepUp(e);\n                        break;\n                    case Nf.PlayRateChanged:\n                        this.rtcComponent.sendPlayRateChange(e);\n                        break;\n                    case Nf.PlayError:\n                        this.accessLog.addToErrorLog(e, \"mediaError\"), this.rtcComponent.sendPlayError(e);\n                        break;\n                    case Nf.MediaEngineStalled:\n                        this.accessLog.updateMediaEngineStallCount(e), this.rtcComponent.sendMediaEngineStalled(e);\n                        break;\n                    case Nf.SwitchComplete:\n                        this.accessLog.addToAccessLog(e), this.rtcComponent.sendSwitchComplete(e);\n                        break;\n                    case Nf.VariantEnded:\n                        this.rtcComponent.sendVariantEnded(e);\n                        break;\n                    case Nf.NwError:\n                        this.accessLog.addToErrorLog(e, \"networkError\"), this.rtcComponent.sendNwError(e);\n                        break;\n                    default:\n                        return void this.logger.error(Vf, `Unknown rtc event eventGroupId:${e}`)\n                }\n                this.rtcStore.finalize(e, t)\n            }\n        }\n        const qf = a => (e, t) => {\n                let i = 0,\n                    r = 0;\n                for (var {\n                        timestamp: n,\n                        value: s\n                    } of e) {\n                    const e = Math.pow(Math.max(0, n - t) / 1e3, a);\n                    i += e * s, r += e\n                }\n                return i / r\n            },\n            Hf = {\n                \"uniform-time-weighted\": qf(0),\n                \"linear-time-weighted\": qf(1),\n                \"quadratic-time-weighted\": qf(2)\n            };\n        class jf {\n            constructor(e, t = \"quadratic-time-weighted\", i = {\n                avgLatencyMs: NaN,\n                avgBandwidth: NaN\n            }) {\n                this.windowSize = e, this.aggregationMethod = t, this.latencyEntries = [], this.bandwidthEntries = [], this.minEntries = 1, this.cleanUpExpiredEntries = this.cleanUpExpiredEntries.bind(this), this.bwSubject = new yi(i)\n            }\n            get estimate$() {\n                return this.bwSubject.asObservable()\n            }\n            record(e) {\n                var {\n                    trequest: t,\n                    tfirst: i,\n                    tload: r,\n                    bitsDownloaded: e\n                } = e;\n                t !== r && (this.recordLatency(t, i), this.recordBandwidth(t, r, 1e3 * e / (r - t)), this.bwSubject.closed || (t = this.getEstimate(), this.bwSubject.next(t)))\n            }\n            getEstimate() {\n                if (this.latencyEntries.length < this.minEntries) return {\n                    avgLatencyMs: NaN,\n                    avgBandwidth: NaN\n                };\n                const e = performance.now() - this.windowSize,\n                    t = Hf[this.aggregationMethod],\n                    i = this.latencyEntries.map(({\n                        start: e,\n                        end: t\n                    }) => ({\n                        timestamp: t,\n                        value: t - e,\n                        duration: 1\n                    }));\n                this.bandwidthEntries = function(r) {\n                    function n(t, i) {\n                        if (t.length) {\n                            for (let e = 0; e < t.length; e++)\n                                if (t[e].start > i.start || t[e].start === i.start && t[e].end > i.end) {\n                                    t.splice(e, 0, i);\n                                    break\n                                }\n                        } else t.push(i)\n                    }\n                    const s = [...r].sort((e, t) => e.start !== t.start ? e.start - t.start : e.end - t.end),\n                        t = [];\n                    for (; s.length;) {\n                        const r = s[0];\n                        let e;\n                        if (s.shift(), t.length && (e = t[t.length - 1]), 0 === t.length || e.end <= r.start) t.push(r);\n                        else if (r.start === e.start) r.end === e.end ? e.bitsPerSec += r.bitsPerSec : r.end < e.end || (e.bitsPerSec += r.bitsPerSec, r.start = e.end, n(s, r));\n                        else {\n                            var a = e.end,\n                                o = e.bitsPerSec;\n                            e.end = r.start;\n                            var i = {\n                                start: r.start,\n                                end: Math.min(a, r.end),\n                                bitsPerSec: r.bitsPerSec + o\n                            };\n                            if (t.push(i), a !== r.end) {\n                                let e = 0,\n                                    t = 0,\n                                    i = 0;\n                                i = a < r.end ? (e = a, t = r.end, r.bitsPerSec) : (e = r.end, t = a, o), n(s, {\n                                    start: e,\n                                    end: t,\n                                    bitsPerSec: i\n                                })\n                            }\n                        }\n                    }\n                    return t\n                }(this.bandwidthEntries);\n                var r = this.bandwidthEntries.map(({\n                    end: e,\n                    bitsPerSec: t\n                }) => ({\n                    timestamp: e,\n                    duration: 1,\n                    value: t\n                }));\n                return {\n                    avgLatencyMs: t(i, e),\n                    avgBandwidth: t(r, e)\n                }\n            }\n            getLatest() {\n                if (0 === this.latencyEntries.length) return {\n                    avgLatencyMs: NaN,\n                    avgBandwidth: NaN\n                };\n                var e = this.latencyEntries[this.latencyEntries.length - 1],\n                    t = this.bandwidthEntries[this.bandwidthEntries.length - 1];\n                return {\n                    avgLatencyMs: e.end - e.start,\n                    avgBandwidth: t.bitsPerSec\n                }\n            }\n            recordLatency(e, t) {\n                this.latencyEntries.push({\n                    start: e,\n                    end: t\n                }), this.updateCleanupTimeout(t)\n            }\n            recordBandwidth(e, t, i) {\n                this.bandwidthEntries.push({\n                    start: e,\n                    end: t,\n                    bitsPerSec: i\n                }), this.updateCleanupTimeout(t)\n            }\n            setCleanupTimeout(e) {\n                this.cleanupTimeout = setTimeout(this.cleanUpExpiredEntries, Math.max(e - performance.now(), 0)), this.cleanupTimestamp = e\n            }\n            clearCleanupTimeout() {\n                void 0 !== this.cleanupTimeout && (clearTimeout(this.cleanupTimeout), this.cleanupTimeout = void 0), this.cleanupTimestamp = void 0\n            }\n            updateCleanupTimeout(e) {\n                e += this.windowSize;\n                (!this.cleanupTimestamp || e < this.cleanupTimestamp) && (this.clearCleanupTimeout(), this.setCleanupTimeout(e))\n            }\n            cleanUpExpiredEntries() {\n                this.clearCleanupTimeout();\n                const t = performance.now() - this.windowSize;\n                if (this.latencyEntries = this.latencyEntries.filter(e => e.end >= t), this.bandwidthEntries = this.bandwidthEntries.filter(e => e.end >= t), this.bwSubject.closed || this.bwSubject.next(this.getEstimate()), 0 < this.latencyEntries.length || 0 < this.bandwidthEntries.length) {\n                    const t = Math.min(...this.latencyEntries.map(e => e.end), ...this.bandwidthEntries.map(e => e.end));\n                    this.updateCleanupTimeout(t)\n                }\n            }\n            destroy() {\n                this.clearCleanupTimeout()\n            }\n        }\n        const Qf = {\n            setCombinedEstimate: function(t, i, r) {\n                const n = Qe();\n                if (void 0 !== t.storage.set) {\n                    var s = t.bandwidthHistoryStorageKey,\n                        a = {\n                            avgLatencyMs: i.avgLatencyMs,\n                            avgBandwidth: i.avgBandwidth\n                        },\n                        a = Object.assign({}, a, {\n                            expires: Date.now() + t.bandwidthHistoryTTL\n                        });\n                    try {\n                        t.storage.set(s, JSON.stringify(a))\n                    } catch (t) {\n                        n.warn(`Error stringifying! Not persisting bandwidth estimates: ${t.message}`)\n                    }\n                    i = {\n                        maxDuration: i.maxDurationSec,\n                        avgFragParseTimeMs: i.avgParseTimeMs,\n                        avgFragBufferCreationDelayMs: i.avgBufferCreateMs,\n                        avgPlaylistLoadTimeMs: i.avgPlaylistLoadTimeMs,\n                        avgPlaylistParseTimeMs: i.avgPlaylistParseTimeMs,\n                        avgInitFragAppendMs: i.avgInitFragAppendMs,\n                        avgDataFragAppendMs: i.avgDataFragAppendMs\n                    };\n                    let e = t.storageKeyPrefix;\n                    r && (e += r);\n                    try {\n                        t.storage.set(e, JSON.stringify(i))\n                    } catch (t) {\n                        n.warn(`Error stringifying! Not persisting bandwidth estimates: ${t.message}`)\n                    }\n                } else n.warn(\"storage.set is not supported! Not persisting bandwidth estimates\")\n            },\n            getCombinedEstimate: function(t, e) {\n                const i = Qe();\n                let r = {};\n                if (void 0 === t.storage.get) return i.warn(\"storage.get is not supported! unable to retreive bandwidth estimates\"), this.convertStorageJsonToCombinedEstimate(r);\n                try {\n                    let e = JSON.parse(t.storage.get(t.bandwidthHistoryStorageKey));\n                    e = null != e && e.expires && e.expires < Date.now() ? null : {\n                        avgLatencyMs: null == e ? void 0 : e.avgLatencyMs,\n                        avgBandwidth: null == e ? void 0 : e.avgBandwidth\n                    }, r = Object.assign(Object.assign({}, r), e)\n                } catch (t) {\n                    i.warn(`Unable to get persisted bandwidth history: ${t.message}`)\n                }\n                let n = t.storageKeyPrefix;\n                e && (n += e);\n                try {\n                    const e = JSON.parse(t.storage.get(n));\n                    r = Object.assign(Object.assign({}, r), e)\n                } catch (t) {\n                    i.warn(`Unable to get persisted bandwidth history: ${t.message}`)\n                }\n                return this.convertStorageJsonToCombinedEstimate(r)\n            },\n            convertStorageJsonToCombinedEstimate: function(e) {\n                return {\n                    avgLatencyMs: (null == e ? void 0 : e.avgLatencyMs) || NaN,\n                    avgBandwidth: (null == e ? void 0 : e.avgBandwidth) || NaN,\n                    maxDurationSec: (null == e ? void 0 : e.maxDuration) || NaN,\n                    avgParseTimeMs: (null == e ? void 0 : e.avgFragParseTimeMs) || NaN,\n                    avgBufferCreateMs: (null == e ? void 0 : e.avgFragBufferCreationDelayMs) || NaN,\n                    avgPlaylistLoadTimeMs: (null == e ? void 0 : e.avgPlaylistLoadTimeMs) || NaN,\n                    avgPlaylistParseTimeMs: (null == e ? void 0 : e.avgPlaylistParseTimeMs) || NaN,\n                    avgInitFragAppendMs: (null == e ? void 0 : e.avgInitFragAppendMs) || NaN,\n                    avgDataFragAppendMs: (null == e ? void 0 : e.avgDataFragAppendMs) || NaN\n                }\n            },\n            getBandwidthEstimate: function(e, t) {\n                const i = this.getCombinedEstimate(e, t),\n                    r = {\n                        avgLatencyMs: null == i ? void 0 : i.avgLatencyMs,\n                        avgBandwidth: null == i ? void 0 : i.avgBandwidth\n                    };\n                return ne(r.avgLatencyMs) || (r.avgLatencyMs = NaN), ne(r.avgBandwidth) || (r.avgBandwidth = NaN), r\n            },\n            getPlaylistEstimate: function(e, t) {\n                const i = this.getCombinedEstimate(e, t),\n                    r = {\n                        avgPlaylistLoadTimeMs: null == i ? void 0 : i.avgPlaylistLoadTimeMs,\n                        avgPlaylistParseTimeMs: null == i ? void 0 : i.avgPlaylistParseTimeMs\n                    };\n                return ne(r.avgPlaylistLoadTimeMs) || (r.avgPlaylistLoadTimeMs = NaN), ne(r.avgPlaylistParseTimeMs) || (r.avgPlaylistParseTimeMs = NaN), r\n            },\n            getFragEstimate: function(e, t) {\n                const i = this.getCombinedEstimate(e, t),\n                    r = {\n                        maxDurationSec: null == i ? void 0 : i.maxDurationSec,\n                        avgParseTimeMs: null == i ? void 0 : i.avgParseTimeMs\n                    };\n                return ne(r.maxDurationSec) || (r.maxDurationSec = NaN), ne(r.avgParseTimeMs) || (r.avgParseTimeMs = NaN), r\n            },\n            getBufferEstimate: function(e, t) {\n                const i = this.getCombinedEstimate(e, t),\n                    r = {\n                        avgBufferCreateMs: null == i ? void 0 : i.avgBufferCreateMs,\n                        avgInitFragAppendMs: null == i ? void 0 : i.avgInitFragAppendMs,\n                        avgDataFragAppendMs: null == i ? void 0 : i.avgDataFragAppendMs\n                    };\n                return ne(r.avgBufferCreateMs) || (r.avgBufferCreateMs = NaN), ne(r.avgInitFragAppendMs) || (r.avgInitFragAppendMs = NaN), ne(r.avgDataFragAppendMs) || (r.avgDataFragAppendMs = NaN), r\n            }\n        };\n        var Wf = Qf;\n        class Gf {\n            constructor(e = 0) {\n                this._minSamples = e, this._sum = 0, this._max = Number.NEGATIVE_INFINITY, this._numSamples = 0\n            }\n            get avg() {\n                return this._numSamples < this._minSamples ? NaN : this._sum / this._numSamples\n            }\n            get max() {\n                return 0 < this.count ? this._max : NaN\n            }\n            get count() {\n                return this._numSamples\n            }\n            reset() {\n                this._sum = 0, this._numSamples = 0, this._max = Number.NEGATIVE_INFINITY\n            }\n            add(e) {\n                this._sum += e, this._max = Math.max(this._max, e), ++this._numSamples\n            }\n        }\n        class zf extends kl {\n            constructor(e, t) {\n                super(e), this.id = t\n            }\n            getBandwidthEstimate(e, t) {\n                var i;\n                const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.bandwidthEstimate);\n                if (ne(r.avgBandwidth) && ne(r.avgLatencyMs)) return r;\n                if (e) {\n                    const i = Qf.getBandwidthEstimate(e, t);\n                    ne(r.avgBandwidth) || (r.avgBandwidth = i.avgBandwidth), ne(r.avgLatencyMs) || (r.avgLatencyMs = i.avgLatencyMs)\n                }\n                return r\n            }\n            getPlaylistEstimate(e, t) {\n                var i;\n                const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.playlistEstimate),\n                    n = e => ne(e.avgPlaylistLoadTimeMs) && ne(e.avgPlaylistParseTimeMs);\n                if (n(r)) return r;\n                if (e) {\n                    const i = Qf.getPlaylistEstimate(e, t);\n                    if (ne(r.avgPlaylistLoadTimeMs) || (r.avgPlaylistLoadTimeMs = i.avgPlaylistLoadTimeMs), ne(r.avgPlaylistParseTimeMs) || (r.avgPlaylistParseTimeMs = i.avgPlaylistParseTimeMs), n(r)) return r;\n                    ne(r.avgPlaylistLoadTimeMs) || (r.avgPlaylistLoadTimeMs = e.statDefaults.playlistLoadTimeMs), ne(r.avgPlaylistParseTimeMs) || (r.avgPlaylistParseTimeMs = e.statDefaults.playlistParseTimeMs)\n                }\n                return r\n            }\n            getBufferEstimate(e, t) {\n                var i;\n                const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.bufferEstimate),\n                    n = e => ne(e.avgBufferCreateMs) && ne(e.avgDataFragAppendMs) && ne(e.avgInitFragAppendMs);\n                if (n(r)) return r;\n                if (e) {\n                    const i = Qf.getBufferEstimate(e, t);\n                    if (ne(r.avgBufferCreateMs) || (r.avgBufferCreateMs = i.avgBufferCreateMs), ne(r.avgDataFragAppendMs) || (r.avgDataFragAppendMs = i.avgDataFragAppendMs), ne(r.avgInitFragAppendMs) || (r.avgInitFragAppendMs = i.avgInitFragAppendMs), n(r)) return r;\n                    ne(r.avgBufferCreateMs) || (r.avgBufferCreateMs = e.statDefaults.fragBufferCreationDelayMs), ne(r.avgDataFragAppendMs) || (r.avgDataFragAppendMs = e.statDefaults.dataFragAppendMs), ne(r.avgInitFragAppendMs) || (r.avgInitFragAppendMs = e.statDefaults.initFragAppendMs)\n                }\n                return r\n            }\n            getFragEstimate(e, t) {\n                var i;\n                const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.fragEstimate),\n                    n = e => ne(e.maxDurationSec) && ne(e.avgParseTimeMs);\n                if (n(r)) return r;\n                if (e) {\n                    const i = Qf.getFragEstimate(e, t);\n                    if (ne(r.maxDurationSec) || (r.maxDurationSec = i.maxDurationSec), ne(r.avgParseTimeMs) || (r.avgParseTimeMs = i.avgParseTimeMs), n(r)) return r;\n                    ne(r.maxDurationSec) || (r.maxDurationSec = e.defaultTargetDuration), ne(r.avgParseTimeMs) || (r.avgParseTimeMs = e.statDefaults.fragParseTimeMs)\n                }\n                return r\n            }\n            getCombinedEstimate() {\n                return Object.assign(Object.assign(Object.assign(Object.assign({}, this.getFragEstimate()), this.getPlaylistEstimate()), this.getBufferEstimate()), this.getBandwidthEstimate())\n            }\n            get statsEntity() {\n                return this.getEntity(this.id)\n            }\n            get bandwidthSample() {\n                var e;\n                return null === (e = this.statsEntity) || void 0 === e ? void 0 : e.bandwidthSample\n            }\n            get bandwidthStatus() {\n                var e;\n                return null === (e = this.statsEntity) || void 0 === e ? void 0 : e.bandwidthStatus\n            }\n            get fragSample() {\n                var e;\n                return null === (e = this.statsEntity) || void 0 === e ? void 0 : e.fragSample\n            }\n            get bandwidthEstimate$() {\n                return this.selectEntity(this.id, \"bandwidthEstimate\")\n            }\n            get fragEstimate$() {\n                return this.selectEntity(this.id, \"fragEstimate\")\n            }\n            get playlistEstimate$() {\n                return this.selectEntity(this.id, \"playlistEstimate\")\n            }\n            get bufferEstimate$() {\n                return this.selectEntity(this.id, \"bufferEstimate\")\n            }\n            get bandwidthSample$() {\n                return this.selectEntity(this.id, ({\n                    bandwidthSample: e\n                }) => e).pipe(Kp())\n            }\n            get fragSample$() {\n                return this.selectEntity(this.id, ({\n                    fragSample: e\n                }) => e).pipe(Kp())\n            }\n            get playlistSample$() {\n                return this.selectEntity(this.id, ({\n                    playlistSample: e\n                }) => e).pipe(Kp())\n            }\n            get bufferMetric$() {\n                return this.selectEntity(this.id, ({\n                    bufferMetric: e\n                }) => e).pipe(Kp())\n            }\n        }\n        class Xf {\n            constructor(e) {\n                this.statsStore = e\n            }\n            getQuery() {\n                return new kl(this.statsStore)\n            }\n            getQueryForItem(e) {\n                return new zf(this.statsStore, e)\n            }\n            remove(e) {\n                this.statsStore.remove(e)\n            }\n            removeAll() {\n                this.statsStore.remove()\n            }\n            setBandwidthSample(e) {\n                this.statsStore.bandwidthSample = e\n            }\n            setFragSample(e) {\n                this.statsStore.fragSample = e\n            }\n            setPlaylistSample(e) {\n                this.statsStore.playlistSample = e\n            }\n            setBufferMetric(e) {\n                this.statsStore.bufferMetric = e\n            }\n            setBandwidthEstimate(e) {\n                this.statsStore.bandwidthEstimate = e\n            }\n            setFragEstimate(e) {\n                this.statsStore.fragEstimate = e\n            }\n            setPlaylistEstimate(e) {\n                this.statsStore.playlistEstimate = e\n            }\n            setBufferEstimate(e) {\n                this.statsStore.bufferEstimate = e\n            }\n        }\n        const Yf = new class extends fl {\n            constructor() {\n                super({}, {\n                    name: \"stats-store\",\n                    producerFn: su\n                })\n            }\n            set statsEntity(e) {\n                Do(\"statsStore.set.stats\"), al(() => {\n                    this.add(e), this.setActive(e.id)\n                })\n            }\n            set playlistSample(t) {\n                Do(`stats.set.playlistSample: ${t}`), this.updateActive(e => {\n                    e.playlistSample = t\n                })\n            }\n            set bandwidthSample(t) {\n                Do(`stats.set.bandwidthSample: ${t}`), this.updateActive(e => {\n                    e.bandwidthSample = t, e.bandwidthStatus.bandwidthSampleCount += 1, e.bandwidthStatus.instantBw = 8e3 * t.loaded / (t.tload - t.trequest)\n                })\n            }\n            set fragSample(t) {\n                Do(`stats.set.fragSample: ${t}`), this.updateActive(e => {\n                    e.fragSample = t\n                })\n            }\n            set bufferMetric(t) {\n                Do(`stats.set.bufferMetric: ${t}`), this.updateActive(e => {\n                    e.bufferMetric = t\n                })\n            }\n            set bandwidthEstimate(t) {\n                Do(`stats.set.bandwidthEstimate: ${t}`), this.updateActive(e => {\n                    e.bandwidthEstimate = t\n                })\n            }\n            set fragEstimate(t) {\n                Do(`stats.set.fragEstimate: ${t}`), this.updateActive(e => {\n                    e.fragEstimate = t\n                })\n            }\n            set playlistEstimate(t) {\n                Do(`stats.set.playlistEstimate: ${t}`), this.updateActive(e => {\n                    e.playlistEstimate = t\n                })\n            }\n            set bufferEstimate(t) {\n                Do(`stats.set.bufferEstimate: ${t}`), this.updateActive(e => {\n                    e.bufferEstimate = t\n                })\n            }\n        };\n        let Jf = null;\n        const Zf = e => new zf(Yf, e);\n\n        function em(e, t) {\n            if (e === t) return !0;\n            if (!e || !t) return !1;\n            let i = Object.keys(e).length === Object.keys(t).length;\n            for (const r of Object.keys(e)) i = i && (isNaN(e[r]) && isNaN(t[r]) || e[r] === t[r]);\n            return i\n        }\n\n        function tm(f, m, g) {\n            return new $t(e => {\n                (e => {\n                    const t = Zf(e);\n                    t.hasEntity(e) ? $i(t) : (i = Yf, e = e, Do(\"stats.loading\"), i.setLoading(!0), i.statsEntity = {\n                        id: e,\n                        bandwidthEstimate: {\n                            avgLatencyMs: NaN,\n                            avgBandwidth: NaN\n                        },\n                        bandwidthStatus: {\n                            bandwidthSampleCount: 0,\n                            instantBw: NaN\n                        },\n                        fragEstimate: {\n                            maxDurationSec: NaN,\n                            avgParseTimeMs: NaN\n                        },\n                        playlistEstimate: {\n                            avgPlaylistLoadTimeMs: NaN,\n                            avgPlaylistParseTimeMs: NaN\n                        },\n                        bufferEstimate: {\n                            avgBufferCreateMs: NaN,\n                            avgInitFragAppendMs: NaN,\n                            avgDataFragAppendMs: NaN\n                        }\n                    }, i.setLoading(!1), Do(\"stats.loaded\"));\n                    var i\n                })(g.itemId);\n                const t = Zf(g.itemId),\n                    {\n                        fragSample$: i,\n                        playlistSample$: r,\n                        bandwidthSample$: n,\n                        bufferMetric$: s\n                    } = t;\n                return an(r.pipe(ji(tr), (h = f, p = m, e => e.pipe(tc(\"statsPlaylistProcessingEpic.in\"), sa((e, t) => (e.playlistLoadTimeMs.add(t.playlistLoadTimeMs), e.playlistParseTimeMs.add(t.playlistParseTimeMs), e), {\n                    playlistLoadTimeMs: new Gf(h.minPlaylistCount),\n                    playlistParseTimeMs: new Gf(h.minPlaylistCount)\n                }), hr(e => ({\n                    avgPlaylistLoadTimeMs: e.playlistLoadTimeMs.avg,\n                    avgPlaylistParseTimeMs: e.playlistParseTimeMs.avg\n                })), Is(em), Za(e => {\n                    p.setPlaylistEstimate(e)\n                })))), n.pipe(ji(tr), (u = f, c = m, n => new $t(e => {\n                    let t = new jf(u.bandwidthHistoryWindowSize, u.bandwidthHistoryAggregationMethod, {\n                        avgLatencyMs: NaN,\n                        avgBandwidth: NaN\n                    });\n                    const i = t.estimate$,\n                        r = an(n.pipe(ln(e => e.complete), Za(e => {}), hr(e => ({\n                            trequest: e.trequest,\n                            tfirst: e.tfirst,\n                            tload: e.tload,\n                            bitsDownloaded: 8 * e.loaded\n                        })), tc(\"statsBandwidthProcessingEpic.in\"), La(e => (t.record(e), Ii))), i.pipe(Is(), tc(\"statsBandwidthProcessingEpic.change\"), Za(e => {\n                            c && c.setBandwidthEstimate(e)\n                        }))).subscribe(e);\n                    return () => {\n                        r.unsubscribe(), t.destroy(), t = void 0\n                    }\n                }))), i.pipe(ji(tr), (l = f, d = m, e => e.pipe(tc(\"statsFragProcessingEpic.in\"), sa((e, t) => (e.durationSec.add(t.durationSec), e.fragParseMs.add(t.parseTimeMs), e), {\n                    durationSec: new Gf,\n                    fragParseMs: new Gf(l.minFragmentCount)\n                }), hr(e => ({\n                    maxDurationSec: e.durationSec.max,\n                    avgParseTimeMs: e.fragParseMs.avg\n                })), Is(em), Za(e => d.setFragEstimate(e))))), s.pipe(ji(tr), (a = f, o = m, e => e.pipe(tc(\"statsBufferMetricProcessingEpic.in\"), sa((e, t) => (ne(t.bufferCreationStart) && ne(t.bufferCreationEnd) && e.bufferCreateMs.add(t.bufferCreationEnd - t.bufferCreationStart), ne(t.startInitAppend) && ne(t.endInitAppend) && e.initFragAppendMs.add(t.endInitAppend - t.startInitAppend), ne(t.startDataAppend) && ne(t.endDataAppend) && e.dataFragAppendMs.add(t.endDataAppend - t.startDataAppend), e), {\n                    bufferCreateMs: new Gf,\n                    initFragAppendMs: new Gf,\n                    dataFragAppendMs: new Gf(a.minFragmentCount)\n                }), hr(e => ({\n                    avgBufferCreateMs: e.bufferCreateMs.avg,\n                    avgInitFragAppendMs: e.initFragAppendMs.avg,\n                    avgDataFragAppendMs: e.dataFragAppendMs.avg\n                })), Is(em), Za(e => {\n                    o.setBufferEstimate(e)\n                }))))).pipe($a(Ii)).subscribe(e), () => {\n                    Wf.setCombinedEstimate(f, Object.assign(Object.assign(Object.assign(Object.assign({}, t.getFragEstimate()), t.getPlaylistEstimate()), t.getBufferEstimate()), t.getBandwidthEstimate()), g.serviceName), m.remove(g.itemId)\n                };\n                var a, o, l, d, u, c, h, p\n            })\n        }\n        const im = {\n            isWebkitMediaElement: e => \"webkitDroppedFrameCount\" in e,\n            isHtmlVideoElement: e => \"getVideoPlaybackQuality\" in e,\n            timeRangeToArray(t) {\n                const i = [];\n                for (let e = 0; e < t.length; e++) i.push([t.start(e), t.end(e)]);\n                return i\n            }\n        };\n        class rm {\n            constructor(e, t) {\n                this.hls = e, this.sessionID = t, this.rtcQuery = null, this.accessLogData = this.createAccessLogEntry(), this.accesslog = [], this.errorlog = []\n            }\n            destroy() {\n                this.rtcQuery = null, this.accesslog = [], this.errorlog = [], this.accessLogData = void 0, this.accessLogReporter = void 0\n            }\n            setRTCQuery(e) {\n                this.rtcQuery = e\n            }\n            setupReporter(e) {\n                this.accessLogReporter = {\n                    SessionID: this.sessionID,\n                    ClientName: null == e ? void 0 : e.clientName,\n                    ServiceName: null == e ? void 0 : e.serviceName\n                }\n            }\n            addPlayTime(e) {\n                var t, e = null === (t = this.rtcQuery) || void 0 === t ? void 0 : t.getEntity(e);\n                !e || \"RTC_STATE_PLAY\" === (e = e.sessionControlRecord).state && (this.accessLogData.PlayTimeWC = (this.accessLogData.PlayTimeWC || 0) + e.eventStartTime)\n            }\n            updatePlaybackInfo(e, t) {\n                this.accessLogData.ViFrDr = this.rtcQuery.getEntity(e).sessionControlRecord.droppedVideoFrames || 0\n            }\n            updateStallCount(e) {\n                \"RTC_STATE_PLAY\" === this.rtcQuery.getEntity(e).sessionControlRecord.state && this.accessLogData.StallCount++\n            }\n            updateMediaEngineStallCount(e) {\n                \"RTC_STATE_PLAY\" === this.rtcQuery.getEntity(e).sessionControlRecord.state && this.accessLogData.MediaEngineStallCount++\n            }\n            updateCanPlay(e) {\n                this.accessLogData.StartupTime = this.rtcQuery.getEntity(e).sessionControlRecord.eventStartTime\n            }\n            updateFragLoaded(e, t, i) {\n                var r;\n                i.fragType === gu.Variant ? (this.accessLogData.NetBytes += i.bytes, this.accessLogData.ADT += i.adt, r = this.aggregateFragObserverdBitrate(i, ++this.accessLogData.fragmentCnt, this.accessLogData.NetBytes, this.accessLogData.ADT), this.accessLogData.OBRLast = r.obrLast, this.accessLogData.OBRMean = r.obrMean, this.aggregateFragMinMaxBitrate(this.accessLogData, r.obr), this.hls.realCurrentTime > i.startPTS && !t && this.accessLogData.overdue++, this.hasGap(i.startPTS, i.endPTS, this.accessLogData.lastStartPTS, this.accessLogData.lastEndPTS) && this.addToAccessLog(e), this.accessLogData.startPTS || (this.accessLogData.startPTS = i.startPTS), this.accessLogData.lastStartPTS = i.startPTS, this.accessLogData.lastEndPTS = i.endPTS, this.accessLogData.videoBytes += i.bytes, this.accessLogData.videoDuration += i.duration) : i.fragType === gu.AltAudio && (this.accessLogData.audioBytes += i.bytes, this.accessLogData.audioDuration += i.duration)\n            }\n            addToAccessLog(e) {\n                var t = this.getVariantInfo(e),\n                    i = this.rtcQuery.getEntity(e).sessionControlRecord.curLevelUrl,\n                    r = this.rtcQuery.getEntity(e).playEndedRecord.PlayType;\n                if (i && \"\" !== i) {\n                    r = this.translateToAccessLogItem(e, i, t, r);\n                    if (r) {\n                        const n = this.accesslog.length - 20;\n                        0 < n && this.accesslog.splice(0, n), this.accesslog.push(r)\n                    }\n                    this.accessLogData = this.createAccessLogEntry();\n                    e = this.rtcQuery.getEntity(e).switchCompleteRecord.MediaDur;\n                    this.accessLogData.lastMediaDur = e || this.hls.bufferedDuration\n                }\n            }\n            addToErrorLog(e, t) {\n                var i = null === (r = this.rtcQuery) || void 0 === r ? void 0 : r.getEntity(e);\n                if (i) {\n                    var r = Number((\"mediaError\" === t ? i.playErrorRecord : i.nwErrorRecord).ErrCode),\n                        i = i.sessionControlRecord.curLevelUrl,\n                        r = this.translateToErrorLogItem(e, i, {\n                            domain: t,\n                            code: r\n                        });\n                    if (r) {\n                        const e = this.errorlog.length - 20;\n                        0 < e && this.errorlog.splice(0, e), this.errorlog.push(r)\n                    }\n                }\n            }\n            getAccessLog(e) {\n                var t;\n                const i = this.accesslog.slice(0),\n                    r = null === (t = this.rtcQuery) || void 0 === t ? void 0 : t.getEntity(e);\n                if (i && r) {\n                    const t = r.sessionControlRecord.curLevelUrl;\n                    if (t && \"\" !== t) {\n                        const r = this.getVariantInfo(e),\n                            n = this.translateToAccessLogItem(e, t, r, this.rtcQuery.getEntity(e).playEndedRecord.PlayType);\n                        n && (n[\"c-provisional-entry\"] = !0, i.push(n))\n                    }\n                }\n                return i\n            }\n            get errorLog() {\n                return this.errorlog\n            }\n            createAccessLogEntry() {\n                return {\n                    fragmentCnt: 0,\n                    overdue: 0,\n                    startPTS: 0,\n                    obrMax: 0,\n                    obrMin: 0,\n                    audioBytes: 0,\n                    audioDuration: 0,\n                    videoBytes: 0,\n                    videoDuration: 0,\n                    svrAddrChanged: 0,\n                    svrAddr: \"\",\n                    PlayTimeWC: 0,\n                    ViFrDr: 0,\n                    StallCount: 0,\n                    MediaEngineStallCount: 0,\n                    ADT: 0,\n                    NetBytes: 0,\n                    StartupTime: 0,\n                    OBRMean: 0,\n                    OBRLast: 0\n                }\n            }\n            convertStringObjectToPrimitive(e) {\n                return e ? \"object\" == typeof e ? e.toString() : e : \"\"\n            }\n            updateSvrAddrStats(t) {\n                const i = bu.parseURL(t);\n                if (i && i.netLoc) {\n                    const t = i.netLoc.indexOf(\":\");\n                    let e = 0 <= t ? i.netLoc.slice(0, t) : i.netLoc;\n                    e.startsWith(\"//\") && (e = e.slice(2)), this.accessLogData.svrAddr ? e !== this.accessLogData.svrAddr && this.accessLogData.svrAddrChanged++ : this.accessLogData.svrAddrChanged = 0, this.accessLogData.svrAddr = e\n                }\n            }\n            translateToAccessLogItem(e, t, i, r) {\n                t = this.convertStringObjectToPrimitive(t);\n                this.updateSvrAddrStats(t);\n                let n = this.rtcQuery.getEntity(e).switchCompleteRecord.MediaDur;\n                n = n || this.hls.bufferedDuration, n = n || 0;\n                const s = {\n                    uri: t,\n                    \"s-ip\": this.accessLogData.svrAddr,\n                    \"s-ip-changes\": this.accessLogData.svrAddrChanged,\n                    \"sc-wwan-count\": -1,\n                    \"c-transfer-duration\": this.accessLogData.ADT,\n                    bytes: this.accessLogData.NetBytes,\n                    \"c-total-media-requests\": this.accessLogData.fragmentCnt,\n                    \"cs-guid\": this.accessLogReporter.SessionID,\n                    \"c-start-time\": this.accessLogData.startPTS,\n                    \"c-startup-time\": this.accessLogData.StartupTime,\n                    \"c-duration-watched\": this.accessLogData.PlayTimeWC / 1e3,\n                    \"c-frames-dropped\": this.accessLogData.ViFrDr,\n                    \"c-stalls\": this.accessLogData.StallCount + this.accessLogData.MediaEngineStallCount,\n                    \"c-duration-downloaded\": this.accessLogData.lastMediaDur ? n - this.accessLogData.lastMediaDur : n,\n                    \"c-overdue\": this.accessLogData.overdue,\n                    \"c-avg-video-bitrate\": 8 * this.accessLogData.videoBytes / (this.accessLogData.videoDuration || 1),\n                    \"c-observed-max-bitrate\": this.accessLogData.obrMax,\n                    \"c-observed-min-bitrate\": this.accessLogData.obrMin,\n                    \"sc-indicated-bitrate\": i.bandwidth || 0,\n                    \"sc-indicated-avg-bitrate\": i.avgBandwidth || 0,\n                    \"c-observed-bitrate\": this.accessLogData.OBRMean,\n                    \"c-switch-bitrate\": this.accessLogData.OBRLast,\n                    \"c-provisional-entry\": !1\n                };\n                return s[\"s-playback-type\"] = r, this.accessLogData.audioBytes && (s[\"c-avg-audio-bitrate\"] = 8 * this.accessLogData.audioBytes / (this.accessLogData.audioDuration || 1)), s\n            }\n            translateToErrorLogItem(e, t, i) {\n                t = this.convertStringObjectToPrimitive(t);\n                return this.updateSvrAddrStats(t), {\n                    date: new Date,\n                    \"cs-guid\": this.accessLogReporter.SessionID + \"-\" + e,\n                    uri: t,\n                    \"s-ip\": this.accessLogData.svrAddr,\n                    status: \"\" + i.code,\n                    domain: i.domain\n                }\n            }\n            hasGap(e, t, i, r) {\n                return void 0 !== e && void 0 !== i && (1 < e - r || 1 < i - t)\n            }\n            aggregateFragObserverdBitrate(e, t, i, r) {\n                r = 8 * i / (r / 1e3);\n                return {\n                    obr: r,\n                    obrLast: 8 * e.bytes / (e.adt / 1e3),\n                    obrMean: r / t\n                }\n            }\n            aggregateFragMinMaxBitrate(e, t) {\n                (!e.obrMax || t > e.obrMax) && (e.obrMax = t), (!e.obrMin || t < e.obrMin) && (e.obrMin = t)\n            }\n            getVariantInfo(e) {\n                var t = this.rtcQuery.getEntity(e).sessionControlRecord.curLevelUrl,\n                    e = null === (e = this.rtcQuery.getEntity(e).sessionControlRecord.manifestData) || void 0 === e ? void 0 : e.variantList;\n                return t && e && e[t] ? e[t] : {}\n            }\n        }\n        const nm = (r, e, t, i, n, s) => {\n                var a, {\n                        absoluteUrl: o,\n                        byteRangeOffset: l,\n                        keyTagInfo: d,\n                        iframe: u,\n                        isInitSegment: c\n                    } = r,\n                    h = o,\n                    p = d[\"method\"],\n                    {\n                        start: o,\n                        end: d\n                    } = l,\n                    t = Lc({\n                        url: h\n                    }, t);\n                let f, m = o,\n                    g = d,\n                    y = !1,\n                    v = ne(o) || ne(d) ? l : void 0;\n                if (\"AES-128\" === p && d && (u || c)) {\n                    const r = d - o;\n                    r % 16 && (g = d + (16 - r % 16)), 0 !== o && (y = !0, m = o - 16), v = {\n                        start: m,\n                        end: g\n                    }\n                }\n                return n && ne(r.mediaSeqNum) && r.mediaOptionType === gu.Variant && (f = [], null === (n = t.reportHTTPResponseHeaders) || void 0 === n || n.forEach(function(e) {\n                    Ou.includes(e) ? f.push(e) : Qe().warn({\n                        name: \"load-media-fragment\"\n                    }, `${e} is not in approved privacy list. Actions required.`)\n                }), 0 === f.length && (f = void 0)), Rc({\n                    url: h,\n                    byteRangeOffset: v,\n                    checkContentLength: !0,\n                    extendMaxTTFB: s,\n                    collectServerInstanceInfo: f,\n                    onProgress: i,\n                    xhrSetup: e.xhrSetup\n                }, t).pipe(hr(([e, t, i]) => {\n                    if (y) {\n                        const t = e;\n                        r.keyTagInfo.iv = new Uint8Array(t.slice(0, 16)), e = t.slice(16)\n                    }\n                    return [r, e, t, i]\n                }), (a = r, e => e.pipe(Vn(e => {\n                    if (e instanceof pc) throw new hc(!1, \"Timeout\", 0, $.FragmentTimeoutError, !0, a, e.stats);\n                    if (e instanceof oc) throw new hc(!1, e.message, e.code, {\n                        code: e.code,\n                        text: \"Fragment Network Error\"\n                    }, !1, a);\n                    throw e\n                }))))\n            },\n            sm = {\n                clearkey: th,\n                fairplaystreaming: Sc,\n                playready: Fc,\n                widevine: Bc\n            },\n            am = {\n                getKeySystemFormat(e) {\n                    e = sm[e];\n                    return e ? e.keyFormatString : \"\"\n                },\n                getKeySystemSecurityLevel(e) {\n                    e = sm[e];\n                    return e ? e.securityLevels : null\n                }\n            },\n            om = {\n                NONE: \"\",\n                \"AES-128\": \"\",\n                \"ISO-23001-7\": \"\",\n                \"SAMPLE-AES\": \"\",\n                \"SAMPLE-AES-CTR\": \"\"\n            },\n            lm = {\n                NONE: 0,\n                \"TYPE-0\": 1,\n                \"TYPE-1\": 2,\n                \"TYPE-2\": 3\n            };\n\n        function dm(e) {\n            return e in lm\n        }\n\n        function um(e) {\n            return null == e ? 4 : lm[e]\n        }\n        const cm = [\"SDR\", \"PQ\", \"HLG\"],\n            hm = {\n                afr: \"af\",\n                aka: \"ak\",\n                amh: \"am\",\n                ara: \"ar\",\n                arg: \"an\",\n                asm: \"as\",\n                ava: \"av\",\n                ave: \"ae\",\n                aym: \"ay\",\n                aze: \"az\",\n                bam: \"bm\",\n                bel: \"be\",\n                ben: \"bn\",\n                bih: \"bh\",\n                bod: \"bo\",\n                bos: \"bs\",\n                bre: \"br\",\n                bul: \"bg\",\n                cat: \"ca\",\n                ces: \"cs\",\n                cha: \"ch\",\n                che: \"ce\",\n                chu: \"cu\",\n                chv: \"cv\",\n                cor: \"kw\",\n                cos: \"co\",\n                cre: \"cr\",\n                cym: \"cy\",\n                dan: \"da\",\n                deu: \"de\",\n                div: \"dv\",\n                dzo: \"dz\",\n                ell: \"el\",\n                eng: \"en\",\n                epo: \"eo\",\n                est: \"et\",\n                eus: \"eu\",\n                ewe: \"ee\",\n                fao: \"fo\",\n                fas: \"fa\",\n                fin: \"fi\",\n                fra: \"fr\",\n                fry: \"fy\",\n                ful: \"ff\",\n                gla: \"gd\",\n                gle: \"ga\",\n                glg: \"gl\",\n                glv: \"gv\",\n                grn: \"gn\",\n                guj: \"gu\",\n                hat: \"ht\",\n                heb: \"he\",\n                her: \"hz\",\n                hin: \"hi\",\n                hmo: \"ho\",\n                hrv: \"hr\",\n                hun: \"hu\",\n                hye: \"hy\",\n                ibo: \"ig\",\n                ido: \"io\",\n                iii: \"ii\",\n                iku: \"iu\",\n                ile: \"ie\",\n                ina: \"ia\",\n                ind: \"id\",\n                isl: \"is\",\n                ita: \"it\",\n                jav: \"jv\",\n                jpn: \"ja\",\n                kal: \"kl\",\n                kan: \"kn\",\n                kas: \"ks\",\n                kat: \"ka\",\n                kau: \"kr\",\n                kaz: \"kk\",\n                khm: \"km\",\n                kik: \"ki\",\n                kin: \"rw\",\n                kir: \"ky\",\n                kom: \"kv\",\n                kon: \"kg\",\n                kor: \"ko\",\n                kua: \"kj\",\n                kur: \"ku\",\n                lao: \"lo\",\n                lat: \"la\",\n                lav: \"lv\",\n                lim: \"li\",\n                lit: \"lt\",\n                ltz: \"lb\",\n                lub: \"lu\",\n                lug: \"lg\",\n                mah: \"mh\",\n                mal: \"ml\",\n                mar: \"mr\",\n                mkd: \"mk\",\n                mlg: \"mg\",\n                mlt: \"mt\",\n                mol: \"mo\",\n                mon: \"mn\",\n                mri: \"mi\",\n                msa: \"ms\",\n                mya: \"my\",\n                nav: \"nv\",\n                nbl: \"nr\",\n                nde: \"nd\",\n                ndo: \"ng\",\n                nep: \"ne\",\n                nld: \"nl\",\n                nno: \"nn\",\n                nob: \"nb\",\n                nya: \"ny\",\n                oci: \"oc\",\n                oji: \"oj\",\n                ori: \"or\",\n                orm: \"om\",\n                oss: \"os\",\n                pan: \"pa\",\n                pli: \"pi\",\n                pol: \"pl\",\n                por: \"pt\",\n                pus: \"ps\",\n                que: \"qu\",\n                roh: \"rm\",\n                ron: \"ro\",\n                run: \"rn\",\n                rus: \"ru\",\n                san: \"sa\",\n                sin: \"si\",\n                slk: \"sk\",\n                slv: \"sl\",\n                sme: \"se\",\n                snd: \"sd\",\n                som: \"so\",\n                spa: \"es\",\n                sqi: \"sq\",\n                srd: \"sc\",\n                srp: \"sr\",\n                sun: \"su\",\n                swa: \"sw\",\n                swe: \"sv\",\n                tah: \"ty\",\n                tam: \"ta\",\n                tat: \"tt\",\n                tel: \"te\",\n                tgk: \"tg\",\n                tgl: \"tl\",\n                tha: \"th\",\n                tir: \"ti\",\n                ton: \"to\",\n                tuk: \"tk\",\n                tur: \"tr\",\n                uig: \"ug\",\n                ukr: \"uk\",\n                urd: \"ur\",\n                uzb: \"uz\",\n                ven: \"ve\",\n                vie: \"vi\",\n                wln: \"wa\",\n                yid: \"yi\",\n                zha: \"za\",\n                zho: \"zh\"\n            },\n            pm = {\n                isLanguageCode: e => e in hm,\n                shortenLanguageCode(e) {\n                    let t;\n                    var i, r;\n                    return e && (r = 0 <= (i = e.indexOf(\"-\")) ? e.slice(0, i) : e, pm.isLanguageCode(r) && (t = hm[r]), t = t || r, 0 < i && (t += \"-\" + e.slice(i + 1))), t\n                }\n            },\n            fm = {\n                getRichestVideoCodec(e) {\n                    if (e && e.length) {\n                        e = e.sort((e, t) => qp(t) - qp(e));\n                        return e && e.length ? e[0] : void 0\n                    }\n                },\n                getRichestAudioCodec(e) {\n                    if (e && e.length) {\n                        e = e.sort((e, t) => jp(t) - jp(e));\n                        return e && e.length ? e[0] : void 0\n                    }\n                },\n                getRichestChannelLayoutForGroupId(t, i) {\n                    if (t && i && i.length) {\n                        let e;\n                        const r = i.filter(e => e.groupId === t);\n                        if (r && r.length) {\n                            const t = r.sort((e, t) => be.getChannelCount(t.channels) - be.getChannelCount(e.channels));\n                            t && t.length && (e = t[0].channels)\n                        }\n                        return e\n                    }\n                }\n            };\n\n        function mm(e) {\n            return new R(L, \"steeringManifestParsingError\", !1, e, $.FormatError)\n        }\n        class gm {\n            constructor(e) {\n                this._url = null, this._programDateTime = null, this._byteRange = null, this.relurl = null, this.baseurl = null, this.isInitSegment = !1, this.mediaSeqNum = NaN, this.cc = NaN, this.iframe = !1, this.bitrate = NaN, this.start = NaN, this.duration = NaN, this.lastByteRangeEndOffset = NaN, this.inheritQuery = e, this.tagList = new Array, this.iframe = !1\n            }\n            getMediaFragment(e, t, i) {\n                const r = {\n                    mediaOptionType: i,\n                    absoluteUrl: this.url,\n                    start: this.start,\n                    duration: this.duration,\n                    mediaSeqNum: this.mediaSeqNum,\n                    discoSeqNum: this.cc,\n                    mediaOptionId: t,\n                    itemId: e,\n                    isLastFragment: !1,\n                    isInitSegment: this.isInitSegment\n                };\n                return null !== (e = this.byteRange) && void 0 !== e && e.length && (r.byteRangeOffset = {\n                    start: this.byteRangeStartOffset,\n                    end: this.byteRangeEndOffset\n                }), this.iframe && (r.iframe = this.iframe), this.levelkey && (r.keyTagInfo = this.levelkey), this.programDateTime && (r.programDateTime = this.programDateTime), r\n            }\n            get url() {\n                return !this._url && this.relurl && this.baseurl && (this._url = bu.buildAbsoluteURL(this.baseurl, this.relurl, {\n                    alwaysNormalize: !0,\n                    inheritQuery: this.inheritQuery\n                })), this._url\n            }\n            set url(e) {\n                this._url = e\n            }\n            get programDateTime() {\n                return !this._programDateTime && this.rawProgramDateTime && (this._programDateTime = new Date(Date.parse(this.rawProgramDateTime))), this._programDateTime\n            }\n            get byteRange() {\n                if (!this._byteRange) {\n                    const i = new Array(2);\n                    var e, t;\n                    this.rawByteRange && (1 === (e = this.rawByteRange.split(\"@\", 2)).length ? (t = this[\"lastByteRangeEndOffset\"], i[0] = t || 0) : i[0] = parseInt(e[1]), i[1] = parseInt(e[0]) + i[0]), this._byteRange = i\n                }\n                return this._byteRange\n            }\n            get byteRangeStartOffset() {\n                return this.byteRange[0]\n            }\n            get byteRangeEndOffset() {\n                return this.byteRange[1]\n            }\n            get rangeString() {\n                return 0 <= this.start && 0 <= this.duration ? `${this.start.toFixed(2)}-${(this.start+this.duration).toFixed(2)}` : \"N/A\"\n            }\n            get fragTag() {\n                return `sn/cc/levelId: ${this.mediaSeqNum}/${this.cc}`\n            }\n        }\n        const ym = {\n                parseMediaCharacteristics: e => e ? e.split(/\\s*,\\s*/) : new Array,\n                addMediaToSelectionArray(e, t, i) {\n                    if (void 0 === e) return -1;\n                    const r = e.MediaSelectionGroupOptions;\n                    let n = r.find(e => e.MediaSelectionOptionsMediaType === t.mediaType && e.MediaSelectionOptionsName === t.name && e.MediaSelectionOptionsExtendedLanguageTag === t.lang);\n                    return n || (n = {\n                        MediaSelectionOptionsMediaType: t.mediaType,\n                        MediaSelectionOptionsExtendedLanguageTag: t.lang,\n                        MediaSelectionOptionsIsDefault: t.default,\n                        MediaSelectionOptionsName: t.name,\n                        MediaSelectionOptionsPersistentID: i,\n                        MediaSelectionOptionsTaggedMediaCharacteristics: t.characteristics\n                    }, t.mediaType === Su.SUBTITLE && (n.MediaSelectionOptionsDisplaysNonForcedSubtitles = t.forced ? vu.NO : vu.YES), i++, r.push(n)), t.persistentID = n.MediaSelectionOptionsPersistentID, i\n                },\n                addDefaultClosedCaptionOption(e, t, i, r) {\n                    e = {\n                        itemId: e,\n                        mediaOptionType: gu.Subtitle,\n                        id: 0,\n                        mediaOptionId: \"cc1_\" + Zl(),\n                        mediaType: Su.CLOSEDCAPTION,\n                        inStreamID: \"CC1\",\n                        groupId: \"cc\",\n                        name: \"English-CC\",\n                        type: \"CLOSED-CAPTIONS\",\n                        default: !1,\n                        autoselect: !1,\n                        forced: !1,\n                        lang: \"en\",\n                        characteristics: [\"public.accessibility.transcribes-spoken-dialog\", \"public.accessibility.describes-music-and-sound\"],\n                        persistentID: r\n                    };\n                    t.push(e), ym.addMediaToSelectionArray(i, e, r)\n                }\n            },\n            vm = {\n                BANDWIDTH: NaN,\n                \"AVERAGE-BANDWIDTH\": NaN\n            },\n            Sm = {\n                \"TIME-OFFSET\": NaN,\n                \"FRAME-RATE\": NaN,\n                SCORE: NaN,\n                \"PLANNED-DURATION\": NaN,\n                DURATION: NaN\n            },\n            bm = /^(\\d+)x(\\d+)$/,\n            Tm = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g;\n        class Em {\n            constructor(e) {\n                this.validTags = e\n            }\n            isKey(e) {\n                return e in this.validTags\n            }\n            trySetValue(e, t, i) {\n                return !!this.isKey(e) && (i[e] = this.parseFunc(t), !0)\n            }\n        }\n        class Im {\n            static parseTags(t) {\n                let i;\n                var r = {};\n                if (!t) return r;\n                for (Tm.lastIndex = 0; null !== (i = Tm.exec(t));) {\n                    const t = i[1].toUpperCase();\n                    let e = i[2];\n                    0 === e.indexOf('\"') && e.lastIndexOf('\"') === e.length - 1 && (e = e.slice(1, -1));\n                    for (const i of Im.tagParsers)\n                        if (i.trySetValue(t, e, r)) break\n                }\n                return r\n            }\n        }\n        Im.tagParsers = [new class extends Em {\n            parseFunc(e) {\n                return e\n            }\n        }({\n            NAME: \"\",\n            TYPE: \"\",\n            DEFAULT: \"\",\n            AUTOSELECT: \"\",\n            FORCED: \"\",\n            LANGUAGE: \"\",\n            URI: \"\",\n            AUDIO: \"\",\n            \"VIDEO-RANGE\": \"\",\n            \"CLOSED-CAPTIONS\": \"\",\n            CODECS: \"\",\n            BYTERANGE: \"\",\n            \"INSTREAM-ID\": \"\",\n            \"GROUP-ID\": \"\",\n            CHANNELS: \"\",\n            CHARACTERISTICS: \"\",\n            KEYFORMAT: \"\",\n            KEYFORMATVERSIONS: \"\",\n            \"DATA-ID\": \"\",\n            VALUE: \"\",\n            METHOD: \"\",\n            \"HDCP-LEVEL\": \"\",\n            \"ALLOWED-CPC\": \"\",\n            SUBTITLES: \"\",\n            ID: \"\",\n            CLASS: \"\",\n            \"START-DATE\": \"\",\n            \"END-DATE\": \"\",\n            \"END-ON-NEXT\": \"\",\n            \"SERVER-URI\": \"\",\n            \"PATHWAY-ID\": \"\"\n        }), new class extends Em {\n            parseFunc(e) {\n                e = parseInt(e);\n                return e > Number.MAX_SAFE_INTEGER ? 1 / 0 : e\n            }\n        }(vm), new class extends Em {\n            constructor() {\n                super(...arguments), this.parseFunc = parseFloat\n            }\n        }(Sm), new class extends Em {\n            parseFunc(e) {\n                let t = (e || \"0x\").slice(2);\n                t = (1 & t.length ? \"0\" : \"\") + t;\n                const i = new Uint8Array(t.length / 2);\n                for (let e = 0; e < t.length / 2; e++) {\n                    var r = parseInt(t.slice(2 * e, 2 * e + 2), 16);\n                    if (!ne(r)) return;\n                    i[e] = r\n                }\n                return i\n            }\n        }({\n            IV: null\n        }), new class extends Em {\n            parseFunc(e) {\n                e = bm.exec(e);\n                let t;\n                return null !== e && (t = {\n                    width: parseInt(e[1], 10),\n                    height: parseInt(e[2], 10)\n                }), t\n            }\n        }({\n            RESOLUTION: null\n        })];\n        const wm = {\n            ExtractVariableParameter: /{\\$(.*?)}/g,\n            LevelPlaylistFast: /#EXTINF:(\\d*(?:\\.\\d+)?)(?:,(.*))?|(?!#)(\\S.+)|#EXT-X-BYTERANGE: *(.+)|#EXT-X-PROGRAM-DATE-TIME:(.+)|#EXT-X-BITRATE:(.+)|#EXT-X-DATERANGE:(.+)|#.*/g,\n            LevelPlaylistSlow: /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\\d+))|(?:#EXT-X-(TARGETDURATION): *(\\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\\d+))|(?:#EXT-X-(MAP):(.+))|(?:#EXT-X-(I-FRAMES)-ONLY)|(?:#EXT-X-(DEFINE):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\\r?\\n?/,\n            MasterPlaylist: /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)|#EXT-X-I-FRAME-STREAM-INF:([^\\r\\n]+)|#EXT-X-DEFINE:([^\\n\\r]*)|#EXT-X-CONTENT-STEERING:([^\\n\\r]*)/g,\n            MasterPlaylistAlternateMedia: /#EXT-X-MEDIA:(.*)/g,\n            SessionData: /#EXT-X-SESSION-DATA[^:]*:(.*)/g,\n            SessionKeys: /#EXT-X-SESSION-KEY:([^\\n\\r]*)/g,\n            VARIABLE_PLAYLIST_REGEX: /(NAME|VALUE)=\\\"(.*)\\\",(NAME|VALUE)=\\\"(.*)\\\"|(IMPORT)=\\\"(.*)\\\"/\n        };\n\n        function Am(e, t, i) {\n            return cu.buildAbsoluteURL(t, e, {\n                alwaysNormalize: !0,\n                inheritQuery: i\n            })\n        }\n        class Om {\n            static isValidPlaylist(e) {\n                return 0 === e.indexOf(\"#EXTM3U\")\n            }\n            static isMediaPlaylist(e) {\n                return 0 < e.indexOf(\"#EXTINF:\") || 0 < e.indexOf(\"#EXT-X-PLAYLIST-TYPE:\")\n            }\n            static replaceVariables(e, t) {\n                let i, r = !1;\n                return e && t && (i = e.replace(wm.ExtractVariableParameter, e => {\n                    wm.ExtractVariableParameter.lastIndex = 0;\n                    e = wm.ExtractVariableParameter.exec(e)[1];\n                    if (e && t.hasOwnProperty(e)) return t[e];\n                    r = !0\n                })), {\n                    updatedString: i,\n                    error: r\n                }\n            }\n            static parseDecryptData(e, t, i) {\n                const r = Im.parseTags(e),\n                    n = (e = r.METHOD) && e in om ? r.METHOD : null;\n                e = null !== (e = r.KEYFORMAT) && void 0 !== e ? e : null;\n                if (n && Om.shouldSelectKeyTag(e, n, i)) {\n                    const s = r.URI,\n                        i = r.IV || null;\n                    if (s && r.IV && !i) {\n                        const s = new R(L, _, !0, `Invalid IV: ${r.IV}`, $.PlaylistErrorInvalidEntry);\n                        throw s.url = t, s\n                    }\n                    const a = s ? cu.buildAbsoluteURL(t, s, {\n                            alwaysNormalize: !0\n                        }) : t,\n                        o = (r.KEYFORMATVERSIONS || \"1\").split(\"/\").map(Number).filter(isFinite);\n                    return new zc(n, a, i, e, o)\n                }\n            }\n            static shouldSelectKeyTag(e, t, i) {\n                return \"AES-128\" === t || \"NONE\" === t || null == i || e === am.getKeySystemFormat(i)\n            }\n            static optOutClosedCaption(t) {\n                let i = !1,\n                    r = !1;\n                if (t)\n                    for (let e = 0; e < t.length; ++e) {\n                        const n = t[e];\n                        if (n.videoCodec && ((r = !0) !== n.iframes && n.closedcaption && \"none\" === n.closedcaption.toLowerCase())) {\n                            i = !0;\n                            break\n                        }\n                    }\n                return !r || i\n            }\n            static parseRootPlaylistAlternateMediaOptions(a, o, l, d, u, c) {\n                let h, p;\n                var f = {\n                        MediaSelectionGroupAllowEmptySelection: 1,\n                        MediaSelectionGroupMediaCharacteristics: [\"public.audible\"],\n                        MediaSelectionGroupMediaType: Su.AUDIO,\n                        MediaSelectionGroupOptions: []\n                    },\n                    m = {\n                        MediaSelectionGroupAllowEmptySelection: 1,\n                        MediaSelectionGroupMediaCharacteristics: [\"public.legible\"],\n                        MediaSelectionGroupMediaType: Su.SUBTITLE,\n                        MediaSelectionGroupOptions: []\n                    },\n                    g = {\n                        videoAlternateOptions: [],\n                        audioAlternateOptions: [],\n                        subtitleAlternateOptions: [],\n                        audioMediaSelectionGroup: f,\n                        subtitleMediaSelectionGroup: m\n                    };\n                let y = 0;\n                for (wm.MasterPlaylistAlternateMedia.lastIndex = 0; null != (h = wm.MasterPlaylistAlternateMedia.exec(o));) {\n                    const o = Om.replaceVariables(h[1], c);\n                    if (o.error) {\n                        p = new R(L, N, !0, $.PlaylistErrorInvalidEXTXDEFINE.text, $.PlaylistErrorInvalidEXTXDEFINE);\n                        break\n                    }\n                    var v = Im.parseTags(o.updatedString);\n                    let e, t, i, r = Su.UNKNOWN;\n                    const S = ym.parseMediaCharacteristics(v.CHARACTERISTICS),\n                        b = v[\"GROUP-ID\"],\n                        T = v.CHANNELS;\n                    let n, s = null;\n                    switch (v.TYPE) {\n                        case \"VIDEO\":\n                            r = Su.VIDEO, t = g.videoAlternateOptions;\n                            break;\n                        case \"AUDIO\":\n                            r = Su.AUDIO, s = gu.AltAudio, t = g.audioAlternateOptions, i = f;\n                            const a = d.find(e => e.audioGroupId === b);\n                            n = a ? a.audioCodecList : [];\n                            break;\n                        case \"SUBTITLES\":\n                            r = Su.SUBTITLE, s = gu.Subtitle, t = g.subtitleAlternateOptions, i = m;\n                            break;\n                        case \"CLOSED-CAPTIONS\":\n                            r = Su.CLOSEDCAPTION, s = gu.Subtitle, e = v[\"INSTREAM-ID\"], t = g.subtitleAlternateOptions, i = m\n                    }\n                    const E = {\n                        itemId: a,\n                        mediaOptionType: s,\n                        mediaType: r,\n                        groupId: b,\n                        channels: T,\n                        groupCodecList: n,\n                        name: v.NAME,\n                        type: v.TYPE,\n                        default: \"YES\" === v.DEFAULT,\n                        autoselect: \"YES\" === v.AUTOSELECT,\n                        forced: \"YES\" === v.FORCED,\n                        characteristics: S,\n                        persistentID: y,\n                        id: t ? t.length : 0,\n                        mediaOptionId: `${v.NAME}_${b}_${y}`,\n                        lang: pm.shortenLanguageCode(v.LANGUAGE)\n                    };\n                    v.URI && (E.url = Am(v.URI, l, u)), E.name || (E.name = E.lang, E.mediaType === Su.CLOSEDCAPTION && (E.name += \" CC\")), E.mediaType === Su.CLOSEDCAPTION && e && (E.inStreamID = e), t && (E.id = t.length, t.push(E)), y = ym.addMediaToSelectionArray(i, E, y)\n                }\n                return 0 !== g.subtitleAlternateOptions.length || Om.optOutClosedCaption(d) || ym.addDefaultClosedCaptionOption(a, g.subtitleAlternateOptions, m, y), {\n                    alternateMediaInfo: g,\n                    playlistParsingError: p\n                }\n            }\n            static parseMediaOptionPlaylist(e, t, i = !0, r, n, s, a, o, l, d = 0, u = !1) {\n                var c;\n                let h = 0,\n                    p = 0;\n                const f = {\n                    itemId: s,\n                    mediaOptionId: a,\n                    mediaOptionType: o,\n                    type: \"\",\n                    version: 0,\n                    url: t,\n                    initSegments: {},\n                    fragments: [],\n                    liveOrEvent: !0,\n                    startSN: 0,\n                    endSN: 0,\n                    iframesOnly: u,\n                    targetduration: 0,\n                    totalduration: 0,\n                    averagetargetduration: 0,\n                    ptsKnown: !1\n                };\n                let m, g, y, v = new zc(\"NONE\", t, null, null, null),\n                    S = !1,\n                    b = !1,\n                    T = 0,\n                    E = null,\n                    I = new gm(i),\n                    w = 0;\n                const A = {};\n                let O, k, C, D = !0,\n                    M = !0;\n                wm.LevelPlaylistFast.lastIndex = 0;\n                for (var x = () => new R(L, _, !0, \"Invalid key system preference for the playlist\", $.IncompatibleAsset); null !== (m = wm.LevelPlaylistFast.exec(e));) {\n                    const e = m[1];\n                    if (e) {\n                        I.duration = parseFloat(e);\n                        const t = (\" \" + m[2]).slice(1);\n                        I.title = t || null, I.tagList.push(t ? [\"INF\", e, t] : [\"INF\", e])\n                    } else if (m[3]) {\n                        if (ne(I.duration)) {\n                            const e = h++;\n                            if (I.start = p + d, I.levelkey = v, b && !S) {\n                                k = x();\n                                break\n                            }\n                            if (S = !1, b = !1, I.mediaSeqNum = e, I.cc = T, I.iframe = f.iframesOnly, I.baseurl = t, (O = Om.replaceVariables((\" \" + m[3]).slice(1), A)).error) {\n                                k = new R(L, N, !0, $.PlaylistErrorInvalidEXTXDEFINE.text, $.PlaylistErrorInvalidEXTXDEFINE);\n                                break\n                            }\n                            if (I.relurl = O.updatedString, I.bitrate = ne(I.byteRangeEndOffset) ? 8 * (I.byteRangeEndOffset - I.byteRangeStartOffset) / I.duration : w, null != y) {\n                                I.rawProgramDateTime = y, I.tagList.push([\"PROGRAM-DATE-TIME\", I.rawProgramDateTime]);\n                                const e = I.programDateTime.getTime();\n                                f.programDateTimeMap = null !== (c = f.programDateTimeMap) && void 0 !== c ? c : {}, f.programDateTimeMap[e] = I.mediaSeqNum, f.dateMediaTimePairs = null !== (c = f.dateMediaTimePairs) && void 0 !== c ? c : [], f.dateMediaTimePairs.push([e, I.start]), y = void 0\n                            }\n                            if (f.fragments.push(I.getMediaFragment(s, a, o)), E = I, p += I.duration, D || !f.initSegments[T] || M)\n                                if (f.iframesOnly && 0 < I.byteRangeStartOffset && !f.initSegments[T] && !M) {\n                                    const e = new gm(i);\n                                    if (e.url = I.url, e.rawByteRange = Math.min(I.byteRangeStartOffset, 1316) + \"@0\", e.baseurl = t, e.isInitSegment = !0, e.cc = T, e.levelkey = v, e.iframe = !0, b && !S) {\n                                        k = x();\n                                        break\n                                    }\n                                    S = !1, b = !1, f.initSegments[T] = e.getMediaFragment(s, a, o)\n                                } else C && (C.discoSeqNum = T, f.initSegments[T] = C);\n                            D = !1, M = !1, I = new gm(i)\n                        }\n                    } else if (m[4]) {\n                        if (I.rawByteRange = (\" \" + m[4]).slice(1), E) {\n                            const e = E.byteRangeEndOffset;\n                            e && (I.lastByteRangeEndOffset = e)\n                        }\n                    } else if (m[5]) y = (\" \" + m[5]).slice(1);\n                    else if (m[6]) {\n                        const e = parseInt(m[6]);\n                        ne(e) && (w = 1e3 * e)\n                    } else if (m[7]) {\n                        const e = m[7],\n                            t = Im.parseTags(e);\n                        t.ID && (f.daterangeTags || (f.daterangeTags = {}), f.daterangeTags[t.ID] = t)\n                    } else {\n                        for (m = m[0].match(wm.LevelPlaylistSlow), g = 1; g < m.length && void 0 === m[g]; g++);\n                        const e = Om.replaceVariables((\" \" + m[g + 1]).slice(1), A),\n                            l = Om.replaceVariables((\" \" + m[g + 2]).slice(1), A);\n                        if (e.error || l.error) {\n                            k = new R(L, N, !0, $.PlaylistErrorInvalidEXTXDEFINE.text, $.PlaylistErrorInvalidEXTXDEFINE);\n                            break\n                        }\n                        const d = e.updatedString,\n                            u = l.updatedString;\n                        switch (m[g]) {\n                            case \"#\":\n                                I.tagList.push(u ? [d, u] : [d]);\n                                break;\n                            case \"PLAYLIST-TYPE\":\n                                f.type = d.toUpperCase(), \"VOD\" === f.type && (f.liveOrEvent = !1);\n                                break;\n                            case \"MEDIA-SEQUENCE\":\n                                0 === f.fragments.length && (h = f.startSN = parseInt(d));\n                                break;\n                            case \"TARGETDURATION\":\n                                f.targetduration = parseFloat(d);\n                                break;\n                            case \"VERSION\":\n                                f.version = parseInt(d);\n                                break;\n                            case \"EXTM3U\":\n                                break;\n                            case \"ENDLIST\":\n                                f.liveOrEvent = !1;\n                                break;\n                            case \"DIS\":\n                                T++, I.tagList.push([\"DIS\"]), D = !0;\n                                break;\n                            case \"DISCONTINUITY-SEQ\":\n                                T = parseInt(d);\n                                break;\n                            case \"KEY\":\n                                const e = d;\n                                if (b = !0, !S) {\n                                    try {\n                                        v = Om.parseDecryptData(e, t, r)\n                                    } catch (e) {\n                                        k = e\n                                    }\n                                    v && (S = !0)\n                                }\n                                break;\n                            case \"START\":\n                                const l = d,\n                                    P = Im.parseTags(l)[\"TIME-OFFSET\"];\n                                ne(P) && (f.startTimeOffset = P);\n                                break;\n                            case \"I-FRAMES\":\n                                f.iframesOnly = !0;\n                                break;\n                            case \"MAP\":\n                                const c = Im.parseTags(d);\n                                if (I.relurl = c.URI, I.rawByteRange = c.BYTERANGE, I.baseurl = t, I.isInitSegment = !0, I.levelkey = v, b && !S) {\n                                    k = x();\n                                    break\n                                }\n                                S = !1, b = !1, C = I.getMediaFragment(s, a, o), M = !0, I = new gm(i);\n                                break;\n                            case \"DEFINE\":\n                                const p = wm.VARIABLE_PLAYLIST_REGEX.exec(d),\n                                    m = \"NAME\" === p[1] ? p[2] : p[4],\n                                    g = \"VALUE\" === p[1] ? p[2] : p[4],\n                                    y = p[5],\n                                    N = p[6];\n                                if (m || g || \"IMPORT\" !== y || !n.hasOwnProperty(N)) {\n                                    if (!m || y || p[1] === p[3] || A.hasOwnProperty(m)) {\n                                        k = new R(L, _, !0, $.PlaylistErrorMissingImportReference.text, $.PlaylistErrorMissingImportReference);\n                                        break\n                                    }\n                                    A[m] = g\n                                } else A[N] = n[N]\n                        }\n                    }\n                }\n                return I = E, I && !I.relurl && (f.fragments.pop(), p -= I.duration), !f.liveOrEvent && 0 < f.fragments.length && (f.fragments[f.fragments.length - 1].isLastFragment = !0), f.totalduration = p, f.averagetargetduration = p / f.fragments.length, f.endSN = h - 1, {\n                    mediaOptionDetails: f,\n                    playlistParsingError: k\n                }\n            }\n            static parseRootPlaylist(t, e, i, r) {\n                const n = [],\n                    s = {};\n                let a, o, l, d, u = null,\n                    c = !0;\n                for (wm.MasterPlaylist.lastIndex = 0; null != (a = wm.MasterPlaylist.exec(e));)\n                    if (a[4]) {\n                        a = wm.VARIABLE_PLAYLIST_REGEX.exec(a[4]);\n                        const t = \"NAME\" === a[1] ? a[2] : a[4],\n                            e = \"VALUE\" === a[1] ? a[2] : a[4],\n                            i = a[5];\n                        if (!t || s.hasOwnProperty(t) || i || a[1] === a[3]) {\n                            d = new R(L, _, !0, $.PlaylistErrorInvalidEXTXDEFINE.text, $.PlaylistErrorInvalidEXTXDEFINE);\n                            break\n                        }\n                        s[t] = e\n                    } else if (a[5]) {\n                    const t = Om.replaceVariables(a[5], s);\n                    if (t.error) {\n                        d = new R(L, _, !0, $.PlaylistErrorInvalidEXTXDEFINE.text, $.PlaylistErrorInvalidEXTXDEFINE);\n                        break\n                    }\n                    const e = Im.parseTags(t.updatedString);\n                    if (\"string\" != typeof e[\"SERVER-URI\"]) {\n                        d = new R(L, _, !0, $.PlaylistErrorInvalidSERVERURI.text, $.PlaylistErrorInvalidSERVERURI);\n                        break\n                    }\n                    if (null != e[\"PATHWAY-ID\"] && \"string\" != typeof e[\"PATHWAY-ID\"]) {\n                        d = new R(L, _, !0, $.PlaylistErrorInvalidPATHWAYID.text, $.PlaylistErrorInvalidPATHWAYID);\n                        break\n                    }\n                    u = {\n                        serverURI: Am(e[\"SERVER-URI\"], i, !1),\n                        initPathwayID: e[\"PATHWAY-ID\"] || \".\"\n                    }\n                } else {\n                    l = Om.replaceVariables(a[1] || a[3], s);\n                    const e = Im.parseTags(l.updatedString);\n                    if (o = Om.replaceVariables(a[2] || e.URI, s), l.error || o.error) {\n                        d = new R(L, _, !0, $.PlaylistErrorInvalidEXTXDEFINE.text, $.PlaylistErrorInvalidEXTXDEFINE);\n                        break\n                    }\n                    if (void 0 !== e.SCORE && !ne(e.SCORE) || e.SCORE < 0) {\n                        d = new R(L, _, !0, $.PlaylistErrorInvalidSCORE.text, $.PlaylistErrorInvalidSCORE), c = !1;\n                        break\n                    }\n                    c && void 0 === e.SCORE && (c = !1);\n                    const u = e.BANDWIDTH,\n                        p = e[\"AVERAGE-BANDWIDTH\"],\n                        f = p || u,\n                        m = null !== (h = e[\"VIDEO-RANGE\"]) && void 0 !== h ? h : \"SDR\";\n                    if (null == (h = m) || !cm.includes(h)) continue;\n                    const g = {\n                            itemId: t,\n                            mediaOptionId: `level_${(f||0)+n.length%1e3/1e3}`,\n                            mediaOptionType: gu.Variant,\n                            attrs: e,\n                            url: Am(o.updatedString, i, r),\n                            name: e.NAME,\n                            audioGroupId: e.AUDIO,\n                            subtitleGroupId: e.SUBTITLES,\n                            iframes: !!a[3],\n                            bandwidth: u,\n                            avgBandwidth: p,\n                            bitrate: f,\n                            videoRange: m,\n                            frameRate: e[\"FRAME-RATE\"],\n                            allowedCPCMap: Om.parseAllowedCPC(e[\"ALLOWED-CPC\"]),\n                            closedcaption: e[\"CLOSED-CAPTIONS\"],\n                            levelCodec: e.CODECS,\n                            score: e.SCORE,\n                            pathwayID: e[\"PATHWAY-ID\"] || \".\"\n                        },\n                        y = e[\"HDCP-LEVEL\"];\n                    dm(y) && (g.hdcpLevel = y);\n                    var h = e.RESOLUTION;\n                    if (h && (g.width = h.width, g.height = h.height), e.CODECS) {\n                        g.videoCodecList = new Array, g.audioCodecList = new Array;\n                        const t = e.CODECS.split(/[ ,]+/),\n                            i = t[\"length\"];\n                        for (let e = 0; e < i; e++) {\n                            const i = t[e];\n                            switch (i.slice(0, 4)) {\n                                case \"avc1\":\n                                    g.videoCodec = be.avc1toavcoti(i), g.videoCodecList.push(g.videoCodec);\n                                    break;\n                                case \"avc3\":\n                                case \"dvav\":\n                                case \"dva1\":\n                                case \"hev1\":\n                                case \"hvc1\":\n                                case \"dvh1\":\n                                case \"dvhe\":\n                                case \"vp09\":\n                                    g.videoCodec = i, g.videoCodecList.push(g.videoCodec);\n                                    break;\n                                default:\n                                    g.audioCodec = i, g.audioCodecList.push(g.audioCodec)\n                            }\n                        }\n                        1 < g.audioCodecList.length && (g.audioCodec = fm.getRichestAudioCodec(g.audioCodecList)), 1 < g.videoCodecList.length && (g.videoCodec = fm.getRichestVideoCodec(g.videoCodecList))\n                    }\n                    if (null != (d = \"string\" != typeof(h = g.pathwayID) ? mm(\"invalid steering manifest PATHWAY-PRIORITY list item data type\") : /^[\\w\\-\\.]+$/.test(h) ? void 0 : mm(\"steering manifest contains invalid pathway ID: \" + h))) break;\n                    let cpc = g.allowedCPCMap ? JSON.stringify(g.allowedCPCMap) : \"null\";\n                    if (!cpc.includes(\"WIDEVINE_HARDWARE\") && !g.url.includes('trickPlay') && !g.videoCodec.includes(\"hvc1\"))\n                    n.push(g)\n                }\n                try{\n                    // console.log(n,  window.screen.width)\n                    let ok = (n.map(  function(item){return{height : item.height, content: item}}));\n                    let screenHeight = (app.cfg.visual.videoRes ?? window.screen.height) ;\n                    ok.sort(function (a, b) {\n                        return a.height - b.height;\n                      });\n                    for (var i = 0; i < ok.length; i++){\n                        if (ok[i].height > screenHeight){\n                            if (i == 0){n.splice(0,n.length);n.push(ok[i].content)} \n                            else{n.splice(0,n.length);n.push(ok[i-1].content)}\n                            console.log('selected' , n[0].height)\n                            break; \n                            \n                        }\n                            \n                    }\n                    if (n.length > 1){\n                        n.splice(0,n.length - 1);                      \n                    }\n                    // console.log(n)\n                    // console.log(ok)\n                    } catch (e){ console.log(e)}\n                return {\n                    variantMediaOptions: n,\n                    contentSteeringOption: u,\n                    masterVariableList: s,\n                    playlistParsingError: d,\n                    scoreAvailable: c\n                }\n            }\n            static parseAllowedCPC(e) {\n                if (\"string\" != typeof e) return null;\n                const n = {};\n                return e.split(\",\").forEach(e => {\n                    const t = e.split(\":\");\n                    let i, r;\n                    if (2 === t.length) i = t[0].trim(), r = t[1].trim();\n                    else {\n                        if (!(2 < t.length)) return;\n                        r = t[t.length - 1].trim(), t.pop(), i = t.join(\":\")\n                    }\n                    if (!(i in n)) {\n                        let e = new Array;\n                        \"\" !== r && (e = r.split(\"/\").map(e => e.trim())), n[i] = e\n                    }\n                }), n\n            }\n            static parseSessionKeys(e, t, i) {\n                var r;\n                const n = [];\n                for (wm.SessionData.lastIndex = 0; r = wm.SessionKeys.exec(e);) try {\n                    const e = Om.parseDecryptData(r[1], t, i);\n                    e && e.isEncrypted && n.push(e)\n                } catch (e) {}\n                return n\n            }\n            static parseSessionData(e, t) {\n                var i;\n                const r = [],\n                    n = new Set;\n                for (wm.SessionData.lastIndex = 0; null != (i = wm.SessionData.exec(e));) {\n                    const e = Im.parseTags(i[1]);\n                    e.LANGUAGE = pm.shortenLanguageCode(e.LANGUAGE);\n                    const t = e.LANGUAGE ? e[\"DATA-ID\"] + \"|\" + e.LANGUAGE : void 0;\n                    \"DATA-ID\" in e ? t && n.has(t) || (\"com.apple.hls.other-tags\" === e[\"DATA-ID\"] && (e.VALUE = function(t) {\n                        let i;\n                        try {\n                            i = JSON.parse(qc.base64DecodeToStr(t))\n                        } catch (e) {\n                            i = t\n                        }\n                        return i\n                    }(e.VALUE)), r.push(e), t && n.add(t)) : Qe().error(`Error processing DATA-ID ${e[\"DATA-ID\"]} and LANGUAGE ${e.LANGUAGE}`)\n                }\n                return {\n                    itemList: r,\n                    baseUrl: t\n                }\n            }\n        }\n        var km, Cm, Dm, Mm, xm, Pm, Rm = Om;\n        const Lm = (e, t, i) => {\n                i = Object.assign(Object.assign({}, e), {\n                    method: \"GET\",\n                    responseType: \"text\",\n                    extendMaxTTFB: i\n                });\n                return Tu(i.url) ? Pc().load(i, t).pipe(hr(e => ({\n                    responseText: e.data.response.data.toString(),\n                    responseURL: e.data.response.uri,\n                    stats: e.stats\n                }))) : Cc(i, t).pipe(hr(([e, t]) => ({\n                    responseText: e.responseText,\n                    responseURL: e.responseURL,\n                    stats: t\n                })))\n            },\n            _m = (e, n, t, i, s, a, o, l, r) => {\n                const {\n                    url: d,\n                    itemId: u,\n                    mediaOptionId: c,\n                    mediaOptionType: h,\n                    iframes: p = !1\n                } = e, f = Lc(e, i);\n                return Lm({\n                    url: d,\n                    xhrSetup: t.xhrSetup\n                }, f, r).pipe(hr(({\n                    responseText: e,\n                    responseURL: t,\n                    stats: i\n                }) => {\n                    t || (s.warn(\"Missing response url. Reusing request url as base url\"), t = d);\n                    var r = performance.now(),\n                        e = Om.parseMediaOptionPlaylist(e, t, !0, a, l, u, c, h, s, n, p);\n                    Nc(e.mediaOptionDetails);\n                    var t = performance.now(),\n                        e = e[\"mediaOptionDetails\"],\n                        r = {\n                            playlistLoadTimeMs: i.tload - i.trequest,\n                            playlistParseTimeMs: t - r\n                        };\n                    return o.setPlaylistSample(r), {\n                        mediaOptionDetails: e,\n                        stats: i\n                    }\n                }), (m = h, g = c, y = d, e => e.pipe(Vn(e => {\n                    if (e instanceof pc) throw new uc(!1, \"Timeout\", 0, $.PlaylistTimeoutError, !0, m, g, y);\n                    if (e instanceof oc) throw new uc(!1, e.message, e.code, {\n                        code: e.code,\n                        text: \"Playlist Network Error\"\n                    }, !1, m, g, y);\n                    throw e\n                }))));\n                var m, g, y\n            },\n            Nm = (f, e, m, t, g) => $i(e).pipe(La(e => {\n                const {\n                    keyTagInfo: t,\n                    isInitSegment: i,\n                    iframe: r,\n                    byteRangeOffset: n\n                } = f, s = t[\"method\"], {\n                    start: a,\n                    end: o\n                } = n;\n                if (\"AES-128\" !== s) return $i(e); {\n                    !t.uri || t.iv || t.format && \"identity\" !== t.format || (t.iv = function(t) {\n                        const i = new Uint8Array(16);\n                        for (let e = 12; e < 16; e++) i[e] = t >> 8 * (15 - e) & 255;\n                        return i\n                    }(f.mediaSeqNum));\n                    const n = e,\n                        s = t.key.buffer,\n                        l = t.iv.buffer,\n                        d = o && (r || i) ? o - a : void 0,\n                        u = !m.enableWebCrypto || !!d,\n                        c = s.slice(0),\n                        h = l.slice(0),\n                        p = {\n                            useJSCrypto: u,\n                            plainTextLength: d\n                        };\n                    return g.decrypt(c, h, \"AES-CBC\", n, p)\n                }\n            }));\n\n        function Fm(e, t) {\n            var i = e.fragments,\n                r = t.mediaSeqNum - e.startSN;\n            return 0 <= r && r < e.fragments.length && $p(t, i[r])\n        }\n\n        function Bm(t, r, n, s, a = !1, o = !1) {\n            if (Fm(t, r)) {\n                var l = r.mediaSeqNum - t.startSN;\n                let i = t.fragments,\n                    e = i[l];\n                var {\n                    startDtsTs: d,\n                    startPts: u,\n                    endPts: r\n                } = r;\n                a && (i = t.fragments = t.fragments.slice(), e = i[l] = Object.assign({}, e)), e.startDtsTs = d, e.startPts = u, e.endPts = r, !s && void 0 === e.isIframeStart || (e.isIframeStart = s), e.start = n, e.duration = b(r, u);\n                for (let e = l, t = !0; 0 < e && (o || t); e--) t = Um(i, e, e - 1, s, u.timescale, a);\n                for (let e = l, t = !0; e < i.length - 1 && (o || t); e++) t = Um(i, e, e + 1, s, u.timescale, a);\n                l = i[i.length - 1];\n                t.totalduration = l.start + l.duration - i[0].start, t.ptsKnown = !0\n            }\n        }\n\n        function Um(e, t, i, r, n, s = !1) {\n            var a = e[t];\n            let o = e[i];\n            var l = null != r && null != o.isIframeStart && o.isIframeStart !== r && o.discoSeqNum === a.discoSeqNum;\n            let d = o.start;\n            !l && null != o.startPts || (d = t < i ? a.start + a.duration : Math.max(a.start - o.duration, 0));\n            n = ne(n) ? 1 / n : Number.EPSILON, n = Math.abs(o.start - d) > n;\n            return !(!l && !n || (s && (o = e[i] = Object.assign({}, o)), n && (o.start = d), l && (o.isIframeStart = r), 0))\n        }\n\n        function $m(e) {\n            if (e.programDateTimeMap) {\n                e.dateMediaTimePairs = [];\n                for (var [t, i] of Object.entries(e.programDateTimeMap)) {\n                    t = Number(t), i = e.fragments[i - e.startSN];\n                    i && (i = i.start, e.dateMediaTimePairs.push([t, i]))\n                }\n                e.dateMediaTimePairs.sort((e, t) => e[0] - t[0])\n            }\n        }\n        class Vm {\n            constructor(e) {\n                this.option = e\n            }\n            get name() {\n                return this.option.name\n            }\n            get priority() {\n                return this.option.priority\n            }\n            get expiry() {\n                return this.option.expiry\n            }\n            filter(i, e) {\n                const r = this.option.initFn && this.option.initFn(i, e) || (e ? Object.assign({}, e) : {});\n                let t = i;\n                return this.option.firstPassFn && i.forEach((e, t) => this.option.firstPassFn(e, t, r, i)), this.option.filterFn && (t = i.filter((e, t) => this.option.filterFn(e, t, r, i))), null != this.option.filterFn && 0 !== t.length || !this.option.minSortingFn || (t = i.sort((e, t) => this.option.minSortingFn(e, t, r, i))), this.option.finalFn && this.option.finalFn(t, r, i), t\n            }\n        }\n\n        function Km(e, t, i) {\n            return (t || []).reduce((e, t) => t.filter(e, i), Array.from(e))\n        }\n\n        function qm(t, e) {\n            return e.filter(e => {\n                return Au(t, null !== (e = e.url) && void 0 !== e ? e : null)\n            })\n        }\n\n        function Hm() {\n            return [new Vm({\n                name: \"Remove Filter\",\n                priority: 0,\n                filterFn: (t, e, i) => !i || i.removed.every(e => t.mediaOptionId !== e)\n            }), new Vm({\n                name: \"Penalty Box Filter\",\n                priority: 1,\n                filterFn: (t, e, i) => {\n                    const r = performance.now();\n                    return !i || i.penaltyBoxQueue.every(e => e.expiry <= r || t.mediaOptionId !== e.mediaOptionId)\n                }\n            }), new Vm({\n                name: \"Compatible IDs Filter\",\n                priority: 1,\n                filterFn: (t, e, i) => !i || null == i.compatibleIds || i.compatibleIds.some(e => e === t.mediaOptionId)\n            })]\n        }\n        class jm extends kl {\n            constructor(e, t, i) {\n                super(e), this.itemId = t, this.mediaOptionType = i, this.allowFilters = this._initFilters()\n            }\n            get mediaOptionList() {\n                var e;\n                return (null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.mediaOptions) || null\n            }\n            get mediaOptionList$() {\n                return this.mediaOptionListInfo$.pipe(hr(({\n                    mediaOptions: e\n                }) => e))\n            }\n            mediaOptionFromId(t) {\n                var e;\n                return null !== (e = (null !== (e = this.mediaOptionList) && void 0 !== e ? e : []).find(e => e.mediaOptionId === t)) && void 0 !== e ? e : null\n            }\n            _getFilteredList(e) {\n                return Km(e.mediaOptions, this.allowFilters, e)\n            }\n            get filteredMediaOptionList() {\n                return this.mediaOptionListInfo ? this._getFilteredList(this.mediaOptionListInfo) : null\n            }\n            get filteredMediaOptionList$() {\n                return this.mediaOptionListInfo$.pipe(La(e => {\n                    const t = [Wu],\n                        i = performance.now();\n                    for (const r of e.penaltyBoxQueue) ne(r.expiry) && r.expiry > i && t.push(bn(r.expiry - i));\n                    return an(...t).pipe(hr(() => this._getFilteredList(e)))\n                }), vl())\n            }\n            get preferredMediaOptionList() {\n                return this.filteredMediaOptionList ? qm(this.preferredHost, this.filteredMediaOptionList) : []\n            }\n            get preferredMediaOptionList$() {\n                return ed([this.preferredHost$, this.filteredMediaOptionList$]).pipe(hr(([e, t]) => qm(e, t)))\n            }\n            getNewHost(e) {\n                e = this.getFallbackVariant(e, !1, !0);\n                return null != e && e.url ? Eu(e.url) : this.preferredHost\n            }\n        }\n\n        function Qm(e) {\n            return \"PQ\" === e.videoRange || \"HLG\" === e.videoRange\n        }\n\n        function Wm(e, t) {\n            return t.iframes === e\n        }\n\n        function Gm(e, t, i, r) {\n            return !r || i.bitrate > r.bitrate && i.bitrate <= e.bitrate ? km.Better : i.bitrate === r.bitrate ? km.Same : km.Worse\n        }\n\n        function zm(e, t) {\n            return e && !t ? -1 : !e && t ? 1 : 0\n        }(dl = km = km || {})[dl.Better = 1] = \"Better\", dl[dl.Same = 0] = \"Same\", dl[dl.Worse = -1] = \"Worse\";\n        class Xm extends jm {\n            constructor(e, t) {\n                super(e, t, gu.Variant)\n            }\n            static makeFilters() {\n                return [...Hm().concat([new Vm({\n                    name: \"HDR Filter\",\n                    priority: 1,\n                    filterFn: (e, t, i) => !i || (i.hasHdrLevels && i.preferHDR) === Qm(e)\n                }), new Vm({\n                    name: \"Viewport Filter\",\n                    priority: 1,\n                    firstPassFn: (e, t, i) => {\n                        if (i && e && !e.iframes && e.videoCodec) {\n                            const t = !i.lowestBitrate || e.bitrate < i.lowestBitrate ? e.bitrate : i.lowestBitrate;\n                            i.lowestBitrate = t\n                        }\n                    },\n                    filterFn: (e, t, i) => !(e && i && i.viewportInfo && e.videoCodec && i.lowestBitrate) || function(e, t) {\n                        return e.width < 1.35 * t.width && e.height < 1.35 * t.height && e.width * e.height < t.width * t.height * 1.35\n                    }({\n                        width: e.width,\n                        height: e.height\n                    }, i.viewportInfo) || e.bitrate === i.lowestBitrate\n                }), new Vm({\n                    name: \"HDCP Filter\",\n                    priority: 2,\n                    filterFn: (e, t, i) => !i || !dm(i.maxHdcpLevel) || um(e.hdcpLevel) < um(i.maxHdcpLevel)\n                })])].sort((e, t) => {\n                    return (null !== (e = e.priority) && void 0 !== e ? e : Number.MAX_SAFE_INTEGER) - (null !== (t = t.priority) && void 0 !== t ? t : Number.MAX_SAFE_INTEGER)\n                })\n            }\n            _initFilters() {\n                return Xm.kAllowFilters\n            }\n            get preferredHost() {\n                var e;\n                return null !== (e = null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.preferredHost) && void 0 !== e ? e : null\n            }\n            get preferredHost$() {\n                return this.selectEntity(this.itemId, e => {\n                    return null !== (e = null == e ? void 0 : e.mediaOptionListTuple[gu.Variant].preferredHost) && void 0 !== e ? e : null\n                })\n            }\n            get mediaOptionListInfo() {\n                var e;\n                return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.mediaOptionListTuple[gu.Variant]) && void 0 !== e ? e : null\n            }\n            get mediaOptionListInfo$() {\n                return this.selectEntity(this.itemId, e => {\n                    return null === (e = null == e ? void 0 : e.mediaOptionListTuple) || void 0 === e ? void 0 : e[gu.Variant]\n                }).pipe(Kp())\n            }\n            get hdrMode$() {\n                return this.mediaOptionListInfo$.pipe(hr(e => !0 === e.preferHDR && e.hasHdrLevels), Is())\n            }\n            get maxHdcpLevel$() {\n                return this.selectEntity(this.itemId, e => {\n                    e = null === (e = null == e ? void 0 : e.mediaOptionListTuple) || void 0 === e ? void 0 : e[gu.Variant];\n                    return null == e ? void 0 : e.maxHdcpLevel\n                }).pipe(Is())\n            }\n            listFallbackVariants(t, e, i, r, n) {\n                var s = this.mediaOptionListInfo,\n                    a = null === (o = this.mediaOptionList) || void 0 === o ? void 0 : o.find(e => e.mediaOptionId === t);\n                if (!a || !s) return null;\n                var o = this.makeFilteredListFromVariant(a, e, n);\n                if (!o) return null;\n                e = Eu(a.url), s = s.hasScore;\n                return Xm._listFallbackVariants(o, a, e, s, i, r, n)\n            }\n            getFallbackVariant(t, e, i, r) {\n                var n = this.mediaOptionListInfo,\n                    s = null === (s = this.mediaOptionList) || void 0 === s ? void 0 : s.find(e => e.mediaOptionId === t);\n                if (!s || !n) return null;\n                e = this.makeFilteredListFromVariant(s, e, r);\n                if (!e) return null;\n                r = Eu(s.url), n = n.hasScore;\n                return Xm._getFallbackVariant(e, s, r, n, i)\n            }\n            makeFilteredListFromVariant(e, t, i) {\n                let r = this.mediaOptionListInfo;\n                if (!e || !this.mediaOptionList || !r) return null;\n                r = Object.assign(Object.assign({}, r), {\n                    includeAllEligiblePathways: !0\n                });\n                e = Array.from(this.mediaOptionList);\n                let n = t ? Km(e, this.allowFilters, Object.assign(Object.assign({}, r), {\n                    preferHDR: !1,\n                    compatibleIds: null\n                })) : this._getFilteredList(r);\n                return n ? (i && 0 < i.length && (n = n.filter(e => !i.includes(e.mediaOptionId))), n) : null\n            }\n            get hasIframes() {\n                var e;\n                return null !== (e = null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.hasIframeLevels) && void 0 !== e && e\n            }\n            canSwitchToSDR(e, t, i = !1) {\n                var r = this.mediaOptionListInfo;\n                if (!this.mediaOptionList || !r) return !1;\n                var n = this.mediaOptionFromId(e);\n                if (!n) return !1;\n                if (!Qm(n)) return !1;\n                var s = Eu(n.url),\n                    e = Km(Array.from(this.mediaOptionList), this.allowFilters, Object.assign(Object.assign({}, r), {\n                        preferHDR: !1,\n                        compatibleIds: null\n                    })),\n                    r = r.hasScore;\n                return null != Xm._getFallbackVariant(e, n, s, r, t, i)\n            }\n            static _listFallbackVariants(e, r, n, t, s, a = !1, i = null) {\n                let o = !1;\n                const l = function(e, s, a) {\n                    const t = [...e],\n                        o = Eu(s.url),\n                        l = s.audioGroupId;\n                    return t.sort((e, t) => {\n                        let i = 0;\n                        var r = a && ne(e.score) && ne(t.score),\n                            n = r ? e.score > t.score && e.score <= s.score : e.bitrate > t.bitrate && e.bitrate <= s.bitrate,\n                            r = r ? e.score === t.score : e.bitrate === t.bitrate;\n                        return n ? i = -1 : r ? (i = zm(Au(o, e.url), Au(o, t.url)), 0 === i && (i = zm(!l || e.audioGroupId === l, !l || t.audioGroupId === l))) : i = 1, i\n                    }), t\n                }(e.filter(e => {\n                    var t = !(e.iframes !== r.iframes || s && Au(n, e.url)),\n                        i = a ? e.bitrate < r.bitrate : e.bitrate <= r.bitrate,\n                        i = t && i;\n                    return r.mediaOptionId === e.mediaOptionId ? (o = i, !1) : i\n                }), r, t);\n                return !o || i && i.includes(r.mediaOptionId) || l.unshift(r), l\n            }\n            static _getFallbackVariant(e, t, i, r, n, s = !1) {\n                let a = null;\n                e = (e = s ? e.filter(e => e.bitrate < t.bitrate) : e).filter(e => e.mediaOptionId !== t.mediaOptionId && e.iframes === t.iframes);\n                if (n && null != i)\n                    for (const o of e) Gm(t, 0, o, a) !== km.Better || Au(i, o.url) || (a = o);\n                else\n                    for (const o of e) {\n                        const r = Gm(t, 0, o, a);\n                        r !== km.Better && (r !== km.Same || !Au(i, o.url) || Au(i, a.url) && o.audioGroupId !== t.audioGroupId) || (a = o)\n                    }\n                return a\n            }\n            getMatchingVariant(e, t) {\n                var i = this.mediaOptionFromId(e),\n                    r = Eu(null == i ? void 0 : i.url),\n                    n = t.mediaOptionType === gu.AltAudio ? \"audioGroupId\" : \"subtitleGroupId\";\n                let s = null;\n                this.mediaOptionListInfo.hasScore;\n                for (const e of this.filteredMediaOptionList)\n                    if (e[n] === t.groupId) {\n                        if (!i) {\n                            s = e;\n                            break\n                        }\n                        var a = Gm(i, 0, e, s);\n                        a !== km.Better && (a !== km.Same || s.mediaOptionId === i.mediaOptionId || e.mediaOptionId !== i.mediaOptionId && !Au(r, e.url)) || (s = e)\n                    } return s\n            }\n            get currentPathwayID() {\n                var e;\n                return null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.currentPathwayID\n            }\n        }\n\n        function Ym(e, t) {\n            switch (e) {\n                case Cm.SendAlternateToPenaltyBox:\n                    e = Cm.RetryRequest, 401 !== t && 403 !== t && 407 !== t && t !== $.CorruptStream.code && t !== $.LivePlaylistUpdateError.code || (e = Cm.SendEndCallback);\n                    break;\n                case Cm.RemoveAlternatePermanently:\n                    e = Cm.SendEndCallback\n            }\n            return e\n        }\n\n        function Jm(e, t, i, r, n, s, a, o = !1) {\n            const l = s.mediaOptionListQueries[n],\n                d = 0 != (e.errorActionFlags & Dm.MoveAllAlternatesMatchingHost),\n                u = s.mediaOptionListQueries[n].mediaOptionFromId(r),\n                c = a.getFallbackMediaOptionTupleFromMediaOptionId(s, n, r, u.backingMediaOptionId, !1, d, o);\n            let {\n                errorAction: h,\n                errorActionFlags: p\n            } = e;\n            return s.isValidMediaOptionTuple(c) ? Au(l.preferredHost, c[n].url) && (p &= ~Dm.MoveAllAlternatesMatchingHost) : (t || (h = Ym(h, i), p = 0), l instanceof Xm && (!0 === l.mediaOptionFromId(r).iframes ? (h = Cm.DoNothing, p = 0) : !t && a.canSwitchToSDR(s, r, d, o) && (h = e.errorAction, p = Dm.SwitchToSDR))), {\n                errorAction: h,\n                errorActionFlags: p\n            }\n        }\n\n        function Zm(e) {\n            let t, i = 0;\n            switch (e) {\n                case 0:\n                    t = Cm.SendAlternateToPenaltyBox, i = Dm.MoveAllAlternatesMatchingHost;\n                    break;\n                case 410:\n                    t = Cm.RemoveAlternatePermanently;\n                    break;\n                case 500:\n                case 502:\n                case 503:\n                case 504:\n                case 404:\n                case 409:\n                case 401:\n                case 403:\n                case 407:\n                case $.LivePlaylistUpdateError.code:\n                case $.PlaylistNotReceived.code:\n                default:\n                    t = Cm.SendAlternateToPenaltyBox, i = 0\n            }\n            return {\n                errorAction: t,\n                errorActionFlags: i\n            }\n        }\n\n        function eg(i, r, n, s, a, o, l) {\n            var {\n                errorAction: d,\n                errorActionFlags: u\n            } = i;\n            let e = !0;\n            switch (d) {\n                case Cm.RemoveAlternatePermanently:\n                case Cm.SendAlternateToPenaltyBox: {\n                    if (null == a || null == o) return r.handled = !1;\n                    const i = n.itemId;\n                    let e = o,\n                        t = n.mediaOptionListQueries[a].mediaOptionFromId(o);\n                    t.backingMediaOptionId && (e = t.backingMediaOptionId, t = n.mediaOptionListQueries[a].mediaOptionFromId(e));\n                    var c = 0 != (u & Dm.MoveAllAlternatesMatchingHost),\n                        h = 0 != (u & Dm.MoveAllAlternatesMatchingHDCP),\n                        p = 0 != (u & Dm.SwitchToSDR),\n                        f = d === Cm.RemoveAlternatePermanently;\n                    if (h && \"hdcpLevel\" in t) {\n                        const r = t.hdcpLevel;\n                        s.setMaxHdcpLevel(i, r)\n                    }\n                    if (p && s.switchToSDROnly(i), c) {\n                        const r = Eu(t.url);\n                        s.moveAllWithMatchingHosts(i, a, r, f)\n                    } else f ? s.removePermanently(i, a, e) : s.addToPenaltyBox(i, a, e);\n                    if (n.enabledMediaOptionIdByType(a) === o) {\n                        let e = [Lu, Lu, Lu];\n                        e = s.getFallbackMediaOptionTupleFromMediaOptionId(n, a, o, null, !1, c, l), n.isValidMediaOptionTuple(e) ? s.setPreferredHost(i, Eu(e[gu.Variant].url)) : r.fatal = !0, r.fatal && (e = [Lu, Lu, Lu]), s.setNextMediaOptions(n.itemId, e)\n                    }\n                    break\n                }\n                case Cm.SendEndCallback:\n                    r.fatal = !0;\n                    break;\n                case Cm.RetryRequest:\n                case Cm.DoNothing:\n                default:\n                    e = !1\n            }\n            return r.handled = e, e\n        }\n\n        function tg(e, t) {\n            t instanceof dc || t instanceof uc || t instanceof hc || (t instanceof gc || t instanceof mc) && le(t.keyuri)\n        }\n\n        function ig(t, i, r) {\n            if (t.handled = !0, r && i < r.maxNumRetry && ne(r.retryDelayMs)) {\n                let e;\n                return e = \"linear\" === r.backoff ? (i + 1) * r.retryDelayMs : Math.pow(2, i) * r.retryDelayMs, e = Math.min(r.maxRetryDelayMs, e), tg(0, t), bn(e)\n            }\n            return t.fatal = !0, tg(0, t), Vi(t)\n        }\n\n        function rg(e, t, i, r, n, s, a, o, l = !1) {\n            return (null == r ? void 0 : r.errorAction) === Cm.RetryRequest ? ig(e, t, i, s.logger) : ng(e, 0, r, n, s, a, o, l)\n        }\n\n        function ng(e, t, i, r, n, s, a, o = !1) {\n            const l = new er;\n            return al(() => {\n                i && (tg(n.logger, e), eg(i, e, r, n, s, a, o)), l.error(e)\n            }), l\n        }\n\n        function sg(t, i, r, n) {\n            return e => e.pipe(Vn(e => {\n                if (t.logger.error(`Got demux error ${e.message}`), e instanceof D || e instanceof F) {\n                    Cm.SendAlternateToPenaltyBox;\n                    return ng(e, 0, {\n                        errorAction: e.fatal ? Cm.SendEndCallback : e instanceof F ? Cm.SendAlternateToPenaltyBox : Cm.RemoveAlternatePermanently,\n                        errorActionFlags: 0\n                    }, i, t, r, n)\n                }\n                throw e\n            }))\n        }\n\n        function ag(e, t, i, r, n) {\n            e = null !== (e = null === (e = n.getKeyInfo(e)) || void 0 === e ? void 0 : e.mediaOptionIds) && void 0 !== e ? e : [];\n            for (const s of e)\n                for (const n of i.mediaOptionListQueries) null != n.mediaOptionFromId(s) && r.updateConsecutiveTimeouts(i.itemId, n.mediaOptionType, t, \"key\")\n        }\n\n        function og(r, t, e, n, s, a) {\n            const o = n.logger,\n                i = s.enabledMediaOptionKeys,\n                l = [];\n            for (const t of r.mediaOptionIds) {\n                const r = i.some(e => e.mediaOptionId === t),\n                    e = s.mediaOptionListQueries.find(e => null != e.mediaOptionFromId(t));\n                if (e) {\n                    const n = e.mediaOptionType,\n                        a = {\n                            mediaOptionId: t,\n                            mediaOptionType: n\n                        };\n                    r ? l.push(a) : l.unshift(a)\n                } else o.warn(`Couldn't find query for ${t}`)\n            }\n            const d = new er;\n            return al(() => {\n                const e = r instanceof mc;\n                ag(r.keyuri, e, s, n, a);\n                let t, i = !1;\n                for (const {\n                        mediaOptionId: e,\n                        mediaOptionType: a\n                    } of l) t = function(e, t, i, r, n) {\n                    let s = {\n                        errorAction: Cm.SendAlternateToPenaltyBox,\n                        errorActionFlags: 0\n                    };\n                    if (e instanceof mc) s.errorAction = Cm.SendAlternateToPenaltyBox;\n                    else {\n                        const t = e.isOkToRetry;\n                        e.keyErrorReason === rc.OutputRestricted ? (s.errorAction = Cm.RemoveAlternatePermanently, s.errorActionFlags |= Dm.MoveAllAlternatesMatchingHDCP) : t ? s = Zm(e.code) : s.errorAction = Cm.RemoveAlternatePermanently\n                    }\n                    s.errorActionFlags &= ~Dm.MoveAllAlternatesMatchingHost;\n                    var a = r.enabledMediaOptionIdByType(i);\n                    return t === a ? Jm(s, !1, e.code, a, i, r, n, e.isTimeout) : s\n                }(r, e, a, s, n), o.error(`[Keys] handleNetworkError uri=${le(r.keyuri)} mediaOptionId=${e} mediaOptionType=${a} action=${JSON.stringify(t)}`), t.errorAction === Cm.RetryRequest && (i = !0), eg(t, r, s, n, a, e);\n                i ? (d.next(), d.complete()) : (tg(0, r), d.error(r))\n            }), d.pipe(La(() => ig(r, t, e, n.logger)))\n        }\n\n        function lg(t, i, r, n, s, a, o, l) {\n            return n = Math.max(0, n), e => e.pipe(Za(() => {\n                null != i && o.updateConsecutiveTimeouts(t, i, !1, \"load\")\n            }), va(e => e.pipe(jr((e, t) => function(e, t, i, r, n, s, a, o) {\n                var l;\n                if (!(e instanceof p)) return Vi(e);\n                let d, u, c, h = !1;\n                if (e instanceof dc) c = {\n                    errorAction: Ym(Zm((l = e).response.code).errorAction, l.response.code),\n                    errorActionFlags: 0\n                };\n                else if (e instanceof uc || e instanceof hc) {\n                    ({\n                        mediaOptionType: u,\n                        mediaOptionId: d,\n                        isTimeout: h\n                    } = e);\n                    const t = null === (l = s.mediaOptionListQueries[u]) || void 0 === l ? void 0 : l.mediaOptionFromId(d);\n                    if (!r && e.isTimeout && null != t && (!(\"iframes\" in t) || !0 !== t.iframes) && (a.updateConsecutiveTimeouts(s.itemId, e.mediaOptionType, !0, \"load\"), e instanceof hc && e.stats)) {\n                        const t = performance.now();\n                        o.setBandwidthSample(Object.assign(Object.assign({}, e.stats), {\n                            tfirst: e.stats.tfirst || t,\n                            tload: e.stats.tload || t,\n                            complete: !0,\n                            mediaOptionType: u\n                        }))\n                    }\n                    c = function(e, t, i, r, n) {\n                        var s = e.response.code;\n                        let a = Zm(s);\n                        var {\n                            mediaOptionId: o,\n                            mediaOptionType: l\n                        } = e;\n                        return t ? a.errorActionFlags &= ~Dm.MoveAllAlternatesMatchingHost : a = function(e, t, i, r, n) {\n                            let {\n                                errorAction: s,\n                                errorActionFlags: a\n                            } = t;\n                            if (e.isTimeout) {\n                                const t = e[\"mediaOptionType\"],\n                                    o = null !== (n = null === (n = n.getErrorInfoByType(t)) || void 0 === n ? void 0 : n.timeouts.load) && void 0 !== n ? n : 0;\n                                !i && r <= o && (s = Cm.DoNothing, a = 0)\n                            }\n                            return {\n                                errorAction: s,\n                                errorActionFlags: a\n                            }\n                        }(e, a, t, i, r), a = Jm(a, t, s, o, l, r, n, e.isTimeout), a\n                    }(e, r, n, s, a)\n                }\n                return rg(e, t, i, c, s, a, u, d, h)\n            }(e, t, _c(e, r), s, n, a, o, l)))))\n        }\n        Xm.kAllowFilters = Xm.makeFilters(), (dl = Cm = Cm || {})[dl.DoNothing = 0] = \"DoNothing\", dl[dl.SendEndCallback = 1] = \"SendEndCallback\", dl[dl.SendAlternateToPenaltyBox = 2] = \"SendAlternateToPenaltyBox\", dl[dl.RemoveAlternatePermanently = 3] = \"RemoveAlternatePermanently\", dl[dl.InsertDiscontinuity = 4] = \"InsertDiscontinuity\", dl[dl.RetryRequest = 5] = \"RetryRequest\", (dl = Dm = Dm || {})[dl.MoveAllAlternatesMatchingHost = 1] = \"MoveAllAlternatesMatchingHost\", dl[dl.MoveAllAlternatesMatchingHDCP = 2] = \"MoveAllAlternatesMatchingHDCP\", dl[dl.SwitchToSDR = 4] = \"SwitchToSDR\";\n        class dg extends kl {\n            constructor(e) {\n                super(e)\n            }\n            get currentConfig() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.config\n            }\n            get extendMaxTTFB() {\n                var e;\n                return null === (e = this.getActive()) || void 0 === e ? void 0 : e.extendMaxTTFB\n            }\n            get config$() {\n                return this.selectActive(e => null == e ? void 0 : e.config)\n            }\n            get userSeek$() {\n                return this.selectActive(e => null == e ? void 0 : e.userSeek)\n            }\n        }\n        A();\n        class ug extends fl {\n            constructor() {\n                super({}, {\n                    name: \"hls-store\",\n                    producerFn: su\n                })\n            }\n        }\n        class cg {\n            constructor(e) {\n                this.store = e\n            }\n            getQuery() {\n                return new dg(this.store)\n            }\n            setHlsEntity(e) {\n                const t = e.id;\n                Do(`hls.set.entity ${t}`), al(() => {\n                    this.store.add(de(e)), this.store.setActive(t)\n                })\n            }\n            removeEntity(e) {\n                Do(`hls.remove ${e}`), this.store.remove(e)\n            }\n            setStartTime(t) {\n                this.store.updateActive(e => {\n                    e.config.startPosition = t\n                })\n            }\n            setUserSeek(t) {\n                this.store.updateActive(e => {\n                    e.userSeek = t\n                })\n            }\n            setExtendMaxTTFB(t) {\n                this.store.updateActive(e => {\n                    e.extendMaxTTFB = t\n                })\n            }\n        }\n        let hg, pg;\n\n        function fg() {\n            return hg = hg || new cg(new ug), hg\n        }\n\n        function mg() {\n            return fg().getQuery().currentConfig\n        }\n\n        function gg(r, n) {\n            if (\"VOD\" !== r.type && \"VOD\" !== n.type && r.iframesOnly === n.iframesOnly) {\n                const s = r.mediaOptionId === n.mediaOptionId,\n                    a = Math.max(r.startSN, n.startSN) - n.startSN,\n                    o = Math.min(r.endSN, n.endSN) - n.startSN,\n                    l = n.startSN - r.startSN,\n                    d = r.fragments,\n                    u = n.fragments;\n                let t = 0;\n                for (let e = a; e <= o; ++e)\n                    if (d[l + e] && u[e]) {\n                        t = d[l + e].discoSeqNum - u[e].discoSeqNum;\n                        break\n                    } const c = {};\n                let i = null;\n                for (let e = 0; e < u.length; e++) {\n                    const h = d[l + e],\n                        a = u[e];\n                    if (t) {\n                        const r = a.discoSeqNum + t;\n                        n.initSegments[a.discoSeqNum] && (n.initSegments[a.discoSeqNum].discoSeqNum = r, c[r] = n.initSegments[a.discoSeqNum], delete n.initSegments[a.discoSeqNum]), a.discoSeqNum = r\n                    }\n                    s && a.mediaSeqNum === (null == h ? void 0 : h.mediaSeqNum) && null != h.startPts && (a.start = h.start, a.duration = h.duration, a.startDtsTs = h.startDtsTs, a.endDtsTs = h.endDtsTs, a.startPts = h.startPts, a.endPts = h.endPts, i = a)\n                }\n                if (Object.keys(c).length && (n.initSegments = c), i) Bm(n, i, i.start, void 0, !1, !0);\n                else if (0 <= l && l < d.length) {\n                    const r = d[l].start,\n                        h = n.fragments;\n                    for (let e = 0; e < u.length; e++) h[e].start += r\n                }\n                n.ptsKnown = n.ptsKnown || s && !0 === r.ptsKnown && r.endSN >= n.startSN, $m(n)\n            }\n        }\n\n        function yg(e, t, i) {\n            let r = t.targetduration;\n            return ne(i.liveSyncDuration) ? r = i.liveSyncDuration : ne(i.liveSyncDurationCount) && (r = i.liveSyncDurationCount * t.targetduration), e + Math.max(0, t.totalduration - r)\n        }\n\n        function vg(e, t, i, r, n) {\n            if (!t.ptsKnown) return 0;\n            var s = t.targetduration,\n                a = t.fragments[0].start,\n                r = n.canContinuePlaybackWithoutGap(t, i, {\n                    avgPlaylistLoadTimeMs: 0,\n                    avgPlaylistParseTimeMs: 0\n                }, r);\n            let o = Math.max(0, e - s);\n            return e < a && !r && (o = a), o\n        }\n\n        function Sg(e) {\n            return 1e3 * (e.averagetargetduration || e.targetduration)\n        }\n\n        function bg(e, t) {\n            var i = Sg(e),\n                t = performance.now() - t;\n            return e.liveOrEvent && i <= t\n        }\n\n        function Tg(t, i, r = NaN) {\n            var n = t.fragments;\n            for (let e = r > t.startSN ? r - t.startSN : 0; e < n.length; ++e) {\n                const t = n[e],\n                    r = t[\"start\"];\n                if (i(t)) return {\n                    timelineOffset: r,\n                    mediaFragment: t\n                }\n            }\n            return null\n        }\n\n        function Eg(e, t, i) {\n            var r = 0 < i.duration,\n                n = i.start + i.duration,\n                n = null == t || t < n || t - n < 1 && i.isLastFragment,\n                e = e.every(e => !$p(e.frag, i));\n            return r && e && n\n        }\n\n        function Ig(e, t, i, r, n) {\n            i = null !== (i = Tg(r, Eg.bind(null, n, void 0), i)) && void 0 !== i ? i : null;\n            let s = null;\n            i && (s = null !== (e = Tg(r, Eg.bind(null, n, e), i.mediaFragment.mediaSeqNum)) && void 0 !== e ? e : null, s || !r.liveOrEvent || r.ptsKnown || (s = i));\n            let a = NaN;\n            null != s && ne(t) && s.mediaFragment.discoSeqNum !== t && (a = s.mediaFragment.discoSeqNum, s = null);\n            t = n.some(e => 0 < e.frag.framesWithoutIDR);\n            return s && t && n[n.length - 1].frag.mediaOptionId !== r.mediaOptionId && (s = null !== (r = Tg(r, e => e.mediaSeqNum === s.mediaFragment.mediaSeqNum - 1)) && void 0 !== r ? r : s), {\n                foundFrag: s,\n                nextDisco: a\n            }\n        }\n\n        function wg(e) {\n            e = e.fragments[e.fragments.length - 1];\n            return e ? e.start + e.duration : 0\n        }\n        class Ag extends kl {\n            constructor(e, t) {\n                super(e), this.mediaOption = t\n            }\n            get itemId() {\n                return this.mediaOption.itemId\n            }\n            get mediaOptionId() {\n                return this.mediaOption.mediaOptionId\n            }\n            get initSegmentEntities() {\n                var e;\n                return null === (e = this.mediaOptionDetailsEntity) || void 0 === e ? void 0 : e.initSegmentCacheEntities\n            }\n            get mediaLibraryEntity() {\n                return this.getEntity(this.itemId)\n            }\n            get mediaOptionDetailsEntityRecord() {\n                var e;\n                return null === (e = this.mediaLibraryEntity) || void 0 === e ? void 0 : e.mediaOptionDetailsEntityRecord\n            }\n            get mediaOptionDetailsEntity() {\n                return this.mediaOptionDetailsEntityRecord ? this.mediaOptionDetailsEntityRecord[this.mediaOptionId] : null\n            }\n            get mediaOptionDetails() {\n                var e;\n                return null === (e = this.mediaOptionDetailsEntity) || void 0 === e ? void 0 : e.mediaOptionDetails\n            }\n            get playlistDuration() {\n                var e;\n                return null === (e = this.mediaOptionDetailsEntity) || void 0 === e ? void 0 : e.playlistDuration\n            }\n            get mediaOptionDetailsEntity$() {\n                const {\n                    itemId: e,\n                    mediaOptionId: t\n                } = this;\n                return this.selectEntity(e, e => {\n                    if (null != e && e.mediaOptionDetailsEntityRecord) return null == e ? void 0 : e.mediaOptionDetailsEntityRecord[t]\n                })\n            }\n            get mediaOptionDetails$() {\n                return this.selectEntity(this.itemId, e => {\n                    return null === (e = null == e ? void 0 : e.mediaOptionDetailsEntityRecord[this.mediaOptionId]) || void 0 === e ? void 0 : e.mediaOptionDetails\n                }).pipe(Kp())\n            }\n            get playlistDuration$() {\n                return this.mediaOptionDetailsEntity$.pipe(hr(e => null == e ? void 0 : e.playlistDuration), Kp(), Is())\n            }\n            get live$() {\n                return this.mediaOptionDetails$.pipe(hr(e => null == e ? void 0 : e.liveOrEvent), Is())\n            }\n        }\n        class Og extends fl {\n            constructor() {\n                super({}, {\n                    name: \"media-library-store\",\n                    idKey: \"itemId\",\n                    producerFn: su\n                })\n            }\n        }\n        class kg {\n            constructor(e) {\n                this.store = e\n            }\n            getQuery() {\n                return new kl(this.store)\n            }\n            getQueryForOption(e) {\n                return new Ag(this.store, e)\n            }\n            createMediaLibraryEntity(e) {\n                var t = {\n                    itemId: e,\n                    mediaOptionDetailsEntityRecord: {}\n                };\n                Do(`library.entity.create: ${e}`), this.store.add(t)\n            }\n            setDetailsLoading(e) {\n                const {\n                    itemId: t,\n                    mediaOptionId: i\n                } = e;\n                Do(`library.details.loading: ${i}`), this.store.update(t, ({\n                    mediaOptionDetailsEntityRecord: e\n                }) => {\n                    e[i] || (e[i] = {\n                        initSegmentCacheEntities: {},\n                        unchangedCount: 0\n                    }), e[i].detailsLoading = !0\n                })\n            }\n            archiveMediaOptionDetails(i, r, n) {\n                const {\n                    itemId: e,\n                    mediaOptionId: s\n                } = i, a = performance.now(), o = wg(i);\n                Do(`library.details.loaded: ${s}`), this.store.update(e, e => {\n                    const t = e.mediaOptionDetailsEntityRecord[s];\n                    t.detailsLoading = !1, t.mediaOptionDetails = i, t.lastUpdateMillis = a, n ? t.unchangedCount = 0 : ++t.unchangedCount, t.playlistDuration = o, t.stats = r, e.liveOrEvent = i.liveOrEvent\n                })\n            }\n            setInitSegmentLoading(e) {\n                const {\n                    itemId: t,\n                    mediaOptionId: i,\n                    discoSeqNum: r\n                } = e;\n                Do(`library.initsegs.loading: ${i}/${r}`), this.store.update(t, e => {\n                    e.mediaOptionDetailsEntityRecord[i].initSegLoading = r\n                })\n            }\n            archiveInitSegmentEntity(i, r) {\n                const {\n                    itemId: e,\n                    mediaOptionId: n,\n                    discoSeqNum: s\n                } = i;\n                Do(`library.initseg.loaded: ${n}/${s}`), this.store.update(e, ({\n                    mediaOptionDetailsEntityRecord: e\n                }) => {\n                    const t = e[n];\n                    t.initSegmentCacheEntities[s] = [i, r], t.initSegLoading = null\n                })\n            }\n            updatePTSDTS(e, i, t, r) {\n                var n = null === (n = this.getQueryForOption({\n                    itemId: e,\n                    mediaOptionId: i\n                })) || void 0 === n ? void 0 : n.mediaOptionDetails;\n                if (n && Fm(n, r)) {\n                    const s = r[\"startDtsTs\"],\n                        {\n                            variantDTS: a,\n                            timelineOffset: o,\n                            iframeMode: l\n                        } = t,\n                        d = b(s, a) + o,\n                        u = Object.assign({}, n);\n                    Bm(u, r, d, l, !0), $m(u);\n                    const c = wg(u);\n                    this.store.update(e, ({\n                        mediaOptionDetailsEntityRecord: e\n                    }) => {\n                        const t = e[i];\n                        null != t && t.mediaOptionDetails && (t.mediaOptionDetails = u, t.playlistDuration = c)\n                    })\n                }\n            }\n            remove(e) {\n                this.store.remove(e)\n            }\n            clear() {\n                this.store.remove()\n            }\n        }\n\n        function Cg() {\n            return pg = pg || new kg(new Og), pg\n        }\n        const Dg = e => Cg().getQueryForOption(e),\n            Mg = (d, e, t = !1, i = !1) => {\n                if (null == e || !_u(e)) return $i(null);\n                const r = e[\"itemId\"],\n                    n = d[\"mediaLibraryService\"],\n                    s = n.getQueryForOption(e);\n                s.hasEntity(r) || n.createMediaLibraryEntity(r);\n                var a = s.mediaOptionDetailsEntity,\n                    o = s.mediaOptionDetails;\n                return null == o || i || \"VOD\" !== o.type && (!o.liveOrEvent || bg(o, a.lastUpdateMillis)) ? (n.setDetailsLoading(e), function(u, e) {\n                    var t;\n                    const {\n                        logger: i,\n                        config: c,\n                        rootPlaylistQuery: h,\n                        rootPlaylistService: p,\n                        statsService: r,\n                        mediaLibraryService: f,\n                        mediaSink: n\n                    } = d, m = n.mediaQuery, s = c.playlistLoadPolicy, a = c.keySystemPreference, o = h.masterVariableList, l = null === (t = null === (t = fg()) || void 0 === t ? void 0 : t.getQuery()) || void 0 === t ? void 0 : t.extendMaxTTFB;\n                    return _m(u, h.itemStartOffset, c, s, i, a, r, o, l).pipe(hr(e => {\n                        const t = f.getQueryForOption(u),\n                            i = t.mediaOptionDetails,\n                            r = e[\"mediaOptionDetails\"],\n                            n = e[\"stats\"];\n                        let s = !0;\n                        if (r.liveOrEvent) {\n                            const d = r[\"mediaOptionType\"];\n                            e = r, s = null == i || e.endSN !== i.endSN || e.liveOrEvent !== i.liveOrEvent, i && gg(i, r);\n                            const u = h.lastLoadedMediaOptionByType(d),\n                                t = u ? null === (l = f.getQueryForOption(u)) || void 0 === l ? void 0 : l.mediaOptionDetails : null;\n                            !r.ptsKnown && t && t.mediaOptionId !== (null == i ? void 0 : i.mediaOptionId) && gg(t, r)\n                        }\n                        r && al(() => {\n                            f.archiveMediaOptionDetails(r, n, s), p.setLastLoadedMediaOptionByType(h.itemId, u.mediaOptionType, u)\n                        });\n                        const a = !s && t.mediaOptionDetailsEntity.unchangedCount >= c.liveMaxUnchangedPlaylistRefresh,\n                            o = function(e, t, i, r) {\n                                t = vg(r.currentTime, e, t, i, r), i = e.fragments[e.fragments.length - 1], r = (null == i ? void 0 : i.start) + (null == i ? void 0 : i.duration);\n                                return {\n                                    expired: null != i && e.liveOrEvent && e.ptsKnown && r < t,\n                                    windowEnd: r,\n                                    minPosition: t\n                                }\n                            }(r, n.tload, c.maxBufferHole, m);\n                        if (a || o.expired) {\n                            var l = a ? $.LivePlaylistUpdateError : {\n                                text: `Live window too far in the past end:${o.windowEnd.toFixed(3)} minPosition:${o.minPosition}`,\n                                code: 0\n                            };\n                            throw new uc(!1, l.text, l.code, l, !1, u.mediaOptionType, u.mediaOptionId, u.url)\n                        }\n                        return r\n                    }), tc(\"getMediaOptionDetailsCommon.emit.loaded\"), lg(u.itemId, u.mediaOptionType, Lc(u, s), c.maxNumAddLevelToPenaltyBox, e, h, p, r)).pipe(Ds(1))\n                }(e, t)) : $i(o).pipe(tc(\"retrieveMediaOptionDetails.emit.cached\")).pipe(Ds(1))\n            };\n        const xg = (t, i) => {\n            if (!i) return $i(null);\n            const r = t[\"logger\"],\n                {\n                    mediaLibraryService: e,\n                    mediaParser: n\n                } = t,\n                s = e.getQueryForOption(i),\n                {\n                    mediaOption: a,\n                    mediaOptionDetailsEntityRecord: o,\n                    mediaOptionDetails: l\n                } = s,\n                d = a[\"mediaOptionId\"];\n            if (null == o || !o[d]) throw new Error(\"retrieveInitSegmentCacheEntity no details entity\");\n            if (!l) throw new Error(\"retrieveInitSegmentCacheEntity no details\");\n            var u = o[d][\"initSegmentCacheEntities\"],\n                c = l[\"initSegments\"],\n                h = i[\"discoSeqNum\"];\n            if (u[h]) {\n                const [t, r] = u[h];\n                let e = t;\n                return r && (e = n.willBeTrackSwitch(i) ? t : r), $i(e)\n            }\n            const p = c[h];\n            return p ? (e.setInitSegmentLoading(p), r.child({\n                name: \"timing\"\n            }), Rg(t, p, !1, !1).pipe(Za(() => {}), ji(tr), La(e => Pg(e, p, t)), Za(() => {}))) : $i(null)\n        };\n\n        function Pg(e, n, t) {\n            const {\n                logger: s,\n                mediaSink: i,\n                rootPlaylistService: r,\n                rootPlaylistQuery: a,\n                mediaParser: o,\n                mediaLibraryService: l,\n                gaplessInstance: d\n            } = t, u = i[\"mediaQuery\"], c = l.getQueryForOption(n), {\n                mediaOption: h,\n                mediaOptionDetails: p\n            } = c, {\n                itemId: f,\n                mediaOptionId: m\n            } = h, {\n                keyTagInfo: g,\n                discoSeqNum: y,\n                mediaOptionType: v\n            } = n, S = u.seeking, b = p.liveOrEvent, T = v === gu.Variant && p.ptsKnown;\n            let E, I;\n            n.isInitSegment ? I = new Uint8Array(e) : E = new Uint8Array(e);\n            var e = {\n                segment: E,\n                initSegment: I,\n                frag: n,\n                ptsKnown: T,\n                seeking: S,\n                live: b,\n                totalDuration: p.totalduration\n            };\n            return o.parseInitSegment(e, null !== (e = null === navigator || void 0 === navigator ? void 0 : navigator.vendor) && void 0 !== e ? e : \"\").pipe(hr(e => {\n                var {\n                    track: t,\n                    moovData: i,\n                    mimeType: r\n                } = e, e = t[\"initSegment\"];\n                d.inGaplessMode && be.isVideoCodec(t.codec) && (s.warn(`Video codec discovered in gapless mode codec:${t.codec}`), d.dequeueSource(\"InvalidFormat\"));\n                r = {\n                    itemId: f,\n                    mediaOptionId: m,\n                    discoSeqNum: y,\n                    initParsedData: i,\n                    data: e,\n                    mimeType: r,\n                    keyTagInfo: g,\n                    fragment: n\n                };\n                return l.archiveInitSegmentEntity(r), r\n            }), sg(r, a, v, m))\n        }\n\n        function Rg(n, s, i, r) {\n            var e;\n            const {\n                rootPlaylistQuery: t,\n                rootPlaylistService: a,\n                config: o,\n                rtcService: l,\n                statsService: d\n            } = n, {\n                itemId: u,\n                mediaOptionType: c\n            } = s, h = o.fragLoadPolicy, p = ne(s.mediaSeqNum);\n            let f;\n            p && (f = {\n                getData: !1,\n                cb: (e, t, i, r) => (a.updateInflightFrag(u, s.mediaOptionType, s, \"loading\", i), !1)\n            });\n            let m = !1;\n            r && null === l.serverInfoInstance && (m = !0);\n            const g = nm(s, o, h, f, m, null === (e = null === (e = fg()) || void 0 === e ? void 0 : e.getQuery()) || void 0 === e ? void 0 : e.extendMaxTTFB).pipe(Za(([, , e, t]) => {\n                i && d.setBandwidthSample(Object.assign(Object.assign({}, e), {\n                    mediaOptionType: s.mediaOptionType\n                })), r && m && (l.serverInfoInstance = t), p && a.updateInflightFrag(u, s.mediaOptionType, s, \"loaded\", e)\n            }), Za(([e, , t]) => {\n                r && l.handleFragLoaded(e, t)\n            }), lg(u, c, Lc(s, h), o.maxNumAddLevelToPenaltyBox, !1, t, a, d));\n            return \"AES-128\" === (null === (e = s.keyTagInfo) || void 0 === e ? void 0 : e.method) ? en([_g(n, s.keyTagInfo, {\n                itemId: s.itemId,\n                mediaOptionId: s.mediaOptionId\n            }), g]).pipe(La(([e, t]) => {\n                const [i, r] = t;\n                return i.keyTagInfo.key = e.key, Nm(i, r, o, n.logger, n.rpcClients.crypto)\n            })) : g.pipe(hr(e => e[1]))\n        }\n        const Lg = (i, r, e) => {\n            const {\n                rootPlaylistService: n,\n                rootPlaylistQuery: s\n            } = i, {\n                timelineOffset: a,\n                mediaFragment: o\n            } = e.foundFrag, {\n                itemId: l,\n                discoSeqNum: d\n            } = o;\n            return xg(i, o).pipe(La(t => (n.updateInflightFrag(l, o.mediaOptionType, o, \"loading\", null), Rg(i, o, !0, !0).pipe(La(e => {\n                return n.updateInflightFrag(l, r, o, \"parsing\", null),\n                    function(e, t, i, y, v, S) {\n                        const r = new Uint8Array(e),\n                            {\n                                legibleSystemAdapter: n,\n                                rootPlaylistService: s,\n                                mediaSink: a,\n                                mediaParser: o,\n                                rootPlaylistQuery: l,\n                                mediaLibraryService: b\n                            } = S,\n                            d = a[\"mediaQuery\"],\n                            u = b.getQueryForOption(y),\n                            {\n                                mediaOption: c,\n                                mediaOptionDetails: h\n                            } = u,\n                            p = h[\"initSegments\"],\n                            {\n                                itemId: T,\n                                mediaOptionId: E\n                            } = c,\n                            {\n                                discoSeqNum: I,\n                                mediaSeqNum: w,\n                                mediaOptionType: f,\n                                isLastFragment: A\n                            } = y,\n                            m = d.seeking,\n                            g = h.liveOrEvent,\n                            O = p[I],\n                            k = f === gu.Variant && h.ptsKnown,\n                            C = {\n                                segment: r,\n                                frag: y,\n                                seeking: m,\n                                live: g,\n                                ptsKnown: k,\n                                totalDuration: h.totalduration,\n                                defaultInitPTS: t,\n                                iframeMediaStart: Up(y) ? y.iframeMediaStart : void 0,\n                                iframeDuration: Up(y) ? y.iframeMediaDuration : void 0,\n                                iframeOriginalStart: Up(y) ? y.iframeOriginalStart : void 0\n                            };\n                        let D;\n                        if (null != i && (null === (t = y.keyTagInfo) || void 0 === t ? void 0 : t.uri) === (null === (t = i.keyTagInfo) || void 0 === t ? void 0 : t.uri)) D = $i(i);\n                        else if (null != i) {\n                            const M = Object.assign(Object.assign({}, i.fragment), {\n                                keyTagInfo: y.keyTagInfo\n                            });\n                            D = Pg(O ? i.data : e, M, S)\n                        } else D = Pg(e, y, S);\n                        return D.pipe(La(m => {\n                            const g = performance.now();\n                            if (null != m) {\n                                const g = m[\"data\"],\n                                    e = new Uint8Array(g);\n                                C.initSegment = e\n                            }\n                            return y.mediaOptionType === gu.Variant && (null == n || n.setupForFrag(y)), o.parseSegment(C, \"\").pipe(hr(e => {\n                                var t = performance.now(),\n                                    {\n                                        startPTS: i,\n                                        startDTS: r,\n                                        endPTS: n,\n                                        endDTS: s,\n                                        firstKeyframePts: a,\n                                        framesWithoutIDR: o,\n                                        dropped: l,\n                                        data1: d,\n                                        data2: u,\n                                        captionData: c,\n                                        id3Samples: h,\n                                        parsedInitSegment: e\n                                    } = e,\n                                    t = {\n                                        durationSec: n.baseTime / n.timescale - i.baseTime / i.timescale,\n                                        parseTimeMs: t - g\n                                    };\n                                S.statsService.setFragSample(t);\n                                let p = Object.assign({}, m);\n                                if (e) {\n                                    const {\n                                        track: g,\n                                        moovData: f,\n                                        mimeType: v\n                                    } = e, S = g[\"initSegment\"];\n                                    p = {\n                                        itemId: T,\n                                        mediaOptionId: E,\n                                        discoSeqNum: I,\n                                        initParsedData: f,\n                                        data: S,\n                                        mimeType: v,\n                                        keyTagInfo: y.keyTagInfo,\n                                        fragment: y\n                                    }, b.archiveInitSegmentEntity(m, p)\n                                }\n                                e = y.keyTagInfo;\n                                return [p, {\n                                    itemId: T,\n                                    mediaOptionId: E,\n                                    mediaSeqNum: w,\n                                    discoSeqNum: I,\n                                    startDtsTs: r,\n                                    endDtsTs: s,\n                                    timelineOffset: v,\n                                    firstKeyframePts: a,\n                                    framesWithoutIDR: o,\n                                    dropped: l,\n                                    data1: d,\n                                    data2: u,\n                                    startPts: i,\n                                    endPts: n,\n                                    keyTagInfo: e,\n                                    isLastFragment: A,\n                                    iframe: null !== (e = y.iframe) && void 0 !== e && e,\n                                    duration: y.duration,\n                                    iframeMediaDuration: Up(y) ? y.iframeMediaDuration : void 0,\n                                    iframeOriginalStart: Up(y) ? y.iframeOriginalStart : void 0,\n                                    captionData: c,\n                                    id3Samples: h\n                                }]\n                            }))\n                        }), sg(s, l, f, E))\n                    }(e, null === (e = s.getInitPTS(d)) || void 0 === e ? void 0 : e.offsetTimestamp, t, o, a, i)\n            }), Za(e => {\n                n.updateInflightFrag(l, r, o, \"parsed\", null)\n            }), tc(`retrieveMediaFragmentCacheEntity.${r}.emit`)))), Ds(1))\n        };\n\n        function _g(e, t, i) {\n            const {\n                keySystemAdapter: r,\n                rootPlaylistQuery: n,\n                rootPlaylistService: s,\n                config: a\n            } = e;\n            return r.getKeyFromDecryptData(t, i).pipe((o = t.uri, l = Lc({\n                url: t.uri\n            }, a.keyLoadPolicy), d = n, u = s, c = r.ksQuery, e => e.pipe(ll(() => {\n                ag(o, !1, d, u, c)\n            }), va(e => e.pipe(jr((e, t) => {\n                if (e instanceof mc || e instanceof gc) return og(e, t, _c(e, l), u, d, c);\n                throw e\n            }))))));\n            var o, l, d, u, c\n        }\n        class Ng {\n            constructor(e, t, i) {\n                this.hls = e, this.destroy$ = new Xt, this.iframeSwitchStart = 0, this.logger = t.child({\n                    name: \"hls-player-events\"\n                }), this.rtc = i, this.subscribeAndEmit()\n            }\n            destroy() {\n                this.destroy$.next()\n            }\n            subscribeAndEmit() {\n                var e = this.loaderQueryListener(new bc(Ec)),\n                    t = this.hls.publicQueries$.pipe(La(([e, t]) => an(this.rootPlaylistQueryListener(e, t), this.mediaElementQueryListener(t, e))));\n                an(e, t, this.activeItemListener(this.hls.itemQueue)).pipe(Vn(e => {\n                    var t = e.message;\n                    return this.logger.error(`Got error in HlsPlayerEvents ${t}`, e), Ii\n                }), Va(this.destroy$), Vs(() => {})).subscribe()\n            }\n            activeItemListener(e) {\n                return e.activeItemById$.pipe(Kp(), La(e => {\n                    e = e.url;\n                    return this.hls.trigger(P.MANIFEST_LOADING, {\n                        url: e\n                    }), Ii\n                }))\n            }\n            rootPlaylistQueryListener(t, e) {\n                var i = t.enabledMediaOptionByType$(gu.Variant).pipe(ln(e => !!e), La(e => {\n                        var t;\n                        return this.hls.trigger(P.LEVEL_SWITCHING, e), null === (t = this.rtc) || void 0 === t || t.handleLevelSwitching(e.url), Ii\n                    })),\n                    r = t.enabledMediaOptionByType$(gu.Variant).pipe(La(i => Dg(i).mediaOptionDetailsEntity$.pipe(ln(e => !0 === (null == e ? void 0 : e.detailsLoading)), Za(e => {\n                        var t = {\n                            url: le(null == i ? void 0 : i.url),\n                            level: i.mediaOptionId,\n                            type: Nu[i.mediaOptionType]\n                        };\n                        return this.hls.trigger(P.LEVEL_LOADING, t), Ii\n                    })))),\n                    n = t.enabledMediaOptionByType$(gu.Variant).pipe(La(e => {\n                        const t = Dg(e);\n                        let i = 0;\n                        return t.mediaOptionDetailsEntity$.pipe(Kp(), ln(e => {\n                            var t = null !== e.stats && !1 === e.detailsLoading && e.lastUpdateMillis > i;\n                            return i = null !== (e = e.lastUpdateMillis) && void 0 !== e ? e : 0, t\n                        }))\n                    }), La(e => {\n                        var t = e.mediaOptionDetails,\n                            i = e.stats,\n                            r = {\n                                mediaOptionId: t.mediaOptionId,\n                                details: t,\n                                playlistType: t.type,\n                                stats: i\n                            };\n                        if (null === (i = this.rtc) || void 0 === i || i.handleLevelLoaded(t, r.stats), this.hls.trigger(P.LEVEL_LOADED, r), 0 === e.unchangedCount) {\n                            const e = {\n                                level: 0,\n                                details: t\n                            };\n                            this.hls.trigger(P.LEVEL_UPDATED, e)\n                        }\n                        if (null != t && t.daterangeTags) {\n                            const e = {\n                                daterangeTags: t.daterangeTags\n                            };\n                            this.hls.trigger(P.DATERANGE_UPDATED, e)\n                        }\n                        return Ii\n                    })),\n                    s = t.enableMediaOptionSwitchedForType$(gu.AltAudio).pipe(La(e => {\n                        e = t.alternateMediaOptionById(gu.AltAudio, e.mediaOptionId);\n                        return e && this.triggerAudioSwitch(e), Ii\n                    })),\n                    a = t.rootPlaylistEntity$.pipe(ln(e => null !== e.enabledMediaOptionKeys[gu.AltAudio].mediaOptionId), Ds(1), La(e => {\n                        const t = e.enabledMediaOptionKeys[gu.AltAudio].mediaOptionId;\n                        return t && (e = e.mediaOptionListTuple[gu.AltAudio].mediaOptions.find(e => e.mediaOptionId === t), this.triggerAudioSwitch(Object.assign(Object.assign({}, e), {\n                            url: le(null == e ? void 0 : e.url)\n                        }))), Ii\n                    }));\n                return an(i, s, Gu(e.textTracksCreated$, e => e).pipe(La(() => t.enabledMediaOptionByType$(gu.Subtitle).pipe(La(e => {\n                    e = t.alternateMediaOptionById(gu.Subtitle, e.mediaOptionId);\n                    return e ? this.hls.trigger(P.SUBTITLE_TRACK_SWITCH, {\n                        track: Object.assign({}, e),\n                        hidden: !1\n                    }) : this.hls.trigger(P.SUBTITLE_TRACK_SWITCH, {\n                        track: void 0,\n                        hidden: !1\n                    }), Ii\n                })))), t.sessionData$.pipe(ln(e => null != e.complete), Ds(1), Za(e => {}), hr(e => {\n                    this.hls.trigger(P.SESSION_DATA_COMPLETE, e)\n                })), t.getPreferredMediaOptionsByType$(gu.Variant).pipe(ka(1), hr(e => {\n                    const t = e;\n                    null === (e = this.rtc) || void 0 === e || e.handleLevelsChanged(t), t.forEach(e => {}), this.hls.trigger(P.LEVELS_CHANGED, {\n                        requiresReset: !1,\n                        levels: t\n                    })\n                })), t.getPreferredMediaOptionsByType$(gu.AltAudio).pipe(hr(e => {\n                    this.hls.trigger(P.AUDIO_TRACKS_UPDATED, {\n                        audioTracks: e\n                    })\n                })), Gu(e.textTracksCreated$, e => e).pipe(La(() => t.getPreferredMediaOptionsByType$(gu.Subtitle).pipe(Ds(1), hr(e => {\n                    this.hls.trigger(P.SUBTITLE_TRACKS_UPDATED, {\n                        subtitleTracks: e\n                    }), this.hls.trigger(P.SUBTITLE_TRACKS_CREATED)\n                })))), n, r, a)\n            }\n            mediaElementQueryListener(s, e) {\n                return an(s.seekTo$.pipe(hr(e => {\n                    var t;\n                    e && ne(e.pos) ? (null === (t = this.rtc) || void 0 === t || t.handleSeek(\"SEEKING\"), this.hls.trigger(P.SEEKING, {\n                        seekToPos: e.pos\n                    })) : null === e && (null === (e = this.rtc) || void 0 === e || e.handleSeek(\"SEEKED\"), this.hls.trigger(P.SEEKED))\n                })), s.desiredRate$.pipe(Ra(0), ha(), hr(e => {\n                    var t = e[0],\n                        i = e[1];\n                    Wp(i) ? 0 == this.iframeSwitchStart && (this.iframeSwitchStart = performance.now()) : this.iframeSwitchStart = 0, this.hls.trigger(P.DESIRED_RATE_CHANGED, {\n                        oldRate: t,\n                        newRate: i\n                    }), null === (e = this.rtc) || void 0 === e || e.handleDesiredRateChanged(t, i)\n                })), s.sourceBufferEntityByType$(yu.AltAudio).pipe(ln(e => !!e), Is((e, t) => e.totalBytes === t.totalBytes), hr(e => {\n                    this.hls.trigger(P.BUFFER_APPENDED)\n                })), s.sourceBufferEntityByType$(yu.Variant).pipe(ln(e => !!e), Is((e, t) => e.totalBytes === t.totalBytes), hr(e => {\n                    var t;\n                    null === (t = this.rtc) || void 0 === t || t.handleVariantBufferAppended(e.timestampOffset, e.totalBytes), this.hls.trigger(P.BUFFER_APPENDED)\n                })), s.stallInfo$.pipe(Kp(), bo(s.combinedBuffer$), hr(([e]) => {\n                    var t;\n                    null === (t = this.rtc) || void 0 === t || t.handleStalled(e, s.getCombinedBufferInfo(e.currentTime, 0).len), this.hls.trigger(P.STALLED, e)\n                })), Mr([$i(e), ed([s.timeupdate$, s.bufferedSegmentsByType$(yu.Variant)]).pipe(ao(1e3), hr(([t, e]) => null == e ? void 0 : e.find(e => e.startPTS <= t && e.endPTS > t)), ln(e => !!e), Ra(null), ha())]).pipe(La(([e, [t, i]]) => {\n                    var r = null == i ? void 0 : i.frag,\n                        t = null == t ? void 0 : t.frag;\n                    if (r && !$p(t, r) && (this.hls.trigger(P.FRAG_CHANGED, i), this.hls.inGaplessMode && this.checkAndTriggerReadyForNext(s, i), !t || r.mediaOptionId !== t.mediaOptionId)) {\n                        const s = e.mediaOptionListQueries[gu.Variant].mediaOptionFromId(r.mediaOptionId);\n                        if (!s) return this.logger.warn(\"variantInfo is undefined in fragChangeMonitor\"), Ii;\n                        const n = t ? t.mediaOptionId : \"\",\n                            i = r.mediaOptionId;\n                        s.iframes && (performance.now(), this.iframeSwitchStart), null === (r = this.rtc) || void 0 === r || r.handleLevelSwitched({\n                            url: s.url,\n                            mediaOptionId: s.mediaOptionId,\n                            oldVariant: \"\" !== n ? n : void 0,\n                            newVariant: i\n                        }), this.hls.trigger(P.LEVEL_SWITCHED, s)\n                    }\n                    return Ii\n                })), s.isBufferedToEnd$(this.hls.config.maxBufferHole, !1).pipe(ln(e => !0 === e), ji(tr), hr(e => {\n                    if (e && !this.hls.itemQueue.isPreloading() && this.hls.inGaplessMode) {\n                        const i = s.getCombinedBufferInfo(s.currentTime, 0);\n                        var t = 0;\n                        i && (t = i.end, e = s.mediaElementDuration, 0 < t && e - s.currentTime < 10 && this.hls.trigger(P.READY_FOR_NEXT_ITEM, {\n                            duration: t\n                        }))\n                    }\n                })))\n            }\n            checkAndTriggerReadyForNext(e, t) {\n                var i, r;\n                t && t.frag && (i = e.currentTime, (r = e.getCombinedBufferInfo(i, 0)) && (i = r.end, r = e.mediaElementDuration, e = e.bufferMonitorInfo, e = Math.max(e.almostDryWaterLevelSeconds, e.lowWaterLevelSeconds / 2), (r - t.endPTS <= e || t.frag.isLastFragment) && this.hls.inGaplessMode && !this.hls.isPreloading && this.hls.trigger(P.READY_FOR_NEXT_ITEM, {\n                    duration: i\n                })))\n            }\n            loaderQueryListener(e) {\n                return an(e.unresolvedUriLoading$.pipe(hr(e => e.map(e => {\n                    e = {\n                        uri: e.uri,\n                        responseType: e.responseType,\n                        userAgent: e.userAgent\n                    };\n                    this.hls.trigger(P.UNRESOLVED_URI_LOADING, e)\n                }))))\n            }\n            triggerAudioSwitch(e) {\n                e && this.hls.trigger(P.AUDIO_TRACK_SWITCHED, {\n                    id: e.id\n                })\n            }\n            triggerManifestLoaded(e) {\n                e = {\n                    levels: e.rootMediaOptionsTuple[gu.Variant],\n                    audioTracks: e.rootMediaOptionsTuple[gu.AltAudio],\n                    subtitleTracks: e.rootMediaOptionsTuple[gu.Subtitle],\n                    url: e.baseUrl,\n                    audioMediaSelectionGroup: e.audioMediaSelectionGroup,\n                    subtitleMediaSelectionGroup: e.subtitleMediaSelectionGroup,\n                    stats: e.stats,\n                    isMediaPlaylist: e.isMediaPlaylist\n                };\n                this.hls.trigger(P.MANIFEST_LOADED, e)\n            }\n            triggerManifestParsed(e) {\n                var t = {\n                    levels: e.mediaOptionListQueries[gu.Variant].filteredMediaOptionList,\n                    firstLevel: 0,\n                    audio: !1,\n                    video: !0,\n                    altAudio: !1,\n                    audioTracks: e.mediaOptionListQueries[gu.AltAudio].filteredMediaOptionList,\n                    audioMediaSelectionGroup: e.audioMediaSelectionGroup,\n                    subtitleMediaSelectionGroup: e.subtitleMediaSelectionGroup,\n                    stats: e.loadStats\n                };\n                null === (e = this.rtc) || void 0 === e || e.handleManifestParsed(t), this.hls.trigger(P.MANIFEST_PARSED, t)\n            }\n            urlRedactedManifestLoaded(e) {\n                const t = Object.assign({}, e);\n                return t.url = le(t.url), t.levels = ue(t.levels), t.audioTracks = ce(t.audioTracks), t.subtitleTracks = ce(t.subtitleTracks), t\n            }\n            urlRedactedManifestParsed(e) {\n                const t = Object.assign({}, e);\n                return t.levels = ue(t.levels), t.audioTracks = ce(t.audioTracks), t\n            }\n        }(A = Mm = Mm || {}).LowBandwidth = \"LowBandwidth\", A.HighBandwidth = \"HighBandwidth\", A.PreferredListChanged = \"PreferredListChanged\", A.IframeModeChange = \"IframeModeChange\", A.None = \"\";\n        const Fg = {\n            minValidBitrate: 2e6,\n            maxValidBitrate: 5e6,\n            maxPreferredBitrate: 3e6,\n            minValidHeight: 480,\n            maxValidHeight: 720\n        };\n\n        function Bg(e, a, o, l, d, u) {\n            return e.reduce((e, t) => {\n                if (t.iframes) return e;\n                let i = e;\n                const r = (n = t.score, s = a && o && l && d && !Ug(t, a, o, l, d, u) ? mu.INVALID : mu.VALID, new Qp(s, n));\n                var n, s;\n                return (!e || r.isGreaterThan(e.bestRank) || r.isEqualTo(e.bestRank) && t.bandwidth < e.selected.bandwidth) && (i = {\n                    selected: t,\n                    bestRank: r\n                }), i\n            }, null).selected\n        }\n\n        function Ug(e, t, i, r, n, s) {\n            var {\n                targetDuration: a,\n                targetStartupMs: o\n            } = i, l = r[\"avgPlaylistLoadTimeMs\"], d = n[\"avgParseTimeMs\"], {\n                avgBufferCreateMs: i,\n                avgInitFragAppendMs: r,\n                avgDataFragAppendMs: n\n            } = s, {\n                avgBandwidth: s,\n                avgLatencyMs: t\n            } = t;\n            return e.bandwidth <= s && (e.avgBandwidth || e.bandwidth) * a / s * 1e3 + l + i + +(t + d + (r + n)) <= o\n        }\n        const $g = {\n            name: \"abr\"\n        };\n\n        function Vg(e, t) {\n            return ne(e) ? Math.min(e, t) : t\n        }\n\n        function Kg(e) {\n            return ne(null == e ? void 0 : e.avgBandwidth)\n        }\n\n        function qg(e, t) {\n            return e.getCurrentWaterLevelByType(yu.Variant, t) / (0 !== e.playbackRate ? Math.abs(e.playbackRate) : 1)\n        }\n\n        function Hg(t, i, e, r) {\n            if (e) return t;\n            let n = -1;\n            if (t < 0) return n;\n            for (let e = t; e < i.length; ++e) {\n                const t = Qg(i[e], r);\n                if (t.altAudio && t.subtitle) {\n                    n = e;\n                    break\n                }\n            }\n            return n\n        }\n\n        function jg(t, e, i, r, n, s, a) {\n            const o = i.preferredMediaOptions[gu.Variant].filter(e => e.iframes === t);\n            if (!o.length) return {\n                variantMediaOption: Lu.mediaOptionId,\n                holdOffDuration: 0,\n                lowestCandidate: null\n            };\n            let l = 0;\n            const d = i.nextMinAutoOptionId;\n            if (d !== Lu.mediaOptionId) {\n                const t = o.findIndex(e => e.mediaOptionId === d);\n                0 <= t && (l = t)\n            }\n            if (l = Hg(l, o, t, i), l < 0) return {\n                variantMediaOption: Lu.mediaOptionId,\n                holdOffDuration: 0,\n                lowestCandidate: null\n            };\n            let u = o.length - 1;\n            const c = i.nextMaxAutoOptionId;\n            if (c !== Lu.mediaOptionId) {\n                const t = o.findIndex(e => e.mediaOptionId === c);\n                0 <= t && (u = t)\n            }\n            var h = i.variantMediaOptionById(r.mediaOptionId),\n                p = r.mediaOptionDetails,\n                f = (null == h ? void 0 : h.iframes) !== t ? 0 : qg(n, e.maxBufferHole);\n            let m, g;\n            if (t) {\n                const t = e.desiredIframeFPS;\n                g = p ? p.targetduration / t : 0, g = Math.max(1 / t, g)\n            } else g = p ? p.targetduration : 0;\n            h = e.abrBandWidthUpFactor, p = e.abrBandWidthFactor;\n            return m = Wg(o, g, l, u, f, t, s.getCombinedEstimate(), s.bandwidthStatus, p, h, e, i, r, n, a), m.variantMediaOption === Lu.mediaOptionId && (m = Wg(o, g, l, u, f + Vg(g, e.maxStarvationDelay), t, s.getCombinedEstimate(), s.bandwidthStatus, p, h, e, i, r, n, a), m.variantMediaOption === Lu.mediaOptionId && 0 <= l && (m.variantMediaOption = o[l].mediaOptionId, m.alternates = t ? null : Qg(o[l], i))), m\n        }\n\n        function Qg(e, t) {\n            var i = t.enabledMediaOptionKeys,\n                r = i[gu.AltAudio],\n                r = _u(r) ? t.mediaOptionListQueries[gu.AltAudio].getMatchingAlternate(r.mediaOptionId, e) : Lu,\n                i = i[gu.Subtitle];\n            return {\n                altAudio: r,\n                subtitle: _u(i) ? t.mediaOptionListQueries[gu.Subtitle].getMatchingAlternate(i.mediaOptionId, e) : Lu\n            }\n        }\n\n        function Wg(i, r, n, e, s, a, o, l, t, d, u, c, h, p, f) {\n            \"bandwidth-history-controller\" !== u.abrBandwidthEstimator && f.warn(`Unsupported configuration: ${u.abrBandwidthEstimator} for ABR bandwidth estimator`);\n            const m = l.bandwidthSampleCount,\n                g = c.abrStatus,\n                y = p.maxBufferSize,\n                v = u.minTargetDurations || 1,\n                S = c.mediaOptionListQueries[gu.Variant].mediaOptionListInfo.hasScore;\n            if (!i.length) return {\n                variantMediaOption: Lu.mediaOptionId,\n                holdOffDuration: -1,\n                lowestCandidate: null\n            };\n            const b = c.enabledMediaOptionIdByType(gu.Variant),\n                T = c.variantMediaOptionById(b),\n                E = null != i.find(e => e.mediaOptionId === b),\n                I = T && T.iframes === a,\n                w = T && I ? T.score : void 0,\n                A = T && I ? T.frameRate : void 0,\n                O = T && I ? T.height : void 0,\n                k = I ? qg(p, u.maxBufferHole) : 0;\n            e = Math.max(0, Math.min(i.length - 1, e)), n = Math.max(0, Math.min(i.length - 1, n));\n            var C = h.mediaOptionDetailsEntityRecord,\n                D = Gg(o.avgBandwidth, d, t, m);\n            let M;\n            for (let t = e; t >= n; t--) {\n                const n = i[t];\n                let e = n.mediaOptionId;\n                const u = n.score,\n                    h = C && C[e] ? C[e].mediaOptionDetails : void 0,\n                    p = C && C[e] ? C[e].lastUpdateMillis : null,\n                    f = h ? h.totalduration / h.fragments.length : r,\n                    B = null != T && n.bitrate > T.bitrate,\n                    m = null != T && n.bitrate < T.bitrate,\n                    U = !(null != A && (B && n.frameRate < A || m && n.frameRate > A)),\n                    $ = !(B && null != O && O > n.height),\n                    V = !(m && (n.bitrate === T.bitrate - 1 || n.bitrate === T.bitrate + 1)),\n                    K = !(S && B && null != w && (u < w || u === w && T && n.bitrate >= T.bitrate)),\n                    q = n.iframes === a;\n                if (ne(f) && q && U && $ && V && K) {\n                    var {\n                        adjustedbw: x,\n                        bitrate: P,\n                        fetchDuration: R,\n                        rejectLevelDueToPeakBW: L,\n                        canFitMultipleSegments: _,\n                        requireAlternates: N,\n                        alternates: F\n                    } = function(e, t, i, r, n, s, a, o, l, d, u, c) {\n                        var h = n ? a.bwUp : a.bwDown,\n                            n = e.bitrate,\n                            a = t ? t.totalduration / t.fragments.length : o,\n                            s = zg(e, t, o, h, ne(s.avgPlaylistLoadTimeMs) ? s.avgPlaylistLoadTimeMs : s.avgLatencyMs, d),\n                            d = e.bandwidth,\n                            i = n < h && h < d && i <= 2 * a,\n                            l = r * ((d || n || 0) * ((null == t ? void 0 : t.targetduration) || a)) / 8 <= l;\n                        let p = null;\n                        u = !u;\n                        return u && (p = Qg(e, c), p.altAudio && p.subtitle || (p = null)), {\n                            adjustedbw: h,\n                            bitrate: n,\n                            fetchDuration: s,\n                            rejectLevelDueToPeakBW: i,\n                            canFitMultipleSegments: l,\n                            requireAlternates: u,\n                            alternates: p\n                        }\n                    }(n, h, k, v, B, o, D, r, y, p, a, c);\n                    if (N && Boolean(F) && (M = e), P < x && _ && !L && (!N || Boolean(F)) && (a || !R || R < s)) {\n                        if (L = x, N = g, x = (x = l).instantBw, (N.fragDownloadSlow || N.fragDownloadTooSlow || ne(x) && x < L) && E && I)\n                            if (k <= 2 * f && B) e = b;\n                            else if (B && d * l.instantBw < P) continue;\n                        return {\n                            variantMediaOption: e,\n                            holdOffDuration: R,\n                            alternates: F,\n                            lowestCandidate: M\n                        }\n                    }\n                }\n            }\n            return {\n                variantMediaOption: Lu.mediaOptionId,\n                holdOffDuration: -1,\n                lowestCandidate: M\n            }\n        }\n\n        function Gg(e, t, i, r) {\n            let n, s;\n            return 4 <= r ? (n = e * t, s = e * i) : n = s = e / 1.8, {\n                bwUp: n,\n                bwDown: s\n            }\n        }\n\n        function zg(e, t, i, r, n, s) {\n            let a = e.bitrate * (t ? t.totalduration / t.fragments.length : i) / r;\n            return null == t || !t.liveOrEvent || t.ptsKnown && !Yg(t.totalduration, n, s) || (a *= 2), ne(n) && (!ne(s) || null != t && t.liveOrEvent) && (a += n / 1e3), a\n        }\n\n        function Xg(t, e) {\n            let i = 1 / 0;\n            if (t === Lu.mediaOptionId) return i;\n            var r = e.find(e => e.mediaOptionId === t);\n            if (!r) return 1 / 0;\n            const n = r.iframes,\n                s = r.bitrate,\n                a = r.frameRate,\n                o = e.find(e => e.iframes === n && (void 0 === a || e.frameRate >= a) && e.bitrate > s);\n            return o && (i = o.bitrate), i\n        }\n\n        function Yg(e, t, i) {\n            return t = ne(t) ? t : 0, !ne(i) || performance.now() - i + t > 1e3 * e\n        }\n\n        function Jg(e, t) {\n            return (null == e ? void 0 : e.fragDownloadSlow) === (null == t ? void 0 : t.fragDownloadSlow) && e.fragDownloadTooSlow === (null == t ? void 0 : t.fragDownloadTooSlow)\n        }\n\n        function Zg(e) {\n            return \"loading\" === (null == e ? void 0 : e.state) && ne(null === (e = e.bwSample) || void 0 === e ? void 0 : e.trequest)\n        }\n        const ey = 2e3;\n\n        function ty(e, t, i, r) {\n            let {\n                fragDownloadSlow: n,\n                fragDownloadTooSlow: s\n            } = t;\n            var a = i.variantMediaOptionById(e.mediaOptionId).bitrate,\n                t = e.bwSample;\n            r = r.child($g);\n            i = t.total || Math.max(t.loaded, Math.round(e.duration * a / 8)), a = performance.now() - t.tfirst, i = t.loaded * e.duration * 1e3 / i;\n            return a >= ey && 1e3 <= a - i && (n || r.warn(`flow indicates low bandwidth, after time/duration behind real time: ${a}/${a-i}`), n = !0), a >= 1e3 * e.duration && (s || r.warn(`too much time spent downloading fragment, likely to switch down ${a} > ${1e3*e.duration}`), s = !0), {\n                fragDownloadSlow: n,\n                fragDownloadTooSlow: s\n            }\n        }\n\n        function iy(e, t, i, r, n) {\n            var s;\n            const a = n.logger.child($g),\n                o = r.isIframeRate,\n                l = i.mediaOptionListQueries[gu.Variant].preferredMediaOptionList,\n                d = i.enabledMediaOptionKeys[gu.Variant];\n            let u = e;\n            if (u !== Mm.None || l.some(e => e.mediaOptionId === d.mediaOptionId) || (u = Mm.PreferredListChanged), u !== Mm.None && !(o && u !== Mm.IframeModeChange && r.getBufferedSegmentsByType(yu.Variant).filter(e => e.frag.iframe).length < t.minFramesBeforeSwitchingLevel)) {\n                o && u === Mm.IframeModeChange && n.setEnabledVariantMediaOptionIdBeforeTrickplaySwitch(i.itemId, d.mediaOptionId);\n                const h = Zf(i.itemId),\n                    p = Dg(d),\n                    f = [Lu, Lu, Lu];\n                if (!o && e === Mm.IframeModeChange) {\n                    const e = function(e, t, i, r) {\n                        const n = i.mediaOptionListQueries[gu.Variant].preferredMediaOptionList,\n                            s = t.targetStartupMs,\n                            a = {\n                                avgPlaylistParseTimeMs: 0,\n                                avgPlaylistLoadTimeMs: 0\n                            },\n                            o = r.getFragEstimate(),\n                            l = {\n                                avgBufferCreateMs: 0,\n                                avgInitFragAppendMs: 0,\n                                avgDataFragAppendMs: 0\n                            },\n                            d = o.maxDurationSec,\n                            u = {\n                                avgLatencyMs: 0,\n                                avgBandwidth: r.getBandwidthEstimate().avgBandwidth\n                            },\n                            c = {\n                                targetDuration: d,\n                                targetStartupMs: s,\n                                metricsOverride: {\n                                    maxValidHeight: 0,\n                                    maxValidBitrate: 0,\n                                    maxPreferredBitrate: 0\n                                }\n                            },\n                            h = n.filter(e => !e.iframes && (!e.width || !e.height || e.width * e.height <= 2488320));\n                        let p = e;\n                        0 < h.length && (p = h[0].mediaOptionId);\n                        e = h.filter(e => Ug(e, u, c, a, o, l));\n                        return 0 < e.length && (p = e[e.length - 1].mediaOptionId), p\n                    }(i.enabledVariantMediaOptionIdBeforeTrickplaySwitch, t, i, h);\n                    n.setNextMaxAutoOptionId(i.itemId, e), n.setEnabledVariantMediaOptionIdBeforeTrickplaySwitch(i.itemId, void 0)\n                }\n                var c = function(e, t, i, r, n, s, a) {\n                    let o = t.nextMaxAutoOptionId;\n                    if (o === Lu.mediaOptionId || Kg(s.getBandwidthEstimate())) return l = e, d = t, u = r, e = n, r = s, s = a.child({\n                        name: \"abr\"\n                    }), a = e.isIframeRate, d.enabledMediaOptionIdByType(gu.Variant), jg(a, l, d, u, e, r, s);\n                    if (n.isIframeRate) return {\n                        variantMediaOption: o,\n                        holdOffDuration: 0,\n                        lowestCandidate: null\n                    }; {\n                        const c = t.variantMediaOptionById(o),\n                            h = t.enabledAlternateMediaOptionByType(gu.Subtitle),\n                            n = t.enabledAlternateMediaOptionByType(gu.AltAudio),\n                            p = null == n ? void 0 : n.persistentID,\n                            f = null == h ? void 0 : h.persistentID,\n                            m = !t.preferHDR,\n                            g = i.getBestMediaOptionTupleFromVariantAndPersistentId(t, c, p, f, void 0, [], m, !1, !1);\n                        return t.isValidMediaOptionTuple(g) ? (o = g[gu.Variant].mediaOptionId, {\n                            variantMediaOption: o,\n                            holdOffDuration: 0,\n                            alternates: {\n                                altAudio: g[gu.AltAudio],\n                                subtitle: g[gu.Subtitle]\n                            },\n                            lowestCandidate: null\n                        }) : {\n                            variantMediaOption: t.enabledMediaOptionKeys[gu.Variant].mediaOptionId,\n                            holdOffDuration: 0,\n                            lowestCandidate: null\n                        }\n                    }\n                    var l, d, u\n                }(t, i, n, p, r, h, a);\n                if (o || e !== Mm.IframeModeChange || n.setNextMaxAutoOptionId(i.itemId, Lu.mediaOptionId), c.variantMediaOption !== d.mediaOptionId) {\n                    f[gu.Variant] = {\n                        itemId: i.itemId,\n                        mediaOptionId: c.variantMediaOption\n                    };\n                    for (const e of [gu.AltAudio, gu.Subtitle]) {\n                        const t = i.enabledMediaOptionIdByType(e);\n                        if (t !== Lu.mediaOptionId) {\n                            const r = e === gu.AltAudio ? null === (s = c.alternates) || void 0 === s ? void 0 : s.altAudio : null === (s = c.alternates) || void 0 === s ? void 0 : s.subtitle;\n                            f[e] = r || {\n                                itemId: i.itemId,\n                                mediaOptionId: t\n                            }\n                        }\n                    }\n                    return n.setEnabledMediaOptions(i.itemId, f), 1\n                }\n            }\n        }\n        const ry = {\n            name: \"iframes\"\n        };\n        (A = xm = xm || {})[A.DISABLED = 0] = \"DISABLED\", A[A.ERRORED = 1] = \"ERRORED\", A[A.SUCCESS = 2] = \"SUCCESS\";\n        const ny = new fl({}, {\n                name: \"item-queue\",\n                producerFn: su,\n                idKey: \"itemId\",\n                resettable: !0\n            }),\n            sy = new class extends kl {}(ny);\n        class ay {\n            constructor() {\n                this.firstItem = !0, this.playingEntity = null, this.loadingEntity = null\n            }\n            static createItem(e, t, i = NaN, r, n) {\n                const s = new Date,\n                    a = `${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}`;\n                Qe();\n                var o = function(e) {\n                    e = cu.parseURL(e).fragment.substr(1);\n                    if (0 === e.length) return null;\n                    const t = new URLSearchParams(e);\n                    if (!t.has(\"t\")) return null;\n                    e = Number(t.get(\"t\"));\n                    return ne(e) ? e : null\n                }(t);\n                if (ne(o)) i = o;\n                else {\n                    const e = mg();\n                    ne(null == e ? void 0 : e.startPosition) && (i = e.startPosition)\n                }\n                return {\n                    itemId: `${e}_${a}`,\n                    name: e,\n                    url: t,\n                    serviceName: n,\n                    createTime: a,\n                    initialSeekTime: i,\n                    itemStartOffset: 0,\n                    platformInfo: r,\n                    config: {}\n                }\n            }\n            get activeItemById$() {\n                return sy.selectActiveId().pipe(hr(e => sy.getActive()))\n            }\n            get removedItems$() {\n                return sy.selectEntityAction(Eo.Remove).pipe(hr(e => e))\n            }\n            get activeItem() {\n                return sy.getActive()\n            }\n            get queueItems$() {\n                return sy.selectAll().pipe(hr(e => null != e ? e : []))\n            }\n            get isFirstItem() {\n                return this.firstItem\n            }\n            get playingItem() {\n                return this.playingEntity\n            }\n            get loadingItem() {\n                return this.loadingEntity\n            }\n            addQueueItem(e, t, i, r, n, s) {\n                sy.getCount();\n                const a = ay.createItem(e, t, i, r, s);\n                null != this.playingEntity && (a.initialSeekTime = void 0), n && (a.itemStartOffset = n, this.firstItem = !1, this.playingEntity = this.activeItem, this.loadingEntity = a), Do(`queue.add.item: ${e}`), al(() => {\n                    ny.add(a), ny.setActive(a.itemId)\n                })\n            }\n            updatePlayingItemId() {\n                this.playingEntity = this.loadingEntity, this.loadingEntity = null, this.clearAllButActive()\n            }\n            resetLoadingItem() {\n                this.removeQueueItem(this.loadingEntity.itemId), this.loadingEntity = null, al(() => {\n                    ny.setActive(this.playingEntity.itemId)\n                })\n            }\n            isPreloading() {\n                return null !== this.playingEntity && null !== this.loadingEntity\n            }\n            setQueueItem(t, i, r, n, s) {\n                Do(\"queue.set.item\"), this.loadingEntity = null, al(() => {\n                    ny.reset();\n                    var e = ay.createItem(t, i, r, n, s);\n                    ny.add(e), ny.setActive(e.itemId)\n                }), this.playingEntity = this.activeItem\n            }\n            removeQueueItem(e) {\n                ny.remove(e)\n            }\n            clearQueue() {\n                ny.reset()\n            }\n            clearAllButActive() {\n                var e;\n                const t = null === (e = this.activeItem) || void 0 === e ? void 0 : e.itemId;\n                al(() => {\n                    sy.getAll().forEach(e => {\n                        e.itemId !== t && ny.remove(e.itemId)\n                    })\n                })\n            }\n            set earlyAudioSelection(t) {\n                ny.updateActive(e => {\n                    e.earlySelection || (e.earlySelection = {}), e.earlySelection.audioPersistentId = t\n                })\n            }\n            get earlyAudioSelection() {\n                var e;\n                return null === (e = this.activeItem.earlySelection) || void 0 === e ? void 0 : e.audioPersistentId\n            }\n            set earlySubtitleSelection(t) {\n                ny.updateActive(e => {\n                    e.earlySelection || (e.earlySelection = {}), e.earlySelection.subtitlePersistentId = t\n                })\n            }\n            get earlySubtitleSelection() {\n                var e;\n                return null === (e = this.activeItem.earlySelection) || void 0 === e ? void 0 : e.subtitlePersistentId\n            }\n        }\n\n        function oy(e, t, i, r, n, s) {\n            return ng(e, 0, Jm({\n                errorAction: Cm.RemoveAlternatePermanently,\n                errorActionFlags: 0\n            }, !1, e.response.code, i, t, s, n), s, n, t, i).pipe(Vn(e => {\n                throw !1 === e.fatal && r.resetMediaSource(), e\n            }))\n        }\n        class ly {\n            constructor(e, t, i, r, n, s) {\n                this.logger = e, this._rootPlaylistService = t, this._rootQuery = i, this._mediaQuery = r, this._iframeMachine = n, this._anchorMSNs = [NaN, NaN], this._avDetails = [null, null], this.logger = e.child({\n                    name: \"fpicker\"\n                }), this._discoSeqNum = NaN, this.lookUpTolerance = Math.max(s.maxBufferHole, s.maxFragLookUpTolerance), this.firstAudioMustOverlapVideoStart = s.firstAudioMustOverlapVideoStart, this.lookUpToleranceAlt = s.firstAudioMustOverlapVideoStart ? 0 : s.maxFragLookUpTolerance\n            }\n            destroy() {\n                this._anchorMSNs = [NaN, NaN], this._avDetails = [null, null], this._rootQuery = null, this._mediaQuery = null, this._rootPlaylistService = null, this._iframeMachine = null\n            }\n            get discoSeqNum() {\n                return this._discoSeqNum\n            }\n            get _discoSeqNum() {\n                return this._rootQuery.discoSeqNum\n            }\n            set _discoSeqNum(e) {\n                this._rootPlaylistService.setDiscoSeqNum(this._rootQuery.itemId, e)\n            }\n            get anchorMSNs() {\n                return this._anchorMSNs\n            }\n            _resolvePosition(e, t, i) {\n                let r = e;\n                var t = this._avDetails[t];\n                if ((null == t ? void 0 : t.mediaOptionId) !== (null == i ? void 0 : i.mediaOptionId) && i.liveOrEvent && !1 === i.ptsKnown && (!t || Math.max(t.startSN, i.startSN) > Math.min(t.endSN, i.endSN))) {\n                    const e = 3 * i.targetduration,\n                        n = (null === (t = i.fragments[0]) || void 0 === t ? void 0 : t.start) + i.totalduration;\n                    r = Math.max(0, n - e)\n                }\n                return r\n            }\n            getDiscoSeqNumForTime(e, t) {\n                return this._mediaQuery.isIframeRate && e.iframesOnly ? Qu.discoSeqNumForTime(e.fragments, t) : (r = t, null == (e = null !== (e = Tg(e, e => {\n                    var t = 0 < e.duration,\n                        i = e.start + e.duration,\n                        e = r < i || r - i < 1 && e.isLastFragment;\n                    return t && e\n                })) && void 0 !== e ? e : null) ? void 0 : e.mediaFragment.discoSeqNum);\n                var r\n            }\n            _updateAnchorByPosition(e, t) {\n                let i = NaN;\n                const r = t[yu.Variant];\n                let n = e;\n                if (r) {\n                    const t = r.fragments;\n                    if (n = this._resolvePosition(e, yu.Variant, r), i = this.getDiscoSeqNumForTime(r, n), !ne(i)) {\n                        const r = t[0],\n                            s = t[t.length - 1],\n                            a = null == r ? void 0 : r.start,\n                            o = (null == s ? void 0 : s.start) + (null == s ? void 0 : s.duration);\n                        this.logger.warn(`${e.toFixed(3)} out of range [${null==a?void 0:a.toFixed(3)},${null==o?void 0:o.toFixed(3)}]`), n <= a ? i = r.discoSeqNum : n >= o ? i = s.discoSeqNum : this.logger.warn(`Unable to determine newCC. fragFirst: ${JSON.stringify(r)} fragLast: ${JSON.stringify(s)}`), ne(i) || this.logger.warn(`Unable to determine newCC. fragFirst: ${JSON.stringify(r)} fragLast: ${JSON.stringify(s)}`)\n                    }\n                } else this.logger.warn(\"No variant details for anchoring\");\n                return this._updateAnchor(i, t), n\n            }\n            _updateAnchor(e, s) {\n                const a = e !== this._discoSeqNum;\n                a && (this._discoSeqNum = e), Bu.forEach(e => {\n                    const t = this._avDetails[e],\n                        i = s[e],\n                        r = (null == t ? void 0 : t.mediaOptionId) !== (null == i ? void 0 : i.mediaOptionId);\n                    if (a || r) this._updateAnchorForType($u(e), i);\n                    else if (i) {\n                        const {\n                            mediaOptionId: s,\n                            ptsKnown: a,\n                            dateMediaTimePairs: t,\n                            startSN: r,\n                            endSN: n\n                        } = i;\n                        this._avDetails[e] = {\n                            mediaOptionId: s,\n                            ptsKnown: a,\n                            dateMediaTimePairs: t,\n                            startSN: r,\n                            endSN: n\n                        }\n                    }\n                })\n            }\n            getNextFragments(i, r, n) {\n                const {\n                    position: s,\n                    bufferInfoTuple: e,\n                    switchContexts: a\n                } = i;\n                let t = e.map((e, t) => dy(s, r[t], a[t], null == e ? void 0 : e.buffered, t === gu.AltAudio ? this.lookUpToleranceAlt : this.lookUpTolerance)).reduce((e, t) => Math.min(t, e), Number.POSITIVE_INFINITY);\n                if (ne(i.discoSeqNum)) {\n                    const s = r.reduce((e, t) => {\n                        if (!t) return e;\n                        t = Qu.getTimeRangeForCC(t.fragments, i.discoSeqNum, n);\n                        return [Math.max(e[0], t[0]), Math.min(e[1], t[1])]\n                    }, [Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY]);\n                    t = Math.min(Math.max(t, s[0]), s[1])\n                }\n                return i.position = this._updateAnchorByPosition(t, r), this._getNextFragmentsInternal(i, r)\n            }\n            _getNextFragmentsInternal(r, n) {\n                const s = [null, null];\n                let a;\n                n.forEach((e, t) => {\n                    var i;\n                    this.firstAudioMustOverlapVideoStart && t === gu.AltAudio && this._mediaQuery.seeking && null !== (i = s[gu.Variant]) && void 0 !== i && i.foundFrag && (a = r.position, r.position = s[gu.Variant].foundFrag.mediaFragment.start), s[t] = this._getNextFragmentForType(r, n, t)\n                });\n                var e = s[yu.Variant],\n                    t = s[yu.AltAudio],\n                    i = null === (o = null == e ? void 0 : e.foundFrag) || void 0 === o ? void 0 : o.mediaFragment,\n                    o = null === (o = null == t ? void 0 : t.foundFrag) || void 0 === o ? void 0 : o.mediaFragment;\n                if (i && o && (o.start > i.start + i.duration ? (this.logger.warn(\"Audio too far ahead\"), s[yu.AltAudio] = ly.noopResult) : i.start > o.start + o.duration && !this._mediaQuery.isIframeRate && (this.logger.warn(\"Video too far ahead\"), s[yu.Variant] = ly.noopResult)), !isFinite(null == e ? void 0 : e.nextDisco) || null != t && !ne(t.nextDisco)) return s; {\n                    const l = s[yu.Variant].nextDisco;\n                    return this._updateAnchor(l, n), ne(a) && (r.position = a, a = NaN), this._getNextFragmentsInternal(r, n)\n                }\n            }\n            _getNextFragmentForType(e, t, i) {\n                var {\n                    position: r,\n                    bufferInfoTuple: n,\n                    switchContexts: s\n                } = e, a = t[i], o = null !== (d = null === (c = n[i]) || void 0 === c ? void 0 : c.buffered) && void 0 !== d ? d : {\n                    start: r,\n                    end: r,\n                    len: 0\n                }, l = this._mediaQuery.getBufferedSegmentsByType(i), d = null !== (c = null === (e = s[i]) || void 0 === e ? void 0 : e.userInitiated) && void 0 !== c && c, u = dy(r, a, s[i], o, this.lookUpTolerance);\n                if (!a) return null;\n                var {\n                    highWaterLevelSeconds: e,\n                    lowWaterLevelSeconds: c\n                } = this._mediaQuery.bufferMonitorInfo, r = o.len;\n                if (!d && e <= r) return ly.noopResult;\n                var e = i === yu.Variant ? yu.AltAudio : yu.Variant,\n                    n = null === (n = n[e]) || void 0 === n ? void 0 : n.buffered,\n                    e = null !== (e = null === (e = s[e]) || void 0 === e ? void 0 : e.userInitiated) && void 0 !== e && e;\n                let h = !1;\n                i === yu.Variant && c <= r && 1 < this._mediaQuery.expectedSbCount && null != n && n.end < o.end && (e || n.end - n.start < c) && (h = !0);\n                let p, f = null,\n                    m = NaN;\n                if (this._mediaQuery.isIframeRate && i === yu.Variant && a.iframesOnly) {\n                    const g = function(e, t, i) {\n                        e = i.nextFragment(a.fragments, (null == e ? void 0 : e.fragments) || [], t, u);\n                        if (!e) return null;\n                        var {\n                            frag: t,\n                            newMediaRootTime: e\n                        } = e;\n                        return {\n                            foundFrag: {\n                                timelineOffset: t.iframeMediaStart,\n                                mediaFragment: t\n                            },\n                            nextDisco: NaN,\n                            newMediaRootTime: e\n                        }\n                    }(t[yu.AltAudio], this._mediaQuery.desiredRate, this._iframeMachine);\n                    if (g) {\n                        ({\n                            foundFrag: f,\n                            nextDisco: m,\n                            newMediaRootTime: p\n                        } = g);\n                        const i = f.mediaFragment;\n                        i.discoSeqNum !== this._discoSeqNum && this._updateAnchor(i.discoSeqNum, t)\n                    }\n                } else {\n                    const g = this._anchorMSNs[i];\n                    ({\n                        foundFrag: f,\n                        nextDisco: m,\n                        newMediaRootTime: p\n                    } = Ig(u, this._discoSeqNum, g, a, l))\n                }\n                return h && this._rootQuery.getInitPTS(null == f ? void 0 : f.mediaFragment.discoSeqNum) ? ly.noopResult : {\n                    foundFrag: f,\n                    nextDisco: m,\n                    newMediaRootTime: p\n                }\n            }\n            _updateAnchorForType(e, t) {\n                var i, r, n, s, a;\n                if (!t) return this._anchorMSNs[e] = NaN, void(this._avDetails[e] = null);\n                ne(this._discoSeqNum) ? (a = this._discoSeqNum, a = null !== (s = null == (n = (r = t.fragments, i = a, r.find(e => e.discoSeqNum === i))) ? void 0 : n.mediaSeqNum) && void 0 !== s ? s : t.startSN, this._anchorMSNs[e] = a, {\n                    mediaOptionId: r,\n                    ptsKnown: n,\n                    dateMediaTimePairs: s,\n                    startSN: a,\n                    endSN: t\n                } = t, this._avDetails[e] = {\n                    mediaOptionId: r,\n                    ptsKnown: n,\n                    dateMediaTimePairs: s,\n                    startSN: a,\n                    endSN: t\n                }) : this.logger.warn(\"Trying to anchor with non-finite discoSeqNum\")\n            }\n        }\n\n        function dy(e, t, i, r, n) {\n            r = null != r ? r : {\n                start: e,\n                end: e,\n                len: 0\n            };\n            i = null !== (i = null == i ? void 0 : i.userInitiated) && void 0 !== i && i, n = null != t && t.iframesOnly ? 0 : n;\n            return i || 0 === r.len ? e : r.end + n\n        }\n        ly.noopResult = {\n            foundFrag: null,\n            nextDisco: NaN\n        };\n        const uy = {\n            name: \"avpipe\"\n        };\n\n        function cy(r) {\n            const {\n                config: o,\n                rootPlaylistService: l,\n                rootPlaylistQuery: d,\n                mediaSink: e,\n                gaplessInstance: t\n            } = r, u = e.mediaQuery, i = ed(Bu.map(e => d.enabledMediaOptionSwitchForType$(e).pipe(Za(e => {})))).pipe(La(e => {\n                if (!_u({\n                        itemId: d.itemId,\n                        mediaOptionId: e[gu.Variant].toId\n                    })) throw new V(!0, `No valid variant enabled id:${e[gu.Variant].toId}`, $.NoValidAlternates);\n                e = e.map(({\n                    fromId: e,\n                    toId: t\n                }, i) => function(t, i, r, n, s) {\n                    var a, o;\n                    const {\n                        rootPlaylistQuery: l,\n                        rootPlaylistService: d,\n                        mediaSink: u,\n                        mediaParser: c,\n                        config: h,\n                        iframeMachine: p\n                    } = t, f = u.mediaQuery;\n                    if (!n || !s || n === s && (r === gu.AltAudio || !p.isStarted)) return Wu;\n                    switch (r) {\n                        case gu.Variant: {\n                            n !== s && c.reset(gu.Variant);\n                            const t = $u(r),\n                                g = l.variantMediaOptionById(n),\n                                y = l.variantMediaOptionById(s),\n                                v = l.itemId;\n                            if (null == y || null == g) return Wu;\n                            var e = !y.iframes && p.isStarted;\n                            if (g.iframes !== y.iframes || e) return u.toggleTrickPlaybackMode(y.iframes), e && (ne(u.mediaQuery.postFlushSeek) || (u.postFlushSeek = p.iframeClockTimeSeconds), p.stop()), u.pause(), (e ? u.flushAll(0, 1 / 0, !0) : u.flushData(t, 0, 1 / 0, !0)).pipe(Za(() => {\n                                var e = u.mediaQuery.postFlushSeek;\n                                ne(e) && d.setPendingSeek(v, e)\n                            }));\n                            if (!h.allowFastSwitchUp || y.iframes) return Wu;\n                            var m = Dg(g).mediaOptionDetails;\n                            if (null != m && null != y && g.bitrate < y.bitrate) {\n                                const r = m.targetduration,\n                                    n = Dg(y),\n                                    s = n.mediaOptionDetails,\n                                    d = n.mediaOptionDetailsEntity.lastUpdateMillis,\n                                    c = f.getCurrentWaterLevelByType(t, h.maxBufferHole),\n                                    p = function(e, t, i, r, n, s, a, o) {\n                                        if (n.nextMaxAutoOptionId !== Lu.mediaOptionId && !Kg(s.getBandwidthEstimate())) return Number.POSITIVE_INFINITY;\n                                        a = Gg(s.getBandwidthEstimate().avgBandwidth, a.abrBandWidthUpFactor, a.abrBandWidthFactor, s.bandwidthStatus.bandwidthSampleCount), s = ne(s.getPlaylistEstimate().avgPlaylistLoadTimeMs) ? s.getPlaylistEstimate().avgPlaylistLoadTimeMs : s.getBandwidthEstimate().avgLatencyMs, a = t.bitrate > e.bitrate ? a.bwUp : a.bwDown;\n                                        return null == i || !i.liveOrEvent || i.ptsKnown && !Yg(i.totalduration, s, o) ? zg(t, i, r, a, s, o) : Number.POSITIVE_INFINITY\n                                    }(g, y, s, r, l.abrStatus, i, h, d) + h.maxStarvationDelay,\n                                    S = f.currentTime + p,\n                                    b = null === (o = null === (a = f.sourceBufferEntityByType(t)) || void 0 === a ? void 0 : a.bufferedSegments) || void 0 === o ? void 0 : o.find(e => e.startPTS >= S);\n                                let e;\n                                if (b) {\n                                    const t = b.endPTS - b.startPTS;\n                                    e = b.startPTS + Math.min(Math.max(t - h.maxFragLookUpTolerance, .5 * t), .75 * t)\n                                }\n                                if (ne(e) && c >= p) return u.flushData(t, e, 1 / 0)\n                            }\n                        }\n                        break;\n                        case gu.AltAudio:\n                            e = l, m = s, o = \"Nah\" === (a = n) ? null : e.alternateMediaOptionById(gu.AltAudio, a), o = Boolean(o && o.url), m = \"Nah\" === a ? null : e.alternateMediaOptionById(gu.AltAudio, m), m = Boolean(m && m.url), o && !m && (d.setEnabledMediaOptionSwitchContextByType(l.itemId, gu.AltAudio, s, void 0), u.resetMediaSource(f.currentTime)), c.reset(gu.AltAudio)\n                    }\n                    return Wu\n                }(r, n, i, e, t));\n                return Jr($i(!0), en(e).pipe(Zs(!1)))\n            }), tc(\"mediaOptionSwitch.audiovideo.out\")), n = Zf(d.itemId), s = r.logger.child(uy), a = new ly(s, l, d, u, r.iframeMachine, o);\n            return ed([d.anchorTime$.pipe(tc(\"anchorTime.audiovideo.in\")), i]).pipe(La(([i, e]) => e ? Ii : u.needData$(o.maxBufferHole, t.inGaplessMode).pipe(hr(e => {\n                var t = [d.enabledMediaOptionSwitchContexts[gu.Variant], d.enabledMediaOptionSwitchContexts[gu.AltAudio]];\n                return u.getSourceBufferInfoAction(e, i, t, o.maxBufferHole)\n            }), _s(e => e ? fn($i(e).pipe(hy(r, a), my(r)), Gu(function(e) {\n                const {\n                    mediaSink: t,\n                    rootPlaylistQuery: i,\n                    rootPlaylistService: r\n                } = e, n = t.mediaQuery, s = e.logger.child($g);\n                return an((a = i, o = s, ed([n.fellBelowLowWater$, a.getInFlightFragByType$(gu.Variant)]).pipe(La(e => {\n                    var [, t] = e;\n                    if (!Zg(t)) return Ii;\n                    const i = performance.now() - t.bwSample.trequest,\n                        r = ey - i,\n                        n = 1e3 * t.duration - i,\n                        s = [Wu];\n                    return 0 < r && s.push(bn(r)), 0 < n && s.push(bn(n)), an(...s).pipe(Zs(e))\n                }), sa((e, [t, i]) => {\n                    const r = Object.assign({}, e);\n                    return t && (r.fragDownloadSlow = !0), ty(i, r, a, o)\n                }, {\n                    fragDownloadSlow: !1,\n                    fragDownloadTooSlow: !1\n                }), Ra({\n                    fragDownloadSlow: !1,\n                    fragDownloadTooSlow: !1\n                }), Is(Jg))), function(r) {\n                    const s = r.mediaSink.mediaQuery,\n                        {\n                            rootPlaylistQuery: e,\n                            config: a\n                        } = r;\n                    return s.desiredRate$.pipe(La(t => 0 === t ? Ii : ed([e.getInFlightFragByType$(gu.Variant), e.mediaOptionListQueries[gu.Variant].preferredMediaOptionList$.pipe(hr(e => e.filter(Wm.bind(null, Wp(t)))))])), ao(100), La(e => {\n                        const [t, i] = e;\n                        if (!Zg(t) || i.findIndex(e => e.mediaOptionId === t.mediaOptionId) <= 0) return Ii;\n                        var r = performance.now() - t.bwSample.trequest,\n                            n = Vg(t.duration, a.maxStarvationDelay),\n                            n = Math.min(1e3 * n, 500 * t.duration / s.playbackRate);\n                        return bn(Math.max(0, n - r), 100).pipe(Zs(e))\n                    })).pipe(sa((e, [t, i]) => function(t, i, r, e) {\n                        let {\n                            fragDownloadSlow: n,\n                            fragDownloadTooSlow: s\n                        } = t;\n                        const {\n                            config: a,\n                            rootPlaylistService: o,\n                            rootPlaylistQuery: l,\n                            mediaSink: d,\n                            statsService: u,\n                            mediaLibraryService: c\n                        } = e, h = e.logger.child($g), p = d.mediaQuery;\n                        if (p.paused) return t;\n                        e = i.bwSample;\n                        if (!ne(e.tfirst)) return t;\n                        const f = performance.now(),\n                            m = f - e.trequest,\n                            g = Vg(i.duration, a.maxStarvationDelay),\n                            y = gu.Variant,\n                            v = i.mediaOptionId,\n                            S = l.variantMediaOptionById(v),\n                            b = c.getQueryForOption(S),\n                            T = S.bitrate,\n                            E = Math.max(1, 8e3 * e.loaded / m),\n                            I = 8 * ((ne(e.total) ? e.total : Math.max(e.loaded, Math.round(i.duration * T / 8))) - e.loaded) / E,\n                            w = qg(p, a.maxBufferHole);\n                        let A;\n                        if (ne(w) && 0 < w && !ne(null === (O = p.seekTo) || void 0 === O ? void 0 : O.pos)) A = w;\n                        else {\n                            const N = m / 1e3;\n                            A = N < g ? g - N : g\n                        }\n                        var O = n;\n                        ({\n                            fragDownloadSlow: n,\n                            fragDownloadTooSlow: s\n                        } = ty(i, t, l, h));\n                        t = 2 * ((null === (t = b.mediaOptionDetails) || void 0 === t ? void 0 : t.targetduration) || i.duration);\n                        if (!(w <= t && (I >= A || n))) return fg().getQuery().extendMaxTTFB && fg().setExtendMaxTTFB(0), {\n                            fragDownloadSlow: n,\n                            fragDownloadTooSlow: s\n                        };\n                        O || h.warn(`likely to stall ${ae({maxTimeToLoadSec:A,minSwitchDuration:t,stats:e,elapsedMs:m,remainingTimeSec:I,instantBw:E,bufferAheadSec:w,fragDownloadSlow:n})}`), n = !0, fg().getQuery().extendMaxTTFB || fg().setExtendMaxTTFB(6e5);\n                        let k;\n                        const C = i.itemId,\n                            D = u.getQueryForItem(C),\n                            M = D.getCombinedEstimate(),\n                            x = Object.assign(Object.assign({}, M), {\n                                avgBandwidth: E\n                            }),\n                            P = D.bandwidthStatus,\n                            R = S.iframes,\n                            L = I >= A && !R,\n                            _ = Hg(0, r, R, l);\n                        if (_ < 0) return {\n                            fragDownloadSlow: n,\n                            fragDownloadTooSlow: s\n                        };\n                        t = Math.max(_, r.findIndex(e => e && e.mediaOptionId === S.mediaOptionId));\n                        if (L) {\n                            let e = Wg(r, i.duration, _, t, A, R, x, P, 1, 1, a, l, b, p, h);\n                            const F = Lu.mediaOptionId;\n                            k = e.variantMediaOption !== F || (e = Wg(r, i.duration, _, t, I, R, x, P, 1, 1, a, l, b, p, h)).variantMediaOption !== F ? e.variantMediaOption : e.lowestCandidate\n                        } else {\n                            const N = Hg(0, r.slice(_, t).reverse(), R, l),\n                                i = t - 1 - N;\n                            (0 <= N || t === _) && (k = r[i].mediaOptionId)\n                        }\n                        if (null != k && k !== l.abrStatus.nextMaxAutoOptionId && o.setNextMaxAutoOptionId(C, k), L) throw h.warn(`loading too slow, abort fragment loading and switch to level ${k}`), u.setBandwidthSample(Object.assign(Object.assign({}, e), {\n                            tfirst: e.tfirst || f,\n                            tload: e.tload || f,\n                            complete: !0,\n                            mediaOptionType: y\n                        })), s = !0, new fc({\n                            mediaOptionType: y,\n                            mediaOptionId: v\n                        }, k, $.FragmentAbortError);\n                        return {\n                            fragDownloadSlow: n,\n                            fragDownloadTooSlow: s\n                        }\n                    }(e, t, i, r), {\n                        fragDownloadSlow: !1,\n                        fragDownloadTooSlow: !1\n                    }), Ra({\n                        fragDownloadSlow: !1,\n                        fragDownloadTooSlow: !1\n                    }), Is(Jg))\n                }(e)).pipe(Ra({\n                    fragDownloadSlow: !1,\n                    fragDownloadTooSlow: !1\n                }), sa((e, t) => ({\n                    fragDownloadSlow: e.fragDownloadSlow || t.fragDownloadSlow,\n                    fragDownloadTooSlow: e.fragDownloadTooSlow || t.fragDownloadTooSlow\n                })), Is(Jg), hr(e => (r.setFragLoadSlow(i.itemId, e), !1)), Vn(e => {\n                    if (e instanceof fc) {\n                        const e = {\n                            fragDownloadSlow: !0,\n                            fragDownloadTooSlow: !0\n                        };\n                        return r.setFragLoadSlow(i.itemId, e), $i(!0)\n                    }\n                    return Vi(e)\n                }));\n                var a, o\n            }(r), e => e)).pipe(Ds(1), Vs(() => {\n                Bu.forEach(e => {\n                    l.updateInflightFrag(d.itemId, e, null, null, null)\n                })\n            })) : Ii))), hr(() => {\n                if (!d.getEntity(d.itemId).manualMode) {\n                    let e = Mm.None;\n                    var i, r, n, s;\n                    i = Af(), r = u, n = o, s = null == r ? void 0 : r.clientWidth, a = null == r ? void 0 : r.clientHeight, r = \"object\" == typeof window && window.devicePixelRatio ? window.devicePixelRatio : 1, a = s && a ? {\n                        width: s * r,\n                        height: a * r\n                    } : void 0, r = (r = (null === (r = i.getQuery()) || void 0 === r ? void 0 : r.viewportInfo) || {}) && a && (r.width !== a.width || r.height !== a.height), n.useViewportSizeForLevelCap && r && (i.updateViewportInfo(a), 1) && (e = Mm.PreferredListChanged);\n                    let t = !1;\n                    var a = d.enabledVariantMediaOption;\n                    ! function(e, t) {\n                        const i = l.logger.child($g),\n                            r = e.abrStatus,\n                            n = r.fragDownloadSlow || r.fragDownloadTooSlow,\n                            s = ne(null === (t = t.seekTo) || void 0 === t ? void 0 : t.pos);\n                        return n && !r.fragDownloadTooSlow && s ? (i.warn(\"could be ignoring low bandwidth due to seek\"), 0) : n\n                    }(d, u) ? u.playbackStarted && function(e, t) {\n                        const i = Zf(t.itemId),\n                            r = i.getBandwidthEstimate(),\n                            n = t.abrStatus;\n                        if (Kg(r)) {\n                            var t = (null === (t = i.bandwidthStatus) || void 0 === t ? void 0 : t.bandwidthSampleCount) || 0,\n                                t = Gg(r.avgBandwidth, e.abrBandWidthUpFactor, e.abrBandWidthFactor, t)[\"bwUp\"];\n                            return t > n.highBWTrigger\n                        }\n                    }(o, d) && (e = Mm.HighBandwidth, l.setNextMinAutoOptionId(a.itemId, a.mediaOptionId)): (e = Mm.LowBandwidth, d.nextMaxAutoOptionId === Lu.mediaOptionId && (l.setNextMaxAutoOptionId(a.itemId, a.mediaOptionId), t = !0)), iy(e, o, d, u, l), t ? l.setNextMaxAutoOptionId(a.itemId, Lu.mediaOptionId) : e === Mm.HighBandwidth && l.setNextMinAutoOptionId(a.itemId, Lu.mediaOptionId)\n                }\n            }), Vs(() => {}))\n        }\n        const hy = (r, n) => e => {\n            const {\n                rootPlaylistQuery: t,\n                mediaSink: a\n            } = r, i = r.logger.child(uy);\n            return e.pipe(ji(tr), bo(t.enabledMediaOptionKeys$), La(([s, e]) => En(py(s, gu.Variant, r, e).pipe(Za(e => {\n                var e = e.detailsEntity;\n                if (!e.mediaOptionDetails.liveOrEvent || e.mediaOptionDetails.ptsKnown) {\n                    const t = e.playlistDuration,\n                        i = (null === (e = s.bufferInfoTuple[0]) || void 0 === e ? void 0 : e.buffered.end) || 0,\n                        r = (null === (e = s.bufferInfoTuple[1]) || void 0 === e ? void 0 : e.buffered.end) || 0,\n                        n = Math.max(i, r);\n                    a.msDuration = ne(a.msDuration) ? Math.max(a.msDuration, t, n) : t\n                }\n            })), py(s, gu.AltAudio, r, e)).pipe(hr(e => ({\n                action: s,\n                detailsAndContext: e\n            })))), La(({\n                action: e,\n                detailsAndContext: t\n            }) => function t(n, s, a, i, d) {\n                var e;\n                const {\n                    mediaSink: u,\n                    iframeMachine: c,\n                    rootPlaylistQuery: o\n                } = a, r = [d[gu.Variant].detailsEntity.mediaOptionDetails, null === (e = null === (e = d[gu.AltAudio]) || void 0 === e ? void 0 : e.detailsEntity) || void 0 === e ? void 0 : e.mediaOptionDetails];\n                let l = s.getNextFragments(i, r, n);\n                const h = l.reduce((e, t) => Math.max(e, ne(null == t ? void 0 : t.newMediaRootTime) ? t.newMediaRootTime : -1 / 0), -1 / 0);\n                return ne(h) && (u.seekTo = h, l = [null, null]), l.every(e => null == (null == e ? void 0 : e.foundFrag)) ? $i(null) : En(...l.map((t, l) => {\n                    if (t && null != t.foundFrag) {\n                        const i = t.foundFrag[\"mediaFragment\"],\n                            r = _g(a, i.keyTagInfo, {\n                                itemId: i.itemId,\n                                mediaOptionId: i.mediaOptionId\n                            });\n                        let e = Lg(a, l, t).pipe(Za(e => {\n                            const t = e[1],\n                                i = d[l].switchContext;\n                            t.switchPosition = null == i ? void 0 : i.switchPosition;\n                            const r = null !== (e = null == i ? void 0 : i.userInitiated) && void 0 !== e && e,\n                                n = u[\"mediaQuery\"],\n                                {\n                                    desiredRate: s,\n                                    isIframeRate: a\n                                } = n,\n                                o = a && c.isStarted && s && s < 0 && s !== c.iframeRate;\n                            (r || o) && (t.flushBeforeAppend = {\n                                start: 0,\n                                end: Number.POSITIVE_INFINITY\n                            })\n                        }));\n                        return e = l === gu.Variant ? e.pipe(Za(e => {\n                            const t = function(t, i, r, n) {\n                                if (!r) return null;\n                                const {\n                                    rootPlaylistService: s,\n                                    rootPlaylistQuery: a\n                                } = i, o = a.itemId, l = r[1], d = l.iframe;\n                                let u = a.getInitPTS(n);\n                                if (null == u || !d && u.iframeMode) {\n                                    const i = null !== (r = l.startDtsTs) && void 0 !== r ? r : null;\n                                    if (null == i) return t.warn(\"updateInitPTS: Variant data missing.\"), null;\n                                    let e = null !== (t = l.timelineOffset) && void 0 !== t ? t : 0;\n                                    d && (e = null !== (t = l.iframeOriginalStart) && void 0 !== t ? t : 0), i.timescale < 1e3 && (i.timescale = 1e3 * i.timescale, i.baseTime = 1e3 * i.baseTime);\n                                    const a = B(e, i.timescale),\n                                        c = {\n                                            baseTime: i.baseTime - a.baseTime,\n                                            timescale: i.timescale\n                                        };\n                                    s.setInitPTS(o, n, i, e, c, d), u = {\n                                        variantDTS: i,\n                                        timelineOffset: e,\n                                        offsetTimestamp: c,\n                                        iframeMode: d\n                                    }\n                                }\n                                return u\n                            }(n, a, e, s.discoSeqNum);\n                            fy(n, a, e, t)\n                        })) : en([e, Gu(o.initPTS$(s.discoSeqNum), e => {\n                            const t = u.mediaQuery.isIframeRate;\n                            return null != e && (t || !e.iframeMode)\n                        })]).pipe(hr(([e, t]) => (fy(n, a, e, t), e))), en([r, e]).pipe(hr(e => e[1]))\n                    }\n                    return $i(null)\n                })).pipe(hr(e => function(g, t, e, i) {\n                    const {\n                        rootPlaylistQuery: r,\n                        mediaSink: n,\n                        config: y\n                    } = t, v = n.mediaQuery, s = v.isIframeRate, a = r.getInitPTS(e);\n                    if (null == a) return g.warn(\"No initPTS info found\"), null;\n                    const o = i[gu.Variant],\n                        l = null == o ? void 0 : o[1];\n                    if (l && l.iframe !== s) return g.warn(`frag mediaSeqNum ${l.mediaSeqNum} discoSeqNum ${l.discoSeqNum} mediaOptionId ${l.mediaOptionId} doesn't match mediaSink's iframeMode ${s}; discard`), null;\n                    const S = [null, null];\n                    if (o) {\n                        const [g, t] = o;\n                        let e = a.offsetTimestamp;\n                        if (s) {\n                            const g = t.startDtsTs,\n                                i = B(t.timelineOffset, g.timescale);\n                            e = {\n                                baseTime: g.baseTime - i.baseTime,\n                                timescale: g.timescale\n                            }\n                        }\n                        S[yu.Variant] = {\n                            initSeg: g,\n                            dataSeg: t,\n                            offsetTimestamp: e\n                        }\n                    }\n                    const d = i[gu.AltAudio];\n                    if (null != d) {\n                        const [g, t] = d;\n                        S[yu.AltAudio] = {\n                            initSeg: g,\n                            dataSeg: t,\n                            offsetTimestamp: a.offsetTimestamp\n                        }\n                    }\n                    const u = S.map((e, t) => {\n                        const i = null == e ? void 0 : e.dataSeg;\n                        if (i) {\n                            const {\n                                itemId: r,\n                                mediaOptionId: n,\n                                mediaSeqNum: s,\n                                discoSeqNum: a,\n                                startPts: o,\n                                endPts: l,\n                                duration: d,\n                                iframe: u\n                            } = i, c = e[\"offsetTimestamp\"], h = b(o, c), p = b(l, c), f = Dg(i), m = S[0];\n                            return m && m.dataSeg.dropped || i.flushBeforeAppend || !((null === (e = null === (e = v.getBufferInfo(h, y.maxBufferHole)[t]) || void 0 === e ? void 0 : e.buffered) || void 0 === e ? void 0 : e.len) >= p - h) ? {\n                                start: h,\n                                duration: u ? d : p - h,\n                                itemId: r,\n                                mediaOptionId: n,\n                                mediaSeqNum: s,\n                                discoSeqNum: a,\n                                targetDuration: f.mediaOptionDetails.targetduration\n                            } : (g.warn(`${Nu[t]} Discarding append due to complete overlap with existing buffer`), S[t] = null)\n                        }\n                        return null\n                    });\n                    return u.every(e => !e) ? null : {\n                        appendDataTuple: S,\n                        inFlightFrags: u,\n                        initPTSInfo: a\n                    }\n                }(n, a, s.discoSeqNum, e)), La(e => {\n                    if (e) return $i(e); {\n                        const e = function(e, r) {\n                            const n = e.enabledMediaOptionKeys,\n                                s = [null, null],\n                                a = [null, null];\n                            return Bu.map(e => {\n                                var t;\n                                if (_u(n[e])) {\n                                    const i = Dg(n[e]).mediaOptionDetailsEntity;\n                                    a[e] = null === (t = i.mediaOptionDetails) || void 0 === t ? void 0 : t.ptsKnown, s[e] = {\n                                        detailsEntity: i,\n                                        switchContext: null === (e = r[e]) || void 0 === e ? void 0 : e.switchContext\n                                    }\n                                }\n                            }), s\n                        }(o, d);\n                        return t(n, s, a, i, e)\n                    }\n                }))\n            }(i, n, r, e, t)), tc(\"mediaProducerEpic.emit\"))\n        };\n\n        function py(e, i, t, r) {\n            const {\n                rootPlaylistQuery: n,\n                mediaLibraryService: s,\n                config: a\n            } = t, o = r[i];\n            if (t.logger.child({\n                    name: Nu[i]\n                }), !o || \"Nah\" === o.mediaOptionId) return $i({\n                detailsEntity: null,\n                switchContext: null\n            });\n            const l = s.getQueryForOption(o);\n            return Mr([$i(e), l.mediaOptionDetailsEntity$.pipe(Is((e, t) => (null == e ? void 0 : e.lastUpdateMillis) === (null == t ? void 0 : t.lastUpdateMillis)), ln(e => {\n                var t = null == e ? void 0 : e.mediaOptionDetails;\n                if (!t) return !0;\n                var i = performance.now(),\n                    r = e.lastUpdateMillis || i,\n                    e = t.liveOrEvent,\n                    t = t.targetduration;\n                return !e || i - r < a.livePlaylistUpdateStaleness * t * 1e3\n            }))]).pipe(ln(([, e]) => {\n                if (i === gu.AltAudio && !n.altMediaOptionHasValidUrl(i, o.mediaOptionId)) return !0;\n                var t = null == e ? void 0 : e.mediaOptionDetails;\n                return null != t && (e = null !== (e = e.lastUpdateMillis) && void 0 !== e ? e : 0, !t.liveOrEvent || !t.ptsKnown || !Yg(null == t ? void 0 : t.totalduration, 0, e))\n            }), Ds(1), bo(n.enabledMediaOptionSwitchContextsByType$(i)), hr(([\n                [, e], t\n            ]) => ({\n                detailsEntity: e,\n                switchContext: t\n            })))\n        }\n\n        function fy(e, t, i, r) {\n            const {\n                mediaLibraryService: n,\n                rootPlaylistQuery: s,\n                mediaSink: a\n            } = t, o = s.itemId;\n            null != r && (a.mediaQuery.isIframeRate || !r.iframeMode ? i && !ne(i[1].iframeMediaDuration) && (performance.now(), n.updatePTSDTS(o, i[1].mediaOptionId, r, i[1])) : e.warn(\"updatePTSDTS iframeMode mismatch\"))\n        }\n        const my = t => e => {\n            const {\n                rootPlaylistQuery: g,\n                rootPlaylistService: y,\n                mediaSink: v,\n                legibleSystemAdapter: o,\n                statsService: l,\n                rtcService: d\n            } = t;\n            return e.pipe(tc(\"mediaConsumerEpic.in\"), La(e => {\n                if (!e) return $i(!1);\n                const {\n                    appendDataTuple: r,\n                    inFlightFrags: m,\n                    initPTSInfo: t\n                } = e, i = t[\"offsetTimestamp\"];\n                return m.forEach((e, t) => {\n                    e && y.updateInflightFrag(e.itemId, t, e, \"appending\", null)\n                }), r.forEach(e => {\n                    e && (e = e.dataSeg, o.addLegibleSamples(i, e.captionData, e.id3Samples, e.endPts))\n                }), v.appendData(r, (e, t, i, r, n) => {\n                    var s, a, o, l, d, u, c, h, p, f = null !== (f = m[t].targetDuration) && void 0 !== f ? f : 10;\n                    return s = v, a = e, o = t, l = i, d = f, u = r, c = g, h = y, p = n, e => e.pipe(Za(() => {\n                        h.updateConsecutiveTimeouts(c.itemId, o, !1, \"append\")\n                    }), va(e => e.pipe(jr((e, t) => {\n                        var i = e instanceof df && e.isTimeout;\n                        if (h.updateConsecutiveTimeouts(c.itemId, o, i, \"append\"), i) return function(e, t, i, r, n, s, a, o) {\n                            let l = {\n                                errorAction: Cm.SendAlternateToPenaltyBox,\n                                errorActionFlags: 0\n                            };\n                            var d = s.getCurrentWaterLevel(i.maxBufferHole),\n                                u = d < i.almostDryBufferSec;\n                            let c = NaN;\n                            s = i.appendErrorMaxRetry, i = a.rootPlaylistEntity.errorsByType[r].timeouts.append;\n                            u && s <= i || s <= t ? l.errorAction = Cm.SendEndCallback : c = 1e3 * d;\n                            s = {\n                                retryDelayMs: c,\n                                maxNumRetry: s,\n                                maxRetryDelayMs: c\n                            };\n                            return l = Jm(l, !1, e.response.code, n, r, a, o), rg(e, t, s, l, a, o, r, n).pipe()\n                        }(e, t, u, o, l, p, c, h);\n                        if (e instanceof uf) return function(e, t, i, r, n, s, a, o, l, d) {\n                            var u = t.type,\n                                u = o.getCurrentWaterLevelByType(u, n.maxBufferHole);\n                            if (u >= n.almostDryBufferSec && !o.isIframeRate) {\n                                const t = 1e3 * r,\n                                    n = {\n                                        errorAction: Cm.RetryRequest,\n                                        errorActionFlags: 0\n                                    };\n                                return 1e3 * u < t && (d.hasFallbackMediaOptionTuple(l, s, a, !1) ? n.errorAction = Cm.SendAlternateToPenaltyBox : n.errorAction = Cm.SendEndCallback), rg(e, i, {\n                                    retryDelayMs: t,\n                                    maxNumRetry: 1 / 0,\n                                    maxRetryDelayMs: t\n                                }, n, l, d, s, a)\n                            }\n                            return i < n.appendErrorMaxRetry ? t.remove(0, Number.POSITIVE_INFINITY) : (e.fatal = !0, Vi(e))\n                        }(e, a, t, d, u, o, l, p, c, h);\n                        if (e instanceof hf) {\n                            const {\n                                mediaOptionType: a,\n                                mediaOptionId: o\n                            } = e;\n                            return oy(e, a, o, s, h, c)\n                        }\n                        throw e\n                    }))))\n                }, g.highestVideoCodec).pipe(hr(e => {\n                    m.forEach((e, t) => {\n                        e && y.updateInflightFrag(e.itemId, t, e, \"appended\", null)\n                    });\n                    var t = e.filter(e => (null == e ? void 0 : e.fragmentType) === gu.Variant);\n                    t.length && (l.setBufferMetric(t[0]), null == d || d.handleFragBuffered(t[0]));\n                    e = r[yu.AltAudio];\n                    if (null !== (t = null == e ? void 0 : e.dataSeg) && void 0 !== t && t.flushBeforeAppend || ne(null === (t = null == e ? void 0 : e.dataSeg) || void 0 === t ? void 0 : t.switchPosition)) {\n                        const {\n                            itemId: i,\n                            mediaOptionId: r\n                        } = e.dataSeg;\n                        y.setEnabledMediaOptionSwitchContextByType(i, gu.AltAudio, r, void 0)\n                    }\n                    return !0\n                }), (n = v, s = y, a = g, e => e.pipe(Vn(e => {\n                    if (e instanceof lf) {\n                        var {\n                            mediaOptionType: t,\n                            mediaOptionId: i\n                        } = e;\n                        return oy(e, t, i, n, s, a)\n                    }\n                    throw e\n                }))));\n                var n, s, a\n            }))\n        };\n\n        function gy(d, u, c, h, p, f) {\n            return u = u.child({\n                name: \"seek\"\n            }), e => e.pipe(La((e, t) => {\n                if (null == e) return Ii;\n                var i, r, n, s, a, o, l = c.mediaQuery.seekTo$.pipe(ka(1), Kp());\n                return i = 0 === t, r = d, n = u, s = p, t = f, (null == (e = e) ? Ii : e instanceof Date ? (a = e, o = t, s.enabledMediaOptionByType$(gu.Variant).pipe(La(e => o.getQueryForOption(e).mediaOptionDetails$), hr(e => function(e, t) {\n                    if (!e || 0 === e.length) return 0;\n                    const i = [...e].sort((e, t) => t[0] - e[0]),\n                        r = t.getTime(),\n                        n = null !== (t = i.find(([e]) => r >= e)) && void 0 !== t ? t : i[i.length - 1],\n                        [s, a] = n,\n                        o = a + (r - s) / 1e3;\n                    return Math.max(0, o)\n                }(e.dateMediaTimePairs, a)), Ds(1))) : function(r, e, a, n, t, o) {\n                    let i = n.enabledMediaOptionByType$(gu.Variant).pipe(La(e => t.getQueryForOption(e).mediaOptionDetails$), ln(e => ne(null == e ? void 0 : e.totalduration)), Ds(1), hr(s => {\n                        var e = !s.liveOrEvent,\n                            t = s.totalduration,\n                            i = n.itemStartOffset;\n                        return e ? ne(r) ? 0 <= r ? r : i + (t + r) : i + (ne(s.startTimeOffset) ? s.startTimeOffset : 0) : !ne(r) || r < 0 || 0 === r && a.liveEdgeForZeroStartPositon ? yg(0, s, a) : function(e, t) {\n                            let i = e;\n                            var r = s.fragments[0].start,\n                                n = s.fragments[s.fragments.length - 1].start + s.fragments[s.fragments.length - 1].duration;\n                            return e < r ? i = r : n < e && (i = yg(0, s, a)), (e < r || n < e) && t.warn(`[live] sanitizeLiveSeek seekTo:${se(e,3)}, sanitizedSeek:${se(i,3)}, liveWindowStart:${se(r,3)}, liveWindowEnd:${se(n,3)}`), i\n                        }(r, o)\n                    }));\n                    return e && (i = i.pipe(Za(e => {}))), i\n                }(e, i, r, s, t, n)).pipe(Vs(() => {\n                    h.setPendingSeek(p.itemId, void 0)\n                }), Va(l))\n            }), Za(e => {\n                ne(e) && (c.seekTo = e)\n            }))\n        }\n\n        function yy(e) {\n            const {\n                logger: r,\n                rootPlaylistService: n,\n                rootPlaylistQuery: t\n            } = e, s = t.itemId;\n            return e => e.pipe(va(e => e.pipe(jr(e => {\n                if (r.error(`Got error in pipeline ${e.message} fatal:${null==e?void 0:e.fatal} handled:${null==e?void 0:e.handled}`), !(e instanceof p) || e.fatal) throw e;\n                return e.handled ? (t = n, i = s, bn(0).pipe(hr(() => {\n                    t.updateEnabledMediaOptions(i)\n                }))) : Ii;\n                var t, i\n            }))))\n        }\n        const vy = () => e => e.pipe(tc(\"mediaFragmentPipelineEpic.in\"), La(i => {\n                if (!i) return Ii;\n                const {\n                    logger: e,\n                    config: t,\n                    platformService: r,\n                    rootPlaylistService: n,\n                    rootPlaylistQuery: s,\n                    keySystemAdapter: a,\n                    mediaSink: o,\n                    mediaParser: l,\n                    gaplessInstance: d,\n                    mediaLibraryService: u\n                } = i, c = s[\"itemId\"], h = o[\"mediaQuery\"], p = a.keyStatusChange$.pipe((f = i, e => e.pipe(La(e => {\n                    const {\n                        decryptdata: t,\n                        status: i,\n                        error: r\n                    } = e, n = f[\"rootPlaylistQuery\"];\n                    if (\"needs-renewal\" === i) return _g(f, t, null);\n                    if (\"error\" !== i || !(r instanceof gc || r instanceof mc) || r.handled) return Ii; {\n                        const {\n                            rootPlaylistService: e,\n                            keySystemAdapter: t\n                        } = f;\n                        return og(r, 0, null, e, n, t.ksQuery)\n                    }\n                }), La(() => Ii))));\n                var f;\n                const m = r.getQuery(),\n                    g = m.displaySupportsHdr$.pipe(Is(), La(e => (n.setHDRPreference(c, e, !0), Ii))),\n                    y = m.viewportInfo$.pipe(Is((e, t) => e && t && e.width === t.width && e.height === t.height), Za(e => {\n                        t.useViewportSizeForLevelCap && n.setViewportInfo(c, e)\n                    }), $a(Ii)),\n                    v = ed([s.hdrMode$.pipe(Is()), s.maxHdcpLevel$.pipe(Is())]).pipe(La(([]) => (d.inGaplessMode || 0 !== s.itemStartOffset || (o.resetMediaSource(), l.reset()), Ii))),\n                    S = an(function(i) {\n                        const {\n                            rootPlaylistQuery: t,\n                            mediaSink: r\n                        } = i, e = t.enabledMediaOptions$.pipe(Kp(), Za(e => {\n                            e = e[gu.AltAudio], e = _u(e) && null != (null == e ? void 0 : e.url) ? 2 : 1;\n                            r.setExpectedSbCount(e)\n                        })), n = en([t.enabledMediaOptionByType$(gu.Variant).pipe(ln(e => _u(e)), La(e => Dg(e).mediaOptionDetails$), Ds(1)), Gu(r.mediaQuery.updating$, e => e)]).pipe(ji(tr), Za(([e]) => {\n                            r.bufferMonitorTargetDuration = e.targetduration\n                        })), s = Fu.map(e => t.enabledMediaOptionByType$(e).pipe(tc(\"mediaOptionRetrieve.switch\"), La(t => {\n                            if (!t || !t.url || !_u(t)) return Ii;\n                            var e = r.mediaQuery.desiredRate$.pipe(hr(e => 0 !== e), Is());\n                            return Mg(i, t).pipe(tc(\"mediaOptionRetrieve.first\"), $a(e), La(e => e ? function e(t, i) {\n                                const r = t.mediaLibraryService;\n                                return function(e) {\n                                    if (!e) return Ii;\n                                    var {\n                                        mediaOptionDetails: t,\n                                        lastUpdateMillis: i,\n                                        unchangedCount: e\n                                    } = e;\n                                    if (null == t || !t.liveOrEvent) return Ii;\n                                    if (bg(t, i)) return bn(0).pipe(Za(() => {}));\n                                    let r = Sg(t);\n                                    return 0 < e && (r /= 2, r = Math.max(r, 5e3)), r -= performance.now() - i, r += 0, r = Math.max(1e3, Math.round(r)), bn(r).pipe(Za(() => {}))\n                                }(r.getQueryForOption(i).mediaOptionDetailsEntity).pipe(La(() => Mg(t, i, !1, !0)), La(() => e(t, i)))\n                            }(i, t) : Ii))\n                        })));\n                        return an(e, n, an(...s)).pipe($a(Ii))\n                    }(i), cy(i), function(t) {\n                        const {\n                            rootPlaylistQuery: i,\n                            mediaSink: e\n                        } = t;\n                        return Gu(e.mediaQuery.mediaElementEntity$, e => e).pipe(La(e => i.anchorTime$.pipe(tc(\"anchorTime.subtitle.in\"), ln(e => ne(null == e ? void 0 : e.pos)), (s => e => {\n                            const {\n                                rootPlaylistQuery: i,\n                                rootPlaylistService: t,\n                                legibleSystemAdapter: r\n                            } = s, n = i.enabledAlternateMediaOptionByType(gu.Subtitle);\n                            if (r.gotTracks) r.selectedTrack = n;\n                            else {\n                                const s = i.preferredMediaOptions[gu.Subtitle];\n                                r.setTracks(s, n, i.getDisabledMediaOption(gu.Subtitle))\n                            }\n                            return e.pipe(tc(\"subtitleEpic.select.in\"), La(() => an(r.nativeSubtitleTrackChange$.pipe(La(e => (e.mediaOptionId !== r.selectedMediaOption.mediaOptionId && t.setEnabledMediaOptionByType(e.itemId, gu.Subtitle, e), Ii))), i.enabledMediaOptionByType$(gu.Subtitle).pipe(hr(e => {\n                                const t = _u(e) ? i.alternateMediaOptionById(gu.Subtitle, e.mediaOptionId) : e;\n                                return r.selectedMediaOption = t, t\n                            })).pipe(Is((e, t) => (null == e ? void 0 : e.mediaOptionId) === (null == t ? void 0 : t.mediaOptionId))))), tc(\"subtitleEpic.select.emit\"))\n                        })(t), (s => e => {\n                            const {\n                                mediaSink: t,\n                                rootPlaylistQuery: i,\n                                legibleSystemAdapter: r,\n                                logger: n\n                            } = s;\n                            return e.pipe(tc(\"subtitleEpic.process.in\"), La(e => {\n                                if (!e || !e.url || !_u(e)) return $i([null, null, null]);\n                                return ed([Dg(e).mediaOptionDetails$, i.discoSeqNum$.pipe(ln(e => ne(e)))]).pipe(La(([e, t]) => ((i, r, e) => {\n                                    const {\n                                        legibleSystemAdapter: n,\n                                        rootPlaylistQuery: t\n                                    } = i;\n                                    return t.initPTS$(e).pipe(La(t => !t || t.iframeMode ? on : n.findFrags$(r, e).pipe(La(e => r && (null == e ? void 0 : e.foundFrags) ? Sy(i, t.offsetTimestamp, e, r) : Wu))))\n                                })(s, e, t)))\n                            }), tc(\"subtitleEpic.process.emit\"))\n                        })(t))))\n                    }(i), p).pipe(Zs(void 0), yy(i)),\n                    b = h.seekTo$.pipe(ln(e => ne(null == e ? void 0 : e.pos)), Is((e, t) => Math.abs(e.pos - t.pos) < Number.EPSILON), La(e => (n.setAnchorTime(c, e), Ii))),\n                    T = h.gotPlaying$.pipe(ln(e => e), Za(e => {\n                        s.mediaOptionListQueries[gu.Variant].filteredMediaOptionList.forEach(e => {})\n                    }), Ds(1), $a(Ii));\n                return an(s.pendingSeek$.pipe(gy(t, e, o, n, s, u)), function() {\n                    const {\n                        config: n,\n                        mediaSink: s,\n                        rootPlaylistQuery: e,\n                        mediaLibraryService: t\n                    } = i, a = (i.logger.child({\n                        name: \"live\"\n                    }), s.mediaQuery);\n                    return e.enabledMediaOptionByType$(gu.Variant).pipe(ln(_u), La(e => t.getQueryForOption(e).mediaOptionDetailsEntity$.pipe(ln(e => {\n                        var t;\n                        return (null === (t = null == e ? void 0 : e.mediaOptionDetails) || void 0 === t ? void 0 : t.ptsKnown) && e.mediaOptionDetails.liveOrEvent\n                    }), Is((e, t) => (null == e ? void 0 : e.lastUpdateMillis) === (null == t ? void 0 : t.lastUpdateMillis)))), hr(e => {\n                        var t = e.mediaOptionDetails,\n                            i = a.currentTime;\n                        a.msDuration < e.playlistDuration ? s.msDuration = e.playlistDuration : ne(s.msDuration) && (s.msDuration = s.msDuration + n.livePlaylistDurationNudge);\n                        let r = NaN;\n                        return i < vg(i, t, e.lastUpdateMillis, n.maxBufferHole, a) && (r = yg(t.fragments[0].start, t, n), s.seekTo = r), r\n                    }))\n                }(), b, S, g, y, v, function() {\n                    const e = i.mediaSink.mediaQuery;\n                    return Mr([$i(i), e.desiredRate$.pipe(ha())]).pipe(La(([e, [t, i]]) => {\n                        const {\n                            rootPlaylistQuery: s,\n                            rootPlaylistService: r,\n                            config: a,\n                            mediaSink: n,\n                            mediaLibraryService: o,\n                            statsService: l\n                        } = e, d = n.mediaQuery;\n                        if (Wp(t) !== Wp(i)) iy(Mm.IframeModeChange, a, s, d, r);\n                        else if (0 === t && 1 === i && !Bu.every(e => {\n                                const t = s.enabledMediaOptionKeys[e],\n                                    i = o.getQueryForOption(t),\n                                    r = l.getQueryForItem(s.itemId),\n                                    n = i.mediaOptionDetailsEntity;\n                                return !(null !== (e = null == n ? void 0 : n.mediaOptionDetails) && void 0 !== e && e.ptsKnown) || d.canContinuePlaybackWithoutGap(n.mediaOptionDetails, n.lastUpdateMillis, r.getPlaylistEstimate(), a.maxBufferHole)\n                            })) return n.pause(), n.flushAll(0, 1 / 0, !0);\n                        return Ii\n                    }), $a(Ii))\n                }(), function(e) {\n                    const t = e.rootPlaylistQuery,\n                        i = e.mediaSink.mediaQuery,\n                        r = t.enabledMediaOptionByType$(gu.Variant);\n                    return Mr([$i(e), i.desiredRate$.pipe(ha())]).pipe(Is((e, t) => e[1] === t[1]), bo(r), La(([\n                        [e, [t, i]], r\n                    ]) => {\n                        t = Wp(t), i = Wp(i);\n                        if (t === i) return Ii;\n                        const n = e[\"rootPlaylistService\"];\n                        return i && e.rootPlaylistQuery.nextMaxAutoOptionId === Lu.mediaOptionId && n.setNextMaxAutoOptionId(e.rootPlaylistQuery.itemId, r.mediaOptionId), Ii\n                    }))\n                }(i), T).pipe(tc(\"mediaFragmentPiplineEpic.emit\"), Zs(void 0))\n            })),\n            Sy = (r, e, t, i) => {\n                const n = r.legibleSystemAdapter,\n                    s = t.foundFrags;\n                return Fr(s).pipe(hr(t => {\n                    return ((e, t, i) => {\n                        const {\n                            rootPlaylistQuery: r,\n                            legibleSystemAdapter: n\n                        } = e;\n                        return Zr(() => ((t, i) => Rg(e, i, !1, !1).pipe(hr(e => ({\n                            initPTS: t,\n                            data: e,\n                            mediaFragment: i\n                        })), tc(\"retrieveSubtitleFragmentCacheEntity.emit\")))(t, i).pipe(hr(({\n                            initPTS: e,\n                            data: t,\n                            mediaFragment: i\n                        }) => ({\n                            frag: i,\n                            cueRange: function(e, t, i, r, n) {\n                                if (e) return n.processSubtitleFrag(e, t, i, r)\n                            }(r.enabledAlternateMediaOptionByType(gu.Subtitle), i, e, t, n)\n                        }))))\n                    })(r, e, t).pipe((i = e => n.checkReadyToLoadNextSubtitleFragment$(t, s).pipe(ln(e => e)), function(e) {\n                        return e.lift(new gs(i))\n                    }));\n                    var i\n                }), Yr(r.config.vttConcurrentLoadCount), Za(e => {\n                    n.reviewParsedFrag(e, t, i) !== kp.CloseEnough && r.legibleSystemAdapter.tryAgain$.next(!0)\n                }))\n            },\n            by = (e, t) => {\n                let i, r = \"\";\n                return i = e.videoCodec && e.audioCodec ? (r = `${e.videoCodec}, ${e.audioCodec}`, t = null != t ? t : \"video/mp4\", \"audiovideo\") : e.videoCodec ? (r = `${e.videoCodec}`, t = null != t ? t : \"video/mp4\", \"video\") : (r = `${null!==(e=e.audioCodec)&&void 0!==e?e:\"\"}`, t = null != t ? t : \"audio/mp4\", \"audio\"), {\n                    mimeType: `${t};codecs=${r}`,\n                    codec: r,\n                    container: t,\n                    type: i\n                }\n            };\n        class Ty {\n            constructor(e, t, i) {\n                this.config = e, this.logger = t, this.demuxClient = i, this.typeSupported = {\n                    mp4: MediaSource.isTypeSupported(\"video/mp4\"),\n                    mpeg: MediaSource.isTypeSupported(\"audio/mpeg\"),\n                    mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n                    ac3: MediaSource.isTypeSupported('audio/mp4; codecs=\"ac-3\"'),\n                    ec3: MediaSource.isTypeSupported('audio/mp4; codecs=\"ec-3\"')\n                }, this.demuxers = [], this.lastInitFrags = [], this.lastFrags = []\n            }\n            parseInitSegment(h, e) {\n                return this.getDemuxerInfo(h, this.lastInitFrags, e, this.demuxClient).pipe(La(({\n                    demuxer: e,\n                    contiguous: t,\n                    trackSwitch: i,\n                    discontinuity: r,\n                    accurateTimeOffset: n\n                }) => {\n                    const s = h[\"frag\"],\n                        {\n                            keyTagInfo: a,\n                            start: o,\n                            mediaOptionType: l\n                        } = s;\n                    if (this.lastInitFrags[l] = s, h.initSegment) {\n                        const e = ze.remuxInitSegment(new Uint8Array(h.initSegment), this.logger, a),\n                            t = Ze.parseInitSegment(e),\n                            {\n                                mimeType: i,\n                                type: r,\n                                codec: n,\n                                container: s\n                            } = by(t);\n                        return $i({\n                            moovData: t,\n                            mimeType: i,\n                            track: {\n                                type: r,\n                                codec: n,\n                                initSegment: e,\n                                container: s\n                            }\n                        })\n                    }\n                    const d = h.segment || h.initSegment,\n                        u = d ? h.initSegment : void 0,\n                        c = Oc(e.observer);\n                    return $i(c.event(v.FRAG_PARSING_INIT_SEGMENT).pipe(hr(this.handleInitSegmentData)), c.event(x.INTERNAL_ERROR).pipe(La(this.handleError)), e.pushWithoutTransfer(d, a, u, o, r, i, t, h.totalDuration, n, void 0, h.iframeMediaStart, h.iframeDuration).pipe($a(Ii))).pipe(Yr(), Ds(1))\n                }))\n            }\n            parseSegment(y, e) {\n                return this.getDemuxerInfo(y, this.lastFrags, e, this.demuxClient).pipe(La(({\n                    demuxer: e,\n                    contiguous: t,\n                    trackSwitch: i,\n                    discontinuity: r,\n                    accurateTimeOffset: n\n                }) => {\n                    const {\n                        frag: h,\n                        defaultInitPTS: p\n                    } = y, {\n                        keyTagInfo: s,\n                        start: a,\n                        duration: f,\n                        mediaOptionType: m\n                    } = h;\n                    let g;\n                    this.lastFrags[m] = h;\n                    const o = Oc(e.observer);\n                    return $i(o.event(v.FRAG_PARSING_INIT_SEGMENT).pipe(La(e => {\n                        var t;\n                        return e.track.initSegment.byteLength !== (null === (t = y.initSegment) || void 0 === t ? void 0 : t.byteLength) && (g = this.handleInitSegmentData(e)), Ii\n                    })), o.event(v.FRAG_PARSING_DATA).pipe(hr(e => {\n                        var {\n                            startPTS: t,\n                            startDTS: i,\n                            firstKeyframePts: r,\n                            framesWithoutIDR: n,\n                            dropped: s,\n                            data1: a,\n                            data2: o,\n                            captionData: l,\n                            id3Samples: d\n                        } = e;\n                        let {\n                            endPTS: u,\n                            endDTS: c\n                        } = e;\n                        return null == u && (this.logger.warn(`${Nu[m]} ${Vp(h)}: null endPTS parsed, using duration ${f}`), u = Object.assign(Object.assign({}, t), {\n                            baseTime: t.baseTime + B(f, t.timescale).baseTime\n                        })), null == c && (this.logger.warn(`${Nu[m]} ${Vp(h)}: null endDTS parsed, using duration ${f}`), c = Object.assign(Object.assign({}, i), {\n                            baseTime: i.baseTime + B(f, i.timescale).baseTime\n                        })), ne(y.iframeMediaStart) || function(e, t, i, r) {\n                            let n = NaN,\n                                s = NaN;\n                            if (ne(i)) s = i, n = .01, isFinite(s) && isFinite(r) && (s += r);\n                            else {\n                                {\n                                    const o = void 0\n                                }\n                            }\n                            var {\n                                startPTS: a,\n                                startDTS: i,\n                                endPTS: r,\n                                endDTS: t\n                            } = t;\n                            if (!(0 <= a.baseTime && 0 <= i.baseTime && 0 < e.duration && (null == r || 0 < b(r, a)) && (null == t || 0 < b(t, i)) && (!ne(n) || !ne(s) || Math.abs(S(i) - s) <= n))) throw new D(!1, `Failed demuxer sanity check frag=${Vp(e)} parsed=${JSON.stringify({startPTS:a,endPTS:r,startDTS:i,endDTS:t})} ${ae({expectedStartDTS:s,fudge:n})}`, $.FailedDemuxerSanityCheck)\n                        }(h, e, (p, y.iframeMediaStart), this.config.audioPrimingDelay), {\n                            startPTS: t,\n                            endPTS: u,\n                            startDTS: i,\n                            endDTS: c,\n                            firstKeyframePts: r,\n                            framesWithoutIDR: n,\n                            dropped: s,\n                            data1: a,\n                            data2: o,\n                            captionData: l,\n                            id3Samples: d,\n                            parsedInitSegment: g\n                        }\n                    })), o.event(x.INTERNAL_ERROR).pipe(La(this.handleError)), e.push(y.segment, s, y.initSegment, a, r, i, t, y.totalDuration, n, p, y.iframeMediaStart, y.iframeDuration).pipe($a(Ii))).pipe(Yr(), Ds(1))\n                }))\n            }\n            reset(e) {\n                if (null == e) return this.demuxers.forEach(e => {\n                    e && e.destroy()\n                }), void(this.demuxers = []);\n                const t = this.demuxers[e];\n                null == t || t.destroy(), this.demuxers[e] = null\n            }\n            destroy(e) {\n                null != e ? this.reset(e) : this.reset()\n            }\n            willBeTrackSwitch(e, t) {\n                var {\n                    mediaOptionType: i,\n                    mediaOptionId: e\n                } = e, i = (t || this.lastFrags)[i];\n                return !(i && i.mediaOptionId === e)\n            }\n            getDemuxerInfo(e, r, t, i) {\n                const {\n                    frag: n,\n                    ptsKnown: s,\n                    seeking: a,\n                    live: o\n                } = e, {\n                    discoSeqNum: l,\n                    mediaSeqNum: d,\n                    mediaOptionType: u\n                } = n;\n                return Zr(() => {\n                    var e = this.demuxers[u];\n                    return e ? $i(e) : i.init(this.typeSupported, this.config, t).pipe(Za(e => this.demuxers[u] = e))\n                }).pipe(hr(e => {\n                    var t = r[u],\n                        i = this.willBeTrackSwitch(n, r);\n                    return {\n                        demuxer: e,\n                        trackSwitch: i,\n                        discontinuity: !(t && l === t.discoSeqNum),\n                        contiguous: !!t && !i && t.mediaSeqNum + 1 === d,\n                        accurateTimeOffset: !a && (s || !o)\n                    }\n                }))\n            }\n            handleInitSegmentData(e) {\n                var t = e[\"track\"],\n                    i = t[\"initSegment\"],\n                    r = Ze.parseInitSegment(i),\n                    {\n                        mimeType: n,\n                        type: s,\n                        codec: a,\n                        container: e\n                    } = by(r, t.container);\n                return {\n                    moovData: r,\n                    mimeType: n,\n                    track: Object.assign(Object.assign({}, t), {\n                        type: s,\n                        codec: a,\n                        initSegment: i,\n                        container: e\n                    })\n                }\n            }\n            handleError(e) {\n                return Vi(e)\n            }\n        }\n\n        function Ey(a, e, t, h, p, i, r, n) {\n            var s = h[\"combined\"],\n                o = function(e) {\n                    let t = 1 / 0;\n                    h.playingFrag && (t = null !== (s = null === (n = e.fragments[h.playingFrag.mediaSeqNum - e.startSN]) || void 0 === n ? void 0 : n.duration) && void 0 !== s ? s : 1 / 0);\n                    var {\n                        minRequiredStartDuration: i,\n                        maxRequiredStartDuration: r,\n                        startTargetDurationFactor: n\n                    } = a, {\n                        targetduration: s,\n                        averagetargetduration: e\n                    } = e, r = n * Math.min(t, e, s, r);\n                    return Math.max(i, r)\n                }(t.details);\n            let l = function(e, t, i) {\n                const {\n                    pos: r,\n                    combined: n,\n                    playingFrag: s\n                } = h;\n                if (0 === n.len) return !1;\n                var a = t.details,\n                    o = a.fragments;\n                let l = 0 != p && 1 != p || n.len >= i;\n                var d = o[a.fragments.length - 1],\n                    t = o[0].start + a.totalduration;\n                let u = !1;\n                if (s) {\n                    const c = qu.search(o, e => s.discoSeqNum - e.discoSeqNum);\n                    u = e && s.discoSeqNum !== e.discoSeqNum || null == c || $p(c, s)\n                }\n                return l && a.liveOrEvent ? l = r <= t - d.duration : a.liveOrEvent || (l = l || t - i <= r), l = l || u, l\n            }(e, t, o);\n            return !l && 0 < s.len && null != e && e.state && (l = function(n, e, t, i, r, s, a) {\n                var o = null === (l = h.sbTuple[gu.Variant]) || void 0 === l ? void 0 : l.buffered,\n                    l = null === (l = h.sbTuple[gu.AltAudio]) || void 0 === l ? void 0 : l.buffered;\n                if ((null == o ? void 0 : o.len) >= t && (!l || l.len >= t)) return 0;\n                if (!(o && n && (d = h.pos, (l = n.start + n.duration) > o.end && (n.start - o.end <= a || n.start <= o.end) && t <= l - d))) return 1 / 0;\n                var d = n.state;\n                let u = n.tstart,\n                    c = 0;\n                switch (d) {\n                    case \"loading\":\n                        c += function(e, t) {\n                            var {\n                                bwSample: i,\n                                duration: r\n                            } = n;\n                            if (!i) return 1 / 0;\n                            r = ne(i.total) ? 8 * i.total : Math.ceil(r * e), e = 8 * i.loaded, r -= e, i = e / (performance.now() - i.tfirst) * 1e3;\n                            if (!ne(i)) return 1 / 0;\n                            t = t.avgBandwidth;\n                            return r / Math.min(t, i)\n                        }(e, i), u = n.tstart + 1e3 * c;\n                    case \"loaded\":\n                    case \"parsing\":\n                        c += function(e, t) {\n                            t = ne(t.avgParseTimeMs) ? t.avgParseTimeMs : 0;\n                            return performance.now() < e ? t / 1e3 : Math.max(0, t - (performance.now() - e)) / 1e3\n                        }(u, r), u = n.tstart + 1e3 * c;\n                    case \"parsed\":\n                    case \"appending\":\n                        c += function(e, t) {\n                            t = ne(t.avgDataFragAppendMs) ? t.avgDataFragAppendMs : 0;\n                            return performance.now() < e ? t / 1e3 : Math.max(0, t - (performance.now() - e)) / 1e3\n                        }(u, s);\n                        break;\n                    default:\n                        c = 1 / 0\n                }\n                return c\n            }(e, t.variant.bitrate, o, i, r, n, a.maxBufferHole) <= s.len), l\n        }\n\n        function Iy(e, t, i, r) {\n            if (200 === t && r && 10 < r.length) {\n                if (Rm.isValidPlaylist(r)) return !0; {\n                    const t = new R(o, _, !0, \"response doesnt have #EXTM3U tag\", $.PlaylistErrorMissingEXTM3U);\n                    throw t.url = e, t\n                }\n            }\n            return !1\n        }\n        const wy = {\n            name: \"pltfrm\"\n        };\n\n        function Ay(e, t) {\n            t = Ah.getKeySystemSecurityLevel(t);\n            return null != e && void 0 !== t[e]\n        }\n\n        function Oy(e) {\n            return e.every(e => e.iframes)\n        }\n\n        function ky(e, t) {\n            return !ne(e) || !ne(t) || e <= t\n        }\n\n        function Cy() {\n            const n = new Set,\n                s = new Set;\n            return e => {\n                const i = (e, t) => {\n                        t = t ? \"audio\" : \"video\";\n                        n.has(e) || s.has(e) || (((e, t) => {\n                            let i = MediaSource.isTypeSupported(`${e}/mp4;codecs=${t}`);\n                            return \"mp4a.40.34\" !== t || i || (i = MediaSource.isTypeSupported(`${e}/mpeg`)), i\n                        })(t, e) ? n : s).add(e)\n                    },\n                    t = (e, t) => (i(e, t), s.has(e));\n                let r = !1;\n                return e.audioCodecList && (r = e.audioCodecList.some(e => t(e, !0))), !r && e.videoCodecList && (r = e.videoCodecList.some(e => t(e, !1))), !r\n            }\n        }\n\n        function Dy(e, t) {\n            for (const i in e)\n                if (e[i].type === t) return e[i];\n            return {}\n        }\n\n        function My(e, t, i) {\n            t.filter(e => !i.includes(e)).map(e => e.mediaOptionId)\n        }\n\n        function xy(e, i, s) {\n            const a = new Map,\n                r = new Array;\n            return e.forEach(t => {\n                var e = Array();\n                ! function(e, t, i) {\n                    var r = Wc.getCapabilities(t.videoCodecList, t.audioCodecList),\n                        t = JSON.stringify(r);\n                    let n;\n                    a.has(t) ? n = a.get(t) : (n = Ah.requestKeySystemAccess(e, r, void 0, s).pipe(hr(() => !0), Vn(e => (s.warn(`Request key system error: ${e.message}`), $i(!1))), Oa({\n                        bufferSize: 1,\n                        refCount: !0\n                    })), a.set(t, n)), i.push(n)\n                }(i, t, e);\n                e = en(e).pipe(hr(e => {\n                    if (void 0 === e.find(e => !1 === e)) return t\n                }));\n                r.push(e)\n            }), en(r).pipe(hr(e => e.filter(e => Boolean(e))))\n        }\n\n        function Py(e, r) {\n            const o = new Set,\n                l = new Set,\n                d = !MediaSource.isTypeSupported('audio/mp4; codecs=\"mp4a.40.2\"; channels=\"-1\"'),\n                u = d && !MediaSource.isTypeSupported('audio/mp4; codecs=\"mp4a.40.2\"; channels=\"2\"; features=\"INVALID\"'),\n                t = e.filter(e => {\n                    let t = !1;\n                    var i;\n                    return e.audioCodecList && e.audioGroupId && (i = fm.getRichestChannelLayoutForGroupId(e.audioGroupId, r), 0 < e.audioCodecList.length && i && (t = ((e, t) => {\n                        var i, r, n, s = be.isDolbyAtmos(e, t);\n                        if (u || d && !s) {\n                            n = `${i=e}/${r=t}`, o.has(n) || l.has(n) || (((e, t) => {\n                                const i = t.split(\"/\"),\n                                    r = parseInt(i[0]);\n                                let n, s;\n                                if (1 < i.length) {\n                                    const t = i[1].split(\",\")[0];\n                                    n = `audio/mp4;codecs=\"${e}\";channels=\"${r}\";features=\"${t}\"`, s = `audio/mp4;codecs=\"${e}\";channels=\"8\";features=\"${t}\"`\n                                } else n = `audio/mp4;codecs=\"${e}\";channels=\"${r}\"`;\n                                let a = MediaSource.isTypeSupported(n);\n                                return !a && s && (a = MediaSource.isTypeSupported(s)), a\n                            })(i, r) ? o : l).add(n);\n                            const a = `${e}/${t}`;\n                            return l.has(a)\n                        }\n                        return !!s\n                    })(fm.getRichestAudioCodec(e.audioCodecList), i))), !t\n                });\n            return My(0, e, t), t\n        }\n\n        function Ry(e, t, l) {\n            const n = 0 < (null == t ? void 0 : t.length),\n                i = e.filter(o => {\n                    var e = function() {\n                            if (!l) return {\n                                highestPlayableAverageBitRate: void 0,\n                                highestPlayablePeakBitRate: void 0,\n                                highestPlayableWidth: void 0,\n                                highestPlayableHeight: void 0,\n                                highestPlayableFrameRate: void 0\n                            };\n                            const e = o.videoCodec,\n                                t = o.videoRange,\n                                i = l.videoDynamicRangeFormats,\n                                r = l.videoCodecs,\n                                n = be.getDynamicRangeType(t, e),\n                                s = be.getCompressionType(e),\n                                a = function(e, t, i, r) {\n                                    if (!r && !i) return {};\n                                    var n, s, t = i ? Dy(i, t) : {},\n                                        r = r ? Dy(r, e) : {};\n                                    let a, o;\n                                    return o = e === fe.SDR ? (a = t, r) : (a = r, t), n = Object.assign({}, a), s = o, Object.keys(s).forEach(e => {\n                                        n[e] || (n[e] = s[e])\n                                    }), n\n                                }(n, s, r, i);\n                            return s !== me.VP09 && (a.highestPlayablePeakBitRateForClearContent = void 0), a\n                        }(),\n                        t = e[\"highestPlayablePeakBitRateForClearContent\"],\n                        i = o.allowedCPCMap || n,\n                        r = ky(o.bandwidth, e.highestPlayablePeakBitRate);\n                    return (i || !t ? r : r || ky(o.bandwidth, t)) && ky(o.avgBandwidth, e.highestPlayableAverageBitRate) && ky(o.width, e.highestPlayableWidth) && ky(o.height, e.highestPlayableHeight) && ky(o.frameRate, e.highestPlayableFrameRate)\n                });\n            return My(0, e, i), i\n        }\n\n        function Ly(e, a, o, l, d, u) {\n            var r = (null == l ? void 0 : l.maxHdcpLevel) || void 0;\n            let c = [...e];\n            (0 < d.disableVideoCodecList.size || 0 < d.disableAudioCodecList.size) && (c = function(e, t, i) {\n                let r = e.filter(e => !e.videoCodec || e.videoCodecList.every(e => {\n                    e = qp(e);\n                    return !t.has(e)\n                }));\n                return r = r.filter(e => !(!e.iframes && e.audioCodec) || e.audioCodecList.every(e => {\n                    e = jp(e);\n                    return !i.has(e)\n                })), My(0, e, r), r\n            }(c, d.disableVideoCodecList, d.disableAudioCodecList)), r && dm(r) && (c = function(e) {\n                const t = um(r),\n                    i = e.filter(e => {\n                        e = e.hdcpLevel;\n                        return !e || um(e) <= t\n                    });\n                return My(0, e, i), i\n            }(c));\n            var t = null == l ? void 0 : l.maxSecurityLevel,\n                e = null == d ? void 0 : d.keySystemPreference;\n            t && e && Ay(t, e) && (c = function(e, t, i) {\n                function r(e) {\n                    return Ay(e, i) ? n[e] : -1\n                }\n                const n = Ah.getKeySystemSecurityLevel(i),\n                    s = Ah.getKeySystemFormat(i),\n                    a = r(t),\n                    o = e.filter(e => {\n                        e = null !== (e = null === (e = e.allowedCPCMap) || void 0 === e ? void 0 : e[s]) && void 0 !== e ? e : [];\n                        let t = !0;\n                        for (const i of e)\n                            if (t = r(i) <= a, !t) break;\n                        return t\n                    });\n                return My(0, e, o), [...o]\n            }(c, t, e)), c = c.map(t => {\n                var e;\n                return t.audioCodecList && t.audioGroupId && ((e = null == (e = a.find(e => e.groupId === t.audioGroupId)) ? void 0 : e.channels) && (t.audioChannelCount = parseInt(e))), t\n            });\n            const h = !(null == d || !d.useMediaKeySystemAccessFilter) && e && navigator && \"function\" == typeof navigator.requestMediaKeySystemAccess;\n            return (h ? xy(c, e, u) : $i(c)).pipe(La(e => {\n                if (0 === e.length || Oy(e)) throw new R(L, f, void 0, \"no media option with compatible codecs found in playlist\", void 0);\n                h && My(0, c, e);\n                const t = navigator && navigator.mediaCapabilities,\n                    n = !(null == d || !d.useMediaCapabilities) && t && \"function\" == typeof t.decodingInfo;\n                let i;\n                return i = n ? function(e, n, s) {\n                    const a = [],\n                        o = Cy(),\n                        l = function(o) {\n                            const l = new Map,\n                                d = navigator && navigator.mediaCapabilities;\n                            return (i, e, t, n, r) => {\n                                const s = {\n                                    type: \"media-source\"\n                                };\n                                n ? s.video = function(e) {\n                                    const t = {\n                                        contentType: `video/mp4;codecs=${e}`,\n                                        width: i.width,\n                                        height: i.height,\n                                        bitrate: i.bandwidth || i.avgBandwidth,\n                                        framerate: i.iframes ? 8 : i.frameRate\n                                    };\n                                    if (i.videoRange) switch (i.videoRange) {\n                                        case \"PQ\":\n                                            be.isDolby(e) ? (t.hdrMetadataType = Pm.DoVi, t.colorGamut = \"rec2020\") : (be.isHEVC(e) || be.isVP09(e)) && (t.hdrMetadataType = Pm.HDR10, t.colorGamut = \"rec2020\"), t.transferFunction = \"pq\";\n                                            break;\n                                        case \"HLG\":\n                                            t.colorGamut = \"rec2020\", t.transferFunction = \"hlg\"\n                                    }\n                                    return t\n                                }(t) : s.audio = function(e, t, i) {\n                                    const r = {\n                                            contentType: `audio/mp4;codecs=${e}`\n                                        },\n                                        n = fm.getRichestChannelLayoutForGroupId(t.audioGroupId, i);\n                                    return n && (r.channels = be.getChannelCount(n).toString(), r.spatialRendering = be.isDolbyAtmos(e, n)), r\n                                }(t, i, e);\n                                e = JSON.stringify(s);\n                                let a;\n                                return l.has(e) ? a = l.get(e) : (a = Fr(d.decodingInfo(s)).pipe(hr(e => {\n                                    const t = e.configuration || e.supportedConfiguration,\n                                        i = t instanceof Object && (!s.video || null == Object.keys(s.video).find(e => !(e in t.video))) && (!s.audio || null == Object.keys(s.audio).find(e => !(e in t.audio))),\n                                        r = e.supported && (!n || e.powerEfficient) && i;\n                                    return r || o.warn(wy, `Unsupported config ${e.supported}/${e.powerEfficient}/${i} ${JSON.stringify(s)} supportedConfig=${JSON.stringify(t)}`), r\n                                })), l.set(e, a)), [...r, a]\n                            }\n                        }(s);\n                    return e.forEach(t => {\n                        var e;\n                        let i = [];\n                        if (null === (e = t.videoCodecList) || void 0 === e || e.forEach(e => {\n                                i = l(t, n, e, !0, i)\n                            }), 0 < (null === (e = t.audioCodecList) || void 0 === e ? void 0 : e.length)) {\n                            const s = fm.getRichestAudioCodec(t.audioCodecList);\n                            i = l(t, n, s, !1, i)\n                        }\n                        let r = $i(t);\n                        0 < i.length && (r = en(i).pipe(hr(e => null == e.find(e => !1 === e) ? t : null), Vn(e => (s.warn(wy, `decodingInfo errror: ${e.message}`), $i(o(t) ? t : null))))), a.push(r)\n                    }), en(a).pipe(hr(e => e.filter(e => Boolean(e))))\n                }(e, a, u) : $i(e = Py((r = e, s = Cy(), s = r.filter(s), My(0, r, s), e = s), a)), i.pipe(hr(e => {\n                    if (0 === e.length || Oy(e)) throw new R(L, f, void 0, \"no media option with compatible codecs found in manifest\", void 0);\n                    if (0 === (t = e = Ry(e, o, l), r = t.filter(e => !e.iframes || !e.width || !e.height || e.width * e.height <= 2488320), My(0, t, r), (e = r).length) || Oy(e)) throw new R(L, f, void 0, \"no media option with compatible codecs found in manifest\", void 0);\n                    var t;\n                    let i = (null == l ? void 0 : l.videoDynamicRangeFormats) || [];\n                    n && 0 === i.length && (i = [{\n                        type: fe.SDR\n                    }, {\n                        type: fe.HDR\n                    }, {\n                        type: fe.HDR10\n                    }, {\n                        type: fe.DolbyVision\n                    }, {\n                        type: fe.HLG\n                    }]);\n                    var {\n                        hdrMediaOptions: r,\n                        sdrMediaOptions: e\n                    } = function(e, t) {\n                        const i = t.reduce((e, t) => {\n                                switch (t.type) {\n                                    case fe.DolbyVision:\n                                        e.doViSupported = !0;\n                                        break;\n                                    case fe.HDR10:\n                                        e.hdr10Supported = !0;\n                                        break;\n                                    case fe.HLG:\n                                        e.hlgSupported = !0\n                                }\n                                return e\n                            }, {\n                                doViSupported: !1,\n                                hdr10Supported: !1,\n                                hlgSupported: !1\n                            }),\n                            {\n                                doViSupported: r,\n                                hdr10Supported: n,\n                                hlgSupported: s\n                            } = i;\n                        return e.reduce((e, t) => {\n                            var i;\n                            switch (be.getDynamicRangeType(t.videoRange, null !== (i = t.videoCodec) && void 0 !== i ? i : \"\")) {\n                                case fe.HDR:\n                                case fe.HDR10:\n                                    n && e.hdrMediaOptions.push(t);\n                                    break;\n                                case fe.DolbyVision:\n                                    r && e.hdrMediaOptions.push(t);\n                                    break;\n                                case fe.HLG:\n                                    s && e.hdrMediaOptions.push(t);\n                                    break;\n                                default:\n                                    \"SDR\" !== t.videoRange && null != t.videoRange || e.sdrMediaOptions.push(t)\n                            }\n                            return e\n                        }, {\n                            hdrMediaOptions: new Array,\n                            sdrMediaOptions: new Array\n                        })\n                    }(e, i);\n                    if (0 === r.length && 0 === e.length || Oy(r) && Oy(e)) throw new R(L, \"manifestIncompatibleVideoRangeError\", void 0, \"mediaOption with compatible VIDEO-RANGE not found in manifest\", void 0);\n                    return {\n                        hdrMediaOptions: r,\n                        sdrMediaOptions: e\n                    }\n                }), Vn(e => {\n                    throw e instanceof R && (e.fatal = !0, e.response = $.IncompatibleAsset), e\n                }));\n                var r, s\n            }))\n        }\n\n        function _y(e, t) {\n            return t.mediaOptionId !== e.mediaOptionId && t.persistentID === e.persistentID && t.groupId !== e.groupId\n        }(A = Pm = Pm || {}).HDR10 = \"smpteSt2086\", A.DoVi = \"smpteSt2094-10\", A.HDR10Plus = \"smpteSt2094-40\";\n        class Ny extends jm {\n            constructor(e, t, i) {\n                super(e, t, i)\n            }\n            static makeFilters() {\n                return Hm()\n            }\n            _initFilters() {\n                return Ny.kAllowFilters\n            }\n            get _mediaOptionType() {\n                return this.mediaOptionType\n            }\n            get preferredHost() {\n                return null\n            }\n            get preferredHost$() {\n                return $i(null)\n            }\n            get mediaOptionListInfo() {\n                var e;\n                return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.mediaOptionListTuple[this._mediaOptionType]) && void 0 !== e ? e : null\n            }\n            get mediaOptionListInfo$() {\n                return this.selectEntity(this.itemId, e => e && e.mediaOptionListTuple ? e.mediaOptionListTuple[this._mediaOptionType] : null).pipe(Kp())\n            }\n            getFallbackVariant(t, e, i, r) {\n                var n;\n                const s = null === (n = this.mediaOptionList) || void 0 === n ? void 0 : n.find(e => e.mediaOptionId === t);\n                if (!s) return null;\n                const a = this.filteredMediaOptionList;\n                if (!a) return null;\n                const o = Eu(s.url);\n                if (i) return null !== (i = a.find(e => _y(s, e) && !Au(o, e.url))) && void 0 !== i ? i : null;\n                let l = null;\n                for (const t of a) !_y(s, t) || l && !Au(o, t.url) || (l = t);\n                return l\n            }\n            getMatchingAlternateWithPersistentId(t, i, r) {\n                var e;\n                return null !== (e = this.preferredMediaOptionList.find(e => !(0 < (null == r ? void 0 : r.length) && r.includes(e.mediaOptionId)) && (!ne(t) || e.persistentID === t) && (!i || this.matchGroup(e, i.audioGroupId, i.subtitleGroupId, i.closedcaption)))) && void 0 !== e ? e : null\n            }\n            matchGroup(e, t, i, r) {\n                let n = !1;\n                switch (e.type) {\n                    case \"CLOSED-CAPTIONS\":\n                        n = !r || e.groupId === r;\n                        break;\n                    case \"SUBTITLES\":\n                        n = !i || e.groupId === i;\n                        break;\n                    case \"AUDIO\":\n                        n = !t || e.groupId === t\n                }\n                return n\n            }\n            getMatchingAlternate(e, t) {\n                e = this.mediaOptionFromId(e);\n                return this.getMatchingAlternateWithPersistentId(null == e ? void 0 : e.persistentID, t, [])\n            }\n            packageAlternateMediaOption(e, t, i) {\n                return t.mediaType === Su.CLOSEDCAPTION ? this.augmentClosedCaptionsWithForcedSubtitles(null == e ? void 0 : e.subtitleGroupId, t, i) : t\n            }\n            augmentClosedCaptionsWithForcedSubtitles(e, t, i) {\n                i = this.pairForcedSubtitleMediaOptionWithClosedCaption(e, t, i);\n                return i ? Object.assign(Object.assign({}, t), {\n                    url: i.url,\n                    backingMediaOptionId: i.mediaOptionId\n                }) : t\n            }\n            pairForcedSubtitleMediaOptionWithClosedCaption(t, i, r) {\n                let n;\n                if (i && i.mediaType === Su.CLOSEDCAPTION) {\n                    let e = this.mediaOptionList;\n                    r && (e = this.preferredMediaOptionList), n = Ny.pairForcedSubtitleMediaOptionWithClosedCaptionInList(t, i, e)\n                }\n                return n\n            }\n            static pairForcedSubtitleMediaOptionWithClosedCaptionInList(t, i, e) {\n                return e.find(function(e) {\n                    return e.mediaType === Su.SUBTITLE && e.lang === i.lang && e.forced && e.autoselect && (!t || e.groupId === t)\n                })\n            }\n        }\n        Ny.kAllowFilters = Ny.makeFilters();\n        class Fy extends kl {\n            constructor(e, t) {\n                super(e), this.itemId = t, this.mediaOptionListQueries = [new Xm(e, this.itemId), new Ny(e, this.itemId, gu.AltAudio), new Ny(e, this.itemId, gu.Subtitle)]\n            }\n            get rootPlaylistEntity() {\n                return this.getEntity(this.itemId)\n            }\n            get rootMediaOptionsTuple() {\n                var e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.mediaOptionListTuple;\n                return e ? [e[0].mediaOptions, e[1].mediaOptions, e[2].mediaOptions] : [\n                    [],\n                    [],\n                    []\n                ]\n            }\n            get itemStartOffset() {\n                var e, t;\n                return null !== (e = this.rootPlaylistEntity) && void 0 !== e && e.itemStartOffset && ne(null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.itemStartOffset) ? null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.itemStartOffset : 0\n            }\n            get highestVideoCodec() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.highestVideoCodec\n            }\n            get baseUrl() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.baseUrl\n            }\n            get anchorTime() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.anchorTime\n            }\n            get discoSeqNum() {\n                var e;\n                return null !== (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.discoSeqNum) && void 0 !== e ? e : NaN\n            }\n            get discoSeqNum$() {\n                return this.selectEntity(this.itemId, \"discoSeqNum\")\n            }\n            get audioMediaSelectionGroup() {\n                var e;\n                return null !== (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.audioMediaSelectionGroup) && void 0 !== e ? e : null\n            }\n            get subtitleMediaSelectionGroup() {\n                var e;\n                return null !== (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.subtitleMediaSelectionGroup) && void 0 !== e ? e : null\n            }\n            get audioMediaSelectionOptions() {\n                var e;\n                return null !== (e = null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.audioMediaSelectionGroup) || void 0 === e ? void 0 : e.MediaSelectionGroupOptions) && void 0 !== e ? e : []\n            }\n            get subtitleMediaSelectionOptions() {\n                var e;\n                return null !== (e = null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.subtitleMediaSelectionGroup) || void 0 === e ? void 0 : e.MediaSelectionGroupOptions) && void 0 !== e ? e : []\n            }\n            get contentSteeringOption() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.contentSteeringOption\n            }\n            get masterVariableList() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.masterVariableList\n            }\n            get loadStats() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.loadStats\n            }\n            get isMediaPlaylist() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.isMediaPlaylist\n            }\n            getInitPTS(e) {\n                var t;\n                return null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.initPtsRecord[e]\n            }\n            get abrStatus$() {\n                return this.selectEntity(this.itemId, e => null == e ? void 0 : e.abrStatus)\n            }\n            get abrStatus() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.abrStatus\n            }\n            get nextMaxAutoOptionId() {\n                var e;\n                return null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.abrStatus) || void 0 === e ? void 0 : e.nextMaxAutoOptionId\n            }\n            get nextMinAutoOptionId() {\n                var e;\n                return null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.abrStatus) || void 0 === e ? void 0 : e.nextMinAutoOptionId\n            }\n            initPTS$(t) {\n                return this.selectEntity(this.itemId, ({\n                    initPtsRecord: e\n                }) => e[t])\n            }\n            get rootPlaylistEntity$() {\n                return this.selectEntity(this.itemId).pipe(ln(e => Boolean(e)), hr(e => e))\n            }\n            get rootPlaylistEntityAdded$() {\n                return this.selectEntityAction(Eo.Add).pipe(hr(e => e.map(e => this.getEntity(e))))\n            }\n            get rootMediaOptionsTuple$() {\n                return ed([this.selectEntity(this.itemId, e => e.mediaOptionListTuple[0].mediaOptions), this.selectEntity(this.itemId, e => e.mediaOptionListTuple[1].mediaOptions), this.selectEntity(this.itemId, e => e.mediaOptionListTuple[2].mediaOptions)])\n            }\n            get sessionData() {\n                var e;\n                return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.sessionData\n            }\n            get sessionData$() {\n                return this.selectEntity(this.itemId, ({\n                    sessionData: e\n                }) => e).pipe(Kp())\n            }\n            get anchorTime$() {\n                return this.selectEntity(this.itemId, \"anchorTime\").pipe(La(e => {\n                    var t;\n                    return ne(null == e ? void 0 : e.pos) ? (null == e ? void 0 : e.pos) !== (null === (t = this.anchorTime) || void 0 === t ? void 0 : t.pos) ? (Qe().warn(`anchorTime doesn't match stored value! ${null==e?void 0:e.pos} !== ${null===(t=this.anchorTime)||void 0===t?void 0:t.pos}`), Ii) : $i(e) : Ii\n                }))\n            }\n            get pendingSeek$() {\n                return this.selectEntity(this.itemId, ({\n                    pendingSeek: e\n                }) => e).pipe(Is((e, t) => e === t || \"number\" == typeof e && \"number\" == typeof t && isNaN(e) && isNaN(t)))\n            }\n            get enabledMediaOptionKeys$() {\n                return this.selectEntity(this.itemId, \"enabledMediaOptionKeys\").pipe(ln(e => Boolean(e)))\n            }\n            get enabledMediaOptionKeys() {\n                var e;\n                return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.enabledMediaOptionKeys) && void 0 !== e ? e : [Lu, Lu, Lu]\n            }\n            get enabledMediaOptionSwitchContexts() {\n                var e;\n                return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.mediaOptionSwitchContexts) && void 0 !== e ? e : [null, null, null]\n            }\n            enabledMediaOptionSwitchContextsByType$(t) {\n                return this.selectEntity(this.itemId, \"mediaOptionSwitchContexts\").pipe(hr(e => null == e ? void 0 : e[t]))\n            }\n            get enabledMediaOptions$() {\n                return ed([this.enabledMediaOptionByType$(gu.Variant), this.enabledMediaOptionByType$(gu.AltAudio), this.enabledMediaOptionByType$(gu.Subtitle)])\n            }\n            get enabledAVOptions$() {\n                return ed([this.enabledMediaOptionByType$(gu.Variant), this.enabledMediaOptionByType$(gu.AltAudio)])\n            }\n            rawEnabledMediaOptionByType$(t) {\n                return this.enabledMediaOptionKeys$.pipe(hr(e => {\n                    const i = e[t];\n                    return _u(i) && this.rootMediaOptionsTuple[t].find(e => {\n                        return t = i, e.itemId === t.itemId && e.mediaOptionId === t.mediaOptionId;\n                        var t\n                    }) || Lu\n                }))\n            }\n            enabledMediaOptionByType$(e) {\n                return this.rawEnabledMediaOptionByType$(e).pipe(Is((e, t) => e.mediaOptionId === t.mediaOptionId && e.url === t.url))\n            }\n            enabledMediaOptionSwitchForType$(e) {\n                return this.rawEnabledMediaOptionByType$(e).pipe(bo(this.enabledMediaOptionSwitchContextsByType$(e)), Ra(null), ha(), hr(([e, t]) => ({\n                    fromId: null == e ? void 0 : e[0].mediaOptionId,\n                    toId: null == t ? void 0 : t[0].mediaOptionId,\n                    switchContext: null == t ? void 0 : t[1]\n                })), Is((e, t) => e.fromId === t.fromId && e.toId === t.toId))\n            }\n            enableMediaOptionSwitchedForType$(t) {\n                return this.enabledMediaOptionByType$(t).pipe(La(e => Gu(Mr([$i(e), this.enabledMediaOptionSwitchContextsByType$(t).pipe(ha())]), ([, e]) => e[0] && !e[1])), hr(([e]) => e))\n            }\n            enabledMediaOptionIdByType(e) {\n                return this.getEntity(this.itemId).enabledMediaOptionKeys[e].mediaOptionId\n            }\n            get enabledVariantMediaOptionIdBeforeTrickplaySwitch() {\n                return this.getEntity(this.itemId).enabledVariantMediaOptionIdBeforeTrickplaySwitch\n            }\n            variantMediaOptionById(e) {\n                return this.mediaOptionListQueries[gu.Variant].mediaOptionFromId(e)\n            }\n            alternateMediaOptionById(e, t) {\n                return this.mediaOptionListQueries[e].mediaOptionFromId(t)\n            }\n            enabledAlternateMediaOptionByType(e) {\n                var t = this.enabledMediaOptionIdByType(e);\n                return this.alternateMediaOptionById(e, t)\n            }\n            get enabledVariantMediaOption() {\n                var e = this.enabledMediaOptionIdByType(gu.Variant);\n                return this.variantMediaOptionById(e)\n            }\n            lastLoadedMediaOptionByType(e) {\n                var t;\n                return null === (t = this.getEntity(this.itemId).lastLoadedMediaOptionKeys) || void 0 === t ? void 0 : t[e]\n            }\n            get nextMediaOptionsKeys$() {\n                return this.selectEntity(this.itemId, \"nextMediaOptionKeys\")\n            }\n            get preferredMediaOptions() {\n                return [this.mediaOptionListQueries[0].preferredMediaOptionList, this.mediaOptionListQueries[1].preferredMediaOptionList, this.mediaOptionListQueries[2].preferredMediaOptionList]\n            }\n            get preferredMediaOptions$() {\n                return ed([this.mediaOptionListQueries[0].preferredMediaOptionList$, this.mediaOptionListQueries[1].preferredMediaOptionList$, this.mediaOptionListQueries[2].preferredMediaOptionList$])\n            }\n            get filteredMediaOptions() {\n                return [this.mediaOptionListQueries[0].filteredMediaOptionList, this.mediaOptionListQueries[1].filteredMediaOptionList, this.mediaOptionListQueries[2].filteredMediaOptionList]\n            }\n            getDisabledMediaOption(e) {\n                return {\n                    itemId: this.itemId,\n                    mediaOptionType: e,\n                    mediaOptionId: \"Nah\"\n                }\n            }\n            getEnabledMediaOptionMask() {\n                return this.enabledMediaOptionKeys.map(e => _u(e))\n            }\n            getPreferredMediaOptionsByType$(e) {\n                return this.mediaOptionListQueries[e].preferredMediaOptionList$\n            }\n            altMediaOptionHasValidUrl(e, t) {\n                t = this.alternateMediaOptionById(e, t);\n                return Boolean(null == t ? void 0 : t.url)\n            }\n            get hdrMode$() {\n                return this.mediaOptionListQueries[gu.Variant].hdrMode$\n            }\n            get maxHdcpLevel$() {\n                return this.mediaOptionListQueries[gu.Variant].maxHdcpLevel$\n            }\n            get currentPathwayID() {\n                return this.mediaOptionListQueries[gu.Variant].currentPathwayID\n            }\n            get preferredHost() {\n                return this.mediaOptionListQueries[gu.Variant].preferredHost\n            }\n            getErrorInfoByType(e) {\n                var t;\n                return null != (null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.errorsByType) ? this.rootPlaylistEntity.errorsByType[e] : null\n            }\n            getInFlightFragByType(e) {\n                var t;\n                return null !== (e = null === (t = null === (t = this.getEntity(this.itemId)) || void 0 === t ? void 0 : t.inFlightFrags) || void 0 === t ? void 0 : t[e]) && void 0 !== e ? e : null\n            }\n            getInFlightFragByType$(t) {\n                return this.selectEntity(this.itemId, e => {\n                    return null === (e = null == e ? void 0 : e.inFlightFrags) || void 0 === e ? void 0 : e[t]\n                })\n            }\n            matchAlternates(e, t, i, r) {\n                t = ne(t) ? this.mediaOptionListQueries[gu.AltAudio].getMatchingAlternateWithPersistentId(t, e, r) : void 0, r = ne(i) ? this.mediaOptionListQueries[gu.Subtitle].getMatchingAlternateWithPersistentId(i, e, r) : void 0;\n                return [t || Lu, r || Lu]\n            }\n            getLegacyMatchingAlternateWithPersistentId(e, t, i) {\n                let r = this.mediaOptionListQueries[e].getMatchingAlternateWithPersistentId(t, i, []);\n                return r = r || this.mediaOptionListQueries[e].getMatchingAlternateWithPersistentId(t, void 0, []), r\n            }\n            isValidMediaOptionTuple(i, e) {\n                const r = e || this.getEnabledMediaOptionMask();\n                return [gu.Variant, gu.AltAudio, gu.Subtitle].reduce((e, t) => e && r[t] === _u(i[t]), !0)\n            }\n            matchGroup(e, t, i, r) {\n                var n = e.mediaOptionType;\n                return this.mediaOptionListQueries[n].matchGroup(e, t, i, r)\n            }\n            get preferHDR() {\n                return this.mediaOptionListQueries[gu.Variant].mediaOptionListInfo.preferHDR\n            }\n        }\n        const By = {\n            name: \"rps\"\n        };\n        class Uy {\n            constructor(e, t) {\n                this.store = e, this.logger = t\n            }\n            getQuery() {\n                return new kl(this.store)\n            }\n            getQueryForId(e) {\n                return new Fy(this.store, e)\n            }\n            set rootPlaylistEntity(e) {\n                Do(\"root.add.rootPlaylist\"), this.store.add(e)\n            }\n            removeItems(e) {\n                Do(`root.add.remove ${JSON.stringify(e)}`), this.store.remove(e)\n            }\n            removeAll() {\n                Do(\"root.add.clear\"), this.store.remove()\n            }\n            setRootPlaylistEntity(e, t) {\n                Do(\"root.set.rootPlaylistEntity\"), this.store.update(e, e => t)\n            }\n            setSessionData(e, t) {\n                Do(\"root.set.sessionData\"), this.store.update(e, e => {\n                    e.sessionData = t\n                })\n            }\n            setAnchorTime(e, t) {\n                Do(`root.set.anchorTime: ${null==t?void 0:t.pos} ${null==t?void 0:t.discoSeqNum}`), this.store.update(e, e => {\n                    e.anchorTime = t\n                })\n            }\n            setDiscoSeqNum(e, t) {\n                Do(`root.set.discoSeqNum: ${t}`), this.store.update(e, e => {\n                    e.discoSeqNum = t\n                })\n            }\n            setPendingSeek(e, t) {\n                Do(\"root.set.pendingSeek\"), this.store.update(e, e => {\n                    e.pendingSeek = t\n                }), void 0 === t && fg().setUserSeek(t)\n            }\n            setEnabledMediaOptionSwitchContextByType(e, i, r, n) {\n                this.store.update(e, e => {\n                    var t;\n                    if (e.enabledMediaOptionKeys[i].mediaOptionId === r) {\n                        const r = null !== (t = e.mediaOptionSwitchContexts) && void 0 !== t ? t : [null, null, null];\n                        r[i] = n ? {\n                            userInitiated: n.userInitiated,\n                            switchPosition: n.switchPosition\n                        } : null, e.mediaOptionSwitchContexts = r\n                    } else Do(`root.set.mediaOptionSwitchContextByType ${r} doesn't match existing mediaOption ${e.enabledMediaOptionKeys[i].mediaOptionId}`)\n                })\n            }\n            setEnabledVariantMediaOptionIdBeforeTrickplaySwitch(e, t) {\n                this.store.update(e, e => {\n                    e.enabledVariantMediaOptionIdBeforeTrickplaySwitch = t\n                })\n            }\n            setEnabledMediaOptionByType(r, n, s, a = !1, o) {\n                s = s || {\n                    itemId: r,\n                    mediaOptionType: n,\n                    mediaOptionId: \"Nah\"\n                }, this.store.update(r, e => {\n                    var t;\n                    const i = null !== (t = [...e.enabledMediaOptionKeys]) ? t : [Lu, Lu, Lu];\n                    if (i[n] = {\n                            itemId: r,\n                            mediaOptionId: s.mediaOptionId\n                        }, this._updateEnabledMediaOptionKeys(e, i), a) {\n                        const r = null !== (t = e.mediaOptionSwitchContexts) && void 0 !== t ? t : [null, null, null];\n                        r[n] = o ? {\n                            userInitiated: o.userInitiated,\n                            switchPosition: o.switchPosition\n                        } : null, e.mediaOptionSwitchContexts = r\n                    }\n                })\n            }\n            _associateForcedSubtitleWithClosedCaption(e, t, i, r) {\n                if ((null == i ? void 0 : i.mediaType) === Su.CLOSEDCAPTION) {\n                    t = r.variantMediaOptionById(t), r = r.mediaOptionListQueries[gu.Subtitle].packageAlternateMediaOption(t, i, !0);\n                    if (r.url !== i.url) {\n                        const n = jy(t, r, e.mediaOptionListTuple[gu.Subtitle].mediaOptions, Qe());\n                        e.mediaOptionListTuple[gu.Subtitle].mediaOptions = n\n                    }\n                }\n            }\n            _updateEnabledMediaOptionKeys(t, i) {\n                var e, r;\n                const n = null !== (e = t.enabledMediaOptionKeys) && void 0 !== e ? e : [Lu, Lu, Lu];\n                let s;\n                for (let e = 0; e < i.length; ++e) {\n                    var a = i[e],\n                        o = n[e].mediaOptionId !== a.mediaOptionId;\n                    if (o && (n[e] = Object.assign({}, a)), e === gu.Variant) {\n                        const i = this.getQueryForId(a.itemId).mediaOptionListQueries[e].mediaOptionList;\n                        o ? t.abrStatus = (r = a.mediaOptionId, o = i, o = Xg(r, o), {\n                            fragDownloadSlow: !1,\n                            fragDownloadTooSlow: !1,\n                            nextMinAutoOptionId: Lu.mediaOptionId,\n                            nextMaxAutoOptionId: Lu.mediaOptionId,\n                            highBWTrigger: o\n                        }) : t.abrStatus.highBWTrigger = Xg(a.mediaOptionId, i), s = a\n                    } else if (e === gu.Subtitle && _u(a)) {\n                        const i = this.getQueryForId(a.itemId),\n                            n = i.alternateMediaOptionById(e, a.mediaOptionId);\n                        this._associateForcedSubtitleWithClosedCaption(t, s.mediaOptionId, n, i)\n                    }\n                }\n                t.enabledMediaOptionKeys = n, t.nextMediaOptionKeys = void 0\n            }\n            setManualMode(e, t) {\n                this.store.update(e, e => {\n                    e.manualMode = t\n                })\n            }\n            setEnabledMediaOptions(e, i) {\n                this.store.update(e, e => {\n                    var t = i.map(({\n                        mediaOptionId: e,\n                        itemId: t\n                    }) => ({\n                        mediaOptionId: e,\n                        itemId: t\n                    }));\n                    this._updateEnabledMediaOptionKeys(e, t)\n                })\n            }\n            setEnabledMediaOptionsAndSwitchContexts(e, i, r) {\n                this.store.update(e, e => {\n                    var t = i.map(({\n                        mediaOptionId: e,\n                        itemId: t\n                    }) => ({\n                        mediaOptionId: e,\n                        itemId: t\n                    }));\n                    this._updateEnabledMediaOptionKeys(e, t), e.mediaOptionSwitchContexts = r\n                })\n            }\n            setNextMediaOptions(e, i) {\n                Do(`root.set.nextMediaOptions: ${JSON.stringify(null==i?void 0:i.map(e=>e.mediaOptionId))}`), this.store.update(e, e => {\n                    var t = i ? i.map(({\n                        itemId: e,\n                        mediaOptionId: t\n                    }) => ({\n                        itemId: e,\n                        mediaOptionId: t\n                    })) : null;\n                    e.nextMediaOptionKeys = t\n                })\n            }\n            updateEnabledMediaOptions(e) {\n                Do(\"root.set.updateEnabledMediaOptions\"), this.store.update(e, e => {\n                    e.nextMediaOptionKeys && !0 !== e.manualMode && (Do(`root.set.updateEnabledMediaOptions ${JSON.stringify(e.nextMediaOptionKeys)}`), this._updateEnabledMediaOptionKeys(e, [...e.nextMediaOptionKeys])), e.nextMediaOptionKeys = void 0\n                })\n            }\n            setLastLoadedMediaOptionByType(r, n, s) {\n                Do(`root.set.lastLoadedMediaOptionByType: ${n} ${(s=s||{itemId:r,mediaOptionType:n,mediaOptionId:\"Nah\"}).mediaOptionId}`), this.store.update(r, e => {\n                    var t;\n                    const i = null !== (t = e.lastLoadedMediaOptionKeys) && void 0 !== t ? t : [Lu, Lu, Lu];\n                    i[n] = {\n                        itemId: r,\n                        mediaOptionId: s.mediaOptionId\n                    }, e.lastLoadedMediaOptionKeys = i\n                })\n            }\n            setPreferredHost(e, t) {\n                Do(`root.set.preferredHost: ${t}`), this.store.update(e, e => {\n                    e && (e.mediaOptionListTuple[gu.Variant].preferredHost = t)\n                })\n            }\n            setViewportInfo(e, t) {\n                Do(`root.set.viewportInfo: ${JSON.stringify(t)}`), this.store.update(e, e => {\n                    e && (e.mediaOptionListTuple[gu.Variant].viewportInfo = t)\n                })\n            }\n            static getExistingPersistentIds(e) {\n                var t;\n                const i = {},\n                    r = null === (t = e.enabledMediaOptionKeys[gu.AltAudio]) || void 0 === t ? void 0 : t.mediaOptionId;\n                if (\"Nah\" !== r) {\n                    const s = e.mediaOptionListTuple[gu.AltAudio],\n                        t = Km(s.mediaOptions, Ny.kAllowFilters, s).find(e => e.mediaOptionId === r);\n                    i.audioPersistentId = null == t ? void 0 : t.persistentID\n                }\n                const n = null === (t = e.enabledMediaOptionKeys[gu.Subtitle]) || void 0 === t ? void 0 : t.mediaOptionId;\n                if (\"Nah\" !== n) {\n                    const s = e.mediaOptionListTuple[gu.Subtitle],\n                        t = Km(s.mediaOptions, Ny.kAllowFilters, s).find(e => e.mediaOptionId === n);\n                    i.subtitlePersistentId = null == t ? void 0 : t.persistentID\n                }\n                return i\n            }\n            static doUpdateRootHDRSwitch(e, t, i, r) {\n                const n = e.mediaOptionListTuple.map(e => Object.assign({}, e));\n                n[gu.Variant].preferHDR = t, n[gu.Variant].hasHdrLevels = i;\n                const s = mg(),\n                    a = sy.getEntity(e.itemId),\n                    o = Zf(e.itemId),\n                    l = o.getBandwidthEstimate(s, null == a ? void 0 : a.serviceName),\n                    d = o.getPlaylistEstimate(s, null == a ? void 0 : a.serviceName),\n                    u = o.getFragEstimate(s, null == a ? void 0 : a.serviceName),\n                    c = o.getBufferEstimate(s, null == a ? void 0 : a.serviceName),\n                    h = {\n                        targetDuration: u.maxDurationSec || (null == s ? void 0 : s.defaultTargetDuration),\n                        targetStartupMs: null == s ? void 0 : s.targetStartupMs\n                    },\n                    p = Uy.getExistingPersistentIds(e);\n                return Qy(Object.assign(Object.assign({}, e), {\n                    mediaOptionListTuple: n,\n                    nextMediaOptionKeys: null\n                }), p, r, l, h, d, u, c)\n            }\n            switchToSDROnly(e) {\n                Do(\"root.switchToSDROnly\"), this.store.update(e, e => {\n                    var t = Uy.doUpdateRootHDRSwitch(e, !1, !1, this.logger)[\"mediaOptionListTuple\"];\n                    e.mediaOptionListTuple = t\n                })\n            }\n            setHDRPreference(e, i, r) {\n                Do(`root.set.HDRPreference: ${i}`), this.store.update(e, e => {\n                    var t = e.mediaOptionListTuple[gu.Variant];\n                    if (t.preferHDR !== i && (!i || t.hasHdrLevels)) {\n                        t = Uy.doUpdateRootHDRSwitch(e, i, t.hasHdrLevels, this.logger);\n                        if (r) return t;\n                        e.mediaOptionListTuple = t.mediaOptionListTuple\n                    }\n                })\n            }\n            setPathwayPriority(e, i) {\n                Do(`root.set.PathwayPriority: [ ${i.join(\", \")} ]`), this.store.update(e, e => {\n                    if (e) {\n                        const t = e.mediaOptionListTuple[gu.Variant];\n                        t.pathwayPriority = i, t.preferredHost = null\n                    }\n                })\n            }\n            setCurrentPathwayID(e, t) {\n                Do(`root.set.currentPathwayID: ${t}`), this.store.update(e, e => {\n                    e && (e.mediaOptionListTuple[gu.Variant].currentPathwayID = t)\n                })\n            }\n            setInitPTS(e, t, i, r, n, s) {\n                Do(`root.set.initPTS: ${e} ${t} variantDTS:${JSON.stringify(i)} timelineOffset: ${r}`), this.store.update(e, e => {\n                    e.initPtsRecord[t] = {\n                        variantDTS: i,\n                        timelineOffset: r,\n                        offsetTimestamp: n,\n                        iframeMode: s\n                    }\n                })\n            }\n            static prunePenaltyBox(e, t) {\n                return e.filter(e => !(e.expiry <= t))\n            }\n            static addToPenaltyBox(e, t, i) {\n                return e.push({\n                    mediaOptionId: i,\n                    expiry: t + 12e4\n                })\n            }\n            addToPenaltyBox(e, r, n) {\n                Do(`root.set.penaltyBox: ${r}: ${n}`), this.store.update(e, ({\n                    mediaOptionListTuple: e\n                }) => {\n                    const t = e[r],\n                        i = performance.now();\n                    t.penaltyBoxQueue = Uy.prunePenaltyBox(t.penaltyBoxQueue, i), Uy.addToPenaltyBox(t.penaltyBoxQueue, i, n)\n                })\n            }\n            prunePenaltyBox(e, r = null) {\n                Do(`root.set.prunePenaltyBox: ${r}`), this.store.update(e, ({\n                    mediaOptionListTuple: e\n                }) => {\n                    var e = r ? [e[r]] : e,\n                        t = performance.now();\n                    for (const i of e) i.penaltyBoxQueue = Uy.prunePenaltyBox(i.penaltyBoxQueue, t)\n                })\n            }\n            removePermanently(e, r, n) {\n                Do(`root.set.removePermanently: ${r}: ${n}`), this.store.update(e, ({\n                    mediaOptionListTuple: e\n                }) => {\n                    const t = e[r],\n                        i = new Set(t.removed);\n                    i.add(n), t.removed = Array.from(i)\n                })\n            }\n            moveAllWithMatchingHosts(e, r, n, s) {\n                Do(`root.set.moveAllMatchingHosts: ${r}:${n} remove:${s}`), this.store.update(e, ({\n                    mediaOptionListTuple: e\n                }) => {\n                    const t = e[r],\n                        i = [...t.mediaOptions].filter(e => Au(n, e.url)).map(e => e.mediaOptionId);\n                    if (s) {\n                        const e = new Set([...t.removed, ...i]);\n                        t.removed = Array.from(e)\n                    } else {\n                        const e = performance.now();\n                        t.penaltyBoxQueue = Uy.prunePenaltyBox(t.penaltyBoxQueue, e);\n                        for (const r of i) Uy.addToPenaltyBox(t.penaltyBoxQueue, e, r)\n                    }\n                })\n            }\n            setMaxHdcpLevel(e, i, r = !1) {\n                Do(`root.set.maxHdcpLevel: ${i}`), this.store.update(e, ({\n                    mediaOptionListTuple: e\n                }) => {\n                    const t = e[gu.Variant];\n                    (r || um(i) < um(t.maxHdcpLevel)) && (t.maxHdcpLevel = i)\n                })\n            }\n            updateConsecutiveTimeouts(e, i, r, n) {\n                this.store.update(e, e => {\n                    const t = e.errorsByType || [{\n                        timeouts: {\n                            load: 0,\n                            append: 0,\n                            key: 0\n                        }\n                    }, {\n                        timeouts: {\n                            load: 0,\n                            append: 0,\n                            key: 0\n                        }\n                    }, {\n                        timeouts: {\n                            load: 0,\n                            append: 0,\n                            key: 0\n                        }\n                    }];\n                    r ? ++t[i].timeouts[n] : t[i].timeouts[n] = 0, e.errorsByType = t\n                })\n            }\n            updateInflightFrag(l, d, u, c, h) {\n                Do(\"root.set.updateInflightFrag\"), this.store.update(l, r => {\n                    if (r.inFlightFrags || (r.inFlightFrags = [null, null]), !(d === gu.Subtitle || u && u.itemId !== l))\n                        if (u) {\n                            let {\n                                start: e,\n                                duration: t\n                            } = u;\n                            var {\n                                mediaOptionId: n,\n                                mediaSeqNum: s,\n                                discoSeqNum: a\n                            } = u, o = r.inFlightFrags[d];\n                            let i = null == o ? void 0 : o.tstart;\n                            c !== (null == o ? void 0 : o.state) && (i = performance.now()), $p(o, u) && (e = o.start, t = o.duration), r.inFlightFrags[d] = {\n                                itemId: l,\n                                mediaOptionId: n,\n                                mediaSeqNum: s,\n                                discoSeqNum: a,\n                                start: e,\n                                duration: t,\n                                tstart: i,\n                                state: c,\n                                bwSample: Object.assign({}, h)\n                            }\n                        } else r.inFlightFrags[d] = null\n                })\n            }\n            setNextMaxAutoOptionId(e, t) {\n                Do(`root.set.nextMaxAutoOptionId: ${t}`), this.store.update(e, ({\n                    abrStatus: e\n                }) => {\n                    e.nextMaxAutoOptionId = t\n                })\n            }\n            setNextMinAutoOptionId(e, t) {\n                Do(`root.set.nextMinAutoOptionId: ${t}`), this.store.update(e, ({\n                    abrStatus: e\n                }) => {\n                    e.nextMinAutoOptionId = t\n                })\n            }\n            setHighBWTrigger(e, t) {\n                Do(`root.set.setHighBWTrigger: ${t}`), this.store.update(e, ({\n                    abrStatus: e\n                }) => {\n                    e.highBWTrigger = t\n                })\n            }\n            setFragLoadSlow(e, t) {\n                Do(`root.set.setFragLoadSlow ${e} ${JSON.stringify(t)}`), this.store.update(e, ({\n                    abrStatus: e\n                }) => {\n                    e.fragDownloadSlow = t.fragDownloadSlow, e.fragDownloadTooSlow = t.fragDownloadTooSlow\n                })\n            }\n            pickMediaOptionTupleByPersistentId(e, t, i, r = !1, n = !1) {\n                var s = e.enabledMediaOptionIdByType(gu.Variant),\n                    s = e.variantMediaOptionById(s);\n                let a, o;\n                if (t === gu.AltAudio) {\n                    const t = e.enabledAlternateMediaOptionByType(gu.Subtitle);\n                    o = null == t ? void 0 : t.persistentID, a = i\n                } else {\n                    const t = e.enabledAlternateMediaOptionByType(gu.AltAudio);\n                    a = null == t ? void 0 : t.persistentID, o = i\n                }\n                const l = e.getEnabledMediaOptionMask();\n                return l[t] = !!(ne(i) && 0 <= i), s ? this.getBestMediaOptionTupleFromVariantAndPersistentId(e, s, a, o, l, void 0, r, n, !1) : [Lu, Lu, Lu]\n            }\n            getFallbackMediaOptionTupleFromMediaOptionId(e, t, i, r, n = !1, s = !1, a = !1) {\n                var o = r ? [r] : [i],\n                    l = e.enabledMediaOptionIdByType(gu.Variant),\n                    r = e.variantMediaOptionById(l),\n                    l = t === gu.AltAudio ? e.alternateMediaOptionById(gu.AltAudio, i) : e.enabledAlternateMediaOptionByType(gu.AltAudio),\n                    l = null == l ? void 0 : l.persistentID,\n                    i = t === gu.Subtitle ? e.alternateMediaOptionById(gu.Subtitle, i) : e.enabledAlternateMediaOptionByType(gu.Subtitle),\n                    i = null == i ? void 0 : i.persistentID;\n                return r ? this.getBestMediaOptionTupleFromVariantAndPersistentId(e, r, l, i, void 0, o, n, s, a) : [Lu, Lu, Lu]\n            }\n            hasFallbackMediaOptionTuple(e, t, i, r) {\n                var n = e.mediaOptionListQueries[t].mediaOptionFromId(i);\n                return e.isValidMediaOptionTuple(this.getFallbackMediaOptionTupleFromMediaOptionId(e, t, i, n.backingMediaOptionId, !1, r))\n            }\n            setLegacyAlternateMediaOption(e, t, i, r, n) {\n                var s = e.enabledMediaOptionIdByType(gu.Variant),\n                    s = e.variantMediaOptionById(s),\n                    s = e.getLegacyMatchingAlternateWithPersistentId(i, r, s);\n                s ? this.setEnabledMediaOptionByType(t, i, s, !0, n) : this.logger.warn(`${Nu[i]} can't find matching mediaOption for persistent id ${r}`)\n            }\n            setEnabledMediaOptionTupleWithMatchedGroups(t, i, e, r) {\n                const n = Ky(t),\n                    s = this.pickMediaOptionTupleByPersistentId(n, i, e);\n                if (!n.isValidMediaOptionTuple(s)) return this.setLegacyAlternateMediaOption(n, t, i, e, r);\n                al(() => {\n                    this.setEnabledMediaOptionByType(t, i, s[i], !0, r), s[gu.Variant].mediaOptionId !== n.enabledMediaOptionIdByType(gu.Variant) && this.setPreferredHost(t, Eu(s[gu.Variant].url)), this.setEnabledMediaOptionByType(t, gu.Variant, s[gu.Variant]);\n                    var e = i === gu.AltAudio ? gu.Subtitle : gu.AltAudio;\n                    s[e].mediaOptionId !== n.enabledMediaOptionIdByType(e) && this.setEnabledMediaOptionByType(t, e, s[e], !1)\n                })\n            }\n            canSwitchToSDR(e, t, i, r = !1) {\n                var n = e.mediaOptionListQueries[gu.Variant].mediaOptionFromId(t),\n                    r = this.getFallbackMediaOptionTupleFromMediaOptionId(e, gu.Variant, t, n.backingMediaOptionId, !0, i, r);\n                return e.isValidMediaOptionTuple(r)\n            }\n            getBestMediaOptionTupleFromVariantAndPersistentId(t, e, i, r, n, s, a, o, l) {\n                var d, u = t.mediaOptionListQueries[gu.Variant].listFallbackVariants(e.mediaOptionId, a, o, l, s);\n                let c = [Lu, Lu, Lu];\n                for (let e = 0; e < u.length; ++e) {\n                    const a = u[e];\n                    if (d = t.matchAlternates(a, i, r, s), t.isValidMediaOptionTuple([a, ...d], n)) {\n                        c = [a, ...d];\n                        break\n                    }\n                }\n                return c\n            }\n        }\n        const $y = new class extends fl {\n            constructor() {\n                super({}, {\n                    name: \"root-playlist-store\",\n                    idKey: \"itemId\",\n                    producerFn: su\n                })\n            }\n            akitaPreAddEntity(e) {\n                return null == e.errorsByType ? Object.assign(Object.assign({}, e), {\n                    errorsByType: [{\n                        timeouts: {\n                            load: 0,\n                            append: 0,\n                            key: 0\n                        }\n                    }, {\n                        timeouts: {\n                            load: 0,\n                            append: 0,\n                            key: 0\n                        }\n                    }, {\n                        timeouts: {\n                            load: 0,\n                            append: 0,\n                            key: 0\n                        }\n                    }]\n                }) : e\n            }\n        };\n        new kl($y);\n        let Vy = null;\n\n        function Ky(e) {\n            return new Fy($y, e)\n        }\n        const qy = (n, e, t, s, i) => {\n            const {\n                rootMediaOptionsTuple: r,\n                sessionKeys: a\n            } = n, o = Array.from(r[gu.Variant]), l = Array.from(r[gu.AltAudio]);\n            let d = !1,\n                u = !1,\n                c = o.map(e => (d = d || Boolean(e.videoCodec), u = u || Boolean(e.audioCodec) || Boolean(e.audioGroupId), e));\n            return d && u && (c = c.filter(({\n                videoCodec: e\n            }) => Boolean(e))), Ly(o, l, a, e, t, i).pipe(hr(({\n                hdrMediaOptions: e,\n                sdrMediaOptions: t\n            }) => {\n                var i = e.concat(t),\n                    r = 0 < e.length;\n                return e.concat(t),\n                    function(e, t, i, r) {\n                        var {\n                            itemId: n,\n                            itemStartOffset: s,\n                            rootMediaOptionsTuple: a,\n                            audioMediaSelectionGroup: o,\n                            subtitleMediaSelectionGroup: l\n                        } = e, d = Array.from(a[gu.AltAudio]), u = Array.from(a[gu.Subtitle]), c = t.every(e => ne(e.score)), h = t.some(e => Wm(!0, e)), p = function(e, t) {\n                            const i = [...e];\n                            return t ? i.sort((e, t) => e.score - t.score || t.bitrate - e.bitrate) : i.sort((e, t) => e.bitrate - t.bitrate), i\n                        }(t, c), f = e.baseUrl, t = null === (a = e.contentSteeringOption) || void 0 === a ? void 0 : a.initPathwayID, a = e.sessionData;\n                        return {\n                            itemId: n,\n                            baseUrl: f,\n                            mediaOptionListTuple: [{\n                                mediaOptions: p,\n                                hasHdrLevels: i,\n                                hasIframeLevels: h,\n                                hasScore: c,\n                                preferHDR: r,\n                                compatibleIds: null,\n                                penaltyBoxQueue: [],\n                                removed: [],\n                                currentPathwayID: t\n                            }, {\n                                mediaOptions: d,\n                                compatibleIds: null,\n                                penaltyBoxQueue: [],\n                                removed: []\n                            }, {\n                                mediaOptions: u,\n                                penaltyBoxQueue: [],\n                                removed: []\n                            }],\n                            audioMediaSelectionGroup: o,\n                            subtitleMediaSelectionGroup: l,\n                            enabledMediaOptionKeys: [Lu, Lu, Lu],\n                            mediaOptionSwitchContexts: [null, null, null],\n                            anchorTime: {\n                                pos: 0\n                            },\n                            discoSeqNum: NaN,\n                            pendingSeek: void 0,\n                            itemStartOffset: s,\n                            initPtsRecord: {},\n                            contentSteeringOption: e.contentSteeringOption,\n                            masterVariableList: e.masterVariableList,\n                            loadStats: e.stats,\n                            isMediaPlaylist: e.isMediaPlaylist,\n                            abrStatus: {\n                                fragDownloadSlow: !1,\n                                fragDownloadTooSlow: !1,\n                                nextMinAutoOptionId: Lu.mediaOptionId,\n                                nextMaxAutoOptionId: Lu.mediaOptionId,\n                                highBWTrigger: NaN\n                            },\n                            sessionData: a\n                        }\n                    }(n, i, r, s)\n            }))\n        };\n\n        function Hy(e, t, i, r, n, s, a) {\n            var o, l, d, u, c, h, p, f = e.mediaOptionListTuple[gu.Variant],\n                m = Km(f.mediaOptions, Xm.kAllowFilters, Object.assign(Object.assign({}, f), {\n                    compatibleIds: null\n                })),\n                g = qm(f.preferredHost, m);\n            return {\n                firstVariant: (o = g, e = Fg, f = f.hasScore, t = t, i = i, r = r, n = n, s = s, a = a, !o || o.length < 1 || o.every(e => e.iframes) ? void t.warn(\"no non-iframe media option found\") : ((o = f ? Bg(o, i, r, n, s, a) : (l = e, d = i, u = r, c = n, h = s, p = a, o.reduce((e, t) => {\n                    if (t.iframes) return e;\n                    let i = e;\n                    const r = function(e, t, i, r, n, s, a) {\n                        var o, l, d = (o = e.bitrate, u = e.height, (l = (e, t, i) => (e - t) * (e - i) <= 0)(o, t.minValidBitrate, t.maxValidBitrate) && l(u, t.minValidHeight, t.maxValidHeight) ? mu.VALID : mu.INVALID),\n                            o = \"PQ\" === (c = e.videoRange) ? pu.PQ : \"HLG\" === c ? pu.HLG : \"SDR\" === c ? pu.SDR : pu.UNKNOWN,\n                            {\n                                videoCodecRank: u,\n                                audioCodecRank: c\n                            } = {\n                                videoCodecRank: qp((l = e).videoCodec),\n                                audioCodecRank: jp(l.audioCodec)\n                            },\n                            l = e.bitrate < t.maxPreferredBitrate ? mu.VALID : mu.INVALID,\n                            t = e.audioChannelCount || 1,\n                            a = i && r && n && s && !Ug(e, i, r, n, s, a) ? mu.INVALID : mu.VALID;\n                        return new Qp(d, o, u, t, c, a, l, e.height)\n                    }(t, l, d, u, c, h, p);\n                    return (!e || r.isGreaterThan(e.bestRank) || r.isEqualTo(e.bestRank) && t.bitrate > e.selected.bitrate) && (i = {\n                        selected: t,\n                        bestRank: r\n                    }), i\n                }, null).selected)) || t.warn(\"no valid first media option found\"), o)),\n                filteredVariants: m,\n                preferredVariants: g\n            }\n        }\n\n        function jy(e, t, i) {\n            if ((null == t ? void 0 : t.mediaType) === Su.CLOSEDCAPTION) {\n                const r = Ny.pairForcedSubtitleMediaOptionWithClosedCaptionInList(e.subtitleGroupId, t, i);\n                if (r) return t = Object.assign(Object.assign({}, t), {\n                    url: r.url,\n                    backingMediaOptionId: r.mediaOptionId\n                }), i.map(e => e.mediaOptionId === t.mediaOptionId ? t : e)\n            }\n            return i\n        }\n\n        function Qy(e, t, i, r, n, s, a, o) {\n            var l;\n            const d = e.itemId,\n                u = e.mediaOptionListTuple[gu.Variant],\n                c = e.mediaOptionListTuple[gu.AltAudio],\n                h = e.mediaOptionListTuple[gu.Subtitle],\n                p = Km(c.mediaOptions, Ny.kAllowFilters, c),\n                f = Km(h.mediaOptions, Ny.kAllowFilters, h);\n            let {\n                firstVariant: m,\n                filteredVariants: g\n            } = Hy(e, i, r, n, s, a, o);\n            if (!m) {\n                const U = u.preferHDR;\n                u.preferHDR = !U && u.hasHdrLevels, u.preferHDR !== U && (i.warn(`No valid first variant found, toggling hdr preference=${U}->${u.preferHDR}`), {\n                    firstVariant: m,\n                    filteredVariants: g\n                } = Hy(e, i, r, n, s, a, o))\n            }\n            if (!m) throw new V(!0, \"No valid first variant found\", $.NoValidAlternates);\n            const y = Eu(m.url),\n                v = {\n                    itemId: d,\n                    mediaOptionId: null !== (o = null == m ? void 0 : m.mediaOptionId) && void 0 !== o ? o : null\n                },\n                S = null != p && p.length ? null === (o = ((i, r, e, n) => {\n                    if (e) {\n                        let t;\n                        return t = ne(i) ? e.MediaSelectionGroupOptions.find(function(e) {\n                            return e.MediaSelectionOptionsPersistentID === i\n                        }) : e.MediaSelectionGroupOptions.find(function(e) {\n                            return e.MediaSelectionOptionsIsDefault\n                        }), t = t || e.MediaSelectionGroupOptions[0], n.find(e => (!r || e.groupId === r) && e.persistentID === (null == t ? void 0 : t.MediaSelectionOptionsPersistentID))\n                    }\n                })(null == t ? void 0 : t.audioPersistentId, m.audioGroupId, e.audioMediaSelectionGroup, p)) || void 0 === o ? void 0 : o.mediaOptionId : null,\n                b = S ? {\n                    itemId: d,\n                    mediaOptionId: S\n                } : Lu,\n                T = ((i, r, n, s, a, o) => {\n                    if (s) {\n                        let t, e;\n                        return t = ne(i) ? s.MediaSelectionGroupOptions.find(function(e) {\n                            return e.MediaSelectionOptionsPersistentID === i\n                        }) : s.MediaSelectionGroupOptions.find(function(e) {\n                            return e.MediaSelectionOptionsIsDefault\n                        }), t && (e = a.find(e => e.mediaType === Su.CLOSEDCAPTION ? (!r || e.groupId === r) && e.persistentID === t.MediaSelectionOptionsPersistentID : e.mediaType === Su.SUBTITLE ? (!n || e.groupId === n) && e.persistentID === t.MediaSelectionOptionsPersistentID : void o.warn(By, `subtitle media option has unknown type ${e.mediaType}`))), e\n                    }\n                })(null == t ? void 0 : t.subtitlePersistentId, m.closedcaption, m.subtitleGroupId, e.subtitleMediaSelectionGroup, f, i),\n                E = null != f && f.length ? null == T ? void 0 : T.mediaOptionId : null,\n                I = E ? {\n                    itemId: d,\n                    mediaOptionId: E,\n                    mediaOptionType: gu.Subtitle\n                } : Lu,\n                {\n                    mediaOptions: w,\n                    audioGroups: A,\n                    subtitleGroups: O\n                } = (t = g, l = m, t.reduce((e, t) => {\n                    if (((e, t) => {\n                            let i = !0;\n                            e.videoCodec && t.videoCodec && (i = be.isCompatibleVideoCodec(e.videoCodec, t.videoCodec));\n                            let r = !1;\n                            e.videoRange && t.videoRange ? r = e.videoRange == t.videoRange : e.videoRange || t.videoRange || (r = !0);\n                            let n = !0;\n                            return e.audioCodec && t.audioCodec && (n = be.isCompatibleAudioCodec(e.audioCodec, t.audioCodec)), i && r && n\n                        })(l, t)) {\n                        const l = t.audioGroupId;\n                        l && e.audioGroups.add(l), e.mediaOptions.add(t)\n                    }\n                    var i = t.subtitleGroupId;\n                    i && e.subtitleGroups.add(i);\n                    t = t.closedcaption;\n                    return t && e.closedCaptionGroups.add(t), e\n                }, {\n                    mediaOptions: new Set,\n                    audioGroups: new Set,\n                    subtitleGroups: new Set,\n                    closedCaptionGroups: new Set\n                })),\n                k = Array.from(w).map(e => e.mediaOptionId),\n                C = m.pathwayID,\n                D = Object.assign(Object.assign({}, u), {\n                    compatibleIds: k,\n                    preferredHost: y,\n                    currentPathwayID: C\n                }),\n                M = [],\n                x = c.mediaOptions.reduce((e, t) => (A.has(t.groupId) && (e.persistentIds.add(t.persistentID), M.push(t.mediaOptionId), e.filteredAudioMediaOptions.push(t), e.altAudio || (e.altAudio = !!t.url)), e), {\n                    filteredAudioMediaOptions: [],\n                    persistentIds: new Set,\n                    altAudio: !1\n                }),\n                P = Object.assign(Object.assign({}, c), {\n                    compatibleIds: M\n                });\n            let R = e.audioMediaSelectionGroup;\n            const L = null == R ? void 0 : R.MediaSelectionGroupOptions;\n            if (L) {\n                const e = L.reduce((e, t) => (x.persistentIds.has(t.MediaSelectionOptionsPersistentID) && e.push(t), e), new Array);\n                R = Object.assign(Object.assign({}, R), {\n                    MediaSelectionGroupOptions: e\n                })\n            }\n            h.mediaOptions = jy(m, T, h.mediaOptions);\n            const _ = h.mediaOptions.reduce((e, t) => (O.has(t.groupId) && (e.persistentIds.add(t.persistentID), e.filteredSubtitleMediaOptions.push(t)), e), {\n                filteredSubtitleMediaOptions: [],\n                persistentIds: new Set\n            });\n            let N = e.subtitleMediaSelectionGroup;\n            const F = null == N ? void 0 : N.MediaSelectionGroupOptions;\n            if (F) {\n                const e = F.reduce((e, t) => (_.persistentIds.has(t.MediaSelectionOptionsPersistentID) && e.push(t), e), new Array);\n                N = Object.assign(Object.assign({}, N), {\n                    MediaSelectionGroupOptions: e\n                })\n            }\n            i = [D, P, h];\n            let B = new Map;\n            mg().useHighestVideoCodecPrivate && (B = null == D ? void 0 : D.mediaOptions.reduce((e, t) => {\n                const i = t.videoCodecList;\n                if (i)\n                    for (const t of i) {\n                        const i = Hp(t),\n                            r = e.get(i);\n                        be.isHigherCodecByFamily(r, t) && e.set(i, t)\n                    }\n                return e\n            }, B)), B.size && B.forEach((e, t) => {});\n            t = {\n                fragDownloadSlow: !1,\n                fragDownloadTooSlow: !1,\n                nextMinAutoOptionId: Lu.mediaOptionId,\n                nextMaxAutoOptionId: Lu.mediaOptionId,\n                highBWTrigger: Xg(v.mediaOptionId, D.mediaOptions)\n            };\n            return Object.assign(Object.assign({}, e), {\n                enabledMediaOptionKeys: [v, b, I],\n                mediaOptionListTuple: i,\n                audioMediaSelectionGroup: R,\n                abrStatus: t,\n                highestVideoCodec: B\n            })\n        }\n        const Wy = (o, l, d, u, c, h, p) => e => e.pipe(tc(\"retrieveRootMediaOptions.input\"), La(t => {\n            var e;\n            if (!t) return Ii;\n            const {\n                itemId: i,\n                platformInfo: r\n            } = t, n = Ky(i), s = l[\"logger\"];\n            if (n.hasEntity(i)) return $i(n);\n            $y.setLoading(!0);\n            const a = performance.now();\n            return function(e, t, u, c, i) {\n                const {\n                    itemId: h,\n                    url: p,\n                    itemStartOffset: f\n                } = e, r = Lc(e, t);\n                return Lm({\n                    url: p,\n                    onProgress: {\n                        getData: !0,\n                        cb: Iy\n                    },\n                    xhrSetup: c.xhrSetup\n                }, r, i).pipe(hr(({\n                    responseText: e,\n                    responseURL: t,\n                    stats: i\n                }) => {\n                    var r = c[\"keySystemPreference\"];\n                    if (t || (u.warn(\"Missing response url. Reusing request url as base url\"), t = p), Rm.isMediaPlaylist(e)) {\n                        const c = \"media-pl-\" + Zl(),\n                            d = Rm.parseMediaOptionPlaylist(e, t, !0, r, {}, h, c, gu.Variant, u, f);\n                        Nc(d.mediaOptionDetails);\n                        var n = {\n                            itemId: h,\n                            mediaOptionId: c,\n                            mediaOptionType: gu.Variant,\n                            url: p,\n                            bandwidth: 0,\n                            bitrate: 0,\n                            iframes: d.mediaOptionDetails.iframesOnly,\n                            pathwayID: \".\"\n                        };\n                        return {\n                            itemId: h,\n                            itemStartOffset: f,\n                            rootMediaOptionsTuple: [\n                                [n],\n                                [],\n                                []\n                            ],\n                            stats: i,\n                            baseUrl: t,\n                            initialDetails: d.mediaOptionDetails,\n                            isMediaPlaylist: !0\n                        }\n                    } {\n                        const u = Rm.parseSessionData(e, t),\n                            c = Rm.parseSessionKeys(e, t, r),\n                            p = Rm.parseRootPlaylist(h, e, t, !0);\n                        if (p.playlistParsingError) throw p.playlistParsingError;\n                        var {\n                            variantMediaOptions: s,\n                            contentSteeringOption: a,\n                            masterVariableList: o\n                        } = p, l = Rm.parseRootPlaylistAlternateMediaOptions(h, e, t, p.variantMediaOptions, !0, o);\n                        if (l.playlistParsingError) throw l.playlistParsingError;\n                        var {\n                            audioAlternateOptions: n,\n                            subtitleAlternateOptions: r,\n                            audioMediaSelectionGroup: e,\n                            subtitleMediaSelectionGroup: l\n                        } = l.alternateMediaInfo;\n                        return {\n                            itemId: h,\n                            itemStartOffset: f,\n                            rootMediaOptionsTuple: [s, n, r],\n                            stats: i,\n                            baseUrl: t,\n                            audioMediaSelectionGroup: e,\n                            subtitleMediaSelectionGroup: l,\n                            contentSteeringOption: a,\n                            sessionData: u,\n                            sessionKeys: c,\n                            masterVariableList: o\n                        }\n                    }\n                }), e => e.pipe(Vn(e => {\n                    if (e instanceof pc) throw new dc(!1, \"Timeout\", 0, $.ManifestTimeoutError, !0);\n                    if (e instanceof oc) throw new dc(!1, e.message, e.code, {\n                        code: e.code,\n                        text: \"Manifest network error\"\n                    }, !1);\n                    throw e\n                })))\n            }(t, o, s, d, null === (e = null === (e = fg()) || void 0 === e ? void 0 : e.getQuery()) || void 0 === e ? void 0 : e.extendMaxTTFB).pipe(Za(e => p.triggerManifestLoaded(e)), Za(({\n                initialDetails: e,\n                stats: t\n            }) => {\n                e && (e = e, t = t, Cg().archiveMediaOptionDetails(e, t, !0))\n            }), bo(u.displaySupportsHdr$), La(([e, t]) => qy(e, r, d, t, s)), hr(e => (l.rootPlaylistEntity = function(e, t, i, r, n, s) {\n                const {\n                    itemId: a,\n                    initialSeekTime: o\n                } = e, l = Zf(a), d = n.enableAdaptiveStartup ? l.getBandwidthEstimate(n, e.serviceName) : void 0, u = n.enableAdaptiveStartup ? l.getPlaylistEstimate(n, e.serviceName) : void 0, c = n.enableAdaptiveStartup ? l.getFragEstimate(n, e.serviceName) : void 0, h = n.enableAdaptiveStartup ? l.getBufferEstimate(n, e.serviceName) : void 0, p = performance.now() - r;\n                let f;\n                n.targetStartupMs > p ? f = n.targetStartupMs - p : (f = n.targetStartupMs, s.warn(`Manifest load took ${p}ms and exceeds targetStartupMs: ${n.targetStartupMs}; resetting targetStartupMs to ${n.targetStartupMs}`));\n                const m = n.enableAdaptiveStartup ? {\n                        targetDuration: c.maxDurationSec || n.defaultTargetDuration,\n                        targetStartupMs: f\n                    } : void 0,\n                    g = Qy(t, i, s, d, m, u, c, h);\n                return g.pendingSeek = o, g\n            }(t, e, c, a, d, s), n)), lg(i, null, Lc(t, o), 0, !1, n, l, h), Vs(() => {\n                $y.setLoading(!1)\n            }))\n        }), tc(\"retrieveRootMediaOptions.emit\"));\n\n        function Gy(t, o, l, d, u, c, h) {\n            return e => e.pipe(Kp(), La(e => {\n                return e ? Mr([$i(e).pipe(Wy(t.manifestLoadPolicy, l, t, d, null, u, c)), (n = t, s = o, a = h.mux, new $t(e => {\n                    const t = new Ty(n, s, a);\n                    return e.next(t), () => {\n                        t.destroy()\n                    }\n                })), (i = t.trickPlaybackConfig, r = o, new $t(e => {\n                    var t = new Zu(i, r);\n                    return e.next(t), () => {}\n                }))]).pipe(hr(([e, t, i]) => ({\n                    rootPlaylistQuery: e,\n                    mediaParser: t,\n                    iframeMachine: i\n                }))) : $i(null);\n                var i, r, n, s, a\n            }))\n        }\n        wc;\n        return class zy extends wc {\n            constructor(e = {}, t) {\n                var i;\n                if (super(), this.destroy$ = new Xt, this.mediaElement$ = new yi(null), this.publicQueriesInternal$ = new yi(null), this.mediaElementAdapter = null, this.rpcService = null, this.rpcClients = null, this.platformService = Af(), this.keySystemAdapter = null, this.legibleSystemAdapter = null, this.sessionID = Zl(), this.statsService = (Jf = Jf || new Xf(Yf), Jf), this.gaplessCapable = !0, this.teardownWG$ = new Xp, this.itemQueue = new ay, (e.liveSyncDurationCount || e.liveMaxLatencyDurationCount) && (e.liveSyncDuration || e.liveMaxLatencyDuration)) throw new Error(\"Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration\");\n                const m = Object.assign(Object.assign({}, Ru), e);\n                if (m.maxRequiredStartDuration < m.minRequiredStartDuration || m.minRequiredStartDuration < 0) throw new Error(\"Illegal config: bad maxRequiredStartDuration or minRequiredStartDuration\");\n                i = (this.hlsConfig = m).buildType, oe = \"production\" === i;\n                const r = this.sessionID;\n                let n = \"silent\";\n                e.debug && (n = m.debugLevel), au(!0), this.logger = null !== (i = this.logger) && void 0 !== i ? i : ([M, h = {}] = [r, (c = {\n                    sendLogs: m.sendLogs || null,\n                    level: \"log\" === n ? \"debug\" : n,\n                    consoleOverride: \"boolean\" != typeof e.debug ? e.debug : void 0,\n                    buildType: m.buildType\n                }, x = c.consoleOverride, Object.assign({\n                    name: \"hls\",\n                    timestamp: c.sendLogs ? Oe.stdTimeFunctions.epochTime : Oe.stdTimeFunctions.isoTime,\n                    browser: {\n                        asObject: !0,\n                        serialize: !0,\n                        transmit: {\n                            send: (e, t) => {}\n                        },\n                        write: {\n                            debug: qe.bind(null, Ke(x || console, \"debug\"), \"debug\"),\n                            info: qe.bind(null, Ke(x || console, \"info\"), \"info\"),\n                            warn: qe.bind(null, Ke(x || console, \"warn\"), \"warn\"),\n                            error: qe.bind(null, Ke(x || console, \"error\"), \"error\"),\n                            fatal: qe.bind(null, Ke(x || console, \"error\"), \"fatal\")\n                        }\n                    }\n                }, c))], Ue && Ue.sessionId === M ? Ue.warn(\"Logger Singleton already setup, returning existing singleton\") : (Ue = Oe($e(h)).child({\n                    sessionId: M,\n                    name: \"hls\"\n                }), Ue.qe = e => Ue.info(e), Ue.sessionId = M), Ue), _o = !1, Lo && (delete window.$$stores, delete window.$$queries), this.hlsConfig.audioPrimingDelay = 0, this.rootPlaylistService = (x = this.logger, Vy = new Uy($y, x), Vy), this.customUrlLoader = Pc(), this.sessionDataLoader = new Fp(m, Cc, this.customUrlLoader.load, this.logger);\n                var s, a, o, l, d, u, c = m.liveMaxLatencyDurationCount,\n                    h = m.liveSyncDurationCount;\n                if (ne(c) && ne(h) && c <= h) throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n                if (ne(m.liveMaxLatencyDuration) && (m.liveMaxLatencyDuration <= m.liveSyncDuration || !ne(m.liveSyncDuration))) throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n                const p = fg();\n                p.setHlsEntity({\n                    id: r,\n                    config: m\n                });\n                const f = Cg(),\n                    g = new Tf(If),\n                    y = (Rh = Rh || new xh(Ph), Rh);\n                this.accessLogInstance = new rm(this, r), this.rtcService = new Kf(this, m, this.accessLogInstance, this.logger), this.playerEvents = new Ng(this, this.logger, this.rtcService);\n                const v = (M = this.platformService, u = M, (() => {\n                        if (\"function\" == typeof matchMedia) {\n                            var e = matchMedia(\"(dynamic-range: high)\"),\n                                t = matchMedia(\"bad query\");\n                            if (e.media !== t.media) return an($i(e), rn(e, \"change\")).pipe(hr(e => e.matches))\n                        }\n                        return $i(!0)\n                    })().pipe(Za(e => {\n                        u.updateSupportsHdr(e)\n                    })).pipe($a(Ii))),\n                    S = this.mediaElement$.pipe((s = m, o = (a = this).logger, l = this.teardownWG$, d = this.rtcService, e => e.pipe(tc(\"playback.mediaElementServiceEpic.in\"), La(e => {\n                        if (!e) return $i(null);\n                        const t = new vf(e, bf, s, a, o, l, d);\n                        return t.openMediaSource(new MediaSource), an($i(t), t)\n                    }), tc(\"playback.mediaElementServiceEpic.emit\"))), Aa()),\n                    b = this.itemQueue.activeItemById$.pipe(La(e => e ? tm(m, this.statsService, e, this.logger) : Ii));\n                this.rpcService = (() => {\n                    let e = null;\n                    return null != m.createRPCService && (e = Lf(m.createRPCService, xf)), m.enableWorker && null == e && (e = _f), null == e && (e = xf), e(this.logger)\n                })(), this.rpcClients = (x = this.rpcService, {\n                    crypto: new kf(x),\n                    mux: new Cf(x)\n                });\n                var T, E, I, w, A, O, k, C, D, c = Mr([this.itemQueue.activeItemById$.pipe(Gy(m, this.logger, this.rootPlaylistService, g, this.statsService, this.playerEvents, this.rpcClients), Za(e => {\n                        var t = null == e ? void 0 : e.rootPlaylistQuery;\n                        this.publicQueriesInternal$.next([t, null]), this.iframeMachine = null == e ? void 0 : e.iframeMachine, t && this.playerEvents.triggerManifestParsed(t)\n                    })), S.pipe((I = this.itemQueue.removedItems$, w = y, A = m, O = g, C = (k = this).rtcService, D = this.logger, e => Mr([((n, s, a, o, l, d, u) => e.pipe(tc(\"[Keys] playback.keySystemServiceEpic.in\"), La(r => r ? new $t(e => {\n                        let t = new Dh(n, r, a, o, l, d, u);\n                        const i = an($i(t), s.pipe(jr(e => t.removeKeysForItems(e)), $a(Ii))).subscribe(e);\n                        return function() {\n                            u.warn(\"[Keys] playback.keySystemServiceEpic.unsubscribe\"), i.unsubscribe(), t.destroy().subscribe(), t = void 0\n                        }\n                    }) : $i(null)), tc(\"[Keys] playback.keySystemServiceEpic.emit\")))(w, I, A, O, k, C, D), ((t, i, r) => e.pipe(tc(\"playback.legibleServiceEpic.in\"), La(e => e ? an($i(e = new _p(e, t, i, r)), e) : $i(null)), tc(\"playback.legibleServiceEpic.emit\")))(A, k, D), e]).pipe(hr(([e, t, i]) => ({\n                        keySystemAdapter: e,\n                        legibleSystemAdapter: t,\n                        mediaSink: i\n                    })))), Za(({\n                        keySystemAdapter: e,\n                        legibleSystemAdapter: t,\n                        mediaSink: i\n                    }) => {\n                        this.keySystemAdapter = e, this.legibleSystemAdapter = t, this.mediaElementAdapter = i\n                    }))]).pipe(hr(([e, t]) => {\n                        var {\n                            keySystemAdapter: i,\n                            legibleSystemAdapter: r,\n                            mediaSink: n\n                        } = t;\n                        if (!(e && i && r && n)) return null;\n                        var {\n                            rootPlaylistQuery: s,\n                            iframeMachine: t,\n                            mediaParser: e\n                        } = e;\n                        return {\n                            logger: this.logger,\n                            config: m,\n                            platformService: this.platformService,\n                            statsService: this.statsService,\n                            rtcService: this.rtcService,\n                            rpcClients: this.rpcClients,\n                            rootPlaylistService: this.rootPlaylistService,\n                            rootPlaylistQuery: s,\n                            mediaLibraryService: f,\n                            keySystemAdapter: i,\n                            legibleSystemAdapter: r,\n                            mediaSink: n,\n                            mediaParser: e,\n                            iframeMachine: t,\n                            customUrlLoader: this.customUrlLoader,\n                            gaplessInstance: this\n                        }\n                    }), Aa()).pipe(La(u => {\n                        if (!u) return Ii;\n                        const {\n                            rootPlaylistQuery: t,\n                            mediaSink: e,\n                            mediaLibraryService: i\n                        } = u;\n                        this.publicQueriesInternal$.next([t, e.mediaQuery]);\n                        const n = e.mediaQuery,\n                            r = $i(u).pipe(vy()),\n                            s = t.rootPlaylistEntity$.pipe(Kp(), Ds(1), Za(() => {\n                                this.commitEarlySelection(u.logger)\n                            })),\n                            a = Gu(Mr([n.haveEnough$, t.sessionData$]), ([e]) => !0 === e, 1).pipe(La(([, e]) => this.sessionDataLoader.loadSessionData(e)), Za(e => {\n                                this.rootPlaylistService.setSessionData(t.itemId, e)\n                            }), Vn(e => (this.logger.error(e.message), Ii))),\n                            o = Zf(t.itemId),\n                            l = function(d, r, u, n, s) {\n                                const a = u.mediaQuery;\n                                return Gu(a.combinedBuffer$, e => 0 < (null == e ? void 0 : e.length)).pipe(La(() => {\n                                    var e = ed([a.seekTo$, a.bufferedSegmentsByType$(yu.Variant)]).pipe(hr(([e, t]) => {\n                                            const i = ne(null == e ? void 0 : e.pos) ? e.pos : a.currentTime,\n                                                r = t.find(e => e.startPTS <= i && e.endPTS > i),\n                                                n = a.getBufferInfo(i, d.maxBufferHole),\n                                                s = a.getCombinedBufferInfo(i, d.maxBufferHole);\n                                            return {\n                                                pos: i,\n                                                sbTuple: n,\n                                                combined: s,\n                                                playingFrag: null !== (t = null == r ? void 0 : r.frag) && void 0 !== t ? t : null\n                                            }\n                                        })),\n                                        t = ed([r.getInFlightFragByType$(gu.Variant), r.enabledMediaOptionByType$(gu.Variant)]).pipe(La(([e, t]) => {\n                                            var i = n.getQueryForOption(t);\n                                            return En($i(e), $i(t), i.mediaOptionDetails$)\n                                        }), hr(([e, t, i]) => [e, {\n                                            variant: t,\n                                            details: i\n                                        }])),\n                                        i = ed([s.bandwidthEstimate$, s.fragEstimate$, s.bufferEstimate$]);\n                                    return ed([a.readyState$, t, e, a.desiredRate$, i])\n                                }), ao(100, tr, {\n                                    leading: !0,\n                                    trailing: !0\n                                }), hr(([, e, t, i, r]) => {\n                                    var [n, s] = e, [a, e, r] = r;\n                                    let o = e,\n                                        l = r;\n                                    return e && (o = {\n                                        maxDurationSec: ne(e.maxDurationSec) ? e.maxDurationSec : d.defaultTargetDuration,\n                                        avgParseTimeMs: ne(e.avgParseTimeMs) ? e.avgParseTimeMs : d.statDefaults.fragParseTimeMs\n                                    }), r && (l = {\n                                        avgBufferCreateMs: ne(r.avgBufferCreateMs) ? r.avgBufferCreateMs : d.statDefaults.fragBufferCreationDelayMs,\n                                        avgInitFragAppendMs: ne(r.avgInitFragAppendMs) ? r.avgInitFragAppendMs : d.statDefaults.initFragAppendMs,\n                                        avgDataFragAppendMs: ne(r.avgDataFragAppendMs) ? r.avgDataFragAppendMs : d.statDefaults.dataFragAppendMs\n                                    }), a = Ey(d, n, s, t, i, a, o, l), u.haveEnough = a\n                                }), Is(), Za(e => {}), $a(Ii))\n                            }(m, (this.logger, t), e, i, o),\n                            d = function() {\n                                const {\n                                    config: e,\n                                    mediaSink: t,\n                                    rootPlaylistQuery: i,\n                                    mediaLibraryService: r,\n                                    gaplessInstance: n\n                                } = u, s = t.mediaQuery, a = i.enabledAVOptions$.pipe(La(e => En(...e.map(e => _u(e) ? r.getQueryForOption(e).mediaOptionDetails$ : $i(null)))));\n                                return Gu(s.combinedBuffer$, e => 0 < (null == e ? void 0 : e.length)).pipe($a(ed([a, s.msReadyState$, s.updating$, s.isIframeRate$, s.isBufferedToEnd$(e.maxBufferHole, !n.inGaplessMode)])), tc(\"checkForEndOfStream\"), ln(([, e, t, i, r]) => \"open\" === e && !1 === t && !i && r), Za(([e]) => {\n                                    null != e[0] && e.every(e => null == e || !1 === e.liveOrEvent && !1 === e.iframesOnly) && !n.inGaplessMode && t.endStream()\n                                }), $a(Ii))\n                            }(),\n                            c = function() {\n                                const {\n                                    config: o,\n                                    iframeMachine: l,\n                                    mediaSink: i\n                                } = u, d = i.mediaQuery;\n                                return d.desiredRate$.pipe(La(a => Wp(a) ? bn(0, Math.abs(1e3 / a)).pipe(hr(() => {\n                                    let e = null;\n                                    const t = d.seekable;\n                                    if (!l.isStarted || t.length < 1) return e;\n                                    var i = l.iframeClockTimeSeconds,\n                                        r = o.leftMediaTimeToAutoPause,\n                                        n = t.start(0),\n                                        s = t.end(t.length - 1);\n                                    return 1 < a && s - i < r ? (e = {\n                                        newRate: 0,\n                                        postFlushSeek: s - r\n                                    }, l.pause()) : a < 0 && i - n < a / -2 && (e = {\n                                        newRate: 1,\n                                        postFlushSeek: n\n                                    }), e\n                                }), Kp(), Za(({\n                                    newRate: e,\n                                    postFlushSeek: t\n                                }) => {\n                                    i.postFlushSeek = t, i.desiredRate = e\n                                }), $a(Ii)) : Ii))\n                            }(),\n                            h = (f = u).config.enableIFramePreloading ? function(t) {\n                                const {\n                                    mediaSink: e,\n                                    rootPlaylistQuery: r,\n                                    mediaLibraryService: n\n                                } = t, i = e.mediaQuery;\n                                return ed([i.desiredRate$, i.waterLevelChangedForType$(yu.Variant)]).pipe(La(([e, t]) => Wp(e) || t !== Dp.AboveHighWater ? Ii : r.enabledMediaOptionByType$(gu.Variant).pipe(hr(e => {\n                                    var t = r.mediaOptionListQueries[gu.Variant].hasIframes,\n                                        i = null !== (i = null === (i = n.getQuery().getEntity(r.itemId)) || void 0 === i ? void 0 : i.liveOrEvent) && void 0 !== i && i;\n                                    return !t || i ? xm.DISABLED : e\n                                }))), Ds(1), _s(e => function(e, t) {\n                                    const i = t.logger;\n                                    return e === xm.DISABLED ? $i(e) : function(e, t) {\n                                        const {\n                                            rootPlaylistQuery: i,\n                                            logger: r,\n                                            config: n,\n                                            mediaSink: s,\n                                            statsService: a\n                                        } = t, o = s.mediaQuery, l = a.getQueryForItem(i.itemId), d = Dg(e), u = jg(!0, n, i, d, o, l, r), c = i.variantMediaOptionById(u.variantMediaOption);\n                                        return Mg(t, c, !0)\n                                    }(e, t).pipe(_s(r => function(e) {\n                                        var {\n                                            mediaSink: t,\n                                            rootPlaylistQuery: i\n                                        } = e, t = Ig((t = t.mediaQuery).currentTime, i.discoSeqNum, 0, r, []);\n                                        return null !== (i = null == t ? void 0 : t.foundFrag) && void 0 !== i && i.mediaFragment ? (t = t.foundFrag.mediaFragment, en([_g(e, t.keyTagInfo, {\n                                            itemId: t.itemId,\n                                            mediaOptionId: t.mediaOptionId\n                                        }), xg(e, t)]).pipe(Za(() => {}), Zs(xm.SUCCESS))) : Vi(\"Unable to find fragment for iframe prefetch\")\n                                    }(t)), Zs(xm.SUCCESS), Vn(e => (i.error(ry, `got error ${e.message} in prefetch`), $i(xm.ERRORED))))\n                                }(e, t)), Vs(() => {}))\n                            }(f) : $i(xm.DISABLED),\n                            p = [s, r, a, l, Gu(ed([n.gotPlaying$, n.gotLoadStart$, n.readyState$]), ([e, t, i]) => !0 === e || !0 === t || 1 <= i).pipe(La(() => n.ended$), La(e => bn(0, e ? void 0 : 1e3)), Za(() => {\n                                this.playbackInfo(m, n)\n                            })), c, h, n.timeupdate$.pipe(hr(e => {\n                                if (this.inGaplessMode && this.isPreloading && ne(this.loadingItem.itemStartOffset) && e >= this.loadingItem.itemStartOffset) {\n                                    const e = this.itemQueue.playingItem.itemId,\n                                        t = this.itemQueue.loadingItem.itemId,\n                                        i = {\n                                            prevItemId: e,\n                                            nextItemId: t,\n                                            nextStartTime: this.loadingItem.itemStartOffset,\n                                            nextDuration: n.msDuration - this.loadingItem.itemStartOffset\n                                        };\n                                    this.itemQueue.updatePlayingItemId(), this.trigger(P.ITEM_TRANSITIONED, i), this.rtcService.itemTransitioned(e, t)\n                                }\n                            })), this.updateLiveSeekableRange(t, e), d];\n                        var f;\n                        if (m.enablePerformanceLogging) {\n                            this.logger.child({\n                                name: \"timing\"\n                            });\n                            const u = En(...Bu.map(r => t.getInFlightFragByType$(r).pipe(Is((e, t) => (null == e ? void 0 : e.state) === (null == t ? void 0 : t.state)), Kp(), bo(n.bufferedRangeTuple$), Za(([e, t]) => {\n                                    const i = Object.assign(Object.assign({}, e), {\n                                        event: \"fragment\",\n                                        name: Nu[r],\n                                        buffered: void 0\n                                    });\n                                    \"appended\" === e.state && (i.buffered = t)\n                                }), Vn(() => Ii)))),\n                                e = En(...Fu.map(e => t.enabledMediaOptionByType$(e).pipe(La(t => null != (null == t ? void 0 : t.url) && _u(t) ? Dg(t).mediaOptionDetailsEntity$.pipe(Kp(), hr(e => ({\n                                    entity: e,\n                                    option: t\n                                })), Is((e, t) => (null == e ? void 0 : e.entity.detailsLoading) === (null == t ? void 0 : t.entity.detailsLoading)), Za(({}) => {})) : Ii), Vn(() => Ii))));\n                            p.push(u, e)\n                        }\n                        return an(...p)\n                    })),\n                    h = this.itemQueue.removedItems$.pipe(ll(e => {\n                        var t;\n                        t = e, Cg().remove(t), this.rootPlaylistService.removeItems(e)\n                    })),\n                    M = p.getQuery().userSeek$.pipe((T = this.itemQueue, E = this.rootPlaylistService, e => e.pipe(Kp(), La(e => en([$i(e), T.activeItemById$.pipe(Kp(), La(e => E.getQueryForId(e.itemId).rootPlaylistEntity$), Ds(1))])), hr(([e, t]) => (E.setPendingSeek(t.itemId, e), e))))),\n                    x = p.getQuery().selectEntityAction(Eo.Add).pipe(Za(() => {\n                        this.logger.warn(`new Hls instance added while old one still active sessionId:${r}`)\n                    }));\n                an(S.pipe(Vn(() => Ii)), an(v, M, b, h, c, this.teardownWG$).pipe(Vn(e => this._handleError(e)))).pipe(Vs(() => {\n                    var e, t;\n                    try {\n                        this.detachMedia(), this.trigger(P.DESTROYING), this.playerEvents.destroy(), null === (e = this.accessLogInstance) || void 0 === e || e.destroy(), null === (t = this.rtcService) || void 0 === t || t.destroy(), Cg().clear(), this.rootPlaylistService.removeAll(), this.itemQueue.clearQueue(), p.removeEntity(this.sessionID)\n                    } catch (e) {\n                        this.logger.error(`Got error in finalize ${e.message}`)\n                    }\n                }), Va(fn(this.destroy$, x))).subscribe()\n            }\n            get publicQueries$() {\n                return this.publicQueriesInternal$.pipe(ln(e => Boolean(e) && Boolean(e[0]) && Boolean(e[1])))\n            }\n            get _activeRootQuery() {\n                var e = this.publicQueriesInternal$.value;\n                return null !== (e = null == e ? void 0 : e[0]) && void 0 !== e ? e : null\n            }\n            get _mediaElementQuery() {\n                var e = this.publicQueriesInternal$.value;\n                return null !== (e = null == e ? void 0 : e[1]) && void 0 !== e ? e : null\n            }\n            static get version() {\n                return \"2.162.2\"\n            }\n            static get Events() {\n                return P\n            }\n            get Events() {\n                return zy.Events\n            }\n            static get DefaultConfig() {\n                return de(Ru)\n            }\n            get DefaultConfig() {\n                return zy.DefaultConfig\n            }\n            static isSupported() {\n                try {\n                    const e = window.MediaSource || window.WebKitMediaSource,\n                        t = window.SourceBuffer || window.WebKitSourceBuffer,\n                        i = e && \"function\" == typeof e.isTypeSupported && e.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"'),\n                        r = !t || t.prototype && \"function\" == typeof t.prototype.appendBuffer && \"function\" == typeof t.prototype.remove;\n                    return !!i && !!r\n                } catch (e) {\n                    return !1\n                }\n            }\n            commitEarlySelection(e) {\n                var t = this.itemQueue.earlyAudioSelection;\n                ne(t) && (this.audioSelectedPersistentID = t, this.itemQueue.earlyAudioSelection = null), ne(t = this.itemQueue.earlySubtitleSelection) && (this.subtitleSelectedPersistentID = t, this.itemQueue.earlySubtitleSelection = null)\n            }\n            _handleError(i) {\n                var r;\n                try {\n                    let t, e = i.message;\n                    if (this.logger.error(`Got unhandled or fatal error ${e}`, i), null === (r = this.rtcService) || void 0 === r || r.handleError(i), t = i instanceof p ? i : new V(!0, i.message, $.InternalError), t.fatal && this.isPreloading && (this.logger.warn(\"Fatal error seen while preloading, calling dequeueSource\"), this.dequeueSource(\"FatalErrorWhileLoading\")), t.fatal) {\n                        let e = Wu;\n                        if (this.mediaElementAdapter) {\n                            const r = this.mediaElementAdapter.mediaQuery,\n                                n = r.getCombinedBufferInfo(r.currentTime, 0);\n                            0 < (null == n ? void 0 : n.len) && (e = Gu(this.mediaElementAdapter.mediaQuery.stallInfo$, e => null != e).pipe(hr(() => {})))\n                        }\n                        return e.pipe(La(() => (this.trigger(P.ERROR, t), Ii)))\n                    }\n                    this.trigger(P.ERROR, t)\n                } catch (i) {\n                    throw this.logger.error(`Error thrown inside _handleError ${i.message}`, i), i\n                }\n                return Ii\n            }\n            updateLiveSeekableRange(e, t) {\n                return e.enabledMediaOptionByType$(gu.Variant).pipe(La(e => {\n                    const t = Dg(e);\n                    let i = 0;\n                    return t.mediaOptionDetailsEntity$.pipe(Kp(), ln(e => {\n                        var t = null !== e.stats && !1 === e.detailsLoading && e.lastUpdateMillis > i;\n                        return i = null !== (e = e.lastUpdateMillis) && void 0 !== e ? e : 0, t\n                    }))\n                }), La(e => (0 === e.unchangedCount && (e.mediaOptionDetails.liveOrEvent ? t.updateLiveSeekableRange(e.mediaOptionDetails) : t.clearLiveSeekableRange()), Ii)))\n            }\n            playbackInfo(i, r) {\n                const n = this.mediaElement$.getValue();\n                if (n) {\n                    const s = n.readyState >= n.HAVE_FUTURE_DATA,\n                        a = {\n                            readyToPlay: s,\n                            playbackLikelyToKeepUp: r.haveEnough && s,\n                            rate: n.playbackRate,\n                            paused: n.paused,\n                            position: n.currentTime,\n                            duration: n.duration,\n                            seekableTimeRanges: im.timeRangeToArray(n.seekable),\n                            loadedTimeRanges: im.timeRangeToArray(n.buffered)\n                        };\n                    let e = 0,\n                        t = 0;\n                    if (im.isHtmlVideoElement(n)) {\n                        const o = n.getVideoPlaybackQuality;\n                        if (o && typeof o == typeof Function) {\n                            const o = n.getVideoPlaybackQuality();\n                            e = a.droppedVideoFrames = o.droppedVideoFrames, a.corruptedVideoFrames = o.corruptedVideoFrames, a.totalVideoFrames = o.totalVideoFrames, t = a.totalVideoFrames - e\n                        }\n                    } else im.isWebkitMediaElement(n) && (e = a.droppedVideoFrames = n.webkitDroppedFrameCount, t = a.decodedFrameCount = n.webkitDecodedFrameCount);\n                    i.enablePerformanceLogging && r.getCombinedMediaSourceBufferInfo(i.maxBufferHole), null === (i = this.rtcService) || void 0 === i || i.handlePlaybackInfo(e, t)\n                }\n            }\n            get currentItem() {\n                return this.isPreloading ? this.playingItem : this.itemQueue.activeItem\n            }\n            get realCurrentTime() {\n                var e, t = this._mediaElementQuery;\n                if (!t) return NaN;\n                if (null !== (e = this.iframeMachine) && void 0 !== e && e.isStarted) {\n                    const r = t.mediaElementDuration,\n                        e = this.iframeMachine.iframeClockTimeSeconds;\n                    return e > r ? r : e\n                }\n                let i = ne(t.postFlushSeek) ? t.postFlushSeek : t.currentTime;\n                return ne(i) && ne(null === (e = this.playingItem) || void 0 === e ? void 0 : e.itemStartOffset) && (i -= this.playingItem.itemStartOffset), i\n            }\n            set realCurrentTime(e) {\n                var t;\n                ne(null === (t = this.playingItem) || void 0 === t ? void 0 : t.itemStartOffset) && (e += this.playingItem.itemStartOffset), this.seekTo = e\n            }\n            get bufferedDuration() {\n                var e;\n                const t = this._mediaElementQuery;\n                return null !== (e = null == t ? void 0 : t.getBufferedDuration()) && void 0 !== e ? e : 0\n            }\n            get sessionData() {\n                var e = this._activeRootQuery;\n                return null == e ? void 0 : e.sessionData\n            }\n            get supportedFrameRates() {\n                const e = this.hlsConfig.trickPlaybackConfig.enabled,\n                    t = [0, 1],\n                    i = this._activeRootQuery,\n                    r = Cg().getQuery();\n                return e && i && r.getEntity(i.itemId) && !1 === r.getEntity(i.itemId).liveOrEvent && t.push(8, 24, 48, 96), t\n            }\n            loadSource(e, i, t) {\n                var r, n, s, a, o, l;\n                if (\"playready\" === this.config.keySystemPreference && !this.config.enablePlayReadyKeySystem) throw new V(!0, \"Playready key system is not supported now\", $.UnsupportedKeySystemError);\n                if (!e || !e.trim().length) throw new V(!0, \"Empty loadSource url\", $.EmptyLoadSourceError);\n                if (e = bu.buildAbsoluteURL(window.location.href, e, {\n                        alwaysNormalize: !0\n                    }), i && Object.keys(i).filter(e => 0 <= [\"itemId\", \"streamID\"].indexOf(e)).reduce((e, t) => t in i ? Object.assign(e, {\n                        [t]: i[t]\n                    }) : e, {}), null !== (l = null == i ? void 0 : i.appData) && void 0 !== l && l.reportingAgent && (this.reportingAgent = i.appData.reportingAgent), null != i && i.userInfo && (this.userInfo = i.userInfo), null === (a = this.accessLogInstance) || void 0 === a || a.setupReporter(i.appData), null != i && i.platformInfo && this.platformService.updatePlatformInfo(i.platformInfo), function(e, t) {\n                        if (t) {\n                            const t = Eu(e);\n                            return void 0 !== Iu.find(e => new RegExp(e).exec(t))\n                        }\n                    }(e, this.config.enableQueryParamsForITunes)) {\n                    const d = {\n                        language: i.language,\n                        dsid: i.dsid,\n                        subs: i.subs\n                    };\n                    r = e, n = null == i ? void 0 : i.platformInfo, s = d, o = n.model, l = n.manufacturer, o && l || Qe().warn(`Missing model/manufacturer in platformInfo model ${o} manufacturer ${l}`), o && l && (a = r, o = n.model, l = n.manufacturer, n = -1 !== a.indexOf(\"?\"), o = encodeURIComponent(o), l = encodeURIComponent(l), r = (a = n ? a : a + \"?\") + wu.deviceName + l + wu.deviceModel + o), e = function(e, t) {\n                        let i;\n                        e = -1 !== e.indexOf(\"?\") ? e : e + \"?\";\n                        const r = Qe();\n                        for (i in t) t[i] ? e += wu[i] + (\"subs\" === i ? encodeURIComponent(t[i]) : t[i]) : r.warn(`Missing ${i} info`);\n                        return e\n                    }(r, s), i.inheritQuery = !1\n                }\n                this.itemQueue.setQueueItem(`item:${null!==(s=null==i?void 0:i.itemId)&&void 0!==s?s:Zl()}`, e, t, null == i ? void 0 : i.platformInfo, null === (t = null == i ? void 0 : i.appData) || void 0 === t ? void 0 : t.serviceName), fg().setStartTime(void 0)\n            }\n            queueSource(e, t, i) {\n                var r;\n                null != t && t.userInfo && (this.userInfo = t.userInfo);\n                var n = null === (r = this._mediaElementQuery) || void 0 === r ? void 0 : r.getCombinedBufferInfo(null === (n = this._mediaElementQuery) || void 0 === n ? void 0 : n.currentTime, 0);\n                let s = 0;\n                n && (s = n.end), this.itemQueue.addQueueItem(`item:${null!==(n=null==t?void 0:t.itemId)&&void 0!==n?n:Zl()}`, e, i, null == t ? void 0 : t.platformInfo, s, null === (t = null == t ? void 0 : t.appData) || void 0 === t ? void 0 : t.serviceName)\n            }\n            dequeueSource(e = \"ApplicationInitiated\") {\n                if (!this.isPreloading && \"InvalidFormat\" === e && this.isFirstItem) return this.logger.error(\"First item has invalid format for gapless. Probably video. Disabling gapless.\"), void(this.gaplessCapable = !1);\n                var t, i;\n                this.isPreloading ? (t = this.loadingItem.url, i = this.loadingItem.itemId, this.mediaElementAdapter.flushData(yu.Variant, this.loadingItem.itemStartOffset, 1 / 0), this.mediaElementAdapter.msDuration = this.loadingItem.itemStartOffset, this.itemQueue.resetLoadingItem(), \"InvalidFormat\" !== e && \"FatalErrorWhileLoading\" !== e || (this.gaplessCapable = !1), this.triggerItemEvicted({\n                    url: t,\n                    itemId: i\n                }, e)) : this.logger.warn(`Nothing to dequeue, no item is preloading dequeue reason: ${e}`)\n            }\n            triggerItemEvicted(e, t) {\n                null !== e ? (t = {\n                    url: e.url,\n                    evictedItemId: e.itemId,\n                    reason: t\n                }, Object.assign(Object.assign({}, t), {\n                    url: le(e.url)\n                }), this.trigger(P.ITEM_EVICTED, t)) : this.logger.error(\"dequeueSource called with no playing or loading item\")\n            }\n            endSource() {\n                this.gaplessCapable = !1, this.isPreloading && (this.logger.warn(\"EndSource called during preloading. Loading item will be removed\"), this.mediaElementAdapter.flushData(yu.Variant, this.loadingItem.itemStartOffset, 1 / 0), this.mediaElementAdapter.msDuration = this.loadingItem.itemStartOffset, this.itemQueue.resetLoadingItem())\n            }\n            get inGaplessMode() {\n                return mg().gapless && this.gaplessCapable\n            }\n            get isPreloading() {\n                return this.itemQueue.isPreloading()\n            }\n            get isFirstItem() {\n                return this.itemQueue.isFirstItem\n            }\n            get loadingItem() {\n                return this.itemQueue.loadingItem\n            }\n            get playingItem() {\n                return this.itemQueue.playingItem\n            }\n            get url() {\n                return this.playingItem ? this.playingItem.url : this.loadingItem ? this.loadingItem.url : void 0\n            }\n            destroy() {\n                const t = this.logger;\n                return this.destroy$.next(), null != this.rpcService && (this.teardownWG$.add(), this.rpcService.teardown(e => {\n                    e && t.error(\"RPCService teardown error:\", e), this.teardownWG$.done()\n                }), this.rpcService = null), null != this.iframeMachine && (this.iframeMachine.destroy(), this.iframeMachine = null), this.teardownWG$.toPromise()\n            }\n            attachMedia(e) {\n                this.trigger(P.MEDIA_ATTACHING, {\n                    media: e\n                }), this.mediaElement$.next(e), this.trigger(P.MEDIA_ATTACHED, {\n                    media: e\n                })\n            }\n            detachMedia() {\n                var e;\n                this.mediaElement$.getValue() && (this.trigger(P.MEDIA_DETACHING), null === (e = this.rtcService) || void 0 === e || e.detachMedia(), null != this.iframeMachine && this.iframeMachine.stop(), this.mediaElement$.next(null), this.trigger(P.MEDIA_DETACHED))\n            }\n            handleResolvedUri(e, t) {\n                this.customUrlLoader.setCustomUrlResponse(e, {\n                    uri: t.uri,\n                    response: t\n                })\n            }\n            get variantOptions$() {\n                return this.publicQueries$.pipe(La(e => {\n                    const [t, i] = e;\n                    return Mr([t.preferredMediaOptions$, i.desiredRate$]).pipe(hr(([e]) => {\n                        const t = i.isIframeRate;\n                        return e[gu.Variant].filter(e => (null !== (e = e.iframes) && void 0 !== e && e) === t).map(e => e.mediaOptionId)\n                    }))\n                }))\n            }\n            get altAudioOptions$() {\n                return this.publicQueries$.pipe(La(e => {\n                    var [e] = e;\n                    return $i(e.audioMediaSelectionOptions)\n                }))\n            }\n            get subtitleOptions$() {\n                return this.publicQueries$.pipe(La(e => {\n                    var [e] = e;\n                    return $i([{\n                        MediaSelectionOptionsName: \"Disable subtitle\",\n                        MediaSelectionOptionsPersistentID: -1\n                    }].concat(e.subtitleMediaSelectionOptions))\n                }))\n            }\n            get levels() {\n                var e;\n                return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.preferredMediaOptions[gu.Variant]) && void 0 !== e ? e : []\n            }\n            get audioTracks() {\n                var e;\n                return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.preferredMediaOptions[gu.AltAudio]) && void 0 !== e ? e : []\n            }\n            get audioMediaOptions() {\n                var e;\n                return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.audioMediaSelectionOptions) && void 0 !== e ? e : []\n            }\n            get subtitleMediaOptions() {\n                var e;\n                return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.subtitleMediaSelectionOptions) && void 0 !== e ? e : []\n            }\n            get playbackLikelyToKeepUp() {\n                var e;\n                return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.playbackLikelyToKeepUp) && void 0 !== e && e\n            }\n            get duration$() {\n                return this.publicQueries$.pipe(La(e => {\n                    var [, e] = e;\n                    return e.mediaElementDuration$\n                }))\n            }\n            get timeupdate$() {\n                return this.publicQueries$.pipe(La(e => {\n                    var [, e] = e;\n                    return e.timeupdate$\n                }))\n            }\n            get playing$() {\n                return this.publicQueries$.pipe(La(e => {\n                    var [, e] = e;\n                    return e.gotPlaying$\n                }))\n            }\n            get desiredRate$() {\n                return this.publicQueries$.pipe(La(e => {\n                    var [, e] = e;\n                    return e.desiredRate$\n                }))\n            }\n            set desiredRate(e) {\n                null != e && this.setRate(e)\n            }\n            get desiredRate() {\n                var e;\n                return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.desiredRate) && void 0 !== e ? e : 0\n            }\n            get effectiveRate() {\n                var e;\n                return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.effectiveRate) && void 0 !== e ? e : 0\n            }\n            get iframeMode() {\n                var e;\n                return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.isIframeRate) && void 0 !== e && e\n            }\n            get accessLog() {\n                return this.accessLogInstance && this._activeRootQuery ? this.accessLogInstance.getAccessLog(this._activeRootQuery.itemId) : []\n            }\n            get errorLog() {\n                return this.accessLogInstance ? this.accessLogInstance.errorLog : []\n            }\n            setRate(e) {\n                var t;\n                const i = this.logger.child({\n                    name: \"iframes\"\n                });\n                if (e === this.desiredRate) return -2;\n                const r = this.mediaElementAdapter;\n                if (!r || isNaN(e)) return i.warn(\"unable to switch to rate, missing adapter or newRate isNaN\"), -1;\n                e = Number(e);\n                const n = Math.abs(e);\n                if (!this.supportedFrameRates.some(e => e === n)) return i.warn(`unsupported rate(${e})`), -3;\n                const s = Wp(e),\n                    a = this.iframeMachine;\n                if (s) {\n                    const e = this._activeRootQuery;\n                    if (null == e || !e.mediaOptionListQueries[gu.Variant].hasIframes) return i.warn(\"no iframe variants available\"), -1;\n                    r.postFlushSeek = null\n                } else null != a && a.isStarted && !ne(null === (t = r.mediaQuery) || void 0 === t ? void 0 : t.postFlushSeek) && (a.pause(), r.postFlushSeek = a.iframeClockTimeSeconds);\n                return r.desiredRate = e, 0\n            }\n            get sessionData$() {\n                return this.publicQueries$.pipe(La(([e]) => e.sessionData$))\n            }\n            set skip(e) {\n                this._mediaElementQuery && (this.realCurrentTime = Math.max(0, this.realCurrentTime + e))\n            }\n            gaplessSeekTo(e) {\n                e < this.playingItem.itemStartOffset && (this.logger.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${this.playingItem.itemStartOffset}`), e = this.playingItem.itemStartOffset), this.isPreloading && (e > this.loadingItem.itemStartOffset && (this.logger.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${this.loadingItem.itemStartOffset}`), e = this.loadingItem.itemStartOffset), e < this._mediaElementQuery.getBufferInfo(this._mediaElementQuery.currentTime, this.config.maxBufferHole)[0].buffered.start && this.dequeueSource(\"SeekToUnbufferedTimeRanges\")), fg().setUserSeek(e)\n            }\n            isIframeInternalSeek(e) {\n                return e === (null === (e = this.iframeMachine) || void 0 === e ? void 0 : e.mediaRootTime)\n            }\n            set seekTo(e) {\n                var t, i = Number(e);\n                if (ne(i))\n                    if (this.inGaplessMode) this.gaplessSeekTo(i);\n                    else {\n                        const r = this.mediaElementAdapter;\n                        !r || !ne(null === (t = r.mediaQuery) || void 0 === t ? void 0 : t.postFlushSeek) || r.mediaQuery.seekTo && !this.isIframeInternalSeek(r.mediaQuery.seekTo.pos) ? fg().setUserSeek(i) : r.schedulePostFlushSeek(i)\n                    }\n                else this.logger.error(`[seek] got invalid seek value ${e}`)\n            }\n            seekToDate(e) {\n                fg().setUserSeek(e)\n            }\n            get availableProgramDateTime() {\n                return new Map(this._currentDateToMediaTimeTuple)\n            }\n            get _currentDateToMediaTimeTuple() {\n                if (!this._activeRootQuery) return [];\n                var e = this._activeRootQuery.enabledMediaOptionKeys[gu.Variant];\n                return _u(e) && null !== (e = null === (e = Cg().getQueryForOption(e).mediaOptionDetails) || void 0 === e ? void 0 : e.dateMediaTimePairs) && void 0 !== e ? e : []\n            }\n            get playingDate() {\n                return function(e, t) {\n                    if (e && 0 !== e.length) {\n                        const i = [...e].sort((e, t) => t[1] - e[1]),\n                            r = null !== (e = i.find(([, e]) => e <= t)) && void 0 !== e ? e : i[i.length - 1],\n                            [n, s] = r;\n                        return new Date(n + 1e3 * (t - s))\n                    }\n                }(this._currentDateToMediaTimeTuple, this.realCurrentTime)\n            }\n            set variantId(e) {}\n            set audioSelectedPersistentID(e) {\n                var t = this._activeRootQuery;\n                null != t && t.preferredMediaOptions[gu.AltAudio] ? (t = t.itemId, e !== this.audioSelectedPersistentID && this.rootPlaylistService.setEnabledMediaOptionTupleWithMatchedGroups(t, gu.AltAudio, e, {\n                    userInitiated: !0\n                })) : !ne(e) || e < 0 || (this.logger.warn(`[audio] no active item, defer audio track selection: persistentId ${e}`), this.itemQueue.earlyAudioSelection = e)\n            }\n            get audioSelectedPersistentID() {\n                var e;\n                return this._activeRootQuery ? null === (e = this._activeRootQuery.enabledAlternateMediaOptionByType(gu.AltAudio)) || void 0 === e ? void 0 : e.persistentID : this.itemQueue.earlyAudioSelection\n            }\n            set subtitleSelectedPersistentID(e) {\n                var t = this._activeRootQuery,\n                    i = null == t ? void 0 : t.preferredMediaOptions[gu.Subtitle];\n                i ? e !== this.subtitleSelectedPersistentID && (t = t.itemId, 0 === i.length && (!ne(e) || e < 0) || (ne(e) && -1 !== e ? this.rootPlaylistService.setEnabledMediaOptionTupleWithMatchedGroups(t, gu.Subtitle, e) : this.rootPlaylistService.setEnabledMediaOptionByType(t, gu.Subtitle, Lu))) : !ne(e) || e < 0 || (this.logger.warn(`[subtitle] no active item, defer subtitle track selection: persistentId ${e}`), this.itemQueue.earlySubtitleSelection = e)\n            }\n            get subtitleSelectedPersistentID() {\n                var e;\n                return this._activeRootQuery ? null === (e = this._activeRootQuery.enabledAlternateMediaOptionByType(gu.Subtitle)) || void 0 === e ? void 0 : e.persistentID : this.itemQueue.earlySubtitleSelection\n            }\n            get selectedMediaArray() {\n                const e = this._activeRootQuery;\n                if (!e) return [];\n                const t = [],\n                    i = e.enabledAlternateMediaOptionByType(gu.AltAudio),\n                    r = e.enabledAlternateMediaOptionByType(gu.Subtitle),\n                    n = i ? e.audioMediaSelectionOptions.find(e => e.MediaSelectionOptionsPersistentID === i.persistentID) : void 0,\n                    s = r ? e.subtitleMediaSelectionOptions.find(e => e.MediaSelectionOptionsPersistentID === r.persistentID) : void 0;\n                if (n) {\n                    const e = {\n                        MediaSelectionGroupMediaType: Su.AUDIO,\n                        MediaSelectionOptionsPersistentID: n.MediaSelectionOptionsPersistentID\n                    };\n                    t.push(e)\n                }\n                if (s) {\n                    let e = vu.NO;\n                    s.MediaSelectionOptionsDisplaysNonForcedSubtitles && (e = s.MediaSelectionOptionsDisplaysNonForcedSubtitles);\n                    const i = {\n                        MediaSelectionGroupMediaType: Su.SUBTITLE,\n                        MediaSelectionOptionsDisplaysNonForcedSubtitles: e,\n                        MediaSelectionOptionsPersistentID: s.MediaSelectionOptionsPersistentID\n                    };\n                    t.push(i)\n                }\n                return t\n            }\n            set selectedMediaArray(e) {\n                this._activeRootQuery ? e.forEach(e => {\n                    e.MediaSelectionGroupMediaType === Su.AUDIO || e.MediaSelectionOptionsMediaType === Su.AUDIO ? this.audioSelectedPersistentID = e.MediaSelectionOptionsPersistentID : e.MediaSelectionGroupMediaType !== Su.SUBTITLE && e.MediaSelectionOptionsMediaType !== Su.SUBTITLE && e.MediaSelectionOptionsMediaType !== Su.CLOSEDCAPTION || (this.subtitleSelectedPersistentID = e.MediaSelectionOptionsPersistentID)\n                }) : this.logger.warn(\"selectedMediaArray: no active item\")\n            }\n            getHTMLTextTrack(e) {\n                return this.legibleSystemAdapter.getExistingHTMLTextTrackWithSubtitleTrackId(e)\n            }\n            get keysystems() {\n                return this.keySystemAdapter.availableKeySystems\n            }\n            setProtectionData(e) {\n                this.keySystemAdapter.initialize(e)\n            }\n            generateKeyRequest(e, t) {\n                this.keySystemAdapter.generateRequest(e, t), this.rtcService.licenseChallengeReceived({\n                    keyuri: e\n                })\n            }\n            setLicenseResponse(e, t) {\n                this.keySystemAdapter.setLicenseResponse(e, t)\n            }\n            get bufferInfo$() {\n                return this.publicQueries$.pipe(La(e => {\n                    const [, t] = e, i = fg().getQuery().currentConfig;\n                    return an(t.timeupdate$, t.bufferedRangeTuple$).pipe(ao(1e3), hr(() => {\n                        var e = t.currentTime;\n                        return {\n                            combined: t.getCombinedBufferInfo(e, i.maxBufferHole),\n                            sbTuple: t.getBufferInfo(e, i.maxBufferHole)\n                        }\n                    }))\n                }))\n            }\n            bufferInfoByType$(t) {\n                return this.bufferInfo$.pipe(hr(e => null === (e = null == e ? void 0 : e.sbTuple) || void 0 === e ? void 0 : e[t]))\n            }\n            levelWithPersistentId(e) {\n                this.logger.warn(\"levelWithPersistentId is deprecated\")\n            }\n            startLoad(e) {\n                this.logger.warn(\"startLoad is deprecated\"), ne(e) && (this.logger.warn(`[seek] Seeking to ${null==e?void 0:e.toFixed(3)} via deprecated \"startLoad\" method. Use loadSource(url, options, startTime) instead.`), this.seekTo = e)\n            }\n            stopLoad() {}\n            get config() {\n                return Object.assign(Object.assign({}, de(mg())), {\n                    set startPosition(e) {\n                        Qe().warn(`Setting start position ${null==e?void 0:e.toFixed(3)} using deprecated method`), fg().setStartTime(e)\n                    }\n                })\n            }\n            get media() {\n                return null != this.mediaElement$.value\n            }\n            set subtitleDisplay(e) {\n                this.logger.warn(`set subtitleDisplay ${e} is deprecated`)\n            }\n        }\n    }, \"object\" == typeof exports && \"undefined\" != typeof module ? module.exports = t() : \"function\" == typeof define && define.amd ? define(t) : (e = \"undefined\" != typeof globalThis ? globalThis : e || Jy).Hls = t()\n}(!1);\n//# sourceMappingURL=hls.js.map"
  },
  {
    "path": "src/renderer/apple-hls.js",
    "content": "/*! For license information please see hls.js.LICENSE.txt \nTL,DR: Don't misuse this file for piracy purpose, all rights of this file and its usage belong to Apple and media copyright holders*/\n(function __HLS_UMD_BUNDLE__(__IN_WORKER__){const self = this;\n    (function (global, factory) {\n      typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n      typeof define === 'function' && define.amd ? define(factory) :\n      (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Hls = factory());\n    })(this, (function () { 'use strict';\n    \n      function hasUMDWorker() {\n          return typeof __HLS_UMD_BUNDLE__ === 'function';\n      }\n    \n      const check = (it) => it && it.Math === Math && it;\n      var global$1 = // eslint-disable-next-line no-undef\n       (check(typeof globalThis == 'object' && globalThis) ||\n          check(typeof window == 'object' && window) ||\n          check(typeof self == 'object' && self) ||\n          check(typeof global == 'object' && global) ||\n          Function('return this')());\n    \n      \n      class JSAESDecryptor {\n          constructor() {\n              this.keySize = null;\n              this.ksRows = null;\n              this.keySchedule = null;\n              this.invKeySchedule = null;\n              // Static after running initTable\n              this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];\n              this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n              this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n              this.sBox = new Uint32Array(256);\n              this.invSBox = new Uint32Array(256);\n              // Changes during runtime\n              this.key = new Uint32Array(0);\n              this.initTable();\n          }\n          // Using view.getUint32() also swaps the byte order.\n          uint8ArrayToUint32Array_(arrayBuffer) {\n              const view = new DataView(arrayBuffer);\n              const length = Math.floor(view.byteLength / 4);\n              const newArray = new Uint32Array(length);\n              for (let i = 0; i < length; i++) {\n                  newArray[i] = view.getUint32(i * 4);\n              }\n              return newArray;\n          }\n          initTable() {\n              const { sBox } = this;\n              const { invSBox } = this;\n              const { subMix } = this;\n              const subMix0 = subMix[0];\n              const subMix1 = subMix[1];\n              const subMix2 = subMix[2];\n              const subMix3 = subMix[3];\n              const { invSubMix } = this;\n              const invSubMix0 = invSubMix[0];\n              const invSubMix1 = invSubMix[1];\n              const invSubMix2 = invSubMix[2];\n              const invSubMix3 = invSubMix[3];\n              const d = new Uint32Array(256);\n              let x = 0;\n              let xi = 0;\n              let i = 0;\n              for (i = 0; i < 256; i++) {\n                  if (i < 128) {\n                      d[i] = i << 1;\n                  }\n                  else {\n                      d[i] = (i << 1) ^ 283;\n                  }\n              }\n              for (i = 0; i < 256; i++) {\n                  let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n                  sx = (sx >>> 8) ^ (sx & 255) ^ 99;\n                  sBox[x] = sx;\n                  invSBox[sx] = x;\n                  // Compute multiplication\n                  const x2 = d[x];\n                  const x4 = d[x2];\n                  const x8 = d[x4];\n                  // Compute sub/invSub bytes, mix columns tables\n                  let t = (d[sx] * 257) ^ (sx * 16843008);\n                  subMix0[x] = (t << 24) | (t >>> 8);\n                  subMix1[x] = (t << 16) | (t >>> 16);\n                  subMix2[x] = (t << 8) | (t >>> 24);\n                  subMix3[x] = t;\n                  // Compute inv sub bytes, inv mix columns tables\n                  t = (x8 * 16843009) ^ (x4 * 65537) ^ (x2 * 257) ^ (x * 16843008);\n                  invSubMix0[sx] = (t << 24) | (t >>> 8);\n                  invSubMix1[sx] = (t << 16) | (t >>> 16);\n                  invSubMix2[sx] = (t << 8) | (t >>> 24);\n                  invSubMix3[sx] = t;\n                  // Compute next counter\n                  if (!x) {\n                      x = xi = 1;\n                  }\n                  else {\n                      x = x2 ^ d[d[d[x8 ^ x2]]];\n                      xi ^= d[d[xi]];\n                  }\n              }\n          }\n          expandKey(keyBuffer) {\n              // convert keyBuffer to Uint32Array\n              const key = this.uint8ArrayToUint32Array_(keyBuffer);\n              let sameKey = true;\n              let offset = 0;\n              while (offset < key.length && sameKey) {\n                  sameKey = key[offset] === this.key[offset];\n                  offset++;\n              }\n              if (sameKey) {\n                  return;\n              }\n              this.key = key;\n              const keySize = (this.keySize = key.length);\n              if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n                  throw new Error('Invalid aes key size=' + keySize);\n              }\n              const ksRows = (this.ksRows = (keySize + 6 + 1) * 4);\n              let ksRow;\n              let invKsRow;\n              const keySchedule = (this.keySchedule = new Uint32Array(ksRows));\n              const invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows));\n              const sbox = this.sBox;\n              const { rcon } = this;\n              const { invSubMix } = this;\n              const invSubMix0 = invSubMix[0];\n              const invSubMix1 = invSubMix[1];\n              const invSubMix2 = invSubMix[2];\n              const invSubMix3 = invSubMix[3];\n              let prev;\n              let t;\n              for (ksRow = 0; ksRow < ksRows; ksRow++) {\n                  if (ksRow < keySize) {\n                      prev = keySchedule[ksRow] = key[ksRow];\n                      continue;\n                  }\n                  t = prev;\n                  if (ksRow % keySize === 0) {\n                      // Rot word\n                      t = (t << 8) | (t >>> 24);\n                      // Sub word\n                      t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 255] << 16) | (sbox[(t >>> 8) & 255] << 8) | sbox[t & 255];\n                      // Mix Rcon\n                      t ^= rcon[(ksRow / keySize) | 0] << 24;\n                  }\n                  else if (keySize > 6 && ksRow % keySize === 4) {\n                      // Sub word\n                      t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 255] << 16) | (sbox[(t >>> 8) & 255] << 8) | sbox[t & 255];\n                  }\n                  keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n              }\n              for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n                  ksRow = ksRows - invKsRow;\n                  if (invKsRow & 3) {\n                      t = keySchedule[ksRow];\n                  }\n                  else {\n                      t = keySchedule[ksRow - 4];\n                  }\n                  if (invKsRow < 4 || ksRow <= 4) {\n                      invKeySchedule[invKsRow] = t;\n                  }\n                  else {\n                      invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 255]] ^ invSubMix2[sbox[(t >>> 8) & 255]] ^ invSubMix3[sbox[t & 255]];\n                  }\n                  invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n              }\n          }\n          // Adding this as a method greatly improves performance.\n          networkToHostOrderSwap(word) {\n              return (word << 24) | ((word & 65280) << 8) | ((word & 16711680) >> 8) | (word >>> 24);\n          }\n          decrypt(inputArrayBuffer, offset, aesIV) {\n              const nRounds = this.keySize + 6;\n              const { invKeySchedule } = this;\n              const invSBOX = this.invSBox;\n              const { invSubMix } = this;\n              const invSubMix0 = invSubMix[0];\n              const invSubMix1 = invSubMix[1];\n              const invSubMix2 = invSubMix[2];\n              const invSubMix3 = invSubMix[3];\n              const initVector = this.uint8ArrayToUint32Array_(aesIV);\n              let initVector0 = initVector[0];\n              let initVector1 = initVector[1];\n              let initVector2 = initVector[2];\n              let initVector3 = initVector[3];\n              const inputInt32 = new Int32Array(inputArrayBuffer);\n              const outputInt32 = new Int32Array(inputInt32.length);\n              let t0, t1, t2, t3;\n              let s0, s1, s2, s3;\n              let inputWords0, inputWords1, inputWords2, inputWords3;\n              let ksRow, i;\n              const swapWord = this.networkToHostOrderSwap;\n              while (offset < inputInt32.length) {\n                  inputWords0 = swapWord(inputInt32[offset]);\n                  inputWords1 = swapWord(inputInt32[offset + 1]);\n                  inputWords2 = swapWord(inputInt32[offset + 2]);\n                  inputWords3 = swapWord(inputInt32[offset + 3]);\n                  s0 = inputWords0 ^ invKeySchedule[0];\n                  s1 = inputWords3 ^ invKeySchedule[1];\n                  s2 = inputWords2 ^ invKeySchedule[2];\n                  s3 = inputWords1 ^ invKeySchedule[3];\n                  ksRow = 4;\n                  // Iterate through the rounds of decryption\n                  for (i = 1; i < nRounds; i++) {\n                      t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 255] ^ invSubMix2[(s2 >> 8) & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow];\n                      t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 255] ^ invSubMix2[(s3 >> 8) & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1];\n                      t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 255] ^ invSubMix2[(s0 >> 8) & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2];\n                      t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 255] ^ invSubMix2[(s1 >> 8) & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3];\n                      // Update state\n                      s0 = t0;\n                      s1 = t1;\n                      s2 = t2;\n                      s3 = t3;\n                      ksRow = ksRow + 4;\n                  }\n                  // Shift rows, sub bytes, add round key\n                  t0 = (invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 255] << 16) ^ (invSBOX[(s2 >> 8) & 255] << 8) ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow];\n                  t1 = (invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 255] << 16) ^ (invSBOX[(s3 >> 8) & 255] << 8) ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1];\n                  t2 = (invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 255] << 16) ^ (invSBOX[(s0 >> 8) & 255] << 8) ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2];\n                  t3 = (invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 255] << 16) ^ (invSBOX[(s1 >> 8) & 255] << 8) ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3];\n                  ksRow = ksRow + 3;\n                  // Write\n                  outputInt32[offset] = swapWord(t0 ^ initVector0);\n                  outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n                  outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n                  outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n                  // reset initVector to last 4 unsigned int\n                  initVector0 = inputWords0;\n                  initVector1 = inputWords1;\n                  initVector2 = inputWords2;\n                  initVector3 = inputWords3;\n                  offset = offset + 4;\n              }\n              return outputInt32.buffer;\n          }\n          destroy() {\n              this.key = undefined;\n              this.keySize = undefined;\n              this.ksRows = undefined;\n              this.sBox = undefined;\n              this.invSBox = undefined;\n              this.subMix = undefined;\n              this.invSubMix = undefined;\n              this.keySchedule = undefined;\n              this.invKeySchedule = undefined;\n              this.rcon = undefined;\n          }\n      }\n    \n      function removePadding(decryptedData) {\n          const decryptedDataView = new Uint8Array(decryptedData);\n          const padding = decryptedDataView[decryptedData.byteLength - 1];\n          const endOffset = decryptedData.byteLength - 1;\n          // Check for PKCS-7 padding: https://tools.ietf.org/html/rfc2315#section-10.3\n          let checkedBytes = 0;\n          if (padding >= 1 && padding <= 16) {\n              for (let i = endOffset; i > endOffset - padding; i--) {\n                  if (decryptedDataView[i] !== padding) {\n                      break;\n                  }\n                  checkedBytes++;\n              }\n          }\n          if (checkedBytes === padding) {\n              decryptedData = decryptedData.slice(0, endOffset - padding + 1); // keep 0 till 'endOffset - padding', both inclusive, to remove the padding bytes\n          }\n          return decryptedData;\n      }\n    \n      // CryptoRPCServer can run in either Worker or main process depending on config.\n      // So we want to minimize the dependency for it in case it's running in Worker.\n      // Thus we use the vanilla RPCService interface that uses old-school callback\n      // patterns. It has zero dependency: no Promise, no RxJS, just plain JavaScript.\n      class CryptoRPCServer {\n          constructor(rpc, logger) {\n              this.rpc = rpc;\n              this.logger = logger;\n              this.decrypt = (key, iv, alg, cipherText, options) => callback => {\n                  const crypto = global$1.crypto;\n                  if ((options === null || options === void 0 ? void 0 : options.useJSCrypto) || !(crypto === null || crypto === void 0 ? void 0 : crypto.subtle)) {\n                      /**\n                       * JSCrypto\n                       */\n                      const jsCrypto = new JSAESDecryptor();\n                      let plainText;\n                      jsCrypto.expandKey(key);\n                      const result = jsCrypto.decrypt(cipherText, 0, iv);\n                      if (options.plainTextLength) {\n                          plainText = result.slice(0, options.plainTextLength); // The input buffer doesn't have padding, just return the expected bytes.\n                      }\n                      else {\n                          plainText = removePadding(result);\n                      }\n                      this.logger.info(`[JSCrypto]: ${cipherText.byteLength} => ${plainText.byteLength} bytes`);\n                      callback(plainText, undefined, [plainText]);\n                  }\n                  else {\n                      /**\n                       * WebCrypto\n                       */\n                      crypto.subtle\n                          .importKey('raw', key, alg, false, ['decrypt'])\n                          .then((key) => crypto.subtle.decrypt({ name: alg, iv }, key, cipherText))\n                          .then((plainText) => {\n                          this.logger.info(`[WebCrypto]: ${cipherText.byteLength} => ${plainText.byteLength} bytes`);\n                          callback(plainText, undefined, [plainText]);\n                      })\n                          .catch((error) => callback(undefined, error));\n                  }\n              };\n              rpc.register('decrypt', this.decrypt);\n          }\n      }\n    \n      const LoggerRPCClient = (rpcService) => {\n          const bindLogger = (bindings = []) => {\n              const logFn = (level) => (...args) => {\n                  rpcService.invoke('logger.log', [bindings, level, ...args])((res, err) => {\n                      if (err != null)\n                          throw err;\n                  });\n              };\n              const logger = {};\n              ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'qe'].forEach((k) => (logger[k] = logFn(k)));\n              logger.child = (b) => bindLogger([...bindings, b]);\n              return logger;\n          };\n          return bindLogger();\n      };\n    \n      /**\n       * HLS Events\n       *\n       * \n       * \n       *\n       */\n      /**\n       * @readonly\n       * @enum {string}\n       */\n      var HlsEvent;\n      (function (HlsEvent) {\n          // fired before MediaSource is attaching to media element - data: { media }\n          HlsEvent[\"MEDIA_ATTACHING\"] = \"hlsMediaAttaching\";\n          // fired when MediaSource has been succesfully attached to media element - data: { media }\n          HlsEvent[\"MEDIA_ATTACHED\"] = \"hlsMediaAttached\";\n          // fired before detaching MediaSource from media element - data: { }\n          HlsEvent[\"MEDIA_DETACHING\"] = \"hlsMediaDetaching\";\n          // fired when MediaSource has been detached from media element\n          HlsEvent[\"MEDIA_DETACHED\"] = \"hlsMediaDetached\";\n          // fired when sourcebuffers have been created - data: { tracks : tracks }\n          HlsEvent[\"BUFFER_CREATED\"] = \"hlsBufferCreated\";\n          // fired when we append a segment to the buffer - data: { segment: segment object }\n          HlsEvent[\"BUFFER_APPENDING\"] = \"hlsBufferAppending\";\n          // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment, timeRanges : bufferd time ranges }\n          HlsEvent[\"BUFFER_APPENDED\"] = \"hlsBufferAppended\";\n          // fired when the media buffer has been flushed\n          HlsEvent[\"BUFFER_FLUSHED\"] = \"hlsBufferFlushed\";\n          // fired to signal that a manifest loading starts - data: { url: manifestURL }\n          HlsEvent[\"MANIFEST_LOADING\"] = \"hlsManifestLoading\";\n          // fired after manifest has been loaded - data: { levels : [available quality levels including iframe levels], audioTracks : [ available audio tracks], subtitleTracks : [ available subtitle tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}, audioMediaSelectionGroup: audio selection group, subtitleMediaSelectionGroup: subtitle selection group}\n          HlsEvent[\"MANIFEST_LOADED\"] = \"hlsManifestLoaded\";\n          // fired after manifest has been parsed - data: { levels : [available quality levels including iframe levels], firstLevel : index of first quality level appearing in Manifest, stats: stats, audio: audio codec, video: video codec, altAudio: if alternate audio present (true/false), audioTracks: audio tracks, audioMediaSelectionGroup: audio selection group}\n          HlsEvent[\"MANIFEST_PARSED\"] = \"hlsManifestParsed\";\n          // fired when a level switch is requested - data: { level : id of new level }\n          HlsEvent[\"LEVEL_SWITCHING\"] = \"hlsLevelSwitching\";\n          // fired when a level switch is effective - data: { level : id of new level }\n          HlsEvent[\"LEVEL_SWITCHED\"] = \"hlsLevelSwitched\";\n          // fired when a level playlist loading starts - data: { url : level URL, level : level, persistentId: persistent id of level being loaded}\n          HlsEvent[\"LEVEL_LOADING\"] = \"hlsLevelLoading\";\n          // fired when a level playlist loading finishes - data: { details : levelDetails object, level : level, persistentId : persistent id of loaded level, stats : { trequest, tfirst, tload, mtime}, playlistType : playlist type }\n          HlsEvent[\"LEVEL_LOADED\"] = \"hlsLevelLoaded\";\n          // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n          HlsEvent[\"LEVEL_UPDATED\"] = \"hlsLevelUpdated\";\n          // fired when levels list has changed due to any error\n          HlsEvent[\"LEVELS_CHANGED\"] = \"hlsLevelsChanged\";\n          // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n          HlsEvent[\"AUDIO_TRACKS_UPDATED\"] = \"hlsAudioTracksUpdated\";\n          // fired when an audio track switch occurs - data: { id : audio track id, type: track type, url: url  } // deprecated in favor AUDIO_TRACK_SWITCHING\n          HlsEvent[\"AUDIO_TRACK_SWITCH\"] = \"hlsAudioTrackSwitch\";\n          // fired when an audio track switch actually occurs - data: { id : audio track id }\n          HlsEvent[\"AUDIO_TRACK_SWITCHED\"] = \"hlsAudioTrackSwitched\";\n          // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }\n          HlsEvent[\"AUDIO_TRACK_LOADED\"] = \"hlsAudioTrackLoaded\";\n          // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n          HlsEvent[\"SUBTITLE_TRACKS_UPDATED\"] = \"hlsSubtitleTracksUpdated\";\n          // fired to notify that subtitle HTML5 text tracks have been created - data: undefined\n          HlsEvent[\"SUBTITLE_TRACKS_CREATED\"] = \"hlsSubtitleTracksCreated\";\n          // fired when an subtitle track switch occurs - data: { track : subtitle track }\n          HlsEvent[\"SUBTITLE_TRACK_SWITCH\"] = \"hlsSubtitleTrackSwitch\";\n          // fired when inline webvtt styles have been parsed - data: { styles: styles }\n          HlsEvent[\"INLINE_STYLES_PARSED\"] = \"hlsInlineStylesParsed\";\n          // fired when all the session data URI loading finished - data: { }\n          HlsEvent[\"SESSION_DATA_COMPLETE\"] = \"hlsSessionDataComplete\";\n          // fired when a fragment loading starts - data: { frag : fragment object }\n          HlsEvent[\"FRAG_LOADING\"] = \"hlsFragLoading\";\n          // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }\n          HlsEvent[\"FRAG_LOADED\"] = \"hlsFragLoaded\";\n          // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tappendStart, tbuffered, length, bwEstimate } }\n          HlsEvent[\"FRAG_BUFFERED\"] = \"hlsFragBuffered\";\n          // fired when fragment matching with current media position is changing - data : { frag : fragment object }\n          HlsEvent[\"FRAG_CHANGED\"] = \"hlsFragChanged\";\n          // Identifier for an internal error event - data: { type : error type, details : error details, fatal : emitter's suggestion whether the error is fatal or not. can be overruled by handler }\n          HlsEvent[\"INTERNAL_ERROR\"] = \"hlsInternalError\";\n          // Identifier for an public error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n          HlsEvent[\"ERROR\"] = \"hlsError\";\n          // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n          HlsEvent[\"DESTROYING\"] = \"hlsDestroying\";\n          // Key request started data: { keyuri: '' , decryptdata: DecryptData object, timestamp: timestamp of the event }\n          HlsEvent[\"KEY_REQUEST_STARTED\"] = \"hlsKeyRequestStarted\";\n          // data: { 'keyuri': 'licenseChallenge': Uint8Array(challengeBytes) keysystem: }\n          HlsEvent[\"LICENSE_CHALLENGE_CREATED\"] = \"hlsLicenseChallengeCreated\";\n          // EME:\n          // Session remove() was called and returned license-release message. data: { keysystem: '', itemId: itemId, releaseRecord: { CDM specific record destruction } }\n          HlsEvent[\"LICENSE_RELEASED\"] = \"hlsLicenseReleased\";\n          // fired when a decrypt key loading is completed - data: { decryptdata: '', keyuri: '', stats : { trequest, tfirst, tload }, timestamp: timestamp of the event }\n          HlsEvent[\"KEY_LOADED\"] = \"hlsKeyLoaded\";\n          // We encountered a url that doesn't start with http data: { uri: ''}\n          HlsEvent[\"UNRESOLVED_URI_LOADING\"] = \"hlsUnresolvedUriLoading\";\n          // fired when trickplay rate changing completed\n          HlsEvent[\"DESIRED_RATE_CHANGED\"] = \"hlsDesiredRateChanged\";\n          // data: { playbackLikelyToKeepUp }\n          HlsEvent[\"PLAYER_STATE_CHANGE\"] = \"hlsPlayerStateChange\";\n          // When seek starts data: {}\n          HlsEvent[\"SEEKING\"] = \"hlsSeeking\";\n          // When seek ends data: {}\n          HlsEvent[\"SEEKED\"] = \"hlsSeeked\";\n          // When stall detected. Stream controller decides if it will report an error. data: { isLowBufferStall: true|false }\n          HlsEvent[\"STALLED\"] = \"hlsStalled\";\n          // When resumed from stall, either playback restart or user hit pause.\n          HlsEvent[\"RESUME_FROM_STALL\"] = \"hlsResumeFromStall\";\n          // Item fully appended\n          HlsEvent[\"READY_FOR_NEXT_ITEM\"] = \"hlsReadyForNextItem\";\n          // Playback transitioned to next item\n          HlsEvent[\"ITEM_TRANSITIONED\"] = \"hlsItemTransitioned\";\n          // Evict loading item\n          HlsEvent[\"ITEM_EVICTED\"] = \"hlsItemEvicted\";\n          // New EXT-X-DATERANGE data available\n          HlsEvent[\"DATERANGE_UPDATED\"] = \"hlsDaterangeUpdated\";\n      })(HlsEvent || (HlsEvent = {}));\n      var HlsEvent$1 = HlsEvent;\n    \n      /*\n       * Demuxer Events\n       *\n       * \n       */\n      /**\n       * @readonly\n       * @enum {string}\n       */\n      var DemuxerEvent;\n      (function (DemuxerEvent) {\n          // fired when Init Segment has been extracted from fragment - data: { tracks: tracks }\n          DemuxerEvent[\"FRAG_PARSING_INIT_SEGMENT\"] = \"hlsFragParsingInitSegment\";\n          // fired when data have been extracted from fragment - data: { data1: segment, startPTS: start PTS, endPTS: end PTS, startDTS: start DTS, endDTS: end DTS, type: video / audio, nb: number of samples, dropped: is dropped }\n          DemuxerEvent[\"FRAG_PARSING_DATA\"] = \"hlsFragParsingData\";\n          // fired when fragment parsing is completed\n          DemuxerEvent[\"FRAG_PARSED\"] = \"hlsFragParsed\";\n          // fired when the first timestamp is found - data: { initPTS90k: initPTS90k }\n          DemuxerEvent[\"INIT_PTS_FOUND\"] = \"hlsInitPtsFound\";\n      })(DemuxerEvent || (DemuxerEvent = {}));\n    \n      /**\n       * HLS Error\n       *\n       * \n       * \n       *\n       */\n      class HlsError extends Error {\n          constructor(type, details, fatal, reason, response) {\n              super(reason);\n              this.type = type;\n              this.details = details;\n              this.fatal = fatal;\n              this.reason = reason;\n              this.response = response;\n              this.handled = false;\n          }\n      }\n      // Inherited error codes from Core Media\n      const PlaylistNotReceived = { code: -12884, text: 'Playlist not received' };\n      const CryptResponseReceivedSlowly = { code: -16833, text: 'Crypt key received slowly' };\n      const LivePlaylistUpdateError = { code: -12888, text: 'Live playlist not updated' };\n      const NoResponseFromMediaRequest = { code: -12889, text: 'No response for fragment' };\n      const IncompatibleAsset = { code: -12927, text: 'IncompatibleAsset' };\n      const CorruptStream = { code: -16041, text: 'Corrupt fragment' };\n      const InternalError = { code: -12645, text: 'InternalException' };\n      const CantSwitchInTime = { code: -12644, text: 'CantSwitchInTime' };\n      const VideoDecoderBadDataErr = { code: -12909, text: 'Buffer error' };\n      const InsufficientDataAvailable = { code: -12928, text: 'Incomplete data' };\n      const AllocationFailed = { code: -12862, text: 'AllocationFailed' };\n      const PlaylistErrorMissingEXTM3U = { code: -12269, text: 'Response doesnt have #EXTM3U tag' };\n      const PlaylistErrorInvalidEntry = { code: -12264, text: 'Invalid entry' };\n      const PlaylistErrorBadTargetDuration = { code: -12271, text: 'Invalid targetduration' };\n      const NoValidAlternates = { code: -12925, text: 'No valid alternates' };\n      const FormatError = { code: -12642, text: 'Incorrect playlist format' };\n      // HLSJS Specific error codes\n      const UnsupportedKeySystemError = { code: -60000, text: 'Unsupported Key System' };\n      const EmptyLoadSourceError = { code: -60001, text: 'Empty loadSource url' };\n      const UndefinedItemIdError = { code: -60002, text: 'Undefined itemId' };\n      const ManifestParseError = { code: -60003, text: 'Manifest parse error' };\n      const DemuxWorkerError = { code: -60004, text: 'Demux worker error' };\n      const DecryptWorkerError = { code: -60005, text: 'Decrypt worker error' };\n      const OutOfRangeSeekError = { code: -60006, text: 'Seeked out of playable range' };\n      const ExceptionInKeyLoadError = { code: -60007, text: 'Exception in Key load' };\n      const FragmentAbortError$1 = { code: -60008, text: 'Fragment abort error' };\n      const ManifestTimeoutError = { code: -60009, text: 'Manifest Timeout Error' };\n      const PlaylistTimeoutError = { code: -60010, text: 'Playlist Timeout Error' };\n      const FragmentTimeoutError = { code: -60011, text: 'Fragment Timeout Error' };\n      const IncompleteSessionData = { code: -60012, text: 'Session data not complete after loading all items' };\n      const SessionDataLoadTimeout = { code: -60013, text: 'Session data load timeout' };\n      const FailedDemuxerSanityCheck = { code: -60014, text: 'Failed demuxer sanity check' };\n      const InvalidADTSSamplingIndex = { code: -60015, text: 'Invalid ADTS sampling index' };\n      const DemuxerNotFound = { code: -60016, text: 'No demux matching with content found' };\n      const InvalidInitTimestamp = { code: -60017, text: 'Invalid initPTS or initDTS' };\n      const NoAVSamplesFound = { code: -60018, text: 'no audio/video samples found' };\n      const NoTSSyncByteFound = { code: -60019, text: 'TS packet did not start with 0x47' };\n      const PESDidNotStartWithADTS = { code: -60020, text: 'AAC PES did not start with ADTS header' };\n      const NoADTSHeaderInPES = { code: -60021, text: 'No ADTS header found in AAC PES' };\n      const InvalidDolbyAudioMagic = { code: -60022, text: 'Invalid dolby audio magic' };\n      const FailedToAllocateVideoMdat = { code: -60023, text: 'Fail allocating video mdat' };\n      const FailedToAllocateAudioMdat = { code: -60024, text: 'Fail allocating audio mdat' };\n      const InsufficientEC3Data = { code: -60025, text: 'Error parsing ec-3, not enough data' };\n      const InvalidEC3Magic = { code: -60026, text: 'Invalid ec-3 magic' };\n      const ReservedStreamType = { code: -60027, text: 'Reserved stream type' };\n      const InsufficientAC3Data = { code: -60028, text: 'error parsing ac-3, not enough data' };\n      const InvalidAC3Magic = { code: -60029, text: 'Invalid ac-3 magic' };\n      const InvalidAC3SamplingRateCode = { code: -60030, text: 'Invalid ac-3 samplingRateCode' };\n      const PlaylistErrorInvalidEXTXDEFINE = { code: -61000, text: 'Encountered undefined/not imported EXT-X-DEFINE property' };\n      const PlaylistErrorMissingImportReference = { code: -61001, text: 'IMPORT references variable not in master playlist and/or NAME' };\n      const PlaylistErrorInvalidSERVERURI = { code: -61002, text: 'Encountered undefined/invalid SERVER-URI attribute for EXT-X-CONTENT-STEERING tag' };\n      const PlaylistErrorInvalidPATHWAYID = { code: -61003, text: 'Encountered invalid PATHWAY-ID attribute for EXT-X-CONTENT-STEERING tag' };\n      const PlaylistErrorInvalidSCORE = { code: -61004, text: 'Encountered negative/non-number SCORE property' };\n      const KeySystemFailedToUpdateSession = { code: -62000, text: 'KeySystem: Promise Rejected while updating session' };\n      const KeySystemFailedToGenerateLicenseRenewal = { code: -62001, text: 'KeySystem: Failed to generate license renewal' };\n      const KeySystemFailedToGenerateLicenseRequest = { code: -62002, text: 'KeySystem: Failed to generate license request' };\n      const KeySystemAbort = { code: -62003, text: 'KeySystem: Aborted' };\n      const KeySystemUnexpectedStateTransition = { code: -62004, text: 'KeySystem: Unexpected state transition' };\n      const KeySystemUnexpectedState = { code: -62005, text: 'KeySystem: Unexpected state' };\n      const KeySystemCDMUnknownError = { code: -62006, text: 'KeySystem: Unknown error from CDM' };\n      const KeySystemRequestTimedOut = { code: -62007, text: 'Key request timed out' };\n      const KeySystemUnexpectedMETHOD = { code: -62008, text: 'Unexpected METHOD attribute' };\n      const KeySystemUnmatchedString = { code: -62009, text: 'KeySystem: string does not match' };\n      const KeySystemInternalError = { code: -62010, text: 'KeySystem: internal-error' };\n      const KeySystemOutputRestricted = { code: -62011, text: 'KeySystem: output-restricted' };\n      const KeySystemSetupError = { code: -62012, text: 'KeySystem: setup error' };\n      const KeySystemFailedToInitialize = { code: -62013, text: 'KeySystem: could not initialize' };\n      const KeySystemFailedToCreateSession = { code: -62014, text: 'KeySystem: could not create session' };\n      const KeySystemUndefinedNavigator = { code: -62015, text: 'KeySystem: navigator undefined' };\n      const KeySystemNoKeySystemsToTry = { code: -62016, text: 'KeySystem: no key systems to try' };\n      const KeySystemNoConstructor = { code: -62017, text: 'KeySystem: No constructor' };\n      const KeySystemNoKeySystemAccess = { code: -62018, text: 'KeySystem: No KeySystemAccess' };\n      const KeySystemCertificateLoadError = { code: -62019, text: 'KeySystem: Certificate Load Error' };\n      class PlaylistParsingError extends HlsError {\n          constructor(type, details, fatal, reason, response) {\n              super(type, details, fatal, reason, response);\n              this.response = response;\n          }\n      }\n      const ErrorResponses = {\n          // Inherited error codes from Core Media\n          PlaylistNotReceived,\n          CryptResponseReceivedSlowly,\n          LivePlaylistUpdateError,\n          NoResponseFromMediaRequest,\n          IncompatibleAsset,\n          CorruptStream,\n          InternalError,\n          CantSwitchInTime,\n          VideoDecoderBadDataErr,\n          InsufficientDataAvailable,\n          AllocationFailed,\n          PlaylistErrorMissingEXTM3U,\n          PlaylistErrorInvalidEntry,\n          PlaylistErrorBadTargetDuration,\n          NoValidAlternates,\n          FormatError,\n          // HLSJS Specific error codes\n          UnsupportedKeySystemError,\n          EmptyLoadSourceError,\n          UndefinedItemIdError,\n          ManifestParseError,\n          DemuxWorkerError,\n          DecryptWorkerError,\n          OutOfRangeSeekError,\n          ExceptionInKeyLoadError,\n          FragmentAbortError: FragmentAbortError$1,\n          ManifestTimeoutError,\n          PlaylistTimeoutError,\n          FragmentTimeoutError,\n          IncompleteSessionData,\n          SessionDataLoadTimeout,\n          FailedDemuxerSanityCheck,\n          InvalidADTSSamplingIndex,\n          DemuxerNotFound,\n          InvalidAC3Magic,\n          InvalidInitTimestamp,\n          NoAVSamplesFound,\n          NoTSSyncByteFound,\n          PESDidNotStartWithADTS,\n          NoADTSHeaderInPES,\n          InvalidDolbyAudioMagic,\n          FailedToAllocateVideoMdat,\n          FailedToAllocateAudioMdat,\n          InsufficientEC3Data,\n          InvalidEC3Magic,\n          ReservedStreamType,\n          InsufficientAC3Data,\n          InvalidAC3SamplingRateCode,\n          PlaylistErrorInvalidEXTXDEFINE,\n          PlaylistErrorMissingImportReference,\n          PlaylistErrorInvalidSERVERURI,\n          PlaylistErrorInvalidPATHWAYID,\n          PlaylistErrorInvalidSCORE,\n          KeySystemFailedToUpdateSession,\n          KeySystemFailedToGenerateLicenseRenewal,\n          KeySystemFailedToGenerateLicenseRequest,\n          KeySystemAbort,\n          KeySystemUnexpectedStateTransition,\n          KeySystemUnexpectedState,\n          KeySystemCDMUnknownError,\n          KeySystemRequestTimedOut,\n          KeySystemUnexpectedMETHOD,\n          KeySystemUnmatchedString,\n          KeySystemInternalError,\n          KeySystemOutputRestricted,\n          KeySystemSetupError,\n          KeySystemFailedToInitialize,\n          KeySystemFailedToCreateSession,\n          KeySystemUndefinedNavigator,\n          KeySystemNoKeySystemsToTry,\n          KeySystemNoConstructor,\n          KeySystemNoKeySystemAccess,\n          KeySystemCertificateLoadError,\n      };\n      const ErrorTypes = {\n          // Identifier for a network error (loading error / timeout ...)\n          NETWORK_ERROR: 'networkError',\n          // Identifier for a media Error (video/parsing/mediasource error)\n          MEDIA_ERROR: 'mediaError',\n          // Identifier for a mux Error (demuxing/remuxing)\n          MUX_ERROR: 'muxError',\n          // Identifier for a key system error (EME)\n          KEY_SYSTEM_ERROR: 'keySystemError',\n          // Identifier for all other errors\n          OTHER_ERROR: 'otherError',\n      };\n      const ErrorDetails = {\n          // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n          MANIFEST_LOAD_ERROR: 'manifestLoadError',\n          // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n          MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',\n          // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}\n          MANIFEST_PARSING_ERROR: 'manifestParsingError',\n          // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}\n          MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',\n          // Identifier for a manifest with only incompatible video-range error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}\n          MANIFEST_INCOMPATIBLE_VIDEO_RANGE_ERROR: 'manifestIncompatibleVideoRangeError',\n          // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n          LEVEL_LOAD_ERROR: 'levelLoadError',\n          // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n          LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',\n          // Identifier for a level switch error - data: { level : faulty level Id, event : error description, response : { code: error code, text: error text }}\n          LEVEL_SWITCH_ERROR: 'levelSwitchError',\n          // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n          AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',\n          // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n          AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',\n          // Identifier for an subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n          SUBTITLE_TRACK_LOAD_ERROR: 'subtitleTrackLoadError',\n          // Identifier for an subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n          SUBTITLE_TRACK_LOAD_TIMEOUT: 'subtitleTrackLoadTimeout',\n          // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n          FRAG_LOAD_ERROR: 'fragLoadError',\n          // Identifier for fragment loop loading error - data: { frag : fragment object, fatal:, response: { code: error code, text: error text }}\n          FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',\n          // Identifier for fragment load timeout error - data: { frag : fragment object, response : { code: error code, text: error text }}\n          FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',\n          // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description , response : { code: error code, text: error text }}\n          FRAG_DECRYPT_ERROR: 'fragDecryptError',\n          // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description, response : { code: error code, text: error text } }\n          // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n          FRAG_PARSING_ERROR: 'fragParsingError',\n          // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text, response: { code: error code, text: error text }}\n          REMUX_ALLOC_ERROR: 'remuxAllocError',\n          // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : {  err : exception , mimeType : mimeType , response : { code: error code, text: error text }}\n          BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',\n          // Identifier for a buffer append error - data: {append error description, response : { code: error code, text: error text }}\n          BUFFER_APPEND_ERROR: 'bufferAppendError',\n          // Identifier for a buffer appending error event - data: {appending error description, response : { code: error code, text: error text }}\n          BUFFER_APPENDING_ERROR: 'bufferAppendingError',\n          // Identifier for a buffer stalled error event - data: {fatal:, bufferLen: , response : { code: error code, text: error text }}\n          BUFFER_STALLED_ERROR: 'bufferStalledError',\n          // Identifier for a buffer full event - data: {fatal:, response : { code: error code, text: error text }}\n          BUFFER_FULL_ERROR: 'bufferFullError',\n          // Identifier for a buffer seek over hole event- data: {fatal:, response : { code: error code, text: error text }}\n          BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',\n          // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area) data: {fatal:, response : { code: error code, text: error text }}\n          BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',\n          // Identifier for an internal exception happening inside hls.js while handling an event\n          // data: { url: , fatal:, response: { code: error code, text: error text } }\n          INTERNAL_EXCEPTION: 'internalException',\n          // Malformed WebVTT contents\n          WEBVTT_EXCEPTION: 'webVTTException',\n          // KEY REQUEST ERRORS\n          // Identifier for decrypt key load error - data: { decryptdata: DecryptData object, stats: { tfirstissue, tlastissue, failCount } response: {code: status code returned from server, text: error message}}\n          KEY_LOAD_ERROR: 'keyLoadError',\n          // Identifier for decrypt key load timeout error - data: { decryptdata: DecryptData object, stats: { tfirstissue, tlastissue, failCount }, response: { code: error code, text: error message }}\n          KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',\n          // Identifier for CDM error - data: { decryptdata: DecryptData object, stats: { tfirstissue, tlastissue, failCount }, reason: error message, response: { code: error code, text: error message }}\n          KEY_SYSTEM_GENERIC_ERROR: 'keySystemGenericError',\n          // data: { url: , fatal:, response: { code: error code, text: error text } }\n          CERT_LOAD_ERROR: 'certificateLoadError',\n          // data: { url: , fatal:, response: { code: error code, text: error text } }\n          CERT_LOAD_TIMEOUT: 'certificateLoadTimeOut',\n          // Identifier for session data item load error - data: { sessionId: '', response : { code: error code, text: error text }}\n          SESSION_DATA_LOAD_ERROR: 'sessionDataLoadError',\n          // Identifier for session data item load timeout error - data: { sessionId: '' , response : { code: error code, text: error text }}\n          SESSION_DATA_LOAD_TIMEOUT: 'sessionDataLoadTimeOut',\n          // Identifier for a Conetent Steering manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n          STEERING_MANIFEST_LOAD_ERROR: 'steeringManifestLoadError',\n          // Identifier for a Conetent Steering manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n          STEERING_MANIFEST_LOAD_TIMEOUT: 'steeringManifestLoadTimeOut',\n          // Identifier for a Conetent Steering manifest parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}\n          STEERING_MANIFEST_PARSING_ERROR: 'steeringManifestParsingError',\n      };\n      /**\n       * @brief If no other error fits, use this error.\n       */\n      class ExceptionError extends HlsError {\n          constructor(fatal, reason, response) {\n              super(ErrorTypes.OTHER_ERROR, ErrorDetails.INTERNAL_EXCEPTION, fatal, reason, response);\n          }\n      }\n    \n      class FragParsingError extends HlsError {\n          constructor(fatal, reason, response) {\n              super(ErrorTypes.MEDIA_ERROR, ErrorDetails.FRAG_PARSING_ERROR, fatal, reason, response);\n          }\n      }\n      class RemuxAllocError extends HlsError {\n          constructor(fatal, reason, response, bytes) {\n              super(ErrorTypes.MUX_ERROR, ErrorDetails.REMUX_ALLOC_ERROR, fatal, reason, response);\n              this.bytes = bytes;\n          }\n      }\n    \n      function convertTimestampToSeconds(ts) {\n          return ts.baseTime / ts.timescale;\n      }\n      function convertSecondsToTimestamp(sec, timescale) {\n          return {\n              baseTime: Math.floor(sec * timescale),\n              timescale,\n          };\n      }\n      function convertTimescale(ts, timescale) {\n          return {\n              baseTime: Math.floor((ts.baseTime * timescale) / ts.timescale),\n              timescale,\n          };\n      }\n      function determineMinTimestamp(a, b) {\n          const aSec = convertTimestampToSeconds(a);\n          const bSec = convertTimestampToSeconds(b);\n          return aSec < bSec ? a : b;\n      }\n      function determineMaxTimestamp(a, b) {\n          const aSec = convertTimestampToSeconds(a);\n          const bSec = convertTimestampToSeconds(b);\n          return aSec > bSec ? a : b;\n      }\n      /**\n       * @returns returns a - b in seconds\n       */\n      function diffSeconds(a, b) {\n          return convertTimestampToSeconds(a) - convertTimestampToSeconds(b);\n      }\n    \n      class EventEmitterPolyfill {\n          constructor() {\n              this.eventMap = {};\n          }\n          _on(eventName, eventRecord, prepend = false) {\n              if (this.eventMap[eventName] == null) {\n                  this.eventMap[eventName] = [];\n              }\n              if (prepend) {\n                  this.eventMap[eventName].splice(0, 0, eventRecord);\n              }\n              else {\n                  this.eventMap[eventName].push(eventRecord);\n              }\n              return this;\n          }\n          _off(eventName, record) {\n              if (this.eventMap[eventName] != null) {\n                  this.eventMap[eventName] = this.eventMap[eventName].filter(r => r.listener !== record.listener);\n                  if (this.eventMap[eventName].length === 0) {\n                      delete this.eventMap[eventName];\n                  }\n              }\n              return this;\n          }\n          on(eventName, listener) {\n              return this._on(eventName, { listener, once: false });\n          }\n          off(eventName, listener) {\n              return this._off(eventName, { listener });\n          }\n          addListener(eventName, listener) {\n              return this.on(eventName, listener);\n          }\n          once(eventName, listener) {\n              return this._on(eventName, { listener, once: true });\n          }\n          removeListener(eventName, listener) {\n              return this.off(eventName, listener);\n          }\n          removeAllListeners(event) {\n              delete this.eventMap[event];\n              return this;\n          }\n          setMaxListeners(n) {\n              return this;\n          }\n          getMaxListeners() {\n              return Infinity;\n          }\n          // eslint-disable-next-line @typescript-eslint/ban-types\n          listeners(eventName) {\n              if (this.eventMap[eventName] == null) {\n                  return [];\n              }\n              return this.eventMap[eventName].map(r => r.listener);\n          }\n          // eslint-disable-next-line @typescript-eslint/ban-types\n          rawListeners(eventName) {\n              return this.listeners(eventName);\n          }\n          emit(eventName, ...args) {\n              if (this.eventMap[eventName] == null) {\n                  return false;\n              }\n              let emitted = false;\n              for (const record of this.eventMap[eventName]) {\n                  try {\n                      record.listener.apply(this, args);\n                      // eslint-disable-next-line no-empty\n                  }\n                  catch (err) { }\n                  emitted = true;\n              }\n              return emitted;\n          }\n          listenerCount(eventName) {\n              if (this.eventMap[eventName] == null) {\n                  return 0;\n              }\n              return this.eventMap[eventName].length;\n          }\n          prependListener(eventName, listener) {\n              return this._on(eventName, { listener, once: false }, true);\n          }\n          prependOnceListener(eventName, listener) {\n              return this._on(eventName, { listener, once: true }, true);\n          }\n          eventNames() {\n              return Object.keys(this.eventMap);\n          }\n      }\n      const EventEmitter = typeof global$1.Buffer !== 'undefined' ? (r => r('events'))(require).EventEmitter : EventEmitterPolyfill;\n    \n      /**\n       * Simple adapter sub-class of Nodejs-like EventEmitter.\n       */\n      class Observer extends EventEmitter {\n          /**\n           * We simply want to pass along the event-name itself\n           * in every call to a handler, which is the purpose of our `trigger` method\n           * extending the standard API.\n           */\n          trigger(event, data) {\n              this.emit(event, data);\n          }\n      }\n    \n      \n      const loggerName$l = { name: 'ADTS' };\n      const ADTS = {\n          getAudioConfig: function (observer, data, offset, audioCodec, logger) {\n              let adtsObjectType; // :int\n              let extensionSamplingIndex; // :int\n              let adtsChanelConfig; // :int\n              let config;\n              const userAgent = navigator.userAgent.toLowerCase();\n              const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];\n              // byte 2\n              adtsObjectType = ((data[offset + 2] & 192) >>> 6) + 1;\n              const adtsSamplingIndex = (data[offset + 2] & 60) >>> 2;\n              if (adtsSamplingIndex > adtsSamplingRates.length - 1) {\n                  const payload = new FragParsingError(true, `invalid ADTS sampling index:${adtsSamplingIndex}`, ErrorResponses.InvalidADTSSamplingIndex);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return;\n              }\n              adtsChanelConfig = (data[offset + 2] & 1) << 2;\n              // byte 3\n              adtsChanelConfig |= (data[offset + 3] & 192) >>> 6;\n              logger.info(loggerName$l, `manifest codec:${audioCodec},ADTS data:type:${adtsObjectType},samplingIndex:${adtsSamplingIndex}[${adtsSamplingRates[adtsSamplingIndex]}Hz],channelConfig:${adtsChanelConfig}`);\n              // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n              if (/firefox/i.test(userAgent)) {\n                  if (adtsSamplingIndex >= 6) {\n                      adtsObjectType = 5;\n                      config = new Array(4);\n                      // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n                      // there is a factor 2 between frame sample rate and output sample rate\n                      // multiply frequency by 2 (see table below, equivalent to substract 3)\n                      extensionSamplingIndex = adtsSamplingIndex - 3;\n                  }\n                  else {\n                      adtsObjectType = 2;\n                      config = new Array(2);\n                  }\n                  // Android : always use AAC\n              }\n              else if (userAgent.indexOf('android') !== -1) {\n                  adtsObjectType = 2;\n                  config = new Array(2);\n              }\n              else {\n                  /*  for other browsers (Chrome/Vivaldi/Opera ...)\n                      always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n                  */\n                  adtsObjectType = 5;\n                  config = new Array(4);\n                  // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n                  if ((audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1)) || (!audioCodec && adtsSamplingIndex >= 6)) {\n                      // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n                      // there is a factor 2 between frame sample rate and output sample rate\n                      // multiply frequency by 2 (see table below, equivalent to substract 3)\n                      extensionSamplingIndex = adtsSamplingIndex - 3;\n                  }\n                  else {\n                      // if (manifest codec is AAC) OR (manifest codec not specified and mono audio)\n                      // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC.  This is not a problem with stereo.\n                      if ((audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1) || (!audioCodec && adtsChanelConfig === 1)) {\n                          adtsObjectType = 2;\n                          config = new Array(2);\n                      }\n                      extensionSamplingIndex = adtsSamplingIndex;\n                  }\n              }\n              /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n                  ISO 14496-3 (AAC).pdf - Table 1.13 â€” Syntax of AudioSpecificConfig()\n                Audio Profile / Audio Object Type\n                0: Null\n                1: AAC Main\n                2: AAC LC (Low Complexity)\n                3: AAC SSR (Scalable Sample Rate)\n                4: AAC LTP (Long Term Prediction)\n                5: SBR (Spectral Band Replication)\n                6: AAC Scalable\n               sampling freq\n                0: 96000 Hz\n                1: 88200 Hz\n                2: 64000 Hz\n                3: 48000 Hz\n                4: 44100 Hz\n                5: 32000 Hz\n                6: 24000 Hz\n                7: 22050 Hz\n                8: 16000 Hz\n                9: 12000 Hz\n                10: 11025 Hz\n                11: 8000 Hz\n                12: 7350 Hz\n                13: Reserved\n                14: Reserved\n                15: frequency is written explictly\n                Channel Configurations\n                These are the channel configurations:\n                0: Defined in AOT Specifc Config\n                1: 1 channel: front-center\n                2: 2 channels: front-left, front-right\n              */\n              // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n              config[0] = adtsObjectType << 3;\n              // samplingFrequencyIndex\n              config[0] |= (adtsSamplingIndex & 14) >> 1;\n              config[1] |= (adtsSamplingIndex & 1) << 7;\n              // channelConfiguration\n              config[1] |= adtsChanelConfig << 3;\n              if (adtsObjectType === 5) {\n                  // extensionSamplingIndex\n                  config[1] |= (extensionSamplingIndex & 14) >> 1;\n                  config[2] = (extensionSamplingIndex & 1) << 7;\n                  // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n                  //    https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n                  config[2] |= 2 << 2;\n                  config[3] = 0;\n              }\n              const audioConfig = { esdsConfig: config, samplerate: adtsSamplingRates[adtsSamplingIndex], channelCount: adtsChanelConfig, segmentCodec: 'aac', codec: 'mp4a.40.' + adtsObjectType };\n              return audioConfig;\n          },\n      };\n    \n      class DemuxerBase {\n          constructor(observer, remuxer, config, typeSupported, logger) {\n              this.observer = observer;\n              this.remuxer = remuxer;\n              this.config = config;\n              this.typeSupported = typeSupported;\n              this.logger = logger;\n          }\n          static probe(data, logger) {\n              throw new Error('Method not implemented');\n          }\n          resetTimeStamp(initPTS90k) { }\n          resetInitSegment(initSegment, duration, keyTagInfo, discontinuity) { }\n          destroy() { }\n      }\n      class EsDemuxer extends DemuxerBase {\n          constructor(observer, remuxer, config, typeSupported, logger) {\n              super(observer, remuxer, config, typeSupported, logger);\n              this.observer = observer;\n              this.remuxer = remuxer;\n              this.config = config;\n              this.typeSupported = typeSupported;\n              this.logger = logger;\n              this.esRemuxer = remuxer;\n          }\n      }\n      class RemuxerBase {\n          constructor(observer, config, logger) {\n              this.observer = observer;\n              this.config = config;\n              this.logger = logger;\n          }\n          resetInitSegment() { }\n          resetTimeStamp(initPTS90k) { }\n          destroy() { }\n      }\n    \n      /*\n       * 2018 Apple Inc. All rights reserved.\n       */\n      var _a$1;\n      let te;\n      let td;\n      const BrowserBufferUtils = {\n          /**\n           * Convert a string object into a uint8Array containing utf-8 encoded text\n           * @param str The string to convert\n           * @returns A uint8Array containing utf-8 encoded text\n        \n        \n           */\n          strToUtf8array(str) {\n              if (!te) {\n                  te = new TextEncoder();\n              }\n              return te.encode(str);\n          },\n          /**\n           * Convert a uint8Array containing utf-8 encoded text into a string object\n           * @param array The array to convert containing utf-8 encoded text\n           * @returns A DOMString containing the decoded text\n           */\n          utf8arrayToStr(array) {\n              if (!td) {\n                  td = new TextDecoder('utf-8');\n              }\n              return td.decode(array);\n          },\n      };\n      const NodeJSBufferUtils = {\n          /**\n           * Convert a string object into a uint8Array containing utf-8 encoded text\n           * @param str The string to convert\n           * @returns A uint8Array containing utf-8 encoded text\n           */\n          strToUtf8array(str) {\n              const buffer = global$1.Buffer.from(str, 'utf-8');\n              return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n          },\n          /**\n           * Convert a uint8Array containing utf-8 encoded text into a string object\n           * @param array The array to convert containing utf-8 encoded text\n           * @returns A DOMString containing the decoded text\n           */\n          utf8arrayToStr(array) {\n              return global$1.Buffer.from(array).toString('utf-8');\n          },\n      };\n      const FallbackBufferUtils = {\n          /**\n           * Convert a string object into a uint8Array containing utf-8 encoded text\n           * @param str The string to convert\n           * @returns A uint8Array containing utf-8 encoded text\n           */\n          strToUtf8array(str) {\n              const utf8 = unescape(encodeURIComponent(str));\n              const result = new Uint8Array(utf8.length);\n              for (let i = 0; i < utf8.length; i++) {\n                  result[i] = utf8.charCodeAt(i);\n              }\n              return result;\n          },\n          /**\n           * Convert a uint8Array containing utf-8 encoded text into a string object\n           * @param array The array to convert containing utf-8 encoded text\n           * @returns A DOMString containing the decoded text\n           */\n          utf8arrayToStr(array) {\n              return String.fromCharCode.apply(null, Array.from(array));\n          },\n      };\n      let BufferUtils = FallbackBufferUtils;\n      if (typeof TextEncoder !== 'undefined' && typeof TextDecoder !== 'undefined') {\n          BufferUtils = BrowserBufferUtils;\n      }\n      else if (typeof ((_a$1 = global$1.Buffer) === null || _a$1 === void 0 ? void 0 : _a$1.from) === 'function') {\n          BufferUtils = NodeJSBufferUtils;\n      }\n    \n      \n      const loggerName$k = { name: 'ID3' };\n      class ID3 {\n          // TODO: <jgainfort 18Mar2021> I am not comfortable with infinite loop ....\n          constructor(data, logger) {\n              this.logger = logger;\n              this._hasTimeStamp = false;\n              this._audioType = null;\n              this._length = 0;\n              this._frames = [];\n              let offset = 0, tagSize, endPos, header, len;\n              do {\n                  header = ID3.readUTF(data, offset, 3);\n                  offset += 3;\n                  // first check for ID3 header\n                  if (header === 'ID3') {\n                      // v2.* tags only\n                      // skip 16 bit version\n                      this._minor = data[offset++];\n                      this._revision = data[offset++];\n                      const tagFlags = data[offset++]; // 1 byte flag (top 3 bits used)\n                      if (tagFlags & 128) {\n                          // is unsynchroized\n                          this._unsynchronized = true;\n                          this.logger.error(loggerName$k, 'id3 tag is unsynchronized');\n                      }\n                      if (tagFlags & 64) {\n                          this._hasExtendedHeader = true;\n                          this.logger.warn(loggerName$k, 'id3 tag has extended header');\n                      }\n                      // retrieve tag(s) length\n                      // The ID3v2 tag size is the sum of the byte length of the extended\n                      // header, the padding and the frames after unsynchronisation. If a\n                      // footer is present this equals to ('total size' - 20) bytes, otherwise\n                      // ('total size' - 10) bytes.\n                      tagSize = ID3.readSynchSafeUint32(data.subarray(offset, offset + 4));\n                      offset += 4;\n                      endPos = offset + tagSize; // tagSize accounts for extended header\n                      if (this._hasExtendedHeader) {\n                          // has extended header\n                          const extendedHeaderSize = ID3.readSynchSafeUint32(data.subarray(offset, offset + 4));\n                          this.logger.warn(loggerName$k, `id3 tag has ${extendedHeaderSize}-byte extended header. usually 6 or 10 bytes`);\n                          offset += extendedHeaderSize;\n                      }\n                      // read ID3 frames\n                      if (this.minor > 2) {\n                          this._parseID3Frames(data, offset, endPos);\n                      }\n                      else {\n                          this.logger.error(loggerName$k, '[id3] doesn\\'t support older than v2.3 tags');\n                      }\n                      offset = endPos;\n                  }\n                  else if (header === '3DI') {\n                      // http://id3.org/id3v2.4.0-structure chapter 3.4.   ID3v2 footer\n                      offset += 7;\n                  }\n                  else {\n                      offset -= 3;\n                      len = offset;\n                      if (len) {\n                          if (!this.hasTimeStamp) {\n                              this.logger.warn(loggerName$k, 'ID3 tag found, but no timestamp');\n                          }\n                          this._length = len;\n                          this._payload = data.slice(0, len);\n                      }\n                      return;\n                  }\n              } while (true); // eslint-disable-line\n          }\n          static isHeader(data, offset) {\n              if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) {\n                  // check version is within range\n                  if (data[offset + 3] < 255 && data[offset + 4] < 255) {\n                      // check size is within range\n                      if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) {\n                          return true;\n                      }\n                  }\n              }\n              return false;\n          }\n          static readSynchSafeUint32(data) {\n              return (data[0] & 127) * 2097152 + (data[1] & 127) * 16384 + (data[2] & 127) * 128 + (data[3] & 127);\n          }\n          static readUTF(data, start, len) {\n              let result = '', offset = start;\n              const end = start + len;\n              do {\n                  result += String.fromCharCode(data[offset++]);\n              } while (offset < end);\n              return result;\n          }\n          isID3Frame(data, offset) {\n              if (data[offset + 4] < 128 && data[offset + 5] < 128 && data[offset + 6] < 128 && data[offset + 7] < 128) {\n                  return true;\n              }\n              return false;\n          }\n          decodeID3Frame(frame) {\n              if (frame.type === 'TXXX') {\n                  return this.decodeTxxxFrame(frame);\n              }\n              else if (frame.type === 'WXXX') {\n                  return this.decodeWxxxFrame(frame);\n              }\n              else if (frame.type === 'PRIV') {\n                  return this.decodePrivFrame(frame);\n              }\n              else if (frame.type[0] === 'T') {\n                  return this.decodeTextFrame(frame);\n              }\n              else {\n                  return { key: frame.type, data: frame.data };\n              }\n          }\n          decodeTxxxFrame(frame) {\n              /*\n              Format:\n              [0]   = {Text Encoding}\n              [1-?] = {Description}\\0{Value}\n              */\n              if (frame.size < 2) {\n                  return undefined;\n              }\n              if (frame.data[0] !== 3) {\n                  // only support UTF-8\n                  return undefined;\n              }\n              let index = 1;\n              const description = this.id3utf8ArrayToStr(frame.data.subarray(index));\n              index += description.length + 1;\n              const value = this.id3utf8ArrayToStr(frame.data.subarray(index));\n              return { key: 'TXXX', description, data: value };\n          }\n          decodeWxxxFrame(frame) {\n              /*\n              Format:\n              [0]   = {Text Encoding}\n              [1-?] = {Description}\\0{Value}\n              */\n              if (frame.size < 2) {\n                  return undefined;\n              }\n              if (frame.data[0] !== 3) {\n                  // only support UTF-8\n                  return undefined;\n              }\n              let index = 1;\n              const description = this.id3utf8ArrayToStr(frame.data.subarray(index));\n              index += description.length + 1;\n              // Need to use the BufferUtils version of utf8arrayToStr since it works\n              // with arrays that doesn't have a '\\0' in the end of the array.\n              const value = BufferUtils.utf8arrayToStr(frame.data.subarray(index));\n              return { key: 'WXXX', description, data: value };\n          }\n          decodeTextFrame(frame) {\n              /*\n              Format:\n              [0]   = {Text Encoding}\n              [1-?] = {Value}\n              */\n              if (frame.size < 2) {\n                  return undefined;\n              }\n              if (frame.data[0] !== 3) {\n                  // only support UTF-8\n                  return undefined;\n              }\n              const data = frame.data.subarray(1);\n              return { key: frame.type, data: this.id3utf8ArrayToStr(data) };\n          }\n          decodePrivFrame(frame) {\n              /*\n              Format: <text string>\\0<binary data>\n              */\n              if (frame.size < 2) {\n                  return undefined;\n              }\n              const owner = this.id3utf8ArrayToStr(frame.data);\n              const privateData = frame.data.slice(owner.length + 1);\n              return { key: 'PRIV', info: owner, data: privateData };\n          }\n          _extractID3Frame(data, frameId, frameLen, frameBodyOffset, endPos) {\n              const frameEnd = frameBodyOffset + frameLen;\n              let frame;\n              if (frameEnd <= endPos) {\n                  frame = { type: frameId, data: data.slice(frameBodyOffset, frameEnd) };\n              }\n              else {\n                  this.logger.error(loggerName$k, `id3 frame ${frameId} size ${frameLen} exceeded ${endPos}`);\n              }\n              return frame;\n          }\n          _parseID3Frames(data, offset, endPos) {\n              let tagId, tagLen, tagStart, timestamp;\n              while (offset + 8 <= endPos) {\n                  this.logger.info(loggerName$k, `[id3] _parseID3Frames ${offset} ${endPos}`);\n                  if (!this.isID3Frame(data, offset)) {\n                      this.logger.error(loggerName$k, `[id3] illegal id3 frame @ offset ${offset}. skip this id3 tag`);\n                      return;\n                  }\n                  tagId = ID3.readUTF(data, offset, 4);\n                  offset += 4;\n                  if (tagId === '') {\n                      this.logger.info(loggerName$k, '[id3] empty tagId. padding.');\n                      return;\n                  }\n                  tagLen = ID3.readSynchSafeUint32(data.subarray(offset, offset + 4));\n                  if (tagLen === 0) {\n                      this.logger.info(loggerName$k, '[id3] zero tag length. padding.');\n                      return;\n                  }\n                  offset += 4;\n                  data[offset++] << (8 + data[offset++]);\n                  tagStart = offset;\n                  this.logger.info(loggerName$k, '[id3] tag id:' + tagId + ' tagLen ' + tagLen + ' offset ' + offset + ' endPos ' + endPos);\n                  this.logger.qe({ critical: true, name: 'id3Parsed', data: { tagId, tagLen, offset, endPos } });\n                  const frame = this._extractID3Frame(data, tagId, tagLen, tagStart, endPos);\n                  if (frame) {\n                      const id3Frame = this.decodeID3Frame(frame);\n                      this._frames.push(id3Frame);\n                  }\n                  switch (tagId) {\n                      case 'PRIV':\n                          // this.logger.info(loggerName, 'parse frame:' + Hex.hexDump(data.subarray(offset,endPos)));\n                          // owner should be \"com.apple.streaming.transportStreamTimestamp\"\n                          if (tagLen === 53 && ID3.readUTF(data, offset, 44) === 'com.apple.streaming.transportStreamTimestamp') {\n                              offset += 44;\n                              // smelling even better ! we found the right descriptor\n                              // skip null character (string end) + 3 first bytes\n                              offset += 4;\n                              // timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.\n                              const pts33Bit = data[offset++] & 1;\n                              this._hasTimeStamp = true;\n                              timestamp = ((data[offset++] << 23) + (data[offset++] << 15) + (data[offset++] << 7) + data[offset++]) / 45;\n                              if (pts33Bit) {\n                                  timestamp += 47721858.84; // 2^32 / 90\n                              }\n                              timestamp = Math.round(timestamp);\n                              this.logger.info(loggerName$k, `ID3 timestamp found: ${timestamp}`);\n                              this._timeStamp = timestamp;\n                          }\n                          else if (tagLen >= 45 && ID3.readUTF(data, offset, 36) === 'com.apple.streaming.audioDescription') {\n                              offset += 37; // skip tag and null terminator\n                              this._audioType = ID3.readUTF(data, offset, 4);\n                              offset += 4;\n                              // skip everything else for now, don't think we need anything from the audio setup\n                              offset += tagLen - 41;\n                              this.logger.info(loggerName$k, `ID3 audio description found: ${this._audioType}`);\n                          }\n                          else {\n                              offset += tagLen;\n                          }\n                          break;\n                      default:\n                          {\n                              offset += tagLen;\n                          }\n                          break;\n                  }\n                  this.logger.info(loggerName$k, `[id3] ${tagId} default tagLen ${tagLen} offset ${offset} endPos ${endPos}`);\n              }\n          }\n          // id3utf8ArrayToStr is different from BufferUtils.utfarrayToStr. It exists when the string ends.\n          // BufferUtils.utfarrayToStr will decode the entire array.\n          // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n          // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n          /** utf.js - UTF-8 <=> UTF-16 convertion\n           *\n           *  Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n           * Version: 1.0\n           * LastModified: Dec 25 1999\n           * This library is free.  You can redistribute it and/or modify it.\n           */\n          id3utf8ArrayToStr(array) {\n              let char2;\n              let char3;\n              let out = '';\n              let i = 0;\n              const length = array.length;\n              while (i < length) {\n                  const c = array[i++];\n                  switch (c >> 4) {\n                      case 0:\n                          return out;\n                      case 1:\n                      case 2:\n                      case 3:\n                      case 4:\n                      case 5:\n                      case 6:\n                      case 7:\n                          // 0xxxxxxx\n                          out += String.fromCharCode(c);\n                          break;\n                      case 12:\n                      case 13:\n                          // 110x xxxx   10xx xxxx\n                          char2 = array[i++];\n                          out += String.fromCharCode(((c & 31) << 6) | (char2 & 63));\n                          break;\n                      case 14:\n                          // 1110 xxxx  10xx xxxx  10xx xxxx\n                          char2 = array[i++];\n                          char3 = array[i++];\n                          out += String.fromCharCode(((c & 15) << 12) | ((char2 & 63) << 6) | ((char3 & 63) << 0));\n                          break;\n                  }\n              }\n          }\n          get hasTimeStamp() {\n              return this._hasTimeStamp;\n          }\n          get timeStamp() {\n              return this._timeStamp;\n          }\n          get audioType() {\n              return this._audioType;\n          }\n          get length() {\n              return this._length;\n          }\n          get payload() {\n              return this._payload;\n          }\n          get frames() {\n              return this._frames;\n          }\n          get minor() {\n              return this._minor;\n          }\n          get revision() {\n              return this._revision;\n          }\n      }\n      var ID3$1 = ID3;\n    \n      \n      const loggerName$j = { name: 'AACDemuxer' };\n      class AACDemuxer extends EsDemuxer {\n          resetInitSegment(initSegment, duration) {\n              this.audioConfig = undefined;\n              this.audioTrack = undefined;\n              this.duration = duration;\n          }\n          static probe(data, logger) {\n              // check if data contains ID3 timestamp and ADTS sync word\n              const id3 = new ID3$1(data, logger);\n              let offset, length;\n              // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n              // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n              // More info https://wiki.multimedia.cx/index.php?title=ADTS\n              for (offset = id3.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n                  if (data[offset] === 255 && (data[offset + 1] & 246) === 240) {\n                      return true;\n                  }\n              }\n              return false;\n          }\n          // feed incoming data to the front of the parsing pipeline\n          append(data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo) {\n              const id3 = new ID3$1(data, this.logger);\n              const pts = id3.hasTimeStamp ? 90 * id3.timeStamp : 90000 * timeOffset;\n              if (!id3.hasTimeStamp) {\n                  this.logger.info(loggerName$j, `missing id3 timestamp at timeOffset ${timeOffset.toFixed(3)}`);\n              }\n              let frameLength, frameIndex, offset, headerLength, stamp, length;\n              let aacSample;\n              let id3Track = undefined;\n              let frames = undefined;\n              let payload = undefined;\n              if (id3.length) {\n                  payload = id3.payload;\n                  if (id3.frames.length) {\n                      frames = id3.frames;\n                  }\n                  this.logger.info(loggerName$j, `[id3] init id3 tag pts=${pts} frames=${id3.frames.length}`);\n                  id3Track = { id3Samples: [{ pts: pts, dts: pts, data: payload, frames: frames }], inputTimescale: 90000 };\n              }\n              // Look for ADTS header\n              for (offset = id3.length, length = data.length; offset < length - 1; offset++) {\n                  if (data[offset] === 255 && (data[offset + 1] & 246) === 240) {\n                      break;\n                  }\n              }\n              if (!this.audioConfig) {\n                  this.audioConfig = ADTS.getAudioConfig(this.observer, data, offset, undefined, this.logger);\n                  if (!this.audioConfig) {\n                      throw 'failed to parse adts config';\n                  }\n                  this.logger.info(loggerName$j, `parsed codec:${this.audioConfig.codec},rate:${this.audioConfig.samplerate},nb channel:${this.audioConfig.channelCount}`);\n              }\n              if (!this.audioTrack) {\n                  const info = { id: 258, inputTimescale: 90000, timescale: NaN, duration: this.duration, encrypted: false, keyTagInfo };\n                  const parsingData = { len: 0, sequenceNumber: 0, esSamples: [] };\n                  this.audioTrack = { info, parsingData, type: 'audio', config: this.audioConfig };\n              }\n              if (id3.audioType === 'zaac' || id3.audioType === 'zach' || id3.audioType === 'zacp') {\n                  this.audioTrack.info.encrypted = true;\n                  this.logger.info(loggerName$j, 'found encrypted aac');\n              }\n              frameIndex = 0;\n              const frameDuration = 92160000 / this.audioConfig.samplerate;\n              while (offset + 5 < length) {\n                  // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n                  headerLength = data[offset + 1] & 1 ? 7 : 9;\n                  // retrieve frame size\n                  frameLength = ((data[offset + 3] & 3) << 11) | (data[offset + 4] << 3) | ((data[offset + 5] & 224) >>> 5);\n                  frameLength -= headerLength;\n                  // stamp = pes.pts;\n                  if (frameLength > 0 && offset + headerLength + frameLength <= length) {\n                      stamp = pts + frameIndex * frameDuration;\n                      aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp, keyTagInfo: keyTagInfo };\n                      this.audioTrack.parsingData.esSamples.push(aacSample);\n                      this.audioTrack.parsingData.len += frameLength;\n                      offset += frameLength + headerLength;\n                      frameIndex++;\n                      // look for ADTS header (0xFFFx)\n                      for (; offset < length - 1; offset++) {\n                          if (ID3$1.isHeader(data, offset)) {\n                              const embedId3 = new ID3$1(data.subarray(offset), this.logger);\n                              if (embedId3.length > 0) {\n                                  offset += embedId3.length; // parses the interleaved ID3 packet\n                                  const localPts = embedId3.hasTimeStamp ? 90 * embedId3.timeStamp : pts;\n                                  id3Track.id3Samples.push({ pts: localPts, dts: localPts, data: embedId3.payload, frames: embedId3.frames });\n                              }\n                              else {\n                                  this.logger.error(loggerName$j, `[id3] invalid length ${length}`);\n                              }\n                          }\n                          if (data[offset] === 255 && (data[offset + 1] & 246) === 240) {\n                              break;\n                          }\n                      }\n                  }\n                  else {\n                      break;\n                  }\n              }\n              this.esRemuxer.remuxEsTracks(this.audioTrack, undefined, id3Track, undefined, timeOffset, contiguous, accurateTimeOffset, keyTagInfo);\n          }\n      }\n    \n      /*\n       * Utility methods to perform bit manipulations.\n       *\n       * 2019 Apple Inc. All rights reserved.\n       */\n      class BitstreamUtils {\n          /**\n           * This method is used to read a value from a bit-range in the data buffer.\n           *\n           * @param {Uint8Array}  data      - Data buffer.\n           * @param {BitStream}   bitStream - Current position in the data buffer; gets updated by this method.\n           * @param {number}      numBits   - Total number of bits to read.\n           *\n           * @return {number} Numeric value of the bits read.\n           *\n           * Usage: bsReadAndUpdate(data, {byteOffset: 1, usedBits: 3}, 7)\n           *            => will read 5 bits from data[1] and 2 bits from data[2] and return the numeric value of those 7 bits.\n           *            => will update the bitStream to {byteOffset: 2, usedBits: 2}\n           */\n          bsReadAndUpdate(data, bitStream, numBits) {\n              const result = this.readBits(data, bitStream, numBits);\n              this.updateOffset(bitStream, numBits);\n              return result;\n          }\n          /**\n           * This method is used to write a value to a bit-range in the data buffer.\n           *\n           * @param {Uint8Array}  data      - Data buffer.\n           * @param {BitStream}   bitStream - Current position in the data buffer; gets updated by this method.\n           * @param {number}      numBits   - Total number of bits to write.\n           * @param {number}      value     - The value to write.\n           *\n           * Usage: bsWriteAndUpdate(data, {byteOffset: 1, usedBits: 3}, 7)\n           *            => will write most significant 5 bits of value to data[1] and remaining 4 bits to data[2].\n           *            => will update the bitStream to {byteOffset: 2, usedBits: 2}\n           */\n          bsWriteAndUpdate(data, bitStream, numBits, value) {\n              const result = this.writeBits(data, bitStream, numBits, value);\n              this.updateOffset(bitStream, numBits);\n              return result;\n          }\n          /**\n           * This method is used to update the bitStream offsets.\n           *\n           * @param {BitStream}   bitStream - Current offset (In) / New offset (Out).\n           * @param {number}      numBits   - Total number of bits to skip.\n           *\n           * Usage: bsSkip({byteOffset: 1, usedBits: 3}, 7)\n           *            => will update the bitStream to {byteOffset: 2, usedBits: 2}\n           */\n          bsSkip(bitStream, numBits) {\n              this.updateOffset(bitStream, numBits);\n          }\n          // private helper methods\n          readBits(data, bitStream, numBits) {\n              if (!data || !bitStream) {\n                  return undefined;\n              }\n              let offset = bitStream.byteOffset;\n              const { usedBits } = bitStream;\n              if (usedBits >= 8 || usedBits + numBits > 32) {\n                  return undefined;\n              }\n              let result;\n              // some strong typed variables for reliable bit manipulation\n              const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage\n              const mask = new Uint32Array(1); // unsigned 32 bit mask value\n              const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage\n              if (usedBits >= 8 || numBits > 32) {\n                  return undefined;\n              }\n              /*\n               * read msb to lsb from data[offset] starting from the first unused bit of data[offset]\n               * for e.g. data[0] => 11110010\n               *          data[1] => 00111101\n               *          data[2] => 00101001\n               *        numBits => 18\n               *       usedBits => 2\n               *     byteOffset => 0\n               * will fetch bits\n               *        data[0] => xx100011\n               *        data[1] => 11011100\n               *        data[2] => 1011xxxx\n               * and return\n               *        00000000 00000010 00111101 11001011\n               */\n              if (usedBits) {\n                  // read unused bits from the partial byte\n                  const bits = 8 - usedBits;\n                  const shift = numBits < bits ? bits - numBits : 0;\n                  mask[0] = 4278190080 >>> (32 - bits);\n                  result = (data[offset] & mask[0]) >>> shift;\n                  offset += 1;\n                  numBits -= bits;\n              }\n              while (numBits > 0) {\n                  byte[0] = data[offset];\n                  // read remaining bits, upto 8 bits at a time\n                  const bits = Math.min(numBits, 8);\n                  const shift = 8 - bits;\n                  mask[0] = (4278190080 >>> (24 + shift)) << shift;\n                  temp[0] = (byte[0] & mask[0]) >> shift;\n                  result = !result ? temp[0] : (result << bits) | temp[0];\n                  offset += 1;\n                  numBits -= bits;\n              }\n              return result;\n          }\n          writeBits(data, bitStream, numBits, value) {\n              if (!data || !bitStream) {\n                  return undefined;\n              }\n              let offset = bitStream.byteOffset;\n              const { usedBits } = bitStream;\n              if (usedBits >= 8 || usedBits + numBits > 32) {\n                  return undefined;\n              }\n              // some strong typed variables for reliable bit manipulation\n              const tval = new Uint32Array(1); // unsigned 32 bit to store the incoming value\n              const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage\n              const mask = new Uint32Array(1); // unsigned 32 bit mask value\n              const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage\n              tval[0] = value;\n              /*\n               * write msb to lsb from value into data[offset] starting from the first unused bit of data[offset]\n               * for e.g. value => 00000000 00000010 00111101 11001011\n               *        numBits => 18\n               *       usedBits => 2\n               *     byteOffset => 0\n               * will get written as\n               *        data[0] => xx100011\n               *        data[1] => 11011100\n               *        data[2] => 1011xxxx\n               */\n              if (usedBits) {\n                  // left align the value, mask the bits, and then right align to exclude the used bits\n                  temp[0] = tval[0] << (32 - numBits);\n                  mask[0] = 4278190080;\n                  byte[0] = (temp[0] & mask[0]) >>> (24 + usedBits);\n                  // clear the bits and write\n                  data[offset] &= ~(mask[0] >>> (24 + usedBits));\n                  data[offset] |= byte[0];\n                  offset += 1;\n                  numBits -= 8 - usedBits;\n              }\n              while (numBits > 0) {\n                  // left align the remaining bits of value and write in blocks of 8\n                  temp[0] = tval[0] << (32 - numBits);\n                  mask[0] = 4278190080;\n                  byte[0] = (temp[0] & mask[0]) >>> 24;\n                  // right align the mask, and then right shift and left shift to clear the used bits\n                  const shift = numBits < 0 ? 8 - numBits : 0;\n                  data[offset] &= ~(((mask[0] >>> 24) >>> shift) << shift);\n                  // write the bits\n                  data[offset] |= byte[0];\n                  numBits -= 8;\n                  offset += 1;\n              }\n              return 0;\n          }\n          updateOffset(bitStream, numBits) {\n              if (!bitStream || !numBits || bitStream.usedBits + numBits > 32) {\n                  return;\n              }\n              // calculate the number of bits seen in the current byte offset\n              const bitsSeenInByte = bitStream.usedBits % 8;\n              // calculate the bytes and bits based on the last read/write operation\n              const bytesAdvanced = Math.floor((bitsSeenInByte + numBits) / 8);\n              const bitsAdvanced = (bitsSeenInByte + numBits) % 8;\n              // update the new position\n              bitStream.byteOffset += bytesAdvanced;\n              bitStream.usedBits = bitsAdvanced;\n          }\n      }\n    \n      const loggerName$i = { name: 'Dolby' };\n      const samplingRateMap = [48000, 44100, 32000];\n      const frameSizeMap = [\n          64,\n          69,\n          96,\n          64,\n          70,\n          96,\n          80,\n          87,\n          120,\n          80,\n          88,\n          120,\n          96,\n          104,\n          144,\n          96,\n          105,\n          144,\n          112,\n          121,\n          168,\n          112,\n          122,\n          168,\n          128,\n          139,\n          192,\n          128,\n          140,\n          192,\n          160,\n          174,\n          240,\n          160,\n          175,\n          240,\n          192,\n          208,\n          288,\n          192,\n          209,\n          288,\n          224,\n          243,\n          336,\n          224,\n          244,\n          336,\n          256,\n          278,\n          384,\n          256,\n          279,\n          384,\n          320,\n          348,\n          480,\n          320,\n          349,\n          480,\n          384,\n          417,\n          576,\n          384,\n          418,\n          576,\n          448,\n          487,\n          672,\n          448,\n          488,\n          672,\n          512,\n          557,\n          768,\n          512,\n          558,\n          768,\n          640,\n          696,\n          960,\n          640,\n          697,\n          960,\n          768,\n          835,\n          1152,\n          768,\n          836,\n          1152,\n          896,\n          975,\n          1344,\n          896,\n          976,\n          1344,\n          1024,\n          1114,\n          1536,\n          1024,\n          1115,\n          1536,\n          1152,\n          1253,\n          1728,\n          1152,\n          1254,\n          1728,\n          1280,\n          1393,\n          1920,\n          1280,\n          1394,\n          1920,\n      ];\n      const Dolby = {\n          getFrameDuration: function (config, timescale) {\n              return (1536 / config.samplerate) * timescale;\n          },\n          getAudioConfig: function (observer, data, offset, logger) {\n              let payload;\n              if (offset + 8 > data.length) {\n                  payload = new FragParsingError(true, 'error parsing ac-3, not enough data', ErrorResponses.InsufficientAC3Data);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return undefined;\n              }\n              if (data[offset] !== 11 || data[offset + 1] !== 119) {\n                  // payload = { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ac-3 magic' };\n                  payload = new FragParsingError(true, 'invalid ac-3 magic', ErrorResponses.InvalidAC3Magic);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return undefined;\n              }\n              const samplingRateCode = data[offset + 4] >> 6;\n              if (samplingRateCode >= 3) {\n                  payload = new FragParsingError(true, `invalid ac-3 samplingRateCode:${samplingRateCode}`, ErrorResponses.InvalidAC3SamplingRateCode);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return undefined;\n              }\n              // get frame size\n              const frameSizeCode = data[offset + 4] & 63;\n              const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;\n              const channelMode = data[offset + 6] >> 5;\n              let skipCount = 0;\n              if (channelMode === 2) {\n                  skipCount += 2;\n              }\n              else {\n                  if (channelMode & 1 && channelMode !== 1) {\n                      skipCount += 2;\n                  }\n                  if (channelMode & 4) {\n                      skipCount += 2;\n                  }\n              }\n              const lfeon = (((data[offset + 6] << 8) | data[offset + 7]) >> (12 - skipCount)) & 1;\n              const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];\n              const channelCount = channelsMap[channelMode] + lfeon;\n              const bsid = data[offset + 5] >> 3;\n              const bsmod = data[offset + 5] & 7;\n              const extraData = (samplingRateCode << 22) | (bsid << 17) | (bsmod << 14) | (channelMode << 11) | (lfeon << 10) | ((frameSizeCode >> 1) << 5);\n              const samplerate = samplingRateMap[samplingRateCode];\n              logger.info(loggerName$i, `parsed codec: ac-3, rate:${samplerate}, nb channel:${channelCount}, first frameLength:${frameLength}`);\n              const audioConfig = { samplerate: samplerate, channelCount: channelCount, segmentCodec: 'ac3', codec: 'ac-3', extraData: extraData };\n              return audioConfig;\n          },\n          getFrameLength: function (observer, data, offset) {\n              let payload;\n              if (offset + 8 > data.length) {\n                  payload = new FragParsingError(true, 'error parsing ac-3, not enough data', ErrorResponses.InsufficientAC3Data);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return undefined;\n              }\n              if (data[offset] !== 11 || data[offset + 1] !== 119) {\n                  payload = new FragParsingError(true, 'invalid ac-3 magic', ErrorResponses.InvalidAC3Magic);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return undefined;\n              }\n              const samplingRateCode = data[offset + 4] >> 6;\n              if (samplingRateCode >= 3) {\n                  payload = new FragParsingError(true, `invalid ac-3 samplingRateCode:${samplingRateCode}`, ErrorResponses.InvalidAC3SamplingRateCode);\n                  observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return undefined;\n              }\n              // get frame size\n              const frameSizeCode = data[offset + 4] & 63;\n              return frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;\n          },\n      };\n    \n      const loggerName$h = { name: 'AC3Demuxer' };\n      class AC3Demuxer extends EsDemuxer {\n          resetInitSegment(initSegment, duration) {\n              this.audioConfig = undefined;\n              this.audioTrack = undefined;\n              this.duration = duration;\n          }\n          static probe(data, logger) {\n              // check if data contains ID3 timestamp and AC3 sync bytes\n              const id3 = new ID3$1(data, logger), offset = id3.length;\n              // look for the ac-3 sync bytes\n              if (id3.hasTimeStamp && data[offset] === 11 && data[offset + 1] === 119) {\n                  // check the bsid to confirm ac-3\n                  const bu = new BitstreamUtils();\n                  const bsid = bu.bsReadAndUpdate(data, { byteOffset: offset + 5, usedBits: 0 }, 5);\n                  if (bsid < 16) {\n                      return true;\n                  }\n              }\n              return false;\n          }\n          // feed incoming data to the front of the parsing pipeline\n          append(data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo) {\n              const id3 = new ID3$1(data, this.logger);\n              const pts = 90 * id3.timeStamp;\n              const length = data.byteLength;\n              let frameIndex = 0;\n              let offset = id3.length;\n              if (!this.audioConfig) {\n                  this.audioConfig = Dolby.getAudioConfig(this.observer, data, offset, this.logger);\n              }\n              if (!this.audioConfig) {\n                  throw 'failed to parse ac3 config';\n              }\n              if (!this.audioTrack) {\n                  const info = { id: 258, inputTimescale: 90000, timescale: NaN, duration: this.duration, encrypted: false, keyTagInfo };\n                  const parsingData = { len: 0, sequenceNumber: 0, esSamples: [] };\n                  this.audioTrack = { info, parsingData, type: 'audio', config: this.audioConfig };\n              }\n              const frameDuration = Dolby.getFrameDuration(this.audioConfig, this.audioTrack.info.inputTimescale); // (1536 / this.audioConfig.samplerate) * this.audioTrack.inputTimescale;\n              if (id3.audioType === 'zac3') {\n                  this.audioTrack.info.encrypted = true;\n                  this.logger.info(loggerName$h, 'found encrypted ac3');\n              }\n              while (offset < length) {\n                  if (ID3$1.isHeader(data, offset)) {\n                      const id3 = new ID3$1(data.subarray(offset), this.logger);\n                      offset += id3.length; // skip the interleaved ID3 packet\n                  }\n                  if (data[offset] !== 11 || data[offset + 1] !== 119) {\n                      const payload = new FragParsingError(true, 'invalid ac-3 magic', ErrorResponses.InvalidAC3Magic);\n                      this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return;\n                  }\n                  const frameLength = Dolby.getFrameLength(this.observer, data, offset);\n                  const stamp = pts + frameIndex * frameDuration;\n                  const ac3Sample = { unit: data.subarray(offset, offset + frameLength), pts: stamp, dts: stamp, keyTagInfo: keyTagInfo };\n                  this.audioTrack.parsingData.esSamples.push(ac3Sample);\n                  this.audioTrack.parsingData.len += frameLength;\n                  offset += frameLength;\n                  frameIndex++;\n              }\n              this.esRemuxer.remuxEsTracks(this.audioTrack, undefined, { id3Samples: [{ pts: pts, dts: pts, data: id3.payload, frames: id3.frames }], inputTimescale: this.audioTrack.info.inputTimescale }, undefined, timeOffset, contiguous, accurateTimeOffset, keyTagInfo);\n          }\n      }\n    \n      const loggerName$g = { name: 'DDPlus' };\n      const DDPlus = {\n          getFrameLength: function (observer, data, offset, logger) {\n              const bs = new BitstreamUtils();\n              let firstIndSubstream = false;\n              let totalFrameLength = 0;\n              let payload;\n              while (offset < data.length) {\n                  if (offset + 8 > data.length) {\n                      payload = new FragParsingError(true, 'error parsing ec-3, not enough data', ErrorResponses.InsufficientEC3Data);\n                      observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return undefined;\n                  }\n                  // skip the ID3 packet, if present\n                  let id3Length = 0;\n                  if (ID3$1.isHeader(data, offset)) {\n                      const id3 = new ID3$1(data.subarray(offset), logger);\n                      id3Length = id3.length || 0;\n                      offset += id3Length;\n                  }\n                  // get syncword (16 bits)\n                  if (data[offset] !== 11 || data[offset + 1] !== 119) {\n                      payload = new FragParsingError(true, 'invalid ec-3 magic', ErrorResponses.InvalidEC3Magic);\n                      observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return undefined;\n                  }\n                  // skip the syncword and start parsing\n                  const bitStream = { byteOffset: offset + 2, usedBits: 0 };\n                  // get strmtyp & substreamid\n                  const strmtyp = bs.bsReadAndUpdate(data, bitStream, 2);\n                  const substreamid = bs.bsReadAndUpdate(data, bitStream, 3);\n                  if (strmtyp === 0 || strmtyp === 2) {\n                      if (firstIndSubstream === true) {\n                          if (substreamid === 0) {\n                              // we're seen all dependent sub-streams\n                              break;\n                          }\n                      }\n                      else {\n                          firstIndSubstream = true; // mark that the first independent substream is seen\n                      }\n                  }\n                  else if (strmtyp !== 1) {\n                      payload = new FragParsingError(true, 'reserved stream type', ErrorResponses.ReservedStreamType);\n                      observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return undefined;\n                  }\n                  // get frmsiz\n                  const frmsiz = bs.bsReadAndUpdate(data, bitStream, 11);\n                  // advance to the next syncframe\n                  const frameLength = (frmsiz + 1) * 2;\n                  offset += frameLength;\n                  totalFrameLength += frameLength + (id3Length || 0);\n              }\n              return totalFrameLength;\n          },\n          getAudioConfig: function (observer, data, offset, logger) {\n              const frameInfo = {\n                  frmsiz: 0,\n                  fscod: 0,\n                  numblkscod: 0,\n                  acmod: 0,\n                  lfeon: 0,\n                  bsid: 0,\n                  strmtyp: 0,\n                  substreamid: 0,\n                  chanmape: 0,\n                  chanmap: 0,\n                  mixdef: 0,\n                  mixdeflen: 0,\n                  bsmod: 0,\n              };\n              const sampleInfo = {\n                  fscod: 0,\n                  acmod: 0,\n                  lfeon: 0,\n                  bsid: 0,\n                  bsmod: 0,\n                  chan_loc: 0,\n                  data_rate: 0,\n                  num_ind_sub: 0,\n                  num_dep_sub: [],\n                  complexity_index_type_a: 0,\n              };\n              const bs = new BitstreamUtils();\n              let firstIndSubstream = false;\n              let totalFrameLength = 0;\n              let payload;\n              while (offset < data.length) {\n                  if (offset + 8 > data.length) {\n                      payload = new FragParsingError(true, 'error parsing ec-3, not enough data', ErrorResponses.InsufficientEC3Data);\n                      observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return undefined;\n                  }\n                  // skip the ID3 packet, if present\n                  let id3Length = 0;\n                  if (ID3$1.isHeader(data, offset)) {\n                      const id3 = new ID3$1(data.subarray(offset), logger);\n                      id3Length = id3.length || 0;\n                      offset += id3Length;\n                  }\n                  // get syncword (16 bits)\n                  if (data[offset] !== 11 || data[offset + 1] !== 119) {\n                      payload = new FragParsingError(true, 'invalid ec-3 magic', ErrorResponses.InvalidEC3Magic);\n                      observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return undefined;\n                  }\n                  // skip the syncword and start parsing\n                  const bitStream = { byteOffset: offset + 2, usedBits: 0 };\n                  // get strmtyp & substreamid\n                  frameInfo.strmtyp = bs.bsReadAndUpdate(data, bitStream, 2);\n                  frameInfo.substreamid = bs.bsReadAndUpdate(data, bitStream, 3);\n                  if (frameInfo.strmtyp === 0 || frameInfo.strmtyp === 2) {\n                      if (firstIndSubstream === true) {\n                          if (frameInfo.substreamid === 0) {\n                              // we're seen all dependent sub-streams\n                              break;\n                          }\n                      }\n                      else {\n                          firstIndSubstream = true; // mark that the first independent substream is seen\n                      }\n                      sampleInfo.num_ind_sub++; // independent substream\n                      sampleInfo.num_dep_sub.push(0); // initialize the dependent sub-stream count to 0\n                  }\n                  else if (frameInfo.strmtyp === 1) {\n                      sampleInfo.num_dep_sub[sampleInfo.num_ind_sub - 1]++; // dependent substream\n                  }\n                  else {\n                      payload = new FragParsingError(true, 'reserved stream type', ErrorResponses.ReservedStreamType);\n                      observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return undefined;\n                  }\n                  // get frmsiz\n                  frameInfo.frmsiz = bs.bsReadAndUpdate(data, bitStream, 11);\n                  // get fscod, numblkscod\n                  frameInfo.fscod = bs.bsReadAndUpdate(data, bitStream, 2);\n                  if (frameInfo.fscod === 3) {\n                      bs.bsSkip(bitStream, 2);\n                      frameInfo.numblkscod = 3;\n                  }\n                  else {\n                      frameInfo.numblkscod = bs.bsReadAndUpdate(data, bitStream, 2);\n                  }\n                  // get acmod\n                  frameInfo.acmod = bs.bsReadAndUpdate(data, bitStream, 3);\n                  // get lfeon\n                  frameInfo.lfeon = bs.bsReadAndUpdate(data, bitStream, 1);\n                  // get bsid\n                  frameInfo.bsid = bs.bsReadAndUpdate(data, bitStream, 5);\n                  bs.bsSkip(bitStream, 5);\n                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                      bs.bsSkip(bitStream, 8);\n                  }\n                  if (frameInfo.acmod === 0) {\n                      bs.bsSkip(bitStream, 5);\n                      if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                          bs.bsSkip(bitStream, 8);\n                      }\n                  }\n                  if (frameInfo.strmtyp === 1) {\n                      // get chanmape\n                      frameInfo.chanmape = bs.bsReadAndUpdate(data, bitStream, 1);\n                      if (frameInfo.chanmape) {\n                          // get chanmap\n                          frameInfo.chanmap = bs.bsReadAndUpdate(data, bitStream, 16);\n                      }\n                  }\n                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                      if (frameInfo.acmod > 2) {\n                          bs.bsSkip(bitStream, 2);\n                      }\n                      if (frameInfo.acmod & 1 && frameInfo.acmod > 2) {\n                          bs.bsSkip(bitStream, 6);\n                      }\n                      if (frameInfo.acmod & 4) {\n                          bs.bsSkip(bitStream, 6);\n                      }\n                      if (frameInfo.lfeon) {\n                          if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                              bs.bsSkip(bitStream, 5);\n                          }\n                      }\n                      if (frameInfo.strmtyp === 0) {\n                          if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                              bs.bsSkip(bitStream, 6);\n                          }\n                          if (frameInfo.acmod === 0) {\n                              if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                  bs.bsSkip(bitStream, 6);\n                              }\n                          }\n                          if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                              bs.bsSkip(bitStream, 6);\n                          }\n                          // get mixdef\n                          frameInfo.mixdef = bs.bsReadAndUpdate(data, bitStream, 2);\n                          if (frameInfo.mixdef === 1) {\n                              bs.bsSkip(bitStream, 5);\n                          }\n                          else if (frameInfo.mixdef === 2) {\n                              bs.bsSkip(bitStream, 12);\n                          }\n                          else if (frameInfo.mixdef === 3) {\n                              // get mixdeflen\n                              frameInfo.mixdeflen = bs.bsReadAndUpdate(data, bitStream, 5);\n                              if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                  bs.bsSkip(bitStream, 5);\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 4);\n                                  }\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                          bs.bsSkip(bitStream, 4);\n                                      }\n                                      if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                          bs.bsSkip(bitStream, 4);\n                                      }\n                                  }\n                              }\n                              if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                  bs.bsSkip(bitStream, 5);\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 7);\n                                      if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                          bs.bsSkip(bitStream, 8);\n                                      }\n                                  }\n                              }\n                              // skip entire block that includes mixdata and mixdatafill\n                              const skipBytes = frameInfo.mixdeflen + 2 + (bitStream.usedBits ? 1 : 0);\n                              bitStream.byteOffset += skipBytes;\n                          }\n                          if (frameInfo.acmod < 2) {\n                              if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                  bs.bsSkip(bitStream, 14);\n                              }\n                              if (frameInfo.acmod === 0) {\n                                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                      bs.bsSkip(bitStream, 14);\n                                  }\n                              }\n                          }\n                          if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                              if (frameInfo.numblkscod === 0) {\n                                  bs.bsSkip(bitStream, 5);\n                              }\n                              else {\n                                  for (let i = 0; i < frameInfo.numblkscod; i++) {\n                                      if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                                          bs.bsSkip(bitStream, 5);\n                                      }\n                                  }\n                              }\n                          }\n                      }\n                  }\n                  frameInfo.bsmod = 0;\n                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                      frameInfo.bsmod = bs.bsReadAndUpdate(data, bitStream, 3);\n                      bs.bsSkip(bitStream, 2);\n                      if (frameInfo.acmod === 2) {\n                          bs.bsSkip(bitStream, 4);\n                      }\n                      if (frameInfo.acmod >= 6) {\n                          bs.bsSkip(bitStream, 2);\n                      }\n                      if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                          bs.bsSkip(bitStream, 8);\n                      }\n                      if (frameInfo.acmod === 0) {\n                          if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                              bs.bsSkip(bitStream, 8);\n                          }\n                      }\n                      if (frameInfo.fscod < 3) {\n                          bs.bsSkip(bitStream, 1);\n                      }\n                  }\n                  if (frameInfo.strmtyp === 0 && frameInfo.numblkscod !== 3) {\n                      bs.bsSkip(bitStream, 1);\n                  }\n                  if (frameInfo.strmtyp === 2) {\n                      let blkid;\n                      if (frameInfo.numblkscod === 3) {\n                          blkid = 1;\n                      }\n                      else {\n                          blkid = bs.bsReadAndUpdate(data, bitStream, 1);\n                      }\n                      if (blkid) {\n                          bs.bsReadAndUpdate(data, bitStream, 6);\n                      }\n                  }\n                  if (bs.bsReadAndUpdate(data, bitStream, 1)) {\n                      const addbsil = bs.bsReadAndUpdate(data, bitStream, 6);\n                      if (frameInfo.strmtyp === 0 && frameInfo.substreamid === 0 && addbsil === 1) {\n                          const flag_ec3_extension_type_reserved = bs.bsReadAndUpdate(data, bitStream, 7);\n                          const flag_ec3_extension_type_a = bs.bsReadAndUpdate(data, bitStream, 1);\n                          const complexity_index_type_a = bs.bsReadAndUpdate(data, bitStream, 8);\n                          // Make sure the values are in range and if yes, flag ATMOS\n                          if (flag_ec3_extension_type_reserved === 0 && flag_ec3_extension_type_a === 1 && complexity_index_type_a >= 1 && complexity_index_type_a <= 16) {\n                              sampleInfo.complexity_index_type_a = complexity_index_type_a;\n                          }\n                      }\n                  }\n                  // find channel map\n                  if (frameInfo.chanmape) {\n                      sampleInfo.chan_loc |= frameInfo.chanmap;\n                  }\n                  else {\n                      // look up channel map using acmod\n                      const acmodToChannelMap = [\n                          40960,\n                          16384,\n                          40960,\n                          57344,\n                          41472,\n                          57856,\n                          47104,\n                          63488,\n                      ];\n                      sampleInfo.chan_loc |= acmodToChannelMap[frameInfo.acmod];\n                  }\n                  if (frameInfo.strmtyp === 0) {\n                      sampleInfo.fscod = frameInfo.fscod;\n                      sampleInfo.bsid = frameInfo.bsid;\n                      sampleInfo.bsmod = frameInfo.bsmod;\n                      sampleInfo.acmod = frameInfo.acmod;\n                      sampleInfo.lfeon = frameInfo.lfeon;\n                  }\n                  sampleInfo.chan_loc |= frameInfo.lfeon ? 1 : 0;\n                  // advance to the next syncframe\n                  const frameLength = (frameInfo.frmsiz + 1) * 2;\n                  offset += frameLength;\n                  totalFrameLength += frameLength + (id3Length || 0);\n              }\n              let channelCount = 0;\n              // get channel count\n              for (let i = 0; i < 16; i++) {\n                  if (sampleInfo.chan_loc & (1 << i)) {\n                      channelCount++;\n                  }\n              }\n              if (sampleInfo.lfeon) {\n                  channelCount++;\n              }\n              // generate DD+ magic cookie\n              let cookieSize = 10 + sampleInfo.num_ind_sub * 3;\n              const samplingRateMap = [48000, 44100, 32000];\n              const samplerate = samplingRateMap[sampleInfo.fscod];\n              sampleInfo.data_rate = (samplerate / 1536) * totalFrameLength * 8;\n              cookieSize = 10 + sampleInfo.num_ind_sub * 3;\n              for (let i = 0; i < sampleInfo.num_ind_sub; i++) {\n                  if (sampleInfo.num_dep_sub[i] > 0) {\n                      cookieSize++;\n                  }\n              }\n              // for ATMOS\n              if (sampleInfo.complexity_index_type_a > 0) {\n                  cookieSize += 2;\n              }\n              // write the cookie\n              const extraDataBytes = new Uint8Array(cookieSize);\n              const bitStream = { byteOffset: 0, usedBits: 0 };\n              bs.bsWriteAndUpdate(extraDataBytes, bitStream, 32, cookieSize);\n              bs.bsWriteAndUpdate(extraDataBytes, bitStream, 32, 1684366131); // 'dec3'\n              bs.bsWriteAndUpdate(extraDataBytes, bitStream, 13, sampleInfo.data_rate); // data_rate\n              bs.bsWriteAndUpdate(extraDataBytes, bitStream, 3, sampleInfo.num_ind_sub); // num_ind_sub\n              for (let i = 0; i < sampleInfo.num_ind_sub; i++) {\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 2, sampleInfo.fscod); // fscod\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 5, sampleInfo.bsid); // bsid\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 1, 0); // reserved\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 1, i === 0 ? 0 : 1); // asvc\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 3, sampleInfo.bsmod); // bsmod\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 3, sampleInfo.acmod); // acmod\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 1, sampleInfo.lfeon); // lfeon\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 3, 0); // reserved\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 4, sampleInfo.num_dep_sub[i]); // num_dep_sub\n                  if (sampleInfo.num_dep_sub[i] > 0) {\n                      bs.bsWriteAndUpdate(extraDataBytes, bitStream, 9, sampleInfo.chan_loc); // chan_loc\n                  }\n                  else {\n                      bs.bsWriteAndUpdate(extraDataBytes, bitStream, 1, 0); // reserved\n                  }\n              }\n              if (sampleInfo.complexity_index_type_a > 0) {\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 7, 0); // flag_ec3_extension_type_reserved; reserved as 0\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 1, 1); // flag_ec3_extension_type_a\n                  bs.bsWriteAndUpdate(extraDataBytes, bitStream, 8, sampleInfo.complexity_index_type_a); // complexity_index_type_a\n              }\n              logger.debug(loggerName$g, `EC3 sampleInfo:${JSON.stringify(sampleInfo)}`);\n              logger.info(loggerName$g, `parsed codec:ec-3, isAtmos: ${sampleInfo.complexity_index_type_a > 0}, rate:${samplerate}, nb channel:${channelCount}, first totalFrameLength:${totalFrameLength}`);\n              const audioConfig = { samplerate: samplerate, channelCount: channelCount, segmentCodec: 'ec3', codec: 'ec-3', extraDataBytes: extraDataBytes };\n              return audioConfig;\n          },\n      };\n      var DDPlus$1 = DDPlus;\n    \n      const loggerName$f = { name: 'EC3Demuxer' };\n      class EC3Demuxer extends EsDemuxer {\n          resetInitSegment(initSegment, duration) {\n              this.audioConfig = undefined;\n              this.audioTrack = undefined;\n              this.duration = duration;\n          }\n          static probe(data, logger) {\n              // check if data contains ID3 timestamp and EC3 sync bytes\n              const id3 = new ID3$1(data, logger), offset = id3.length;\n              // look for the ec-3 sync bytes\n              if (id3.hasTimeStamp && data[offset] === 11 && data[offset + 1] === 119) {\n                  // check the bsid to confirm ec-3\n                  const bu = new BitstreamUtils();\n                  const bsid = bu.bsReadAndUpdate(data, { byteOffset: offset + 5, usedBits: 0 }, 5);\n                  if (bsid === 16) {\n                      return true;\n                  }\n              }\n              return false;\n          }\n          // feed incoming data to the front of the parsing pipeline\n          append(data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo) {\n              const id3 = new ID3$1(data, this.logger);\n              const pts = 90 * id3.timeStamp;\n              const length = data.length;\n              let frameIndex = 0;\n              let offset = id3.length;\n              if (!this.audioConfig) {\n                  this.audioConfig = DDPlus$1.getAudioConfig(this.observer, data, offset, this.logger);\n              }\n              if (!this.audioConfig) {\n                  throw 'failed to parse ec-3 config';\n              }\n              if (!this.audioTrack) {\n                  const info = { id: 258, inputTimescale: 90000, timescale: NaN, duration: this.duration, encrypted: false, keyTagInfo };\n                  const parsingData = { len: 0, sequenceNumber: 0, esSamples: [] };\n                  this.audioTrack = { info, parsingData, type: 'audio', config: this.audioConfig };\n              }\n              const frameDuration = Dolby.getFrameDuration(this.audioConfig, this.audioTrack.info.inputTimescale); // (1536 / this.audioConfig.samplerate) * this.audioTrack.inputTimescale;\n              if (id3.audioType === 'zec3') {\n                  this.audioTrack.info.encrypted = true;\n                  this.logger.info(loggerName$f, 'found encrypted ec3');\n              }\n              while (offset < length) {\n                  const frameLength = DDPlus$1.getFrameLength(this.observer, data, offset, this.logger);\n                  const stamp = pts + frameIndex * frameDuration;\n                  const ec3Sample = { unit: data.subarray(offset, offset + frameLength), pts: stamp, dts: stamp, keyTagInfo: keyTagInfo };\n                  this.audioTrack.parsingData.esSamples.push(ec3Sample);\n                  this.audioTrack.parsingData.len += frameLength;\n                  offset += frameLength;\n                  frameIndex++;\n              }\n              this.esRemuxer.remuxEsTracks(this.audioTrack, undefined, { id3Samples: [{ pts: pts, dts: pts, data: id3.payload, frames: id3.frames }], inputTimescale: this.audioTrack.info.inputTimescale }, undefined, timeOffset, contiguous, accurateTimeOffset, keyTagInfo);\n          }\n      }\n    \n      \n      const MpegAudio = {\n          BitratesMap: [\n              32,\n              64,\n              96,\n              128,\n              160,\n              192,\n              224,\n              256,\n              288,\n              320,\n              352,\n              384,\n              416,\n              448,\n              32,\n              48,\n              56,\n              64,\n              80,\n              96,\n              112,\n              128,\n              160,\n              192,\n              224,\n              256,\n              320,\n              384,\n              32,\n              40,\n              48,\n              56,\n              64,\n              80,\n              96,\n              112,\n              128,\n              160,\n              192,\n              224,\n              256,\n              320,\n              32,\n              48,\n              56,\n              64,\n              80,\n              96,\n              112,\n              128,\n              144,\n              160,\n              176,\n              192,\n              224,\n              256,\n              8,\n              16,\n              24,\n              32,\n              40,\n              48,\n              56,\n              64,\n              80,\n              96,\n              112,\n              128,\n              144,\n              160,\n          ],\n          SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n          SamplesCoefficients: [\n              // MPEG 2.5\n              [\n                  0,\n                  72,\n                  144,\n                  12,\n              ],\n              // Reserved\n              [\n                  0,\n                  0,\n                  0,\n                  0,\n              ],\n              // MPEG 2\n              [\n                  0,\n                  72,\n                  144,\n                  12,\n              ],\n              // MPEG 1\n              [\n                  0,\n                  144,\n                  144,\n                  12,\n              ],\n          ],\n          BytesInSlot: [\n              0,\n              1,\n              1,\n              4,\n          ],\n          onFrame: function (parsingData, data, bitRate, samplerate, channelCount, frameIndex, pts) {\n              const frameDuration = 103680000 / samplerate;\n              const stamp = pts + frameIndex * frameDuration;\n              parsingData.esSamples.push({ unit: data, pts: stamp, dts: stamp });\n              parsingData.len += data.length;\n          },\n          onNoise: function (data, logger) {\n              logger.warn('mpeg audio has noise: ' + data.length + ' bytes');\n          },\n          parseFrames: function (parsingData, data, start, end, frameIndex, pts, logger) {\n              const BitratesMap = [\n                  32,\n                  64,\n                  96,\n                  128,\n                  160,\n                  192,\n                  224,\n                  256,\n                  288,\n                  320,\n                  352,\n                  384,\n                  416,\n                  448,\n                  32,\n                  48,\n                  56,\n                  64,\n                  80,\n                  96,\n                  112,\n                  128,\n                  160,\n                  192,\n                  224,\n                  256,\n                  320,\n                  384,\n                  32,\n                  40,\n                  48,\n                  56,\n                  64,\n                  80,\n                  96,\n                  112,\n                  128,\n                  160,\n                  192,\n                  224,\n                  256,\n                  320,\n                  32,\n                  48,\n                  56,\n                  64,\n                  80,\n                  96,\n                  112,\n                  128,\n                  144,\n                  160,\n                  176,\n                  192,\n                  224,\n                  256,\n                  8,\n                  16,\n                  24,\n                  32,\n                  40,\n                  48,\n                  56,\n                  64,\n                  80,\n                  96,\n                  112,\n                  128,\n                  144,\n                  160,\n              ];\n              const SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];\n              if (start + 2 > end) {\n                  return -1; // we need at least 2 bytes to detect sync pattern\n              }\n              if (data[start] === 255 || (data[start + 1] & 224) === 224) {\n                  // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n                  if (start + 24 > end) {\n                      return -1;\n                  }\n                  const headerB = (data[start + 1] >> 3) & 3;\n                  const headerC = (data[start + 1] >> 1) & 3;\n                  const headerE = (data[start + 2] >> 4) & 15;\n                  const headerF = (data[start + 2] >> 2) & 3;\n                  const headerG = !!(data[start + 2] & 2);\n                  if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n                      const columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;\n                      const bitRate = BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n                      const columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n                      const sampleRate = SamplingRateMap[columnInSampleRates * 3 + headerF];\n                      const padding = headerG ? 1 : 0;\n                      const channelCount = data[start + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n                      const frameLength = headerC === 3 ? (((headerB === 3 ? 12 : 6) * bitRate) / sampleRate + padding) << 2 : (((headerB === 3 ? 144 : 72) * bitRate) / sampleRate + padding) | 0;\n                      if (start + frameLength > end) {\n                          return -1;\n                      }\n                      MpegAudio.onFrame(parsingData, data.subarray(start, start + frameLength), bitRate, sampleRate, channelCount, frameIndex, pts);\n                      return frameLength;\n                  }\n              }\n              // noise or ID3, trying to skip\n              let offset = start + 2;\n              while (offset < end) {\n                  if (data[offset - 1] === 255 && (data[offset] & 224) === 224) {\n                      // sync pattern is found\n                      MpegAudio.onNoise(data.subarray(start, offset - 1), logger);\n                      return offset - start - 1;\n                  }\n                  offset++;\n              }\n              return -1;\n          },\n          parse: function (parsingData, data, offset, pts, logger) {\n              const length = data.length;\n              let frameIndex = 0;\n              let parsed;\n              while (offset < length && (parsed = MpegAudio.parseFrames(parsingData, data, offset, length, frameIndex++, pts, logger)) > 0) {\n                  offset += parsed;\n              }\n          },\n          getAudioConfig: function (data, offset) {\n              const headerB = (data[offset + 1] >> 3) & 3;\n              const headerC = (data[offset + 1] >> 1) & 3;\n              const headerE = (data[offset + 2] >> 4) & 15;\n              const headerF = (data[offset + 2] >> 2) & 3;\n              const headerG = (data[offset + 2] >> 1) & 1;\n              if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n                  const columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;\n                  const bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n                  const columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n                  const samplerate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n                  const channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n                  const sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n                  const bytesInSlot = MpegAudio.BytesInSlot[headerC];\n                  const frameLength = parseInt(((sampleCoefficient * bitRate) / samplerate + headerG), 10) * bytesInSlot;\n                  const result = { segmentCodec: 'mp3', codec: 'mp3', samplerate, channelCount, frameLength };\n                  return result;\n              }\n              return undefined;\n          },\n          isHeaderPattern: function (data, offset) {\n              return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0;\n          },\n          probe: function (data, offset) {\n              // same as isHeader but we also check that MPEG frame follows last MPEG frame\n              // or end of data is reached\n              if (offset + 1 < data.length && MpegAudio.isHeaderPattern(data, offset)) {\n                  // MPEG header Length\n                  const headerLength = 4;\n                  // MPEG frame Length\n                  const header = MpegAudio.getAudioConfig(data, offset);\n                  let frameLength = headerLength;\n                  if (header && header.frameLength) {\n                      frameLength = header.frameLength;\n                  }\n                  const newOffset = offset + frameLength;\n                  if (newOffset === data.length || (newOffset + 1 < data.length && MpegAudio.isHeaderPattern(data, newOffset))) {\n                      return true;\n                  }\n              }\n              return false;\n          },\n      };\n      var MpegAudio$1 = MpegAudio;\n    \n      \n      const loggerName$e = { name: 'MP3Demuxer' };\n      class MP3Demuxer extends EsDemuxer {\n          resetInitSegment(initSegment, duration) {\n              this.audioConfig = undefined;\n              this.audioTrack = undefined;\n              this.duration = duration;\n          }\n          static probe(data, logger) {\n              // check if data contains ID3 timestamp and MPEG sync word\n              const id3 = new ID3$1(data, logger);\n              let offset, length;\n              if (id3.hasTimeStamp) {\n                  // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n                  // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n                  // More info http://www.mp3-tech.org/programmer/frame_header.html\n                  for (offset = id3.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n                      if (MpegAudio$1.probe(data, offset)) {\n                          logger.warn(loggerName$e, 'MPEG Audio sync word found !');\n                          return true;\n                      }\n                  }\n              }\n              return false;\n          }\n          // feed incoming data to the front of the parsing pipeline\n          append(data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo) {\n              const id3 = new ID3$1(data, this.logger);\n              const pts = 90 * id3.timeStamp;\n              if (!this.audioConfig) {\n                  this.audioConfig = MpegAudio$1.getAudioConfig(data, id3.length);\n              }\n              if (!this.audioConfig) {\n                  throw 'unable to parse mp3 header';\n              }\n              if (!this.audioTrack) {\n                  const info = { id: 258, inputTimescale: 90000, timescale: NaN, duration: this.duration, encrypted: false, keyTagInfo };\n                  const parsingData = { len: 0, sequenceNumber: 0, esSamples: [] };\n                  this.audioTrack = { info, parsingData, type: 'audio', config: this.audioConfig };\n              }\n              MpegAudio$1.parse(this.audioTrack.parsingData, data, id3.length, pts, this.logger);\n              this.esRemuxer.remuxEsTracks(this.audioTrack, undefined, { id3Samples: [{ pts: pts, dts: pts, data: id3.payload, frames: id3.frames }], inputTimescale: 90000 }, undefined, timeOffset, contiguous, accurateTimeOffset);\n          }\n      }\n    \n      /**\n       * AAC Helper\n       *\n       * \n       * \n       *\n       */\n      function getSilentFrame(codec, channelCount) {\n          switch (codec) {\n              case 'mp4a.40.2':\n                  if (channelCount === 1) {\n                      return new Uint8Array([0, 200, 0, 128, 35, 128]);\n                  }\n                  else if (channelCount === 2) {\n                      return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);\n                  }\n                  else if (channelCount === 3) {\n                      return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);\n                  }\n                  else if (channelCount === 4) {\n                      return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);\n                  }\n                  else if (channelCount === 5) {\n                      return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);\n                  }\n                  else if (channelCount === 6) {\n                      return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]);\n                  }\n                  break;\n              // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n              default:\n                  if (channelCount === 1) {\n                      // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n                      return new Uint8Array([\n                          1,\n                          64,\n                          34,\n                          128,\n                          163,\n                          78,\n                          230,\n                          128,\n                          186,\n                          8,\n                          0,\n                          0,\n                          0,\n                          28,\n                          6,\n                          241,\n                          193,\n                          10,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          94,\n                      ]);\n                  }\n                  else if (channelCount === 2) {\n                      // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n                      return new Uint8Array([\n                          1,\n                          64,\n                          34,\n                          128,\n                          163,\n                          94,\n                          230,\n                          128,\n                          186,\n                          8,\n                          0,\n                          0,\n                          0,\n                          0,\n                          149,\n                          0,\n                          6,\n                          241,\n                          161,\n                          10,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          94,\n                      ]);\n                  }\n                  else if (channelCount === 3) {\n                      // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n                      return new Uint8Array([\n                          1,\n                          64,\n                          34,\n                          128,\n                          163,\n                          94,\n                          230,\n                          128,\n                          186,\n                          8,\n                          0,\n                          0,\n                          0,\n                          0,\n                          149,\n                          0,\n                          6,\n                          241,\n                          161,\n                          10,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          90,\n                          94,\n                      ]);\n                  }\n                  break;\n          }\n          return null;\n      }\n    \n      function isFiniteNumber(value) {\n          return typeof value === 'number' && isFinite(value);\n      }\n      /**\n       * For getting float string for a given value with type checking\n       * @param val Number\n       * @param precision Number of digits after decimal\n       */\n      function toFixed(val, precision) {\n          if (isFiniteNumber(val)) {\n              // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n              return val.toFixed(precision);\n          }\n          return `${val}`;\n      }\n      /**\n       * Stringify except print numbers with fixed precision\n       * @param obj the value to stringify\n       * @param precision Number of digits after decimal. Default 3\n       */\n      function stringifyWithPrecision(obj, precision = 3) {\n          return JSON.stringify(obj, (_key, value) => {\n              return !isNaN(value) && (value === null || value === void 0 ? void 0 : value.toFixed) ? Number(value === null || value === void 0 ? void 0 : value.toFixed(precision)) : value;\n          });\n      }\n      /**\n       * Replace all occurrences of an instance in a string\n       *\n       * @param {string|RegExp} search - What to change\n       * @param {string} replacement - Replace search for this\n       * @param {string} target - Target string to have elements replaced\n       * @returns {string}\n       */\n      const replaceAll = (search, replacement, target = '') => target.split(search).join(replacement);\n      let shouldRedactUrl = true;\n      function setupRedactUrl(buildType) {\n          shouldRedactUrl = buildType === 'production';\n      }\n      function redactUrl(url) {\n          return shouldRedactUrl ? '<redacted>' : url;\n      }\n      // Naive deep copy of any serializable object\n      // shallow copy for function, symbol\n      function deepCpy(obj) {\n          if (!obj) {\n              return obj;\n          }\n          switch (typeof obj) {\n              case 'object':\n                  if (Array.isArray(obj)) {\n                      return obj.map(deepCpy);\n                  }\n                  const result = {};\n                  for (const [key, value] of Object.entries(obj)) {\n                      result[key] = deepCpy(value);\n                  }\n                  return result;\n              default:\n                  return obj;\n          }\n      }\n      function urlRedactedLevelInfo(indata) {\n          const outdata = [...indata];\n          for (let i = 0; i < outdata.length; i++) {\n              outdata[i] = Object.assign({}, outdata[i]);\n              outdata[i].url = redactUrl(outdata[i].url);\n              if (outdata[i].attrs) {\n                  outdata[i].attrs = Object.assign({}, outdata[i].attrs);\n                  outdata[i].attrs.URI = redactUrl(outdata[i].attrs.URI);\n              }\n          }\n          return outdata;\n      }\n      function urlRedactedAltMediaOption(indata) {\n          const outdata = [...indata];\n          for (let i = 0; i < outdata.length; i++) {\n              outdata[i] = Object.assign({}, outdata[i]);\n              outdata[i].url = redactUrl(outdata[i].url);\n          }\n          return outdata;\n      }\n    \n      /**\n       * Generate MP4 Box\n       *\n       * \n       * \n       *\n       */\n      const UINT32_MAX$1 = Math.pow(2, 32) - 1;\n      class MP4 {\n          static init() {\n              MP4.types = {\n                  avc1: [],\n                  avcC: [],\n                  btrt: [],\n                  dinf: [],\n                  dref: [],\n                  esds: [],\n                  free: [],\n                  ftyp: [],\n                  hdlr: [],\n                  mdat: [],\n                  mdhd: [],\n                  mdia: [],\n                  mfhd: [],\n                  minf: [],\n                  moof: [],\n                  moov: [],\n                  mp4a: [],\n                  '.mp3': [],\n                  dac3: [],\n                  'ac-3': [],\n                  dec3: [],\n                  'ec-3': [],\n                  mvex: [],\n                  mvhd: [],\n                  pasp: [],\n                  sdtp: [],\n                  stbl: [],\n                  stco: [],\n                  stsc: [],\n                  stsd: [],\n                  stsz: [],\n                  stts: [],\n                  tfdt: [],\n                  tfhd: [],\n                  traf: [],\n                  trak: [],\n                  trun: [],\n                  trex: [],\n                  tkhd: [],\n                  vmhd: [],\n                  smhd: [],\n                  uuid: [],\n                  encv: [],\n                  enca: [],\n                  // map encryption boxes\n                  frma: [],\n                  schm: [],\n                  schi: [],\n                  senc: [],\n                  saio: [],\n                  saiz: [],\n                  sinf: [],\n                  tenc: [],\n                  // moof encryption boxes\n                  sbgp: [],\n                  seig: [],\n                  sgpd: [],\n                  pssh: [],\n              };\n              let i;\n              for (i in MP4.types) {\n                  // eslint-disable-next-line no-prototype-builtins\n                  if (MP4.types.hasOwnProperty(i)) {\n                      MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];\n                  }\n              }\n              const videoHdlr = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  118,\n                  105,\n                  100,\n                  101,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  86,\n                  105,\n                  100,\n                  101,\n                  111,\n                  72,\n                  97,\n                  110,\n                  100,\n                  108,\n                  101,\n                  114,\n                  0,\n              ]);\n              const audioHdlr = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  115,\n                  111,\n                  117,\n                  110,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  83,\n                  111,\n                  117,\n                  110,\n                  100,\n                  72,\n                  97,\n                  110,\n                  100,\n                  108,\n                  101,\n                  114,\n                  0,\n              ]);\n              MP4.HDLR_TYPES = {\n                  video: videoHdlr,\n                  audio: audioHdlr,\n              };\n              const dref = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  12,\n                  117,\n                  114,\n                  108,\n                  32,\n                  0,\n                  0,\n                  0,\n                  1,\n              ]);\n              const stco = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n              ]);\n              MP4.STTS = MP4.STSC = MP4.STCO = stco;\n              MP4.STSZ = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n              ]);\n              MP4.VMHD = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n              ]);\n              MP4.SMHD = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n              ]);\n              MP4.STSD = new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n              ]); // entry_count\n              const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n              const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n              const minorVersion = new Uint8Array([0, 0, 0, 1]);\n              MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n              MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n          }\n          static set16(num, data, index) {\n              data[index] = (num >> 8) & 255;\n              data[index + 1] = num & 255;\n              return index + 2;\n          }\n          static set32(num, data, index) {\n              data[index] = (num >> 24) & 255;\n              data[index + 1] = (num >> 16) & 255;\n              data[index + 2] = (num >> 8) & 255;\n              data[index + 3] = num & 255;\n              return index + 4;\n          }\n          static box(type, ...params) {\n              // eslint-disable-next-line prefer-rest-params\n              const payload = Array.prototype.slice.call(arguments, 1);\n              let size = 8, i = payload.length;\n              const len = i;\n              // calculate the total size we need to allocate\n              while (i--) {\n                  size += payload[i].byteLength;\n              }\n              const result = new Uint8Array(size);\n              result[0] = (size >> 24) & 255;\n              result[1] = (size >> 16) & 255;\n              result[2] = (size >> 8) & 255;\n              result[3] = size & 255;\n              result.set(type, 4);\n              // copy the payload into the result\n              for (i = 0, size = 8; i < len; i++) {\n                  // copy payload[i] array @ offset size\n                  result.set(payload[i], size);\n                  size += payload[i].byteLength;\n              }\n              return result;\n          }\n          static hdlr(type) {\n              return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n          }\n          static mdat(data) {\n              return MP4.box(MP4.types.mdat, data);\n          }\n          static mdhd(timescale, duration) {\n              duration *= timescale;\n              const upperWordDuration = Math.floor(duration / (UINT32_MAX$1 + 1));\n              const lowerWordDuration = Math.floor(duration % (UINT32_MAX$1 + 1));\n              return MP4.box(MP4.types.mdhd, new Uint8Array([\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  2,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  3,\n                  (timescale >> 24) & 255,\n                  (timescale >> 16) & 255,\n                  (timescale >> 8) & 255,\n                  timescale & 255,\n                  upperWordDuration >> 24,\n                  (upperWordDuration >> 16) & 255,\n                  (upperWordDuration >> 8) & 255,\n                  upperWordDuration & 255,\n                  lowerWordDuration >> 24,\n                  (lowerWordDuration >> 16) & 255,\n                  (lowerWordDuration >> 8) & 255,\n                  lowerWordDuration & 255,\n                  85,\n                  196,\n                  0,\n                  0,\n              ]));\n          }\n          static mdia(track) {\n              const mdhd = MP4.mdhd(track.info.timescale, track.info.duration);\n              const hdlr = MP4.hdlr(track.type);\n              const minf = MP4.minf(track);\n              return MP4.box(MP4.types.mdia, mdhd, hdlr, minf);\n          }\n          static mfhd(sequenceNumber) {\n              return MP4.box(MP4.types.mfhd, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  sequenceNumber >> 24,\n                  (sequenceNumber >> 16) & 255,\n                  (sequenceNumber >> 8) & 255,\n                  sequenceNumber & 255, // sequence_number\n              ]));\n          }\n          static minf(track) {\n              if (track.type === 'audio') {\n                  return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n              }\n              else {\n                  return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n              }\n          }\n          static moof(baseMediaDecodeTime, track) {\n              if (!MP4.types) {\n                  MP4.init();\n              }\n              const traf = MP4.traf(track, baseMediaDecodeTime);\n              const moof = MP4.box(MP4.types.moof, MP4.mfhd(track.sequenceNumber), traf);\n              return moof;\n          }\n          /**\n           * @param tracks... (optional) {array} the tracks associated with this movie\n           */\n          static moov(tracks) {\n              let i = tracks.length;\n              const boxes = [];\n              while (i--) {\n                  boxes[i] = MP4.trak(tracks[i]);\n              }\n              return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].info.timescale, tracks[0].info.duration)].concat(boxes).concat(MP4.mvex(tracks)));\n          }\n          static mvex(tracks) {\n              let i = tracks.length;\n              const boxes = [];\n              while (i--) {\n                  boxes[i] = MP4.trex(tracks[i]);\n              }\n              return MP4.box(MP4.types.mvex, ...boxes);\n              // return MP4.box.apply(null, [MP4.types.mvex, .concat(boxes));\n          }\n          static mvhd(timescale, duration) {\n              duration *= timescale;\n              const upperWordDuration = Math.floor(duration / (UINT32_MAX$1 + 1));\n              const lowerWordDuration = Math.floor(duration % (UINT32_MAX$1 + 1));\n              const bytes = new Uint8Array([\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  2,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  3,\n                  (timescale >> 24) & 255,\n                  (timescale >> 16) & 255,\n                  (timescale >> 8) & 255,\n                  timescale & 255,\n                  upperWordDuration >> 24,\n                  (upperWordDuration >> 16) & 255,\n                  (upperWordDuration >> 8) & 255,\n                  upperWordDuration & 255,\n                  lowerWordDuration >> 24,\n                  (lowerWordDuration >> 16) & 255,\n                  (lowerWordDuration >> 8) & 255,\n                  lowerWordDuration & 255,\n                  0,\n                  1,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  64,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  255,\n                  255,\n                  255,\n                  255,\n              ]);\n              return MP4.box(MP4.types.mvhd, bytes);\n          }\n          static sdtp(track) {\n              const samples = track.samples || [], bytes = new Uint8Array(4 + samples.length);\n              let flags, i;\n              // leave the full box header (4 bytes) all zero\n              // write the sample table\n              for (i = 0; i < samples.length; i++) {\n                  flags = samples[i].flags;\n                  bytes[i + 4] = (flags.dependsOn << 4) | (flags.isDependedOn << 2) | flags.hasRedundancy;\n              }\n              return MP4.box(MP4.types.sdtp, bytes);\n          }\n          static stbl(track) {\n              const stsd = MP4.stsd(track);\n              const stts = MP4.box(MP4.types.stts, MP4.STTS);\n              const stsc = MP4.box(MP4.types.stsc, MP4.STSC);\n              const stsz = MP4.box(MP4.types.stsz, MP4.STSZ);\n              const stco = MP4.box(MP4.types.stco, MP4.STCO);\n              return MP4.box(MP4.types.stbl, stsd, stts, stsc, stsz, stco);\n          }\n          static avc1(track) {\n              let sps = [], pps = [], i, data, len;\n              // assemble the SPSs\n              const codingName = track.info.encrypted ? MP4.types.encv : MP4.types.avc1;\n              for (i = 0; i < track.config.sps.length; i++) {\n                  data = track.config.sps[i];\n                  len = data.byteLength;\n                  sps.push((len >>> 8) & 255);\n                  sps.push(len & 255);\n                  sps = sps.concat(Array.prototype.slice.call(data)); // SPS\n              }\n              // assemble the PPSs\n              for (i = 0; i < track.config.pps.length; i++) {\n                  data = track.config.pps[i];\n                  len = data.byteLength;\n                  pps.push((len >>> 8) & 255);\n                  pps.push(len & 255);\n                  pps = pps.concat(Array.prototype.slice.call(data));\n              }\n              const avcc = MP4.box(MP4.types.avcC, new Uint8Array([\n                  1,\n                  sps[3],\n                  sps[4],\n                  sps[5],\n                  255,\n                  224 | track.config.sps.length, // 3bit reserved (111) + numOfSequenceParameterSets\n              ]\n                  .concat(sps)\n                  .concat([\n                  track.config.pps.length, // numOfPictureParameterSets\n              ])\n                  .concat(pps))), // \"PPS\"\n              width = track.config.width, height = track.config.height, hSpacing = track.config.pixelRatio[0], vSpacing = track.config.pixelRatio[1];\n              // console.log('avcc:' + Hex.hexDump(avcc));\n              const sinf = track.info.encrypted && track.info.keyTagInfo ? MP4.sinf(track.info.keyTagInfo, track.type, MP4.types.avc1) : new Uint8Array();\n              // console.log('video sinf:' + Hex.hexDump(sinf));\n              return MP4.box(codingName, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  (width >> 8) & 255,\n                  width & 255,\n                  (height >> 8) & 255,\n                  height & 255,\n                  0,\n                  72,\n                  0,\n                  0,\n                  0,\n                  72,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  18,\n                  100,\n                  97,\n                  105,\n                  108,\n                  121,\n                  109,\n                  111,\n                  116,\n                  105,\n                  111,\n                  110,\n                  47,\n                  104,\n                  108,\n                  115,\n                  46,\n                  106,\n                  115,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  24,\n                  17,\n                  17,\n              ]), // pre_defined = -1\n              avcc, sinf, MP4.box(MP4.types.btrt, new Uint8Array([\n                  0,\n                  28,\n                  156,\n                  128,\n                  0,\n                  45,\n                  198,\n                  192,\n                  0,\n                  45,\n                  198,\n                  192,\n              ])), // avgBitrate\n              MP4.box(MP4.types.pasp, new Uint8Array([\n                  hSpacing >> 24,\n                  (hSpacing >> 16) & 255,\n                  (hSpacing >> 8) & 255,\n                  hSpacing & 255,\n                  vSpacing >> 24,\n                  (vSpacing >> 16) & 255,\n                  (vSpacing >> 8) & 255,\n                  vSpacing & 255,\n              ])));\n          }\n          static esds(config) {\n              const configlen = config.esdsConfig.length;\n              return new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  3,\n                  23 + configlen,\n                  0,\n                  1,\n                  0,\n                  4,\n                  15 + configlen,\n                  64,\n                  21,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  5,\n              ]\n                  .concat([configlen])\n                  .concat(config.esdsConfig)\n                  .concat([6, 1, 2])); // GASpecificConfig)); // length + audio config descriptor\n          }\n          static audioStsd(config) {\n              const samplerate = config.samplerate;\n              return new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  config.channelCount,\n                  0,\n                  16,\n                  0,\n                  0,\n                  0,\n                  0,\n                  (samplerate >> 8) & 255,\n                  samplerate & 255,\n                  0,\n                  0,\n              ]);\n          }\n          static dac3(config) {\n              const extraData = config.extraData;\n              return new Uint8Array([(extraData >> 16) & 255, (extraData >> 8) & 255, extraData & 255]);\n          }\n          static dec3(config) {\n              return config.extraDataBytes;\n          }\n          static mp4a(info, config) {\n              let codingName = MP4.types.mp4a;\n              let sinf = null;\n              if (info.encrypted && info.keyTagInfo) {\n                  codingName = MP4.types.enca;\n                  sinf = MP4.sinf(info.keyTagInfo, 'audio', MP4.types.mp4a);\n              }\n              else {\n                  sinf = new Uint8Array();\n              }\n              const stsd = MP4.audioStsd(config);\n              const esds = MP4.box(MP4.types.esds, MP4.esds(config));\n              return MP4.box(codingName, stsd, esds, sinf);\n          }\n          static mp3(config) {\n              return MP4.box(MP4.types['.mp3'], MP4.audioStsd(config));\n          }\n          static ac3(info, config) {\n              let codingName = MP4.types['ac-3'];\n              let sinf = null;\n              if (info.encrypted && info.keyTagInfo) {\n                  codingName = MP4.types.enca;\n                  sinf = MP4.sinf(info.keyTagInfo, 'audio', MP4.types['ac-3']);\n              }\n              else {\n                  sinf = new Uint8Array();\n              }\n              return MP4.box(codingName, MP4.audioStsd(config), MP4.box(MP4.types.dac3, MP4.dac3(config)), sinf);\n          }\n          static ec3(info, config) {\n              let codingName = MP4.types['ec-3'];\n              let sinf = null;\n              if (info.encrypted && info.keyTagInfo) {\n                  codingName = MP4.types.enca;\n                  sinf = MP4.sinf(info.keyTagInfo, 'audio', MP4.types['ec-3']);\n              }\n              else {\n                  sinf = new Uint8Array();\n              }\n              return MP4.box(codingName, MP4.audioStsd(config), MP4.box(MP4.types.dec3, MP4.dec3(config)), sinf);\n          }\n          static stsd(track) {\n              if (track.type === 'audio') {\n                  if (track.config.segmentCodec === 'mp3' && track.config.codec === 'mp3') {\n                      return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track.config));\n                  }\n                  if (track.config.segmentCodec === 'ac3') {\n                      return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track.info, track.config));\n                  }\n                  else if (track.config.segmentCodec === 'ec3') {\n                      return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ec3(track.info, track.config));\n                  }\n                  else if (track.config.segmentCodec === 'aac') {\n                      return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track.info, track.config));\n                  }\n                  else {\n                      throw `unknown segmentCodec ${track.config.segmentCodec}`;\n                  }\n              }\n              else {\n                  return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n              }\n          }\n          static tkhd(track) {\n              const id = track.info.id;\n              const duration = track.info.duration * track.info.timescale;\n              const upperWordDuration = Math.floor(duration / (UINT32_MAX$1 + 1));\n              const lowerWordDuration = Math.floor(duration % (UINT32_MAX$1 + 1));\n              let width = 0;\n              let height = 0;\n              if (track.type === 'video') {\n                  width = track.config.width;\n                  height = track.config.height;\n              }\n              return MP4.box(MP4.types.tkhd, new Uint8Array([\n                  1,\n                  0,\n                  0,\n                  7,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  2,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  3,\n                  (id >> 24) & 255,\n                  (id >> 16) & 255,\n                  (id >> 8) & 255,\n                  id & 255,\n                  0,\n                  0,\n                  0,\n                  0,\n                  upperWordDuration >> 24,\n                  (upperWordDuration >> 16) & 255,\n                  (upperWordDuration >> 8) & 255,\n                  upperWordDuration & 255,\n                  lowerWordDuration >> 24,\n                  (lowerWordDuration >> 16) & 255,\n                  (lowerWordDuration >> 8) & 255,\n                  lowerWordDuration & 255,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  64,\n                  0,\n                  0,\n                  0,\n                  (width >> 8) & 255,\n                  width & 255,\n                  0,\n                  0,\n                  (height >> 8) & 255,\n                  height & 255,\n                  0,\n                  0,\n              ]));\n          }\n          static traf(track, baseMediaDecodeTime) {\n              const sencOffset = 76; // mdat header\n              const sampleEncryptionBoxTuple = MP4.senc(track);\n              const sampleDependencyTable = MP4.sdtp(track), sampleEncryptionBox = sampleEncryptionBoxTuple.boxData, sampleEncryptionOffsetBox = sampleEncryptionBox.length ? MP4.saio(sencOffset) : new Uint8Array(), sampleEncryptionSizeBox = sampleEncryptionBox.length ? MP4.saiz(sampleEncryptionBoxTuple.defaultSampleInfoSize, sampleEncryptionBoxTuple.sampleInfoSizes) : new Uint8Array(), sampleToGroupBox = MP4.sbgp(track), sampleGroupDescriptionBox = MP4.sgpd(track), id = track.id, upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1)), lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));\n              // console.log('sampleToGroupBox:' + Hex.hexDump(sampleToGroupBox));\n              // console.log('sampleGroupDescriptionBox:' + Hex.hexDump(sampleGroupDescriptionBox));\n              return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([\n                  0,\n                  2,\n                  0,\n                  0,\n                  id >> 24,\n                  (id >> 16) & 255,\n                  (id >> 8) & 255,\n                  id & 255, // track_ID\n              ])), MP4.box(MP4.types.tfdt, new Uint8Array([\n                  1,\n                  0,\n                  0,\n                  0,\n                  upperWordBaseMediaDecodeTime >> 24,\n                  (upperWordBaseMediaDecodeTime >> 16) & 255,\n                  (upperWordBaseMediaDecodeTime >> 8) & 255,\n                  upperWordBaseMediaDecodeTime & 255,\n                  lowerWordBaseMediaDecodeTime >> 24,\n                  (lowerWordBaseMediaDecodeTime >> 16) & 255,\n                  (lowerWordBaseMediaDecodeTime >> 8) & 255,\n                  lowerWordBaseMediaDecodeTime & 255,\n              ])), sampleEncryptionBox, sampleEncryptionOffsetBox, sampleEncryptionSizeBox, sampleToGroupBox, sampleGroupDescriptionBox, MP4.trun(track, sampleDependencyTable.length +\n                  sampleEncryptionBox.length +\n                  sampleToGroupBox.length +\n                  sampleGroupDescriptionBox.length +\n                  sampleEncryptionOffsetBox.length +\n                  sampleEncryptionSizeBox.length + 16 + // tfhd\n               20 + // tfdt\n               8 + // traf header\n               16 + // mfhd\n               8 + // moof header\n               8), // mdat header\n              sampleDependencyTable);\n          }\n          /**\n           * Generate a track box.\n           * @param track {object} a track definition\n           * @return {Uint8Array} the track box\n           */\n          static trak(track) {\n              if ('trakData' in track) {\n                  // cached trak\n                  return track.trakData;\n              }\n              track.info.duration = track.info.duration || 4294967295;\n              const trak = MP4.types.trak;\n              const thkd = MP4.tkhd(track);\n              const mdia = MP4.mdia(track);\n              return MP4.box(trak, thkd, mdia);\n          }\n          static trex(track) {\n              const id = track.info.id;\n              return MP4.box(MP4.types.trex, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  id >> 24,\n                  (id >> 16) & 255,\n                  (id >> 8) & 255,\n                  id & 255,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  0,\n                  1,\n              ]));\n          }\n          static trun(track, offset) {\n              const samples = track.samples || [], len = samples.length, arraylen = 12 + 16 * len, array = new Uint8Array(arraylen);\n              let i, sample, duration, size, flags, cts;\n              offset += 8 + arraylen;\n              array.set([\n                  0,\n                  0,\n                  15,\n                  1,\n                  (len >>> 24) & 255,\n                  (len >>> 16) & 255,\n                  (len >>> 8) & 255,\n                  len & 255,\n                  (offset >>> 24) & 255,\n                  (offset >>> 16) & 255,\n                  (offset >>> 8) & 255,\n                  offset & 255, // data_offset\n              ], 0);\n              for (i = 0; i < len; i++) {\n                  sample = samples[i];\n                  duration = sample.duration;\n                  size = sample.size;\n                  flags = sample.flags;\n                  cts = sample.cts;\n                  array.set([\n                      (duration >>> 24) & 255,\n                      (duration >>> 16) & 255,\n                      (duration >>> 8) & 255,\n                      duration & 255,\n                      (size >>> 24) & 255,\n                      (size >>> 16) & 255,\n                      (size >>> 8) & 255,\n                      size & 255,\n                      (flags.isLeading << 2) | flags.dependsOn,\n                      (flags.isDependedOn << 6) | (flags.hasRedundancy << 4) | (flags.paddingValue << 1) | flags.isNonSync,\n                      flags.degradPrio & (240 << 8),\n                      flags.degradPrio & 15,\n                      (cts >>> 24) & 255,\n                      (cts >>> 16) & 255,\n                      (cts >>> 8) & 255,\n                      cts & 255, // sample_composition_time_offset\n                  ], 12 + 16 * i);\n              }\n              return MP4.box(MP4.types.trun, array);\n          }\n          static initSegment(tracks) {\n              if (!MP4.types) {\n                  MP4.init();\n              }\n              const movie = MP4.moov(tracks);\n              const result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n              result.set(MP4.FTYP);\n              result.set(movie, MP4.FTYP.byteLength);\n              return result;\n          }\n          // encryption boxes\n          static saio(sencOffset) {\n              const subOffset = sencOffset + 4 + 4; // skip version/flags and sample_count\n              return MP4.box(MP4.types.saio, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  0,\n                  1,\n                  (subOffset >> 24) & 255,\n                  (subOffset >> 16) & 255,\n                  (subOffset >> 8) & 255,\n                  subOffset & 255,\n              ]));\n          }\n          static saiz(defaultSampleInfoSize, sampleInfoSizes) {\n              if (!isFiniteNumber(defaultSampleInfoSize)) {\n                  defaultSampleInfoSize = 0;\n              }\n              const sampleCount = sampleInfoSizes.length;\n              const perSampleSizeData = defaultSampleInfoSize === 0 ? new Uint8Array(sampleInfoSizes) : new Uint8Array();\n              return MP4.box(MP4.types.saiz, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  defaultSampleInfoSize,\n                  (sampleCount >> 24) & 255,\n                  (sampleCount >> 16) & 255,\n                  (sampleCount >> 8) & 255,\n                  sampleCount & 255,\n              ]), perSampleSizeData);\n          }\n          static senc(track) {\n              const samples = track.samples || [], sampleCount = samples.length;\n              let totalSubsamples = 0;\n              let lastSize = NaN;\n              let hasDefaultSampleSize = true;\n              const sampleInfoSizes = [];\n              if (!track.encrypted || sampleCount <= 0) {\n                  return { boxData: new Uint8Array(), sampleInfoSizes, defaultSampleInfoSize: 0 };\n              }\n              const defaultPerSampleIVSize = track.defaultPerSampleIVSize ? track.defaultPerSampleIVSize : 0;\n              for (const sample of samples) {\n                  if (sample.subsamples) {\n                      totalSubsamples += sample.subsamples.length;\n                  }\n              }\n              if (totalSubsamples <= 0) {\n                  // don't create a senc if there are no subsamples\n                  return { boxData: new Uint8Array(), sampleInfoSizes, defaultSampleInfoSize: 0 };\n              }\n              // 4 bytes for sample_count\n              // 2 bytes per sample for subsample_count\n              // 6 bytes per subsample for unsigned int(16) BytesOfClearData and unsigned int(32) BytesOfProtectedData;\n              // defaultPerSampleIVSize bytes per sample\n              const boxdata = new Uint8Array(4 + (sampleCount * 2 + sampleCount * defaultPerSampleIVSize + totalSubsamples * 6));\n              let offset = this.set32(sampleCount, boxdata, 0);\n              for (const sample of samples) {\n                  const subsamples = sample.subsamples ? sample.subsamples : [];\n                  let subsampleSize = 2; // size in bytes of the subsample entry - start with 2 for the subsample count\n                  if (sample.iv) {\n                      // per sample IV from cenc aux data\n                      boxdata.set(sample.iv, offset);\n                      offset += sample.iv.byteLength;\n                      subsampleSize += sample.iv.byteLength;\n                  }\n                  offset = this.set16(subsamples.length, boxdata, offset);\n                  for (const subsample of subsamples) {\n                      offset = this.set16(subsample[0], boxdata, offset);\n                      offset = this.set32(subsample[1], boxdata, offset);\n                      subsampleSize += 6;\n                  }\n                  sampleInfoSizes.push(subsampleSize);\n                  if (!isFiniteNumber(lastSize)) {\n                      lastSize = subsampleSize;\n                  }\n                  hasDefaultSampleSize = hasDefaultSampleSize && lastSize === subsampleSize;\n                  lastSize = subsampleSize;\n              }\n              const boxData = MP4.box(MP4.types.senc, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  2,\n              ]), boxdata);\n              return { boxData, defaultSampleInfoSize: hasDefaultSampleSize ? lastSize : 0, sampleInfoSizes };\n          }\n          static sinf(decryptdata, type, originalCodingName) {\n              return MP4.box(MP4.types.sinf, MP4.frma(originalCodingName), MP4.schm(), MP4.schi(decryptdata, type));\n          }\n          static frma(originalCodingName) {\n              return MP4.box(MP4.types.frma, new Uint8Array(originalCodingName));\n          }\n          static schm() {\n              return MP4.box(MP4.types.schm, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n                  99,\n                  98,\n                  99,\n                  115,\n                  0,\n                  1,\n                  0,\n                  0,\n              ]));\n          }\n          static schi(decryptdata, type) {\n              return MP4.box(MP4.types.schi, MP4.tenc(decryptdata, type));\n          }\n          static tenc(decryptdata, trackType) {\n              let skipPattern = 0;\n              if (trackType === 'video') {\n                  skipPattern = 25; // 1 default_crypt_byte_block, 9 default_skip_byte_block\n              }\n              const defaultIV = new Uint8Array(17);\n              defaultIV[0] = 16; // default_constant_IV_size (16)\n              if (decryptdata.iv && decryptdata.iv.byteLength === 16) {\n                  defaultIV.set(decryptdata.iv, 1);\n              }\n              if (!decryptdata.keyId) {\n                  throw 'tenc: no key id found in decryptdata';\n              }\n              return MP4.box(MP4.types.tenc, new Uint8Array([\n                  1,\n                  0,\n                  0,\n                  0,\n                  0,\n                  skipPattern,\n                  1,\n                  0,\n              ]), decryptdata.keyId, // default_KID, 16 bytes\n              defaultIV);\n          }\n          // only using this to write seig entries\n          static sbgp(track) {\n              if (!track.encrypted || track.samples.length === 0 || !track.samples[0].keyTagInfo) {\n                  return new Uint8Array();\n              }\n              // at this point we're assuming all samples in the track have the same key id\n              // this should hold true for the current ts/mp4 remux path\n              const sampleCount = track.samples.length;\n              return MP4.box(MP4.types.sbgp, new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  0,\n              ]), new Uint8Array(MP4.types.seig), // grouping_type\n              new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  1,\n                  (sampleCount >> 24) & 255,\n                  (sampleCount >> 16) & 255,\n                  (sampleCount >> 8) & 255,\n                  sampleCount & 255,\n                  0,\n                  1,\n                  0,\n                  1,\n              ]));\n          }\n          // only using this to write seig entries\n          static sgpd(track) {\n              if (!track.encrypted || track.samples.length === 0 || !track.samples[0].keyTagInfo) {\n                  return new Uint8Array();\n              }\n              const sDecryptdata = track.samples[0].keyTagInfo;\n              let skipPattern = 0;\n              if (track.type === 'video') {\n                  skipPattern = 25; // 1 default_crypt_byte_block, 9 default_skip_byte_block\n              }\n              const sizeAndIv = new Uint8Array(17);\n              sizeAndIv[0] = 16;\n              if (sDecryptdata.iv) {\n                  sizeAndIv.set(sDecryptdata.iv, 1);\n              }\n              if (!sDecryptdata.keyId) {\n                  throw 'sgpd: no keyid in decryptdata';\n              }\n              return MP4.box(MP4.types.sgpd, new Uint8Array([\n                  1,\n                  0,\n                  0,\n                  0,\n              ]), new Uint8Array(MP4.types.seig), // grouping_type\n              new Uint8Array([\n                  0,\n                  0,\n                  0,\n                  37,\n                  0,\n                  0,\n                  0,\n                  1,\n              ]), new Uint8Array([\n                  0,\n                  skipPattern,\n                  1,\n                  0,\n              ]), sDecryptdata.keyId, sizeAndIv);\n          }\n          /**\n           * @param {Uint8Array} systemId 16 bytes\n           * @param {array of Uint8Array} keyids The list of key ids described by this PSSH box\n           * @param {Uint8Array} An arbitrary buffer of data to be used in the data field of the PSSH box\n           * @returns {Uint8Array} Bytes representing a PSSH box\n           */\n          static pssh(systemId, keyids, data) {\n              if (!MP4.types) {\n                  MP4.init();\n              }\n              if (!systemId) {\n                  throw new TypeError('Bad system id');\n              }\n              if (systemId.byteLength !== 16) {\n                  throw new RangeError('Invalid system id');\n              }\n              let version;\n              let kids;\n              if (keyids) {\n                  version = 1;\n                  kids = new Uint8Array(keyids.length * 16);\n                  for (let ix = 0; ix < keyids.length; ix++) {\n                      const k = keyids[ix]; // uint8array\n                      if (k.byteLength !== 16) {\n                          throw new RangeError('Invalid key');\n                      }\n                      kids.set(k, ix * 16);\n                  }\n              }\n              else {\n                  version = 0;\n                  kids = new Uint8Array();\n              }\n              let kidCount;\n              if (version > 0) {\n                  kidCount = new Uint8Array(4);\n                  if (keyids.length > 0) {\n                      new DataView(kidCount.buffer).setUint32(0, keyids.length, false); // Big endian\n                  }\n              }\n              else {\n                  kidCount = new Uint8Array();\n              }\n              const dataSize = new Uint8Array(4); // Mandatory field\n              if (data && data.byteLength > 0) {\n                  new DataView(dataSize.buffer).setUint32(0, data.byteLength, false); // Big endian\n              }\n              return MP4.box(MP4.types.pssh, new Uint8Array([\n                  version,\n                  0,\n                  0,\n                  0,\n              ]), systemId, // 16 bytes\n              kidCount, kids, dataSize, data || new Uint8Array());\n          }\n      }\n      var MP4$1 = MP4;\n    \n      var VideoDynamicRangeType;\n      (function (VideoDynamicRangeType) {\n          // should be same as AirPlayVideoDynamicRangeFormat\n          VideoDynamicRangeType[VideoDynamicRangeType[\"SDR\"] = 0] = \"SDR\";\n          VideoDynamicRangeType[VideoDynamicRangeType[\"HDR\"] = 1] = \"HDR\";\n          VideoDynamicRangeType[VideoDynamicRangeType[\"HDR10\"] = 2] = \"HDR10\";\n          VideoDynamicRangeType[VideoDynamicRangeType[\"DolbyVision\"] = 3] = \"DolbyVision\";\n          VideoDynamicRangeType[VideoDynamicRangeType[\"HLG\"] = 4] = \"HLG\";\n      })(VideoDynamicRangeType || (VideoDynamicRangeType = {}));\n      var CompressionType;\n      (function (CompressionType) {\n          // should be same as AirPlayCompressionType\n          CompressionType[CompressionType[\"H264\"] = 16] = \"H264\";\n          CompressionType[CompressionType[\"HEVC\"] = 64] = \"HEVC\";\n          CompressionType[CompressionType[\"VP09\"] = 65] = \"VP09\";\n      })(CompressionType || (CompressionType = {}));\n    \n      // import { AudioSegmentCodecType } from '../types/tracks';\n      /*\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const ac3Codecs = new Set(['ac-3', 'mp4a.a5', 'mp4a.A5']);\n      const ec3Codecs = new Set(['ec-3', 'mp4a.a6', 'mp4a.A6']);\n      const SampleDurationMap = { aac: 1024, mp3: 1024, ac3: 1536, ec3: 1536 };\n      const MediaUtil = {\n          isAC3(codec) {\n              return Boolean(codec && ac3Codecs.has(codec));\n          },\n          isEC3(codec) {\n              return Boolean(codec && ec3Codecs.has(codec));\n          },\n          isDolbyAtmos(codec, channels) {\n              const parameters = channels.split('/');\n              return Boolean(MediaUtil.isEC3(codec) && parameters.length > 1 && parameters[1].split(',').find((x) => x === 'JOC'));\n          },\n          isAAC(codec) {\n              let match;\n              return Boolean(codec && (codec === 'aac' || ((match = codec.match(/^mp4a\\.40\\.(.*)/)) !== null && match[1] !== '34')));\n          },\n          isMP3(codec) {\n              let match;\n              return Boolean(codec && (codec === 'mp3' || ((match = codec.match(/^mp4a\\.40\\.(.*)/)) !== null && match[1] === '34')));\n          },\n          isAVC(codec) {\n              // basic match without validation\n              return Boolean(codec && codec.match(/^avc[13]\\.(.*)/));\n          },\n          isXHEAAC: function (codec) {\n              return Boolean(codec === 'mp4a.40.42');\n          },\n          isALAC: function (codec) {\n              return Boolean(codec === 'alac');\n          },\n          isFLAC: function (codec) {\n              return Boolean(codec === 'fLaC');\n          },\n          isHEVC(codec) {\n              // basic match without validation\n              return Boolean(codec && codec.match(/^(hev|hvc)1\\..*/));\n          },\n          isDolby(codec) {\n              return Boolean(codec && codec.match(/^dv(h1|he|a1|av)\\..*/));\n          },\n          isVP09(codec) {\n              // basic match without validation\n              return Boolean(codec && codec.match(/^vp09\\..*/));\n          },\n          isCompatibleCodecString(c1, c2) {\n              const codecs1 = c1.split(',');\n              const codecs2 = c2.split(',');\n              const videoCodec1 = codecs1.filter((codec) => MediaUtil.isVideoCodec(codec));\n              const videoCodec2 = codecs2.filter((codec) => MediaUtil.isVideoCodec(codec));\n              const audioCodec1 = codecs1.filter((codec) => MediaUtil.isAudioCodec(codec));\n              const audioCodec2 = codecs2.filter((codec) => MediaUtil.isAudioCodec(codec));\n              const videoOk = (videoCodec1.length === 0 && videoCodec2.length === 0) || (videoCodec1.length === videoCodec2.length && MediaUtil.isCompatibleVideoCodec(videoCodec1[0], videoCodec2[0]));\n              const audioOk = (audioCodec1.length === 0 && audioCodec2.length === 0) || (audioCodec1.length === audioCodec2.length && MediaUtil.isCompatibleAudioCodec(audioCodec1[0], audioCodec2[0]));\n              return videoOk && audioOk;\n          },\n          isVideoCodec(codec) {\n              return MediaUtil.isAVC(codec) || MediaUtil.isDolby(codec) || MediaUtil.isHEVC(codec) || MediaUtil.isVP09(codec);\n          },\n          isAudioCodec(codec) {\n              return MediaUtil.isAC3(codec) || MediaUtil.isEC3(codec) || MediaUtil.isAAC(codec) || MediaUtil.isMP3(codec);\n          },\n          isCompatibleVideoCodec(c1, c2) {\n              return Boolean(c1 &&\n                  c2 &&\n                  (c1 === c2 ||\n                      (MediaUtil.isDolby(c1) && MediaUtil.isDolby(c2)) ||\n                      (MediaUtil.isHEVC(c1) && MediaUtil.isHEVC(c2)) ||\n                      (MediaUtil.isAVC(c1) && MediaUtil.isAVC(c2)) ||\n                      (MediaUtil.isVP09(c1) && MediaUtil.isVP09(c2))));\n          },\n          isCompatibleAudioCodec(c1, c2) {\n              return Boolean(c1 &&\n                  c2 &&\n                  (c1 === c2 ||\n                      (MediaUtil.isAAC(c1) && MediaUtil.isAAC(c2)) ||\n                      (MediaUtil.isAC3(c1) && MediaUtil.isAC3(c2)) ||\n                      (MediaUtil.isEC3(c1) && MediaUtil.isEC3(c2)) ||\n                      (MediaUtil.isMP3(c1) && MediaUtil.isMP3(c2))));\n          },\n          getSegmentCodec(audioCodec) {\n              let segmentCodec;\n              if (MediaUtil.isAAC(audioCodec)) {\n                  segmentCodec = 'aac';\n              }\n              else if (MediaUtil.isAC3(audioCodec)) {\n                  segmentCodec = 'ac3';\n              }\n              else if (MediaUtil.isEC3(audioCodec)) {\n                  segmentCodec = 'ec3';\n              }\n              else if (audioCodec === 'mp3') {\n                  segmentCodec = 'mp3';\n              }\n              else {\n                  throw new Error(`invalid audio config, codec ${audioCodec}`);\n              }\n              return segmentCodec;\n          },\n          getChannelCount(channels) {\n              if (!channels) {\n                  return 0;\n              }\n              const parameters = channels.split('/');\n              const channelCount = parseInt(parameters[0]);\n              if (!isFiniteNumber(channelCount)) {\n                  return 0;\n              }\n              return channelCount;\n          },\n          avc1toavcoti(codec) {\n              var _a, _b;\n              const avcdata = codec.split('.');\n              let result;\n              if (avcdata.length > 2) {\n                  result = avcdata.shift() + '.';\n                  result += parseInt((_a = avcdata.shift()) !== null && _a !== void 0 ? _a : '').toString(16);\n                  result += ('000' + parseInt((_b = avcdata.shift()) !== null && _b !== void 0 ? _b : '').toString(16)).substr(-4);\n              }\n              else {\n                  result = codec;\n              }\n              return result;\n          },\n          getDynamicRangeType(videoRange, videoCodec) {\n              let type = VideoDynamicRangeType.SDR; // default to SDR\n              if (videoRange === 'PQ' && MediaUtil.isDolby(videoCodec)) {\n                  type = VideoDynamicRangeType.DolbyVision;\n              }\n              else if (videoRange === 'PQ' && (MediaUtil.isHEVC(videoCodec) || MediaUtil.isVP09(videoCodec))) {\n                  type = VideoDynamicRangeType.HDR10;\n              }\n              else if (videoRange === 'HLG' && (videoCodec.indexOf('hvc1') !== -1 || MediaUtil.isVP09(videoCodec))) {\n                  type = VideoDynamicRangeType.HLG;\n              }\n              return type;\n          },\n          getCompressionType(videoCodec) {\n              let compressionType = CompressionType.H264;\n              if (MediaUtil.isHEVC(videoCodec) || MediaUtil.isDolby(videoCodec)) {\n                  compressionType = CompressionType.HEVC;\n              }\n              else if (MediaUtil.isVP09(videoCodec)) {\n                  compressionType = CompressionType.VP09;\n              }\n              return compressionType;\n          },\n          isHigherCodecByFamily(currentCodec, newCodec) {\n              if (!currentCodec) {\n                  return true;\n              }\n              const splitCurrentCodec = currentCodec.split('.');\n              const splitNewCodec = newCodec.split('.');\n              if (splitCurrentCodec[0] !== splitNewCodec[0]) {\n                  throw new Error(`mismatch in codec family current/new: ${splitCurrentCodec[0]}/${splitNewCodec[0]}`);\n              }\n              switch (splitCurrentCodec[0]) {\n                  case 'avc1':\n                  case 'avc3':\n                      return splitNewCodec[1] > splitCurrentCodec[1];\n                  case 'vp09':\n                      return newCodec > currentCodec;\n                  case 'hvc1':\n                  case 'hev1':\n                      const currentTier = splitCurrentCodec[3].substring(0, 1) === 'H' ? 1 : 0;\n                      const currentLevel = splitCurrentCodec[3].substring(1);\n                      const newTier = splitNewCodec[3].substring(0, 1) === 'H' ? 1 : 0;\n                      const newLevel = splitNewCodec[3].substring(1);\n                      return splitNewCodec[1] > splitCurrentCodec[1] || splitNewCodec[2] > splitCurrentCodec[2] || newTier > currentTier || newLevel > currentLevel;\n                  case 'dvh1':\n                      return splitNewCodec[1] > splitCurrentCodec[1] || splitNewCodec[2] > splitCurrentCodec[2];\n              }\n          },\n      };\n    \n      class SilentAudio {\n          static getTrack(observer, id, codec, channelCount, logger) {\n              let track;\n              const segmentCodec = MediaUtil.getSegmentCodec(codec);\n              switch (segmentCodec) {\n                  case 'aac':\n                      {\n                          let config;\n                          if (channelCount === 1) {\n                              config = ADTS.getAudioConfig(observer, new Uint8Array([255, 241, 92, 64, 1, 127, 252]), 0, codec, logger);\n                          }\n                          else {\n                              config = ADTS.getAudioConfig(observer, new Uint8Array([255, 241, 92, 128, 1, 191, 252]), 0, codec, logger);\n                          }\n                          if (config) {\n                              const info = { id, timescale: config.samplerate, duration: 0, encrypted: false, keyTagInfo: undefined };\n                              track = { type: 'audio', info, config };\n                          }\n                      }\n                      break;\n                  case 'ac3':\n                  case 'ec3':\n                      {\n                          const config = Dolby.getAudioConfig(observer, new Uint8Array([11, 119, 69, 17, 128, 64, 47, 132]), 0, logger);\n                          if (config) {\n                              const info = { id, timescale: config.samplerate, duration: 0, encrypted: false, keyTagInfo: undefined };\n                              track = { type: 'audio', info, config };\n                          }\n                      }\n                      break;\n              }\n              return track;\n          }\n          static getSample(codec, channelCount) {\n              let sample;\n              switch (codec) {\n                  case 'mp4a.40.2':\n                  case 'mp4a.40.5':\n                      if (channelCount === 1) {\n                          sample = new Uint8Array([0, 208, 0, 7]);\n                      }\n                      else {\n                          sample = new Uint8Array([33, 0, 3, 64, 104, 28]);\n                      }\n                      break;\n                  case 'ac-3':\n                  case 'ec-3':\n                      sample = new Uint8Array([\n                          11,\n                          119,\n                          69,\n                          17,\n                          128,\n                          64,\n                          47,\n                          132,\n                          41,\n                          3,\n                          253,\n                          214,\n                          124,\n                          253,\n                          243,\n                          215,\n                          233,\n                          95,\n                          185,\n                          123,\n                          78,\n                          20,\n                          40,\n                          106,\n                          97,\n                          190,\n                          74,\n                          253,\n                          43,\n                          218,\n                          208,\n                          140,\n                          191,\n                          176,\n                          144,\n                          120,\n                          214,\n                          181,\n                          44,\n                          124,\n                          129,\n                          251,\n                          91,\n                          109,\n                          187,\n                          109,\n                          198,\n                          225,\n                          43,\n                          172,\n                          116,\n                          140,\n                          176,\n                          123,\n                          38,\n                          144,\n                          211,\n                          247,\n                          225,\n                          64,\n                          29,\n                          53,\n                          175,\n                          96,\n                          16,\n                          57,\n                          121,\n                          87,\n                          78,\n                          203,\n                          81,\n                          37,\n                          7,\n                          72,\n                          228,\n                          132,\n                          37,\n                          169,\n                          38,\n                          231,\n                          97,\n                          229,\n                          247,\n                          194,\n                          208,\n                          8,\n                          12,\n                          83,\n                          74,\n                          139,\n                          137,\n                          17,\n                          22,\n                          26,\n                          221,\n                          203,\n                          107,\n                          113,\n                          94,\n                          93,\n                          75,\n                          33,\n                          208,\n                          247,\n                          146,\n                          105,\n                          39,\n                          143,\n                          6,\n                          36,\n                          1,\n                          227,\n                          108,\n                          70,\n                          11,\n                          180,\n                          152,\n                          218,\n                          182,\n                          218,\n                          209,\n                          59,\n                          85,\n                          104,\n                          201,\n                          70,\n                          37,\n                          82,\n                          219,\n                          68,\n                          55,\n                          225,\n                          144,\n                          99,\n                          149,\n                          0,\n                          119,\n                          26,\n                          14,\n                          69,\n                          164,\n                          241,\n                          204,\n                          222,\n                          81,\n                          177,\n                          142,\n                          80,\n                          20,\n                          100,\n                          97,\n                          143,\n                          101,\n                          221,\n                          140,\n                          113,\n                          31,\n                          208,\n                          124,\n                          25,\n                          64,\n                          29,\n                          49,\n                          77,\n                          140,\n                          30,\n                          155,\n                          74,\n                          214,\n                          204,\n                          138,\n                          229,\n                          109,\n                          172,\n                          95,\n                          130,\n                          70,\n                          230,\n                          134,\n                          88,\n                          59,\n                          179,\n                          212,\n                          155,\n                          232,\n                          0,\n                          0,\n                          0,\n                          0,\n                          0,\n                          173,\n                          234,\n                      ]);\n                      break;\n              }\n              return sample;\n          }\n          static getSegment(silentTrack, sequenceNumber, startDtsTimescale, segmentDuration) {\n              if (!silentTrack) {\n                  return;\n              }\n              const { timescale } = silentTrack.info;\n              const { segmentCodec } = silentTrack.config;\n              const silentFrame = SilentAudio.getSample(silentTrack.config.codec, silentTrack.config.channelCount);\n              if (!silentFrame) {\n                  return;\n              }\n              const samples = [];\n              const track = {\n                  id: silentTrack.info.id,\n                  sequenceNumber,\n                  type: 'audio',\n                  encrypted: false,\n                  samples,\n                  defaultPerSampleIVSize: 0,\n              };\n              const sampleDuration = SampleDurationMap[segmentCodec];\n              const nbSamples = Math.ceil((segmentDuration * timescale) / sampleDuration);\n              const baseTime = Math.round(nbSamples * sampleDuration + startDtsTimescale);\n              const endTs = { baseTime, timescale };\n              let offset = 0;\n              const mdatSize = nbSamples * silentFrame.byteLength + 8;\n              const mdat = new Uint8Array(mdatSize);\n              mdat[0] = (mdatSize >> 24) & 255;\n              mdat[1] = (mdatSize >> 16) & 255;\n              mdat[2] = (mdatSize >> 8) & 255;\n              mdat[3] = mdatSize & 255;\n              if (!MP4$1.types) {\n                  MP4$1.init();\n              }\n              mdat.set(MP4$1.types.mdat, 4);\n              offset += 8;\n              for (let i = 0; i < nbSamples; i++) {\n                  samples.push({\n                      duration: sampleDuration,\n                      size: silentFrame.byteLength,\n                      cts: 0,\n                      flags: {\n                          isLeading: 0,\n                          isDependedOn: 0,\n                          hasRedundancy: 0,\n                          degradPrio: 0,\n                          dependsOn: 1,\n                          isNonSync: 0,\n                          paddingValue: 0,\n                      },\n                  });\n                  mdat.set(silentFrame, offset);\n                  offset += silentFrame.byteLength;\n              }\n              const moof = MP4$1.moof(startDtsTimescale, track);\n              const silentFragData = new Uint8Array(moof.byteLength + mdat.byteLength);\n              silentFragData.set(moof);\n              silentFragData.set(mdat, moof.byteLength);\n              return { silentFragData, endTs };\n          }\n      }\n    \n      // 10 seconds\n      const MAX_SILENT_FRAME_DURATION = 10000;\n      class EsRemuxer extends RemuxerBase {\n          constructor(observer, config, typeSupported, vendor, logger) {\n              super(observer, config, logger);\n              this.typeSupported = typeSupported;\n              this.isVideoContiguous = false;\n              this.logger = logger.child({ name: 'EsRemuxer' });\n              const userAgent = navigator.userAgent;\n              this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n          }\n          resetTimeStamp(defaultTimeStamp) {\n              this._initPTS = this._initDTS = defaultTimeStamp;\n          }\n          resetInitSegment() {\n              this.currentInitTrack = undefined;\n              this._silentAudioTrack = undefined;\n          }\n          /**\n           * @param timeOffset        The position in the media element corresponding to this fragment when playback rate = 1\n           * @param contiguous        Whether this fragment is contiguous with previously appended fragment\n           * @param accurateTimeOffset  Whether timeOffset is reliable\n           * @param keyTagInfo       Information from EXT-X-KEY tag\n           * @param iframeMediaStart  in iframe mode, the desired start DTS of the remuxed fragment\n           * @param iframeDuration    in iframe mode, the desired duration of the remuxed fragment\n           */\n          remuxEsTracks(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, keyTagInfo, iframeMediaStart, iframeDuration) {\n              var _a;\n              if (!contiguous) {\n                  this.isVideoContiguous = false;\n              }\n              // generate Init Segment if needed\n              let silentAudioSegment;\n              const timelineOffset = typeof iframeMediaStart === 'undefined' ? timeOffset : iframeMediaStart;\n              if (!this.currentInitTrack) {\n                  if (audioTrack && audioTrack.config.codec) {\n                      // when we start out in non-iframe mode we need to store the audio parameters\n                      // we won't get this info from the iframe playlist since the demuxer will skip audio samples\n                      this._audioTrackInfo = { id: audioTrack.info.id, codec: audioTrack.config.codec, channelCount: audioTrack.config.channelCount };\n                  }\n                  if (videoTrack && iframeDuration && this._audioTrackInfo) {\n                      const silentAudioBase = SilentAudio.getTrack(this.observer, this._audioTrackInfo.id, this._audioTrackInfo.codec, this._audioTrackInfo.channelCount, this.logger);\n                      if (silentAudioBase) {\n                          this._silentAudioTrack = Object.assign(Object.assign({}, silentAudioBase), { info: Object.assign(Object.assign({}, silentAudioBase.info), { inputTimescale: 90000 }), parsingData: { len: 0, sequenceNumber: 0, esSamples: [] } });\n                          // need to populate samples for generateIS\n                          const segmentStartPTS = this._initPTS + Math.round(timelineOffset * this._silentAudioTrack.info.timescale);\n                          silentAudioSegment = SilentAudio.getSegment(this._silentAudioTrack, videoTrack.parsingData.sequenceNumber, segmentStartPTS, iframeDuration);\n                          videoTrack.parsingData.sequenceNumber++;\n                      }\n                  }\n                  else {\n                      this._silentAudioTrack = undefined;\n                  }\n                  this.updateInitPTSDTS(videoTrack, audioTrack, timeOffset); // Use real audioTrack info to update PTSDTS\n                  this.generateIS(this._silentAudioTrack ? this._silentAudioTrack : audioTrack, videoTrack);\n              }\n              if (this.currentInitTrack) {\n                  const remuxVideo = videoTrack && videoTrack.parsingData.esSamples.length;\n                  const isVideoContiguous = this.isVideoContiguous;\n                  let audioData, videoData;\n                  // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n                  // calculated in remuxAudio.\n                  if (videoTrack && iframeDuration && this._silentAudioTrack && !silentAudioSegment) {\n                      // samples could have been generated before init segment generation\n                      const segmentStartPTS = this._initPTS + Math.round((timelineOffset + this.config.audioPrimingDelay) * this._silentAudioTrack.info.timescale);\n                      silentAudioSegment = SilentAudio.getSegment(this._silentAudioTrack, videoTrack.parsingData.sequenceNumber, segmentStartPTS, iframeDuration);\n                  }\n                  if (audioTrack && audioTrack.parsingData.esSamples.length) {\n                      // if initSegment was generated without video samples, regenerate it again\n                      if (!isFiniteNumber(audioTrack.info.timescale)) {\n                          this.logger.warn('regenerate InitSegment as audio detected');\n                          this.updateInitPTSDTS(videoTrack, audioTrack, timeOffset); // Use real audioTrack info to update PTSDTS\n                          this.generateIS(audioTrack, videoTrack);\n                      }\n                      audioData = this.remuxAudio(audioTrack, timelineOffset, contiguous, accurateTimeOffset, keyTagInfo);\n                      if (remuxVideo) {\n                          let audioTrackLength;\n                          if (audioData) {\n                              audioTrackLength = convertTimestampToSeconds(audioData.endPTS) - convertTimestampToSeconds(audioData.startPTS);\n                          }\n                          // if initSegment was generated without video samples, regenerate it again\n                          if (!isFiniteNumber(videoTrack.info.timescale)) {\n                              this.logger.warn('regenerate InitSegment as video detected');\n                              this.updateInitPTSDTS(videoTrack, audioTrack, timeOffset); // Use real audioTrack info to update PTSDTS\n                              this.generateIS(audioTrack, videoTrack);\n                          }\n                          videoData = this.remuxVideo(videoTrack, timelineOffset, isVideoContiguous, audioTrackLength, iframeDuration);\n                      }\n                  }\n                  else {\n                      if (remuxVideo) {\n                          videoData = this.remuxVideo(videoTrack, timelineOffset, isVideoContiguous, undefined, iframeDuration);\n                      }\n                      if (videoData && audioTrack && audioTrack.config.codec) {\n                          audioData = this.remuxEmptyAudio(audioTrack, timelineOffset, contiguous, accurateTimeOffset, videoData, keyTagInfo);\n                      }\n                  }\n                  let parsingData;\n                  if (silentAudioSegment) {\n                      parsingData = {\n                          data1: videoData.data1,\n                          data2: silentAudioSegment.silentFragData,\n                          startDTS: videoData.startDTS,\n                          startPTS: videoData.startPTS,\n                          endDTS: determineMaxTimestamp(videoData.endDTS, silentAudioSegment.endTs),\n                          endPTS: determineMaxTimestamp(videoData.endPTS, silentAudioSegment.endTs),\n                          type: 'audiovideo',\n                          track: this.currentInitTrack,\n                      };\n                  }\n                  else if (videoData && audioData) {\n                      parsingData = {\n                          data1: videoData.data1,\n                          data2: audioData.data1,\n                          startDTS: determineMinTimestamp(videoData.startDTS, audioData.startDTS),\n                          startPTS: determineMinTimestamp(videoData.startPTS, audioData.startPTS),\n                          endDTS: determineMaxTimestamp(videoData.endDTS, audioData.endDTS),\n                          endPTS: determineMaxTimestamp(videoData.endPTS, audioData.endPTS),\n                          type: 'audiovideo',\n                          track: this.currentInitTrack,\n                          dropped: videoData.dropped,\n                          framesWithoutIDR: videoData.framesWithoutIDR,\n                          firstKeyframePts: videoData.firstKeyframePts,\n                      };\n                  }\n                  else if (videoData) {\n                      parsingData = {\n                          data1: videoData.data1,\n                          startDTS: videoData.startDTS,\n                          startPTS: videoData.startPTS,\n                          endDTS: videoData.endDTS,\n                          endPTS: videoData.endPTS,\n                          type: 'video',\n                          track: this.currentInitTrack,\n                          dropped: videoData.dropped,\n                          framesWithoutIDR: videoData.framesWithoutIDR,\n                          firstKeyframePts: videoData.firstKeyframePts,\n                      };\n                  }\n                  else if (audioData) {\n                      parsingData = {\n                          data1: audioData.data1,\n                          startDTS: audioData.startDTS,\n                          startPTS: audioData.startPTS,\n                          endDTS: audioData.endDTS,\n                          endPTS: audioData.endPTS,\n                          type: 'audio',\n                          track: this.currentInitTrack,\n                      };\n                  }\n                  else {\n                      this.logger.error('Missing video and audio data');\n                  }\n                  if (textTrack && textTrack.captionSamples.length) {\n                      this.remuxText(textTrack, parsingData);\n                  }\n                  if ((_a = id3Track === null || id3Track === void 0 ? void 0 : id3Track.id3Samples) === null || _a === void 0 ? void 0 : _a.length) {\n                      this.remuxID3(id3Track, parsingData);\n                  }\n                  this.observer.trigger(DemuxerEvent.FRAG_PARSING_DATA, parsingData);\n              }\n              else {\n                  this.logger.error('failed to generate IS');\n              }\n              // notify end of parsing\n              this.observer.trigger(DemuxerEvent.FRAG_PARSED);\n          }\n          /**\n           * @param videoTrack\n           * @param audioTrack\n           * @param timeOffset Position in media element corresponding to the beginning of this segment\n           */\n          updateInitPTSDTS(videoTrack, audioTrack, timeOffset) {\n              let initPTS = Infinity, initDTS = Infinity;\n              const videoSamples = videoTrack ? videoTrack.parsingData.esSamples : [];\n              const audioSamples = audioTrack ? audioTrack.parsingData.esSamples : [];\n              if (isFiniteNumber(this._initPTS)) {\n                  return;\n              }\n              if (audioTrack && audioSamples.length) {\n                  // remember first PTS of this demuxing context. for audio, PTS = DTS\n                  initPTS = initDTS = audioSamples[0].pts - audioTrack.info.inputTimescale * timeOffset;\n              }\n              if (videoTrack && videoSamples.length) {\n                  // let's use input time scale as MP4 video timescale\n                  // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n                  const inputTimeScale = videoTrack.info.inputTimescale;\n                  videoTrack.info.timescale = inputTimeScale;\n                  initPTS = Math.min(initPTS, getVideoStartPts(videoSamples) - inputTimeScale * timeOffset);\n                  initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);\n                  this.observer.trigger(DemuxerEvent.INIT_PTS_FOUND, { initPTS: convertSecondsToTimestamp(initPTS, inputTimeScale) });\n              }\n              if (isFiniteNumber(initPTS) && isFiniteNumber(initDTS)) {\n                  this._initPTS = initPTS;\n                  this._initDTS = initDTS;\n              }\n              else {\n                  const payload = new FragParsingError(false, 'invalid initPTS or initDTS', ErrorResponses.InvalidInitTimestamp);\n                  this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n              }\n          }\n          generateIS(audioTrack, videoTrack) {\n              // const observer = this.observer;\n              const videoSamples = videoTrack ? videoTrack.parsingData.esSamples : [];\n              const typeSupported = this.typeSupported;\n              let container = 'audio/mp4';\n              let track;\n              if (audioTrack && videoTrack && videoSamples.length) {\n                  const inputTimeScale = videoTrack.info.inputTimescale;\n                  videoTrack.info.timescale = inputTimeScale;\n                  audioTrack.info.timescale = audioTrack.config.samplerate;\n                  const initSegment = MP4.initSegment([videoTrack, audioTrack]);\n                  track = {\n                      type: 'audiovideo',\n                      container: 'video/mp4',\n                      codec: `${videoTrack.config.codec},${audioTrack.config.codec}`,\n                      initSegment,\n                  };\n              }\n              else if (audioTrack) {\n                  // let's use audio sampling rate as MP4 time scale.\n                  // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n                  // using audio sampling rate here helps having an integer MP4 frame duration\n                  // this avoids potential rounding issue and AV sync issue\n                  audioTrack.info.timescale = audioTrack.config.samplerate;\n                  this.logger.info(`audio sampling rate : ${audioTrack.config.samplerate}`);\n                  switch (audioTrack.config.segmentCodec) {\n                      case 'mp3':\n                          if (typeSupported.mpeg) {\n                              // Chrome and Safari\n                              container = 'audio/mpeg';\n                              audioTrack.config.codec = '';\n                          }\n                          else if (typeSupported.mp3) {\n                              // Firefox\n                              audioTrack.config.codec = 'mp3';\n                          }\n                          break;\n                  }\n                  const initSegment = audioTrack.config.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]);\n                  track = {\n                      type: 'audio',\n                      container: container,\n                      codec: audioTrack.config.codec,\n                      initSegment,\n                  };\n              }\n              else if (videoTrack && videoSamples.length) {\n                  // let's use input time scale as MP4 video timescale\n                  // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n                  const inputTimeScale = videoTrack.info.inputTimescale;\n                  videoTrack.info.timescale = inputTimeScale;\n                  const initSegment = MP4.initSegment([videoTrack]);\n                  track = {\n                      type: 'video',\n                      container: 'video/mp4',\n                      codec: videoTrack.config.codec,\n                      initSegment,\n                  };\n              }\n              if (track) {\n                  this.currentInitTrack = track;\n                  const data = { track };\n                  this.observer.trigger(DemuxerEvent.FRAG_PARSING_INIT_SEGMENT, data);\n              }\n              else {\n                  const payload = new FragParsingError(false, 'no audio/video samples found', ErrorResponses.NoAVSamplesFound);\n                  this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n              }\n          }\n          remuxVideo(track, timeOffset, contiguous, audioTrackLength, iframeDuration) {\n              let offset = 8;\n              let mp4SampleDuration;\n              let mdat;\n              let firstPTS;\n              let firstDTS;\n              let lastPTS;\n              let lastDTS;\n              let dropped = track.parsingData.dropped;\n              const dropFrames = !contiguous && this.config.forceKeyFrameOnDiscontinuity;\n              const inputSamples = track.parsingData.esSamples;\n              const timeScale = track.info.inputTimescale;\n              const outputSamples = [];\n              const encrypted = track.info.encrypted;\n              // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n              // normalizePts will make PTS/DTS value monotonic, we use last known DTS value as reference value\n              let nextAvcDts;\n              // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n              if (contiguous) {\n                  // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n                  nextAvcDts = this.nextAvcDts;\n              }\n              else {\n                  // if not contiguous, let's use sample\n                  nextAvcDts = normalizePts(inputSamples[0].dts, inputSamples[0].pts);\n              }\n              inputSamples.forEach(function (sample) {\n                  sample.pts = normalizePts(sample.pts, nextAvcDts);\n                  sample.dts = normalizePts(sample.dts, nextAvcDts);\n              });\n              // sort video samples by DTS then PTS then demux id order\n              inputSamples.sort(function (a, b) {\n                  const deltadts = a.dts - b.dts;\n                  const deltapts = a.pts - b.pts;\n                  return deltadts ? deltadts : deltapts ? deltapts : a.id - b.id;\n              });\n              let firstKeyframePts;\n              const firstKeyframeIndex = inputSamples.findIndex((sample) => sample.key);\n              if (inputSamples[firstKeyframeIndex]) {\n                  firstKeyframePts = inputSamples[firstKeyframeIndex].pts;\n              }\n              if (dropFrames) {\n                  if (firstKeyframeIndex > 0) {\n                      this.logger.warn(`Dropped ${firstKeyframeIndex} out of ${inputSamples.length} video samples due to a missing keyframe`);\n                      inputSamples.splice(0, firstKeyframeIndex);\n                      dropped += firstKeyframeIndex;\n                  }\n                  else if (firstKeyframeIndex === -1) {\n                      this.logger.warn(`No keyframe found out of ${inputSamples.length} video samples`);\n                      dropped += inputSamples.length;\n                  }\n              }\n              const firstSample = inputSamples[0];\n              const lastSample = inputSamples[inputSamples.length - 1];\n              // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)\n              const PTSDTSshift = inputSamples.reduce((prev, curr) => Math.max(Math.min(prev, curr.pts - curr.dts), -18000), 0);\n              if (PTSDTSshift < 0) {\n                  this.logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${Math.round(PTSDTSshift / 90)} ms to overcome this issue`);\n                  for (let i = 0; i < inputSamples.length; i++) {\n                      inputSamples[i].dts += PTSDTSshift;\n                  }\n              }\n              const isSafari = this.isSafari;\n              // on Safari let's signal the same sample duration for all samples\n              // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n              // set this constant duration as being the avg delta between consecutive DTS.\n              mp4SampleDuration = Math.round((lastSample.dts - firstSample.dts) / (inputSamples.length - 1));\n              // compute first DTS/PTS, normalize them against reference value\n              firstDTS = Math.max(firstSample.dts, 0);\n              firstPTS = Math.max(firstSample.pts, 0);\n              if (isFiniteNumber(iframeDuration)) {\n                  firstDTS = timeOffset * timeScale;\n                  firstPTS = timeOffset * timeScale;\n              }\n              // if fragment are contiguous, detect hole/overlapping between fragments\n              if (contiguous) {\n                  // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n                  const delta = firstDTS - nextAvcDts;\n                  const foundHole = delta > mp4SampleDuration;\n                  const foundOverlap = delta < -1;\n                  if (foundHole || foundOverlap) {\n                      if (foundHole) {\n                          this.logger.warn(`AVC: ${delta}/90000 hole between fragments detected`);\n                      }\n                      else {\n                          this.logger.warn(`AVC: ${delta}/90000 overlapping between fragments detected`);\n                      }\n                  }\n              }\n              let nbNalu = 0;\n              let naluLen = 0;\n              const nbSamples = inputSamples.length;\n              for (let i = 0; i < nbSamples; i++) {\n                  // compute total/avc sample length and nb of NAL units\n                  const sample = inputSamples[i], units = sample.units, nbUnits = units.length;\n                  let sampleLen = 0;\n                  for (let j = 0; j < nbUnits; j++) {\n                      sampleLen += units[j].data.length;\n                  }\n                  naluLen += sampleLen;\n                  nbNalu += nbUnits;\n                  sample.length = sampleLen;\n                  // normalize PTS/DTS\n                  if (isSafari) {\n                      // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples\n                      sample.dts = firstDTS + i * mp4SampleDuration;\n                  }\n                  else {\n                      // ensure sample monotonic DTS\n                      sample.dts = Math.max(sample.dts, firstDTS);\n                  }\n                  // ensure that computed value is greater or equal than sample DTS\n                  sample.pts = Math.max(sample.pts, sample.dts);\n              }\n              // compute lastPTS/lastDTS\n              lastDTS = Math.max(lastSample.dts, 0);\n              lastPTS = Math.max(lastSample.pts, 0, lastDTS);\n              if (isFiniteNumber(iframeDuration)) {\n                  lastDTS = timeOffset * timeScale;\n                  lastPTS = timeOffset * timeScale;\n              }\n              /* concatenate the video data and construct the mdat in place\n                (need 8 more bytes to fill length and mpdat type) */\n              const mdatSize = naluLen + 4 * nbNalu + 8;\n              try {\n                  mdat = new Uint8Array(mdatSize);\n              }\n              catch (err) {\n                  const payload = new RemuxAllocError(false, `fail allocating video mdat ${mdatSize}`, ErrorResponses.FailedToAllocateVideoMdat, mdatSize);\n                  this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  return;\n              }\n              const view = new DataView(mdat.buffer);\n              view.setUint32(0, mdatSize);\n              mdat.set(MP4.types.mdat, 4);\n              for (let i = 0; i < nbSamples; i++) {\n                  const avcSample = inputSamples[i], avcSampleUnits = avcSample.units;\n                  let mp4SampleLength = 0, compositionTimeOffset;\n                  // convert NALU bitstream to MP4 format (prepend NALU with size field)\n                  const subsamples = [];\n                  let bytesClear = 0;\n                  for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n                      const unit = avcSampleUnits[j], unitData = unit.data, unitDataLen = unit.data.byteLength;\n                      view.setUint32(offset, unitDataLen);\n                      offset += 4;\n                      mdat.set(unitData, offset);\n                      offset += unitDataLen;\n                      mp4SampleLength += 4 + unitDataLen;\n                      if (encrypted) {\n                          if (unitDataLen <= 48 || (unit.type !== 1 && unit.type !== 5)) {\n                              bytesClear += 4 + unitDataLen;\n                          }\n                          else {\n                              let encryptedDataLen = unitDataLen - 32;\n                              if (encryptedDataLen % 16 === 0) {\n                                  encryptedDataLen -= 16; // different than fMP4 encryption - TS always requires at least 1 clear byte at the end\n                              }\n                              subsamples.push([bytesClear + 36, encryptedDataLen]);\n                              bytesClear = unitDataLen - 32 - encryptedDataLen;\n                          }\n                      }\n                  }\n                  if (bytesClear > 0) {\n                      subsamples.push([bytesClear, 0]);\n                  }\n                  if (!isSafari) {\n                      // expected sample duration is the Decoding Timestamp diff of consecutive samples\n                      if (i < nbSamples - 1) {\n                          mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n                      }\n                      else {\n                          const config = this.config, lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts;\n                          if (config.stretchShortVideoTrack) {\n                              // In some cases, a segment's audio track duration may exceed the video track duration.\n                              // Since we've already remuxed audio, and we know how long the audio track is, we look to\n                              // see if the delta to the next segment is longer than the minimum of maxBufferHole and\n                              // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate\n                              // the duration of the last frame to minimize any potential gap between segments.\n                              const maxBufferHole = config.maxBufferHole, maxSeekHole = config.maxSeekHole, gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale), deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n                              if (deltaToFrameEnd > gapTolerance) {\n                                  // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n                                  // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.\n                                  mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n                                  if (mp4SampleDuration < 0) {\n                                      mp4SampleDuration = lastFrameDuration;\n                                  }\n                                  this.logger.info(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);\n                              }\n                              else {\n                                  mp4SampleDuration = lastFrameDuration;\n                              }\n                          }\n                          else {\n                              mp4SampleDuration = lastFrameDuration;\n                          }\n                      }\n                      compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n                  }\n                  else {\n                      compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));\n                  }\n                  if (isFiniteNumber(iframeDuration)) {\n                      compositionTimeOffset = 0;\n                      mp4SampleDuration = iframeDuration * timeScale;\n                  }\n                  outputSamples.push({\n                      size: mp4SampleLength,\n                      // constant duration\n                      duration: mp4SampleDuration,\n                      cts: compositionTimeOffset,\n                      flags: {\n                          isLeading: 0,\n                          isDependedOn: 0,\n                          hasRedundancy: 0,\n                          degradPrio: 0,\n                          dependsOn: avcSample.key ? 2 : 1,\n                          isNonSync: avcSample.key ? 0 : 1,\n                          paddingValue: 0,\n                      },\n                      keyTagInfo: avcSample.keyTagInfo,\n                      subsamples: subsamples,\n                  });\n              }\n              // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n              this.nextAvcDts = lastDTS + mp4SampleDuration;\n              this.isVideoContiguous = true;\n              if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n                  const flags = outputSamples[0].flags;\n                  // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n                  // https://code.google.com/p/chromium/issues/detail?id=229412\n                  flags.dependsOn = 2;\n                  flags.isNonSync = 0;\n              }\n              const moofSegment = {\n                  sequenceNumber: track.parsingData.sequenceNumber++,\n                  id: track.info.id,\n                  type: track.type,\n                  encrypted: track.info.encrypted,\n                  samples: outputSamples,\n                  defaultPerSampleIVSize: 0,\n              };\n              const moof = MP4.moof(firstDTS + this.config.audioPrimingDelay * timeScale, moofSegment);\n              track.parsingData.esSamples = [];\n              const fullSegment = new Uint8Array(moof.byteLength + mdat.byteLength);\n              fullSegment.set(moof);\n              fullSegment.set(mdat, moof.byteLength);\n              const type = 'video';\n              const data = {\n                  data1: fullSegment,\n                  startPTS: convertSecondsToTimestamp(firstPTS / timeScale, timeScale),\n                  endPTS: convertSecondsToTimestamp((lastPTS + mp4SampleDuration) / timeScale, timeScale),\n                  startDTS: convertSecondsToTimestamp(firstDTS / timeScale, timeScale),\n                  endDTS: convertSecondsToTimestamp(this.nextAvcDts / timeScale, timeScale),\n                  type,\n                  dropped,\n                  framesWithoutIDR: firstKeyframeIndex,\n                  firstKeyframePts: convertSecondsToTimestamp(firstKeyframePts / timeScale, timeScale),\n              };\n              return data;\n          }\n          remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, keyTagInfo) {\n              const inputTimeScale = track.info.inputTimescale, mp4timeScale = track.info.timescale, scaleFactor = inputTimeScale / mp4timeScale, mp4SampleDuration = track.config.segmentCodec === 'aac' ? 1024 : track.config.segmentCodec === 'mp3' ? 1152 : 1536, inputSampleDuration = mp4SampleDuration * scaleFactor, rawMPEG = track.config.segmentCodec === 'mp3' && this.typeSupported.mpeg, outputSamples = [], encrypted = track.info.encrypted, timeOffsetMpegTS = this._initPTS + timeOffset * inputTimeScale;\n              let view, offset = rawMPEG ? 0 : 8, audioSample, mp4Sample, unit, mdat, moof, firstPTS, firstDTS, lastDTS, pts, dts, fillFrame, newStamp, nextAudioPts;\n              const bu = new BitstreamUtils();\n              const inputSamples = track.parsingData.esSamples;\n              // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n              // for sake of clarity:\n              // consecutive fragments are frags with\n              //  - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n              //  - less than 20 audio frames distance\n              // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n              // this helps ensuring audio continuity\n              // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n              nextAudioPts = this.nextAudioPts;\n              contiguous =\n                  contiguous ||\n                      (inputSamples.length &&\n                          nextAudioPts &&\n                          ((accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000) || Math.abs(normalizePts(inputSamples[0].pts - nextAudioPts, timeOffsetMpegTS)) < 20 * inputSampleDuration));\n              if (!contiguous) {\n                  // if fragments are not contiguous, let's use sample\n                  nextAudioPts = normalizePts(inputSamples[0].pts, this._initPTS);\n              }\n              // compute normalized PTS\n              inputSamples.forEach(function (sample) {\n                  sample.pts = sample.dts = normalizePts(sample.pts, nextAudioPts);\n              });\n              // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n              // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n              // In an effort to prevent this from happening, we inject frames here where there are gaps.\n              // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n              // frame.\n              // only inject/drop audio frames in case time offset is accurate\n              if (accurateTimeOffset && track.config.segmentCodec === 'aac') {\n                  for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {\n                      // First, let's see how far off this frame is from where we expect it to be\n                      const sample = inputSamples[i];\n                      pts = sample.pts;\n                      const delta = pts - nextPts;\n                      const duration = Math.abs((1000 * delta) / inputTimeScale);\n                      // If we're overlapping by more than a duration, drop this sample\n                      if (delta <= -inputSampleDuration) {\n                          this.logger.warn(`Dropping 1 audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${duration} ms overlap.`);\n                          inputSamples.splice(i, 1);\n                          track.parsingData.len -= sample.unit.length;\n                          // Don't touch nextPtsNorm or i\n                          // Insert missing frames if:\n                          // 1: We're more than one frame away\n                          // 2: Not more than MAX_SILENT_FRAME_DURATION away\n                          // 3: currentTime (aka nextPtsNorm) is not 0\n                      }\n                      else if (delta >= inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {\n                          const missing = Math.round(delta / inputSampleDuration);\n                          this.logger.warn(`Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round((1000 * delta) / inputTimeScale)} ms gap.`);\n                          for (let j = 0; j < missing; j++) {\n                              newStamp = Math.max(nextPts, 0);\n                              fillFrame = getSilentFrame(track.config.codec, track.config.channelCount);\n                              if (!fillFrame) {\n                                  this.logger.warn('Unable to get silent frame for given audio codec; duplicating last frame instead.');\n                                  fillFrame = sample.unit.subarray(0);\n                              }\n                              inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp, keyTagInfo: keyTagInfo });\n                              track.parsingData.len += fillFrame.length;\n                              nextPts += inputSampleDuration;\n                              i += 1;\n                          }\n                          // Adjust sample to next expected pts\n                          sample.pts = sample.dts = nextPts;\n                          nextPts += inputSampleDuration;\n                          i += 1;\n                          // Otherwise, just adjust pts\n                      }\n                      else {\n                          nextPts += inputSampleDuration;\n                          if (i === 0) {\n                              sample.pts = sample.dts = nextAudioPts;\n                          }\n                          else {\n                              sample.pts = sample.dts = inputSamples[i - 1].pts + inputSampleDuration;\n                          }\n                          i += 1;\n                      }\n                  }\n              }\n              for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n                  audioSample = inputSamples[j];\n                  unit = audioSample.unit;\n                  pts = audioSample.pts;\n                  dts = audioSample.dts;\n                  // if not first sample\n                  if (lastDTS !== undefined) {\n                      mp4Sample.duration = Math.round((dts - lastDTS) / scaleFactor);\n                  }\n                  else {\n                      const delta = Math.round((1000 * (pts - nextAudioPts)) / inputTimeScale);\n                      let numMissingFrames = 0;\n                      // if fragment are contiguous, detect hole/overlapping between fragments\n                      // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n                      if (contiguous && track.config.segmentCodec === 'aac') {\n                          // log delta\n                          if (delta) {\n                              if (delta > 0 && delta < MAX_SILENT_FRAME_DURATION) {\n                                  numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\n                                  this.logger.info(`${delta} ms hole between AAC samples detected,filling it`);\n                                  if (numMissingFrames > 0) {\n                                      fillFrame = getSilentFrame(track.config.codec, track.config.channelCount);\n                                      if (!fillFrame) {\n                                          fillFrame = unit.subarray(0);\n                                      }\n                                      track.parsingData.len += numMissingFrames * fillFrame.length;\n                                  }\n                                  // if we have frame overlap, overlapping for more than half a frame duraion\n                              }\n                              else if (delta < -12) {\n                                  // drop overlapping audio frames... browser will deal with it\n                                  this.logger.info(`drop overlapping AAC sample, expected/parsed/delta:${(nextAudioPts / inputTimeScale).toFixed(3)}s/${(pts / inputTimeScale).toFixed(3)}s/${-delta}ms`);\n                                  track.parsingData.len -= unit.byteLength;\n                                  continue;\n                              }\n                              // set PTS/DTS to expected PTS/DTS\n                              pts = dts = nextAudioPts;\n                          }\n                      }\n                      // remember first PTS of our audioSamples, ensure value is positive\n                      firstPTS = Math.max(0, pts);\n                      firstDTS = Math.max(0, dts);\n                      if (track.parsingData.len > 0) {\n                          /* concatenate the audio data and construct the mdat in place\n                            (need 8 more bytes to fill length and mdat type) */\n                          const mdatSize = rawMPEG ? track.parsingData.len : track.parsingData.len + 8;\n                          try {\n                              mdat = new Uint8Array(mdatSize);\n                          }\n                          catch (err) {\n                              const payload = new RemuxAllocError(false, `fail allocating audio mdat ${mdatSize}`, ErrorResponses.FailedToAllocateAudioMdat, mdatSize);\n                              this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                              return;\n                          }\n                          if (!rawMPEG) {\n                              view = new DataView(mdat.buffer);\n                              view.setUint32(0, mdatSize);\n                              mdat.set(MP4.types.mdat, 4);\n                          }\n                      }\n                      else {\n                          // no audio samples\n                          return;\n                      }\n                      for (let i = 0; i < numMissingFrames; i++) {\n                          newStamp = pts - (numMissingFrames - i) * inputSampleDuration;\n                          fillFrame = getSilentFrame(track.config.codec, track.config.channelCount);\n                          if (!fillFrame) {\n                              this.logger.warn('Unable to get silent frame for given audio codec; duplicating this frame instead.');\n                              fillFrame = unit.subarray(0);\n                          }\n                          mdat.set(fillFrame, offset);\n                          offset += fillFrame.byteLength;\n                          mp4Sample = {\n                              size: fillFrame.byteLength,\n                              cts: 0,\n                              duration: 1024,\n                              flags: {\n                                  isLeading: 0,\n                                  isDependedOn: 0,\n                                  hasRedundancy: 0,\n                                  degradPrio: 0,\n                                  dependsOn: 1,\n                                  paddingValue: 0,\n                                  isNonSync: 0,\n                              },\n                              keyTagInfo: audioSample.keyTagInfo,\n                              subsamples: encrypted ? [[fillFrame.byteLength, 0]] : [],\n                          };\n                          outputSamples.push(mp4Sample);\n                      }\n                  }\n                  mdat.set(unit, offset);\n                  const unitLen = unit.byteLength;\n                  offset += unitLen;\n                  const subsamples = [];\n                  if (encrypted) {\n                      if (track.config.segmentCodec === 'ec3') {\n                          let bytesSeen = 0;\n                          // for ec3, a protected block is a single sync frame; the sample may have one or more sync frames\n                          while (bytesSeen < unit.byteLength) {\n                              const frameLength = (bu.bsReadAndUpdate(unit, { byteOffset: bytesSeen + 2, usedBits: 5 }, 11) + 1) * 2;\n                              bytesSeen += frameLength;\n                              const clearBytes = Math.min(frameLength, 16); // 16 bytes in the clear\n                              subsamples.push([clearBytes, frameLength - clearBytes]);\n                          }\n                      }\n                      else {\n                          const clearBytes = Math.min(unitLen, 16); // both aac and ac3 have 16 bytes in the clear\n                          subsamples.push([clearBytes, unitLen - clearBytes]);\n                      }\n                  }\n                  mp4Sample = {\n                      size: unitLen,\n                      cts: 0,\n                      duration: 0,\n                      flags: {\n                          isLeading: 0,\n                          isDependedOn: 0,\n                          hasRedundancy: 0,\n                          degradPrio: 0,\n                          dependsOn: 1,\n                          paddingValue: 0,\n                          isNonSync: 0,\n                      },\n                      keyTagInfo: audioSample.keyTagInfo,\n                      subsamples: subsamples,\n                  };\n                  outputSamples.push(mp4Sample);\n                  lastDTS = dts;\n              }\n              let lastSampleDuration = 0;\n              const nbSamples = outputSamples.length;\n              // set last sample duration as being identical to previous sample\n              if (nbSamples >= 2) {\n                  lastSampleDuration = outputSamples[nbSamples - 2].duration;\n                  mp4Sample.duration = lastSampleDuration;\n              }\n              if (nbSamples) {\n                  // next audio sample PTS should be equal to last sample PTS + duration\n                  this.nextAudioPts = pts + scaleFactor * lastSampleDuration;\n                  track.parsingData.len = 0;\n                  if (rawMPEG) {\n                      moof = new Uint8Array();\n                  }\n                  else {\n                      const moofSegment = {\n                          sequenceNumber: track.parsingData.sequenceNumber++,\n                          id: track.info.id,\n                          type: track.type,\n                          encrypted: track.info.encrypted,\n                          samples: outputSamples,\n                          defaultPerSampleIVSize: 0,\n                      };\n                      moof = MP4.moof((firstDTS + this.config.audioPrimingDelay * inputTimeScale) / scaleFactor, moofSegment);\n                  }\n                  const fullSegment = new Uint8Array(moof.byteLength + mdat.byteLength);\n                  fullSegment.set(moof);\n                  fullSegment.set(mdat, moof.byteLength);\n                  track.parsingData.esSamples = [];\n                  const audioData = {\n                      data1: fullSegment,\n                      startPTS: convertSecondsToTimestamp(firstPTS / inputTimeScale, inputTimeScale),\n                      endPTS: convertSecondsToTimestamp(this.nextAudioPts / inputTimeScale, inputTimeScale),\n                      startDTS: convertSecondsToTimestamp(firstDTS / inputTimeScale, inputTimeScale),\n                      endDTS: convertSecondsToTimestamp((dts + scaleFactor * lastSampleDuration) / inputTimeScale, inputTimeScale),\n                      type: 'audio',\n                  };\n                  return audioData;\n              }\n              return null;\n          }\n          remuxEmptyAudio(track, timeOffset, contiguous, accurateTimeOffset, videoData, keyTagInfo) {\n              const inputTimeScale = track.info.inputTimescale, mp4timeScale = track.config.samplerate ? track.config.samplerate : inputTimeScale, scaleFactor = inputTimeScale / mp4timeScale, nextAudioPts = this.nextAudioPts, \n              // sync with video's timestamp\n              startDTS = (nextAudioPts !== undefined ? nextAudioPts : convertTimestampToSeconds(videoData.startDTS) * inputTimeScale) + this._initDTS, endDTS = convertTimestampToSeconds(videoData.endDTS) * inputTimeScale + this._initDTS, \n              // one sample's duration value\n              sampleDuration = 1024, frameDuration = scaleFactor * sampleDuration, \n              // samples count of this segment's duration\n              nbSamples = Math.ceil((endDTS - startDTS) / frameDuration), \n              // silent frame\n              silentFrame = getSilentFrame(track.config.codec, track.config.channelCount);\n              this.logger.warn('remux empty Audio');\n              // Can't remux if we can't generate a silent frame...\n              if (!silentFrame) {\n                  this.logger.error('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n                  return null;\n              }\n              const samples = [];\n              for (let i = 0; i < nbSamples; i++) {\n                  const stamp = startDTS + i * frameDuration;\n                  samples.push({ unit: silentFrame, pts: stamp, dts: stamp, keyTagInfo: keyTagInfo });\n                  track.parsingData.len += silentFrame.length;\n              }\n              track.parsingData.esSamples = samples;\n              return this.remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, keyTagInfo);\n          }\n          remuxID3(track, parsingData) {\n              const length = track.id3Samples.length;\n              let sample;\n              const inputTimeScale = track.inputTimescale;\n              // consume samples\n              if (length) {\n                  for (let index = 0; index < length; index++) {\n                      sample = track.id3Samples[index];\n                      // setting id3 pts, dts to relative time\n                      sample.pts = sample.pts / inputTimeScale;\n                      sample.dts = sample.dts / inputTimeScale;\n                  }\n                  parsingData.id3Samples = track.id3Samples;\n              }\n              track.id3Samples = [];\n          }\n          remuxText(track, parsingData) {\n              track.captionSamples.sort(function (a, b) {\n                  return a.pts - b.pts;\n              });\n              const length = track.captionSamples.length;\n              let sample;\n              const inputTimeScale = track.inputTimescale;\n              // consume samples\n              if (length) {\n                  for (let index = 0; index < length; index++) {\n                      sample = track.captionSamples[index];\n                      // setting text pts, dts to relative time\n                      sample.pts = sample.pts / inputTimeScale;\n                  }\n                  if (!parsingData.captionData) {\n                      parsingData.captionData = {};\n                  }\n                  parsingData.captionData.ts = track.captionSamples;\n              }\n              track.captionSamples = [];\n          }\n      }\n      function normalizePts(value, reference) {\n          let offset;\n          if (reference === undefined) {\n              return value;\n          }\n          if (reference < value) {\n              // - 2^33\n              offset = -8589934592;\n          }\n          else {\n              // + 2^33\n              offset = 8589934592;\n          }\n          /* PTS is 33bit (from 0 to 2^33 -1)\n            if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n            PTS looping occured. fill the gap */\n          while (Math.abs(value - reference) > 4294967296) {\n              value += offset;\n          }\n          return value;\n      }\n      function getVideoStartPts(videoSamples) {\n          const startPTS = videoSamples.reduce((minPTS, sample) => {\n              const delta = sample.pts - minPTS;\n              if (delta < -4294967296) {\n                  // 2^32, see normalizePts for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n                  return normalizePts(minPTS, sample.pts);\n              }\n              else if (delta > 0) {\n                  return minPTS;\n              }\n              else {\n                  return sample.pts;\n              }\n          }, videoSamples[0].pts);\n          return startPTS;\n      }\n    \n      var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n    \n      function tryStringify (o) {\n        try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n      }\n    \n      var quickFormatUnescaped = format$1;\n    \n      function format$1(f, args, opts) {\n        var ss = (opts && opts.stringify) || tryStringify;\n        var offset = 1;\n        if (typeof f === 'object' && f !== null) {\n          var len = args.length + offset;\n          if (len === 1) return f\n          var objects = new Array(len);\n          objects[0] = ss(f);\n          for (var index = 1; index < len; index++) {\n            objects[index] = ss(args[index]);\n          }\n          return objects.join(' ')\n        }\n        if (typeof f !== 'string') {\n          return f\n        }\n        var argLen = args.length;\n        if (argLen === 0) return f\n        var str = '';\n        var a = 1 - offset;\n        var lastPos = -1;\n        var flen = (f && f.length) || 0;\n        for (var i = 0; i < flen;) {\n          if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n            lastPos = lastPos > -1 ? lastPos : 0;\n            switch (f.charCodeAt(i + 1)) {\n              case 100: // 'd'\n                if (a >= argLen)\n                  break\n                if (lastPos < i)\n                  str += f.slice(lastPos, i);\n                if (args[a] == null)  break\n                str += Number(args[a]);\n                lastPos = i = i + 2;\n                break\n              case 79: // 'O'\n              case 111: // 'o'\n              case 106: // 'j'\n                if (a >= argLen)\n                  break\n                if (lastPos < i)\n                  str += f.slice(lastPos, i);\n                if (args[a] === undefined) break\n                var type = typeof args[a];\n                if (type === 'string') {\n                  str += '\\'' + args[a] + '\\'';\n                  lastPos = i + 2;\n                  i++;\n                  break\n                }\n                if (type === 'function') {\n                  str += args[a].name || '<anonymous>';\n                  lastPos = i + 2;\n                  i++;\n                  break\n                }\n                str += ss(args[a]);\n                lastPos = i + 2;\n                i++;\n                break\n              case 115: // 's'\n                if (a >= argLen)\n                  break\n                if (lastPos < i)\n                  str += f.slice(lastPos, i);\n                str += String(args[a]);\n                lastPos = i + 2;\n                i++;\n                break\n              case 37: // '%'\n                if (lastPos < i)\n                  str += f.slice(lastPos, i);\n                str += '%';\n                lastPos = i + 2;\n                i++;\n                break\n            }\n            ++a;\n          }\n          ++i;\n        }\n        if (lastPos === -1)\n          return f\n        else if (lastPos < flen) {\n          str += f.slice(lastPos);\n        }\n    \n        return str\n      }\n    \n      const format = quickFormatUnescaped;\n    \n      var browser = pino;\n    \n      const _console = pfGlobalThisOrFallback().console || {};\n      const stdSerializers = {\n        mapHttpRequest: mock,\n        mapHttpResponse: mock,\n        wrapRequestSerializer: passthrough,\n        wrapResponseSerializer: passthrough,\n        wrapErrorSerializer: passthrough,\n        req: mock,\n        res: mock,\n        err: asErrValue\n      };\n    \n      function shouldSerialize (serialize, serializers) {\n        if (Array.isArray(serialize)) {\n          const hasToFilter = serialize.filter(function (k) {\n            return k !== '!stdSerializers.err'\n          });\n          return hasToFilter\n        } else if (serialize === true) {\n          return Object.keys(serializers)\n        }\n    \n        return false\n      }\n    \n      function pino (opts) {\n        opts = opts || {};\n        opts.browser = opts.browser || {};\n    \n        const transmit = opts.browser.transmit;\n        if (transmit && typeof transmit.send !== 'function') { throw Error('pino: transmit option must have a send function') }\n    \n        const proto = opts.browser.write || _console;\n        if (opts.browser.write) opts.browser.asObject = true;\n        const serializers = opts.serializers || {};\n        const serialize = shouldSerialize(opts.browser.serialize, serializers);\n        let stdErrSerialize = opts.browser.serialize;\n    \n        if (\n          Array.isArray(opts.browser.serialize) &&\n          opts.browser.serialize.indexOf('!stdSerializers.err') > -1\n        ) stdErrSerialize = false;\n    \n        const levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace'];\n    \n        if (typeof proto === 'function') {\n          proto.error = proto.fatal = proto.warn =\n          proto.info = proto.debug = proto.trace = proto;\n        }\n        if (opts.enabled === false) opts.level = 'silent';\n        const level = opts.level || 'info';\n        const logger = Object.create(proto);\n        if (!logger.log) logger.log = noop$2;\n    \n        Object.defineProperty(logger, 'levelVal', {\n          get: getLevelVal\n        });\n        Object.defineProperty(logger, 'level', {\n          get: getLevel,\n          set: setLevel\n        });\n    \n        const setOpts = {\n          transmit,\n          serialize,\n          asObject: opts.browser.asObject,\n          levels,\n          timestamp: getTimeFunction(opts)\n        };\n        logger.levels = pino.levels;\n        logger.level = level;\n    \n        logger.setMaxListeners = logger.getMaxListeners =\n        logger.emit = logger.addListener = logger.on =\n        logger.prependListener = logger.once =\n        logger.prependOnceListener = logger.removeListener =\n        logger.removeAllListeners = logger.listeners =\n        logger.listenerCount = logger.eventNames =\n        logger.write = logger.flush = noop$2;\n        logger.serializers = serializers;\n        logger._serialize = serialize;\n        logger._stdErrSerialize = stdErrSerialize;\n        logger.child = child;\n    \n        if (transmit) logger._logEvent = createLogEventShape();\n    \n        function getLevelVal () {\n          return this.level === 'silent'\n            ? Infinity\n            : this.levels.values[this.level]\n        }\n    \n        function getLevel () {\n          return this._level\n        }\n        function setLevel (level) {\n          if (level !== 'silent' && !this.levels.values[level]) {\n            throw Error('unknown level ' + level)\n          }\n          this._level = level;\n    \n          set$1(setOpts, logger, 'error', 'log'); // <-- must stay first\n          set$1(setOpts, logger, 'fatal', 'error');\n          set$1(setOpts, logger, 'warn', 'error');\n          set$1(setOpts, logger, 'info', 'log');\n          set$1(setOpts, logger, 'debug', 'log');\n          set$1(setOpts, logger, 'trace', 'log');\n        }\n    \n        function child (bindings) {\n          if (!bindings) {\n            throw new Error('missing bindings for child Pino')\n          }\n          const bindingsSerializers = bindings.serializers;\n          if (serialize && bindingsSerializers) {\n            var childSerializers = Object.assign({}, serializers, bindingsSerializers);\n            var childSerialize = opts.browser.serialize === true\n              ? Object.keys(childSerializers)\n              : serialize;\n            delete bindings.serializers;\n            applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize);\n          }\n          function Child (parent) {\n            this._childLevel = (parent._childLevel | 0) + 1;\n            this.error = bind(parent, bindings, 'error');\n            this.fatal = bind(parent, bindings, 'fatal');\n            this.warn = bind(parent, bindings, 'warn');\n            this.info = bind(parent, bindings, 'info');\n            this.debug = bind(parent, bindings, 'debug');\n            this.trace = bind(parent, bindings, 'trace');\n            if (childSerializers) {\n              this.serializers = childSerializers;\n              this._serialize = childSerialize;\n            }\n            if (transmit) {\n              this._logEvent = createLogEventShape(\n                [].concat(parent._logEvent.bindings, bindings)\n              );\n            }\n          }\n          Child.prototype = this;\n          return new Child(this)\n        }\n        return logger\n      }\n    \n      pino.levels = {\n        values: {\n          fatal: 60,\n          error: 50,\n          warn: 40,\n          info: 30,\n          debug: 20,\n          trace: 10\n        },\n        labels: {\n          10: 'trace',\n          20: 'debug',\n          30: 'info',\n          40: 'warn',\n          50: 'error',\n          60: 'fatal'\n        }\n      };\n    \n      pino.stdSerializers = stdSerializers;\n      pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime });\n    \n      function set$1 (opts, logger, level, fallback) {\n        const proto = Object.getPrototypeOf(logger);\n        logger[level] = logger.levelVal > logger.levels.values[level]\n          ? noop$2\n          : (proto[level] ? proto[level] : (_console[level] || _console[fallback] || noop$2));\n    \n        wrap(opts, logger, level);\n      }\n    \n      function wrap (opts, logger, level) {\n        if (!opts.transmit && logger[level] === noop$2) return\n    \n        logger[level] = (function (write) {\n          return function LOG () {\n            const ts = opts.timestamp();\n            const args = new Array(arguments.length);\n            const proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this;\n            for (var i = 0; i < args.length; i++) args[i] = arguments[i];\n    \n            if (opts.serialize && !opts.asObject) {\n              applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize);\n            }\n            if (opts.asObject) write.call(proto, asObject(this, level, args, ts));\n            else write.apply(proto, args);\n    \n            if (opts.transmit) {\n              const transmitLevel = opts.transmit.level || logger.level;\n              const transmitValue = pino.levels.values[transmitLevel];\n              const methodValue = pino.levels.values[level];\n              if (methodValue < transmitValue) return\n              transmit(this, {\n                ts,\n                methodLevel: level,\n                methodValue,\n                transmitLevel,\n                transmitValue: pino.levels.values[opts.transmit.level || logger.level],\n                send: opts.transmit.send,\n                val: logger.levelVal\n              }, args);\n            }\n          }\n        })(logger[level]);\n      }\n    \n      function asObject (logger, level, args, ts) {\n        if (logger._serialize) applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize);\n        const argsCloned = args.slice();\n        let msg = argsCloned[0];\n        const o = {};\n        if (ts) {\n          o.time = ts;\n        }\n        o.level = pino.levels.values[level];\n        let lvl = (logger._childLevel | 0) + 1;\n        if (lvl < 1) lvl = 1;\n        // deliberate, catching objects, arrays\n        if (msg !== null && typeof msg === 'object') {\n          while (lvl-- && typeof argsCloned[0] === 'object') {\n            Object.assign(o, argsCloned.shift());\n          }\n          msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : undefined;\n        } else if (typeof msg === 'string') msg = format(argsCloned.shift(), argsCloned);\n        if (msg !== undefined) o.msg = msg;\n        return o\n      }\n    \n      function applySerializers (args, serialize, serializers, stdErrSerialize) {\n        for (const i in args) {\n          if (stdErrSerialize && args[i] instanceof Error) {\n            args[i] = pino.stdSerializers.err(args[i]);\n          } else if (typeof args[i] === 'object' && !Array.isArray(args[i])) {\n            for (const k in args[i]) {\n              if (serialize && serialize.indexOf(k) > -1 && k in serializers) {\n                args[i][k] = serializers[k](args[i][k]);\n              }\n            }\n          }\n        }\n      }\n    \n      function bind (parent, bindings, level) {\n        return function () {\n          try{\n          const args = new Array(1 + arguments.length);\n          args[0] = bindings;\n          for (var i = 1; i < args.length; i++) {\n            args[i] = arguments[i - 1];\n          }\n          return parent[level].apply(this, args)}\n          catch(e){\n            \n          }\n        }\n      }\n    \n      function transmit (logger, opts, args) {\n        const send = opts.send;\n        const ts = opts.ts;\n        const methodLevel = opts.methodLevel;\n        const methodValue = opts.methodValue;\n        const val = opts.val;\n        const bindings = logger._logEvent.bindings;\n    \n        applySerializers(\n          args,\n          logger._serialize || Object.keys(logger.serializers),\n          logger.serializers,\n          logger._stdErrSerialize === undefined ? true : logger._stdErrSerialize\n        );\n        logger._logEvent.ts = ts;\n        logger._logEvent.messages = args.filter(function (arg) {\n          // bindings can only be objects, so reference equality check via indexOf is fine\n          return bindings.indexOf(arg) === -1\n        });\n    \n        logger._logEvent.level.label = methodLevel;\n        logger._logEvent.level.value = methodValue;\n    \n        send(methodLevel, logger._logEvent, val);\n    \n        logger._logEvent = createLogEventShape(bindings);\n      }\n    \n      function createLogEventShape (bindings) {\n        return {\n          ts: 0,\n          messages: [],\n          bindings: bindings || [],\n          level: { label: '', value: 0 }\n        }\n      }\n    \n      function asErrValue (err) {\n        const obj = {\n          type: err.constructor.name,\n          msg: err.message,\n          stack: err.stack\n        };\n        for (const key in err) {\n          if (obj[key] === undefined) {\n            obj[key] = err[key];\n          }\n        }\n        return obj\n      }\n    \n      function getTimeFunction (opts) {\n        if (typeof opts.timestamp === 'function') {\n          return opts.timestamp\n        }\n        if (opts.timestamp === false) {\n          return nullTime\n        }\n        return epochTime\n      }\n    \n      function mock () { return {} }\n      function passthrough (a) { return a }\n      function noop$2 () {}\n    \n      function nullTime () { return false }\n      function epochTime () { return Date.now() }\n      function unixTime () { return Math.round(Date.now() / 1000.0) }\n      function isoTime () { return new Date(Date.now()).toISOString() } // using Date.now() for testability\n    \n      /* eslint-disable */\n      /* istanbul ignore next */\n      function pfGlobalThisOrFallback () {\n        function defd (o) { return typeof o !== 'undefined' && o }\n        try {\n          if (typeof globalThis !== 'undefined') return globalThis\n          Object.defineProperty(Object.prototype, 'globalThis', {\n            get: function () {\n              delete Object.prototype.globalThis;\n              return (this.globalThis = this)\n            },\n            configurable: true\n          });\n          return globalThis\n        } catch (e) {\n          return defd(self) || defd(window) || defd(this) || {}\n        }\n      }\n    \n      let LoggerSingleton;\n      function addQELevel(options = {}) {\n          return Object.assign(Object.assign({}, options), { customLevels: Object.assign(Object.assign({}, (options.customLevels || {})), { qe: 35 }) });\n      }\n      const setupLoggerSingleton = (sessionId, name, options = {}, stream) => {\n          if (!LoggerSingleton || LoggerSingleton.sessionId !== sessionId) {\n              LoggerSingleton = browser(addQELevel(options)).child({ sessionId, name: name });\n              LoggerSingleton.qe = (msg) => LoggerSingleton.info(msg);\n              LoggerSingleton.sessionId = sessionId;\n          }\n          else {\n              LoggerSingleton.warn('Logger Singleton already setup, returning existing singleton');\n          }\n          return LoggerSingleton;\n      };\n      /**\n       * Get the configuration for the Pino logger\n       *\n       * @param {object} config - Configuration that overrides/extends the defaults set by this function\n       * @return {object}\n       */\n      function getLoggerConfig(config = {}) {\n          const { consoleOverride } = config;\n          return Object.assign({ name: 'hls', timestamp: !config.sendLogs ? browser.stdTimeFunctions.isoTime : browser.stdTimeFunctions.epochTime, browser: {\n                  asObject: true,\n                  serialize: true,\n                  transmit: {\n                      send: (level, logEvent) => {\n                          if (config.sendLogs && logEvent) {\n                              config.sendLogs(level, logEvent); // Custom send function\n                          }\n                      },\n                  },\n                  write: {\n                      debug: consoleWriteFn.bind(null, logFn(consoleOverride || console, 'debug'), 'debug'),\n                      info: consoleWriteFn.bind(null, logFn(consoleOverride || console, 'info'), 'info'),\n                      warn: consoleWriteFn.bind(null, logFn(consoleOverride || console, 'warn'), 'warn'),\n                      error: consoleWriteFn.bind(null, logFn(consoleOverride || console, 'error'), 'error'),\n                      fatal: consoleWriteFn.bind(null, logFn(consoleOverride || console, 'error'), 'fatal'),\n                  },\n              } }, config);\n      }\n      const noop$1 = () => { };\n      function logFn(consoleObj, consoleLevel) {\n          consoleObj = consoleLevel in consoleObj ? consoleObj : console;\n          const logFn = consoleObj[consoleLevel] || consoleObj.log;\n          if (logFn) {\n              return logFn.bind(consoleObj);\n          }\n          return noop$1;\n      }\n      function consoleWriteFn(method, logLevel, o) {\n          const { time, sessionId, critical, name, msg } = o;\n          let logData = '';\n          if ('data' in o) {\n              try {\n                  const keys = [];\n                  const refs = [];\n                  logData = JSON.stringify(o.data, (key, value) => {\n                      if (typeof value === 'object' && value !== null) {\n                          const circularRefIndex = refs.indexOf(value);\n                          if (circularRefIndex !== -1) {\n                              return `[Circular object reference: '${keys[circularRefIndex]}']`;\n                          }\n                          keys.push(key);\n                          refs.push(value);\n                      }\n                      return value;\n                  });\n              }\n              catch (e) {\n                  logData = `Log serialization error: \"${e}\"`;\n              }\n          }\n          method(`${getCustomLocaleTimeString(time)}| [SessionID: ${sessionId}] | [${logLevel}] >${critical ? ' [QE Critical]' : ''} [${name}] ${msg ? msg : ''} ${logData}`);\n      }\n      /**\n       * Returns local date and time with millisecond precision and timezone identifier\n       */\n      function getCustomLocaleTimeString(isoDateTime) {\n          const date = new Date(isoDateTime);\n          const off = date.getTimezoneOffset();\n          const hrs = pad(Math.floor(Math.abs(off) / 60));\n          const min = pad(Math.abs(off) % 60);\n          let tz = off <= 0 ? 'UTC+' + hrs : 'UTC-' + hrs;\n          tz = min ? tz + ':' + min : tz;\n          return (date.getFullYear() + '-' +\n              pad(date.getMonth() + 1) + '-' +\n              pad(date.getDate()) + ' ' +\n              pad(date.getHours()) + ':' +\n              pad(date.getMinutes()) + ':' +\n              pad(date.getSeconds()) + '.' +\n              (date.getMilliseconds() / 1000).toFixed(3).slice(2, 5) + ' ' +\n              tz);\n      }\n      /** Print Helpers **/\n      function pad(number) {\n          if (number < 10) {\n              return '0' + number;\n          }\n          return number.toString();\n      }\n      /**\n       * getLogger get the logger singleton defined in hls.ts\n       *\n       * Usage:\n       * getLogger().info({ name: \"yourModuleName\" }, 'msg to log');\n       * if you do not provide { name: \"yourModuleName\" }, log line will have 'name: \"hls\"'. A default name\n       */\n      const getLogger = () => {\n          if (!LoggerSingleton) {\n              LoggerSingleton = browser(addQELevel()).child({ name: 'hls' });\n              LoggerSingleton.qe = (msg) => LoggerSingleton.info(msg);\n              LoggerSingleton.warn('getLogger called without hls object instantiated, returning a logger that is not configured');\n          }\n          return LoggerSingleton;\n      };\n    \n      const MuxerHelper = {\n          bin2str(buffer) {\n              return String.fromCharCode.apply(null, Array.from(buffer));\n          },\n          readUint16(buffer, offset) {\n              const val = (buffer[offset] << 8) | buffer[offset + 1];\n              return val < 0 ? 65536 + val : val;\n          },\n          readSint32(buffer, offset) {\n              const val = (buffer[offset] << 24) | (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | buffer[offset + 3];\n              return val;\n          },\n          readUint32(buffer, offset) {\n              const val = MuxerHelper.readSint32(buffer, offset);\n              return val < 0 ? 4294967296 + val : val;\n          },\n          writeUint32(buffer, offset, value) {\n              buffer[offset] = value >> 24;\n              buffer[offset + 1] = (value >> 16) & 255;\n              buffer[offset + 2] = (value >> 8) & 255;\n              buffer[offset + 3] = value & 255;\n          },\n          readUint64(buffer, offset) {\n              let result = MuxerHelper.readUint32(buffer, offset);\n              result *= Math.pow(2, 32);\n              result += MuxerHelper.readUint32(buffer, offset + 4);\n              return result;\n          },\n          writeUint64(buffer, offset, value) {\n              const UINT32_MAX = Math.pow(2, 32) - 1;\n              const upper = Math.floor(value / (UINT32_MAX + 1));\n              const lower = Math.floor(value % (UINT32_MAX + 1));\n              MuxerHelper.writeUint32(buffer, offset, upper);\n              MuxerHelper.writeUint32(buffer, offset + 4, lower);\n          },\n          // Find the data for a box specified by its path\n          findBox(data, path) {\n              let results = [];\n              let ix;\n              let size;\n              let type;\n              let end;\n              let subresults;\n              if (!path.length) {\n                  // short-circuit the search for empty paths\n                  return [];\n              }\n              for (ix = 0; ix < data.byteLength;) {\n                  size = MuxerHelper.readUint32(data, ix);\n                  type = MuxerHelper.bin2str(data.subarray(ix + 4, ix + 8));\n                  end = size > 1 ? ix + size : data.byteLength;\n                  if (type === path[0]) {\n                      if (path.length === 1) {\n                          // this is the end of the path and we've found the box we were\n                          // looking for\n                          results.push(data.subarray(ix + 8, end));\n                      }\n                      else {\n                          // recursively search for the next box along the path\n                          subresults = MuxerHelper.findBox(data.subarray(ix + 8, end), path.slice(1));\n                          if (subresults.length) {\n                              results = results.concat(subresults);\n                          }\n                      }\n                  }\n                  ix = end;\n              }\n              // we've finished searching all of data\n              return results;\n          },\n          // Find the offset and data for a box specified by its path\n          findBoxWithOffset(data, offset, path, walkedPath) {\n              let results = [];\n              let ix;\n              let size;\n              let type;\n              let end;\n              let subresults;\n              if (!path.length) {\n                  // short-circuit the search for empty paths\n                  return [];\n              }\n              for (ix = 0; ix < data.byteLength;) {\n                  size = MuxerHelper.readUint32(data, ix);\n                  type = MuxerHelper.bin2str(data.subarray(ix + 4, ix + 8));\n                  end = size > 1 ? ix + size : data.byteLength;\n                  if (type === path[0]) {\n                      if (walkedPath) {\n                          walkedPath.push({ offset: ix + offset, type: type, size: size });\n                      }\n                      if (path.length === 1) {\n                          // this is the end of the path and we've found the box we were\n                          // looking for\n                          results.push({ offset: ix + offset, type: type, data: data.subarray(ix + 8, end), boxSize: size, walkedPath: walkedPath ? walkedPath.slice(0) : undefined });\n                      }\n                      else {\n                          // recursively search for the next box along the path\n                          subresults = MuxerHelper.findBoxWithOffset(data.subarray(ix + 8, end), ix + offset + 8, path.slice(1), walkedPath ? walkedPath.slice(0) : undefined);\n                          if (subresults.length) {\n                              results = results.concat(subresults);\n                              walkedPath = walkedPath ? walkedPath.slice(0, -1) : undefined;\n                          }\n                      }\n                  }\n                  ix = end;\n              }\n              // we've finished searching all of data\n              return results;\n          },\n      };\n    \n      /**\n       * Hex dumper class\n       *\n       * \n       * \n       *\n       */\n      const Hex = {\n          hexDump: function (array, limit = Infinity) {\n              if (!array) {\n                  return '';\n              }\n              const buffer = new Uint8Array(array);\n              let i, str = '';\n              for (i = 0; i < buffer.length && i < limit; i++) {\n                  let h = buffer[i].toString(16);\n                  if (h.length < 2) {\n                      h = '0' + h;\n                  }\n                  str += h;\n              }\n              return str;\n          },\n      };\n      var Hex$1 = Hex;\n    \n      const loggerName$d = { name: 'MP4EncryptionRemuxer' };\n      class MP4EncryptionRemuxer extends RemuxerBase {\n          constructor(observer, config, typeSupported, vendor, logger) {\n              super(observer, config, logger);\n          }\n          static _isCommonEncryptionInternal(decryptMethod) {\n              return Boolean(decryptMethod && !(decryptMethod === 'NONE' || decryptMethod === 'AES-128'));\n          }\n          static remuxInitSegment(initSegment, logger, keyTagInfo, sinfArray) {\n              if (!keyTagInfo) {\n                  return initSegment;\n              }\n              let remuxedInitSegment = initSegment;\n              if (MP4EncryptionRemuxer._isCommonEncryptionInternal(keyTagInfo.method)) {\n                  const keyId = keyTagInfo.keyId;\n                  let isCbc2 = false;\n                  const newTraks = []; // list of trak boxes\n                  const traks = MuxerHelper.findBoxWithOffset(initSegment, 0, ['moov', 'trak']);\n                  logger.info(loggerName$d, 'trying to patch map');\n                  traks.forEach((trakTuple) => {\n                      const trak = trakTuple.data;\n                      let mediaType;\n                      let encBoxChildrenOffset = 0;\n                      const stsdTuple = MuxerHelper.findBoxWithOffset(trak, 0, ['mdia', 'minf', 'stbl', 'stsd'], [])[0];\n                      // skip the sample entry count\n                      const sampleEntries = stsdTuple.data.subarray(8);\n                      let isAudio = true;\n                      let encBoxes = MuxerHelper.findBoxWithOffset(sampleEntries, stsdTuple.offset + 16, ['enca']);\n                      if (encBoxes.length === 0) {\n                          isAudio = false;\n                          encBoxes = MuxerHelper.findBoxWithOffset(sampleEntries, stsdTuple.offset + 16, ['encv']);\n                      }\n                      encBoxes.forEach((encBoxTuple) => {\n                          let encBoxChildren = null;\n                          let newTrak = null;\n                          if (isAudio) {\n                              // encrypted AudioSampleEntry - skip 28 bytes\n                              encBoxChildren = encBoxTuple.data.subarray(28);\n                              mediaType = 'audio';\n                              encBoxChildrenOffset = stsdTuple.offset + 16 + 8 + 28;\n                          }\n                          else {\n                              // encrypted VisualSampleEntry - skip 78 bytes\n                              encBoxChildren = encBoxTuple.data.subarray(78);\n                              mediaType = 'video';\n                              encBoxChildrenOffset = stsdTuple.offset + 16 + 8 + 78;\n                          }\n                          if (encBoxChildren) {\n                              const sinfTuples = MuxerHelper.findBoxWithOffset(encBoxChildren, encBoxChildrenOffset, ['sinf']);\n                              sinfTuples.forEach((sinfTuple) => {\n                                  const sinf = sinfTuple.data;\n                                  const frma = MuxerHelper.findBox(sinf, ['frma'])[0];\n                                  const schm = MuxerHelper.findBox(sinf, ['schm'])[0];\n                                  if (!frma) {\n                                      logger.error(loggerName$d, 'missing frma box');\n                                      return;\n                                  }\n                                  else if (!schm) {\n                                      logger.error(loggerName$d, 'missing schm box');\n                                      return;\n                                  }\n                                  const scheme = MuxerHelper.bin2str(schm.subarray(4, 8));\n                                  const format = MuxerHelper.bin2str(frma.subarray(0, 4));\n                                  if (format === 'aac ') {\n                                      if (!MP4$1.types) {\n                                          MP4$1.init();\n                                      }\n                                      logger.info(loggerName$d, 'found frma with type \\'aac \\', patching to \\'mp4a\\'');\n                                      frma.set(MP4$1.types.mp4a, 0);\n                                  }\n                                  if (scheme === 'cbcs' || scheme === 'cenc') {\n                                      if (sinfArray) {\n                                          sinfArray.push(sinf); // used for unit tests until we get a more generic parser\n                                      }\n                                      const tenc = MuxerHelper.findBox(sinf, ['schi', 'tenc'])[0];\n                                      if (tenc) {\n                                          const kKeyIdOffset = 8; // keyID offset is always 8 within the tenc box\n                                          // Look for default key id:\n                                          const tencKeyId = tenc.subarray(kKeyIdOffset, kKeyIdOffset + 16);\n                                          logger.info(loggerName$d, `found 'tenc' patching map with keyId default:${Hex$1.hexDump(tencKeyId)}->${Hex$1.hexDump(keyId)}`);\n                                          tenc.set(keyId, kKeyIdOffset);\n                                          // we may not need to do this, but at some point we were authoring content with zeros for the IV\n                                          // chrome does use this value, so set it to be safe\n                                          const defaultIsProtected = tenc[6];\n                                          const defaultPerSampleIVSize = tenc[7];\n                                          if (defaultIsProtected === 1 && defaultPerSampleIVSize === 0) {\n                                              const defaultConstantIVSize = tenc[24];\n                                              if (defaultConstantIVSize > 0 && keyTagInfo.iv && defaultConstantIVSize === keyTagInfo.iv.length) {\n                                                  logger.info(loggerName$d, 'patching iv for good measure');\n                                                  tenc.set(keyTagInfo.iv, 25);\n                                              }\n                                          }\n                                      }\n                                  }\n                                  else if (scheme === 'cbc2') {\n                                      logger.info(loggerName$d, 'found \\'cbc2\\' scheme, converting to \\'cbcs\\'');\n                                      isCbc2 = true;\n                                      if (!MP4$1.types) {\n                                          MP4$1.init();\n                                      }\n                                      // create a sinf from the existing format and new scheme and scheme info boxes\n                                      const frmaTuple = MuxerHelper.findBoxWithOffset(sinf, 0, ['frma'])[0];\n                                      const newSchi = MP4$1.box(MP4$1.types.schi, MP4$1.tenc(keyTagInfo, mediaType));\n                                      const newSinf = MP4$1.box(MP4$1.types.sinf, sinf.subarray(frmaTuple.offset, frmaTuple.boxSize), MP4$1.schm(), newSchi);\n                                      // create a new track from the existing trak with the new sinf spliced in\n                                      newTrak = MP4$1.box(MP4$1.types.trak, trak.subarray(0, sinfTuple.offset), newSinf, trak.subarray(sinfTuple.offset + sinfTuple.boxSize));\n                                      const newTrackData = newTrak.subarray(8);\n                                      // need to update all the sizes down the box path in the new track\n                                      // we can re-use the offsets from the already parsed path since they're before the splice point\n                                      const sizeIncrease = newSinf.byteLength - sinfTuple.boxSize;\n                                      if (stsdTuple.walkedPath) {\n                                          stsdTuple.walkedPath.push({ type: 'stsd', offset: encBoxTuple.offset, size: encBoxTuple.boxSize }); // enc* offset is special\n                                          stsdTuple.walkedPath.forEach((step) => {\n                                              MuxerHelper.writeUint32(newTrackData, step.offset, step.size + sizeIncrease);\n                                          });\n                                      }\n                                  }\n                              });\n                          }\n                          if (!newTrak) {\n                              newTrak = initSegment.subarray(trakTuple.offset, trakTuple.offset + trakTuple.boxSize);\n                          }\n                          newTraks.push(newTrak);\n                      });\n                      const edtsTuple = MuxerHelper.findBoxWithOffset(trak, 0, ['edts'])[0];\n                      if (edtsTuple) {\n                          if (!MP4$1.types) {\n                              MP4$1.init();\n                          }\n                          logger.info(loggerName$d, 'overwriting edts box');\n                          trak.set(MP4$1.types.free, edtsTuple.offset + 4);\n                      }\n                  });\n                  if (isCbc2) {\n                      const cbcsInitSegment = MP4EncryptionRemuxer.remuxCbc2InitSegment(initSegment, newTraks, logger);\n                      remuxedInitSegment = cbcsInitSegment ? cbcsInitSegment : initSegment;\n                  }\n              }\n              return remuxedInitSegment;\n          }\n          /**\n           * @param traksToAppend Array of trak boxes to replace traks in initSegment with.\n           */\n          static remuxCbc2InitSegment(initSegment, traksToAppend, logger) {\n              const ftypTuple = MuxerHelper.findBoxWithOffset(initSegment, 0, ['ftyp'])[0];\n              if (!ftypTuple) {\n                  logger.error(loggerName$d, 'no ftyp found');\n                  return;\n              }\n              const moovTuple = MuxerHelper.findBoxWithOffset(initSegment, ftypTuple.boxSize, ['moov'])[0];\n              let moovChildren = [];\n              let ix = 0;\n              while (ix < moovTuple.data.byteLength) {\n                  const size = MuxerHelper.readUint32(moovTuple.data, ix);\n                  const type = MuxerHelper.bin2str(moovTuple.data.subarray(ix + 4, ix + 8));\n                  const end = size > 1 ? ix + size : moovTuple.data.byteLength;\n                  switch (type) {\n                      case 'trak': {\n                          if (traksToAppend) {\n                              // Just append these here where the traks used to be\n                              moovChildren = moovChildren.concat(traksToAppend);\n                              traksToAppend = undefined;\n                          }\n                          break;\n                      }\n                      default:\n                          moovChildren.push(moovTuple.data.subarray(ix, end));\n                          break;\n                  }\n                  ix = end;\n              }\n              const newMoov = MP4$1.box(MP4$1.types.moov, ...moovChildren);\n              const newInitSegment = new Uint8Array(ftypTuple.boxSize + newMoov.byteLength);\n              newInitSegment.set(initSegment.subarray(0, ftypTuple.boxSize));\n              newInitSegment.set(newMoov, ftypTuple.boxSize);\n              return newInitSegment;\n          }\n          static remuxOverflowSegment(data, logger) {\n              if (!MP4$1.types) {\n                  MP4$1.init();\n              }\n              const tfdts = MuxerHelper.findBoxWithOffset(data, 0, ['moof', 'traf', 'tfdt'], []);\n              let newDataSize = data.byteLength;\n              let newData;\n              // total all tfdts in segment so we know the size increase (can have multiple moofs in a segment)\n              tfdts.forEach((tfdt) => {\n                  // increase the data size by 4 bytes for each 32 bit tfdt\n                  if (tfdt.data[0] === 0) {\n                      newDataSize += 4;\n                  }\n              });\n              if (newDataSize > data.byteLength) {\n                  newData = new Uint8Array(newDataSize);\n                  let newOffset = 0;\n                  let dataBoxIndex = 0;\n                  while (dataBoxIndex < data.byteLength) {\n                      const size = MuxerHelper.readUint32(data, dataBoxIndex);\n                      const type = MuxerHelper.bin2str(data.subarray(dataBoxIndex + 4, dataBoxIndex + 8));\n                      const dataBoxEnd = size > 1 ? dataBoxIndex + size : data.byteLength;\n                      if (type === 'moof') {\n                          const newMoof = MP4EncryptionRemuxer.remuxOverflowMoof(data.subarray(dataBoxIndex + 8, dataBoxEnd));\n                          newData.set(newMoof, newOffset);\n                          newOffset += newMoof.byteLength;\n                      }\n                      else {\n                          newData.set(data.subarray(dataBoxIndex, dataBoxEnd), newOffset);\n                          newOffset += size;\n                      }\n                      dataBoxIndex = dataBoxEnd;\n                  }\n              }\n              else {\n                  logger.warn(loggerName$d, 'no increase in size');\n              }\n              return newData ? newData : data;\n          }\n          static remuxOverflowMoof(moofData) {\n              let moofIndex = 0;\n              const moofChildren = [];\n              while (moofIndex < moofData.byteLength) {\n                  const size = MuxerHelper.readUint32(moofData, moofIndex);\n                  const type = MuxerHelper.bin2str(moofData.subarray(moofIndex + 4, moofIndex + 8));\n                  if (type === 'traf') {\n                      const newTraf = MP4EncryptionRemuxer.remuxOverflowTraf(moofData.subarray(moofIndex + 8, moofIndex + size));\n                      moofChildren.push(newTraf);\n                  }\n                  else {\n                      moofChildren.push(moofData.subarray(moofIndex, moofIndex + size));\n                  }\n                  moofIndex = size > 1 ? moofIndex + size : moofData.byteLength;\n              }\n              const newMoof = MP4$1.box(MP4$1.types.moof, ...moofChildren);\n              const sizeDiff = newMoof.byteLength - moofData.byteLength - 8; // moofData doesn't include header, so subtract 8\n              const truns = MuxerHelper.findBoxWithOffset(newMoof, 0, ['moof', 'traf', 'trun'], []);\n              truns.forEach((trun) => {\n                  const dataOffsetPresent = (trun.data[3] & 1) !== 0;\n                  if (dataOffsetPresent) {\n                      const dataOffset = MuxerHelper.readUint32(trun.data, 8);\n                      MuxerHelper.writeUint32(trun.data, 8, dataOffset + sizeDiff);\n                  }\n              });\n              const saios = MuxerHelper.findBoxWithOffset(newMoof, 0, ['moof', 'traf', 'saio'], []);\n              saios.forEach((saio) => {\n                  const version = saio.data[0] & 1;\n                  let dataOffset = 4;\n                  if (saio.data[3] & 1) {\n                      // aux info type and parameter\n                      dataOffset += 8;\n                  }\n                  const ec = MuxerHelper.readUint32(saio.data, dataOffset);\n                  dataOffset += 4;\n                  if (!version) {\n                      for (let i = 0; i < ec; i++) {\n                          const value = MuxerHelper.readUint32(saio.data, dataOffset);\n                          MuxerHelper.writeUint32(saio.data, dataOffset, value + sizeDiff);\n                          dataOffset += 4;\n                      }\n                  }\n                  else {\n                      for (let i = 0; i < ec; i++) {\n                          const value = MuxerHelper.readUint64(saio.data, dataOffset);\n                          MuxerHelper.writeUint64(saio.data, dataOffset, value + sizeDiff);\n                          dataOffset += 8;\n                      }\n                  }\n              });\n              return newMoof;\n          }\n          static remuxOverflowTraf(trafData) {\n              let trafIndex = 0;\n              const trafChildren = [];\n              while (trafIndex < trafData.byteLength) {\n                  const size = MuxerHelper.readUint32(trafData, trafIndex);\n                  const type = MuxerHelper.bin2str(trafData.subarray(trafIndex + 4, trafIndex + 8));\n                  if (type === 'tfdt' && trafData[trafIndex + 8] === 0) {\n                      const tfdtValue = MuxerHelper.readUint32(trafData, trafIndex + 12);\n                      const newTfdt = MP4$1.box(MP4$1.types.tfdt, new Uint8Array([\n                          1,\n                          0,\n                          0,\n                          0,\n                          0,\n                          0,\n                          0,\n                          0,\n                          tfdtValue >> 24,\n                          (tfdtValue >> 16) & 255,\n                          (tfdtValue >> 8) & 255,\n                          tfdtValue & 255,\n                      ]));\n                      trafChildren.push(newTfdt);\n                  }\n                  else {\n                      trafChildren.push(trafData.subarray(trafIndex, trafIndex + size));\n                  }\n                  trafIndex = size > 1 ? trafIndex + size : trafData.byteLength;\n              }\n              const newTraf = MP4$1.box(MP4$1.types.traf, ...trafChildren);\n              return newTraf;\n          }\n          remuxText(track, parsingData) {\n              track.captionSamples.sort(function (a, b) {\n                  return a.pts - b.pts;\n              });\n              const length = track.captionSamples.length;\n              if (length) {\n                  if (!parsingData.captionData) {\n                      parsingData.captionData = {};\n                  }\n                  parsingData.captionData.mp4 = track.captionSamples;\n              }\n              track.captionSamples = [];\n          }\n          remuxIFrame(startDTS, videoTrack, audioTrack, iframeDuration, track) {\n              if (!videoTrack.samples || !videoTrack.samples.length || !videoTrack.samples[0].data) {\n                  return null;\n              }\n              let streamType;\n              const moof = MP4$1.moof(startDTS * videoTrack.timescale, videoTrack);\n              const iframeSegment = new Uint8Array(moof.byteLength + videoTrack.samples[0].data.byteLength + 8);\n              iframeSegment.set(moof);\n              MuxerHelper.writeUint32(iframeSegment, moof.byteLength, videoTrack.samples[0].data.byteLength + 8);\n              iframeSegment.set(MP4$1.types.mdat, moof.byteLength + 4);\n              iframeSegment.set(videoTrack.samples[0].data, moof.byteLength + 8);\n              videoTrack.sequenceNumber++;\n              const videoTimescale = videoTrack.timescale;\n              const videoEndTs = convertSecondsToTimestamp(startDTS + iframeDuration, videoTimescale);\n              const videoStartTs = convertSecondsToTimestamp(startDTS, videoTimescale);\n              let endTs;\n              let audioSegment;\n              if (audioTrack) {\n                  streamType = 'audiovideo';\n                  audioTrack.sequenceNumber = videoTrack.sequenceNumber;\n                  videoTrack.sequenceNumber++;\n                  audioSegment = SilentAudio.getSegment(audioTrack, audioTrack.sequenceNumber, startDTS * audioTrack.info.timescale, iframeDuration);\n                  endTs = determineMaxTimestamp(audioSegment.endTs, videoEndTs);\n              }\n              else {\n                  streamType = 'video';\n                  endTs = videoEndTs;\n              }\n              const data = {\n                  data1: iframeSegment,\n                  data2: audioSegment === null || audioSegment === void 0 ? void 0 : audioSegment.silentFragData,\n                  startPTS: videoStartTs,\n                  startDTS: videoStartTs,\n                  endPTS: endTs,\n                  endDTS: endTs,\n                  type: streamType,\n                  dropped: 0,\n                  track,\n              };\n              // send the data\n              this.observer.trigger(DemuxerEvent.FRAG_PARSING_DATA, data);\n              // notify end of parsing\n              this.observer.trigger(DemuxerEvent.FRAG_PARSED);\n          }\n          remuxEmsgAndRawData(audioDuration, hasAudio, videoDuration, hasVideo, textTrack, id3Track, timeOffset, timescale, rawFragment, track) {\n              let streamType;\n              if (hasAudio && hasVideo) {\n                  streamType = 'audiovideo';\n              }\n              else if (hasAudio) {\n                  streamType = 'audio';\n              }\n              else if (hasVideo) {\n                  streamType = 'video';\n              }\n              const fragDuration = Math.max(videoDuration, audioDuration);\n              const data = {\n                  data1: rawFragment,\n                  track,\n                  startPTS: convertSecondsToTimestamp(timeOffset, timescale),\n                  startDTS: convertSecondsToTimestamp(timeOffset, timescale),\n                  endPTS: undefined,\n                  endDTS: undefined,\n                  type: streamType,\n                  dropped: 0,\n              };\n              if (fragDuration) {\n                  data.endPTS = convertSecondsToTimestamp(timeOffset + fragDuration, timescale);\n                  data.endDTS = convertSecondsToTimestamp(timeOffset + fragDuration, timescale);\n              }\n              if (textTrack && textTrack.captionSamples.length) {\n                  this.remuxText(textTrack, data);\n              }\n              if (id3Track && id3Track.id3Samples.length > 0) {\n                  this.remuxID3(id3Track, data);\n              }\n              this.observer.trigger(DemuxerEvent.FRAG_PARSING_DATA, data);\n              this.observer.trigger(DemuxerEvent.FRAG_PARSED);\n              return data;\n          }\n          remuxID3(track, parsingData) {\n              let sample;\n              const length = track.id3Samples.length;\n              const PTSOffset = 10;\n              const DTSOffset = 10;\n              if (length) {\n                  for (let index = 0; index < length; index++) {\n                      sample = track.id3Samples[index];\n                      // emsg pts is aligned with media content and have 10s offset to avoid negative time in audio samples\n                      sample.pts = sample.pts - PTSOffset;\n                      sample.dts = sample.dts - DTSOffset;\n                  }\n                  parsingData.id3Samples = [...track.id3Samples];\n              }\n              track.id3Samples = [];\n          }\n      }\n    \n      \n      const UINT32_MAX = Math.pow(2, 32) - 1;\n      const MAX_UPPER_32_VALUE = Math.pow(2, 20) - 1; // 52 bit integer float precision\n      const LARGE_TIMESCALE = 1000000;\n      const loggerName$c = { name: 'MP4Demuxer' };\n      class MP4Demuxer extends DemuxerBase {\n          constructor(observer, remuxer, config, typeSupported = undefined, logger) {\n              super(observer, remuxer, config, {}, logger);\n              this.mp4Remuxer = remuxer;\n              // may need a little headroom for priming audio samples, so shift everything by the max value we expect\n              // that should be 2112 audio samples at 22050 hz\n              this.audioPrimingDelay = config.audioPrimingDelay;\n              if (this.audioPrimingDelay > 0) {\n                  this.logger.info(loggerName$c, `using audioPrimingDelay of ${this.audioPrimingDelay}`);\n              }\n          }\n          resetTimeStamp(initPTS90k) {\n              if (isFiniteNumber(initPTS90k)) {\n                  if (this.initData.audio && !this.initData.video) {\n                      // if this is an audio only track go ahead and convert initPTS to the sample rate to avoid cumulative rounding errors\n                      this.initPtsTs = { baseTime: Math.round((initPTS90k * this.initData.audio.timescale) / 90000), timescale: this.initData.audio.timescale };\n                  }\n                  else {\n                      this.initPtsTs = { baseTime: initPTS90k, timescale: 90000 };\n                  }\n              }\n              else {\n                  this.initPtsTs = undefined;\n              }\n          }\n          static isHEVCFlavor(codec) {\n              if (!codec) {\n                  return false;\n              }\n              const delimit = codec.indexOf('.');\n              const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);\n              return (baseCodec === 'hvc1' ||\n                  baseCodec === 'hev1' /*\n            baseCodec === 'phvc' ||\n            baseCodec === 'ehvc' ||\n            baseCodec === 'zhvc' ||*/\n                  ||\n                      baseCodec === 'chvc' ||\n                  baseCodec === 'qhvc' ||\n                  baseCodec === 'qhev' ||\n                  baseCodec === 'muxa' ||\n                  // Dolby Vision\n                  baseCodec === 'dvh1' ||\n                  baseCodec === 'dvhe' /*\n            baseCodec === 'ddh1' ||\n            baseCodec === 'zdh1' ||*/\n                  ||\n                      baseCodec === 'cdh1' ||\n                  baseCodec === 'qdh1' ||\n                  baseCodec === 'qdhe');\n          }\n          resetInitSegment(initSegment, duration, keyTagInfo) {\n              // jshint unused:false\n              this._silentAudioTrack = undefined;\n              if (initSegment && initSegment.byteLength) {\n                  const remuxedInitSegment = MP4EncryptionRemuxer.remuxInitSegment(initSegment, this.logger, keyTagInfo);\n                  const initData = (this.initData = MP4Demuxer.parseInitSegment(remuxedInitSegment));\n                  let track;\n                  if (initData.foundLargeTimescale) {\n                      this.logger.warn(loggerName$c, 'large timescale found, will check for 32 bit tfdts');\n                  }\n                  const parsedAudioCodec = initData.audioCodec;\n                  const parsedVideoCodec = initData.videoCodec;\n                  if (initData.audio && initData.video) {\n                      track = { type: 'audiovideo', container: 'video/mp4', codec: parsedAudioCodec + ',' + parsedVideoCodec, initSegment: remuxedInitSegment };\n                  }\n                  else {\n                      if (initData.audio && parsedAudioCodec) {\n                          track = { type: 'audio', container: 'audio/mp4', codec: parsedAudioCodec, initSegment: remuxedInitSegment };\n                      }\n                      if (initData.video && parsedVideoCodec) {\n                          track = { type: 'video', container: 'video/mp4', codec: parsedVideoCodec, initSegment: remuxedInitSegment };\n                      }\n                  }\n                  if (initData.video) {\n                      // needed to generate moofs for iframe mode frames\n                      // we need the track data to create a new moof for muxed iframe mode\n                      const parsedVideoTrack = initData.video;\n                      const trakData = initSegment.subarray(parsedVideoTrack.trakOffset, parsedVideoTrack.trakOffset + parsedVideoTrack.trakSize);\n                      this._videoTrack = Object.assign(Object.assign({}, parsedVideoTrack), { info: { id: parsedVideoTrack.id, timescale: parsedVideoTrack.timescale, duration }, trakData: trakData, sequenceNumber: 0, samples: [] });\n                      this.trySEICaptions = !MediaUtil.isVP09(parsedVideoCodec);\n                      this._captionTrack = Object.assign(Object.assign({}, initData.caption), { sequenceNumber: 0, captionSamples: [] });\n                      this.logger.info(loggerName$c, 'assume SEI closed caption exists');\n                  }\n                  if (initData.audio && parsedAudioCodec) {\n                      // only need id and codec for silent audio generation\n                      this._audioTrack = Object.assign({}, initData.audio);\n                  }\n                  if (initData.caption) {\n                      // use clcp track if present\n                      this.trySEICaptions = false;\n                      this.logger.info(loggerName$c, `use clcp track id ${initData.caption.id}`);\n                      this._captionTrack = Object.assign(Object.assign({}, initData.caption), { sequenceNumber: 0, captionSamples: [] });\n                  }\n                  this.remuxedInitDataTrack = track;\n                  const eventData = { track };\n                  this.observer.trigger(DemuxerEvent.FRAG_PARSING_INIT_SEGMENT, eventData);\n              }\n          }\n          static probe(data, logger) {\n              // ensure we find a moof box in the first 128kB\n              return MuxerHelper.findBox(data.subarray(0, Math.min(data.length, 512000)), ['moof']).length > 0;\n          }\n          static parseHvcC(data) {\n              let codecConfig;\n              if (data) {\n                  const version = data[0];\n                  if (version === 1) {\n                      const tmpByte = data[1];\n                      codecConfig = {\n                          profileSpace: tmpByte >> 6,\n                          tierFlag: (tmpByte & 32) >> 5 ? 'H' : 'L',\n                          profileIDC: tmpByte & 31,\n                          profileCompat: MuxerHelper.readUint32(data, 2),\n                          constraintIndicator: data.subarray(6, 12),\n                          levelIDC: data[12],\n                      };\n                  }\n                  else {\n                      getLogger().warn(loggerName$c, `Unhandled version ${version} in hvcC box`);\n                  }\n              }\n              else {\n                  getLogger().warn(loggerName$c, 'No hvcC box');\n              }\n              return codecConfig;\n          }\n          static hvcCToCodecString(baseCodecType, codecConfig) {\n              const profileSpaceStr = codecConfig.profileSpace ? String.fromCharCode(codecConfig.profileSpace + 'A' - 1) : '';\n              const codecString = baseCodecType + '.' + profileSpaceStr + codecConfig.profileIDC + '.' + codecConfig.profileCompat.toString(16).toUpperCase() + '.' + codecConfig.tierFlag + codecConfig.levelIDC;\n              // append constraint indicators, ignoring trailing zero bytes\n              let constraintIndicatorStr = '';\n              for (let i = codecConfig.constraintIndicator.length - 1; i >= 0; --i) {\n                  const byte = codecConfig.constraintIndicator[i];\n                  if (!(byte === 0 && constraintIndicatorStr === '')) {\n                      const encodedByte = byte.toString(16).toUpperCase();\n                      constraintIndicatorStr = '.' + (constraintIndicatorStr === '' ? encodedByte : encodedByte + constraintIndicatorStr);\n                  }\n              }\n              return codecString + constraintIndicatorStr;\n          }\n          static parseDvcC(data) {\n              let codecConfig;\n              if (data) {\n                  codecConfig = {\n                      versionMajor: data[0],\n                      versionMinor: data[1],\n                      profile: (data[2] >> 1) & 127,\n                      level: ((data[2] << 5) & 32) | ((data[3] >> 3) & 31),\n                  };\n              }\n              else {\n                  getLogger().warn(loggerName$c, 'No dvcC box');\n              }\n              return codecConfig;\n          }\n          static dvcCToCodecString(baseCodecType, codecConfig) {\n              const profileStr = MP4Demuxer.checkAndAddLeadingZero(codecConfig.profile);\n              const levelStr = MP4Demuxer.checkAndAddLeadingZero(codecConfig.level);\n              return baseCodecType + '.' + profileStr + '.' + levelStr;\n          }\n          static parseVpcC(data) {\n              let codecConfig;\n              if (data) {\n                  codecConfig = {\n                      profile: data[4],\n                      level: data[5],\n                      bitDepth: (data[6] >> 4) & 15,\n                  };\n              }\n              else {\n                  getLogger().warn(loggerName$c, 'No vpcC box');\n              }\n              return codecConfig;\n          }\n          static vpcCToCodecString(baseCodecType, codecConfig) {\n              const profileStr = MP4Demuxer.checkAndAddLeadingZero(codecConfig.profile);\n              const levelStr = MP4Demuxer.checkAndAddLeadingZero(codecConfig.level);\n              const subsampling = MP4Demuxer.checkAndAddLeadingZero(codecConfig.bitDepth);\n              return baseCodecType + '.' + profileStr + '.' + levelStr + '.' + subsampling;\n          }\n          static checkAndAddLeadingZero(num) {\n              return (num < 10 ? '0' : '') + num;\n          }\n          /**\n           * Parses an MP4 initialization segment and extracts stream type and\n           * timescale values for any declared tracks. Timescale values indicate the\n           * number of clock ticks per second to assume for time-based values\n           * elsewhere in the MP4.\n           *\n           * To determine the start time of an MP4, you need two pieces of\n           * information: the timescale unit and the earliest base media decode\n           * time. Multiple timescales can be specified within an MP4 but the\n           * base media decode time is always expressed in the timescale from\n           * the media header box for the track:\n           * ```\n           * moov > trak > mdia > mdhd.timescale\n           * moov > trak > mdia > hdlr\n           * ```\n           * @param init {Uint8Array} the bytes of the init segment\n           * @return {object} a hash of track type to timescale values or null if\n           * the init segment is malformed.\n           */\n          static parseInitSegment(initSegment) {\n              const result = { foundLargeTimescale: false, tracksById: {} };\n              const traksTuple = MuxerHelper.findBoxWithOffset(initSegment, 0, ['moov', 'trak']);\n              traksTuple.forEach((trakTuple) => {\n                  const trak = trakTuple.data;\n                  const tkhd = MuxerHelper.findBox(trak, ['tkhd'])[0];\n                  if (tkhd) {\n                      let version = tkhd[0];\n                      const index = version === 0 ? 12 : 20;\n                      const id = MuxerHelper.readUint32(tkhd, index);\n                      const mdhd = MuxerHelper.findBox(trak, ['mdia', 'mdhd'])[0];\n                      if (mdhd) {\n                          version = mdhd[0];\n                          let timescaleIndex = version === 0 ? 12 : 20;\n                          const timescale = MuxerHelper.readUint32(mdhd, timescaleIndex);\n                          timescaleIndex += 4;\n                          if (timescale >= LARGE_TIMESCALE) {\n                              result.foundLargeTimescale = true;\n                          }\n                          const duration = version === 0 ? MuxerHelper.readUint32(mdhd, timescaleIndex) : 0; // TODO: read 64 bit? Maybe we don't care, but TS sets this value and we're trying to share track data\n                          const hdlr = MuxerHelper.findBox(trak, ['mdia', 'hdlr'])[0];\n                          if (hdlr) {\n                              const hdlrType = MuxerHelper.bin2str(hdlr.subarray(8, 12));\n                              const hdlrToTypeMap = { soun: 'audio', vide: 'video', clcp: 'caption' };\n                              const type = hdlrToTypeMap[hdlrType] || hdlrType;\n                              if (type) {\n                                  // extract codec info. TODO : parse codec details to be able to build MIME type\n                                  const codecBoxes = MuxerHelper.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);\n                                  let codecType;\n                                  if (codecBoxes.length) {\n                                      const codecBox = codecBoxes[0];\n                                      codecType = MuxerHelper.bin2str(codecBox.subarray(12, 16));\n                                      getLogger().info(loggerName$c, `MP4Demuxer:${type}:${codecType} found`);\n                                      const stsdData = MP4Demuxer.parseStsd(codecBox);\n                                      let newTrack;\n                                      if (type === 'caption') {\n                                          const captionTrack = Object.assign({ id, type, timescale, duration, isTimingTrack: false, sequenceNumber: 0, captionSamples: [] }, stsdData);\n                                          result.caption = captionTrack;\n                                          newTrack = captionTrack;\n                                      }\n                                      else {\n                                          const mediaTrack = Object.assign({ id,\n                                              type,\n                                              timescale,\n                                              duration, isTimingTrack: true, trakOffset: trakTuple.offset, trakSize: trakTuple.boxSize, sequenceNumber: 0, samples: [], fragmentDuration: 0 }, stsdData);\n                                          if (type === 'video') {\n                                              result.video = mediaTrack;\n                                              result.videoCodec = mediaTrack.codec;\n                                          }\n                                          else {\n                                              result.audio = mediaTrack;\n                                              result.audioCodec = mediaTrack.codec;\n                                          }\n                                          newTrack = mediaTrack;\n                                      }\n                                      result.tracksById[id] = newTrack;\n                                  }\n                              }\n                          }\n                      }\n                  }\n              });\n              const trexTuple = MuxerHelper.findBoxWithOffset(initSegment, 0, ['moov', 'mvex', 'trex']);\n              trexTuple.forEach((trexTuple) => {\n                  const trex = trexTuple.data;\n                  const id = MuxerHelper.readUint32(trex, 4);\n                  const defaultSampleSize = MuxerHelper.readUint32(trex, 16);\n                  result.tracksById[id].defaultSampleSize = defaultSampleSize;\n              });\n              return result;\n          }\n          static parseStsd(stsd) {\n              let defaultPerSampleIVSize;\n              let codec;\n              // skip the sample entry count\n              const sampleEntries = stsd.subarray(8);\n              let baseCodecType = MuxerHelper.bin2str(sampleEntries.subarray(4, 8));\n              let encBox = null;\n              let encBoxChildren = null;\n              if (baseCodecType === 'enca') {\n                  // audio\n                  encBox = MuxerHelper.findBox(sampleEntries, ['enca'])[0];\n                  encBoxChildren = encBox.subarray(28);\n              }\n              else if (baseCodecType === 'encv') {\n                  // video\n                  encBox = MuxerHelper.findBox(sampleEntries, ['encv'])[0];\n                  // FIXME: May have optional clap and pasp atoms after 78 bytes\n                  encBoxChildren = encBox.subarray(78);\n              }\n              const encrypted = !!encBoxChildren;\n              defaultPerSampleIVSize = 0;\n              if (encBoxChildren) {\n                  const sinfs = MuxerHelper.findBox(encBoxChildren, ['sinf']);\n                  sinfs.forEach((sinf) => {\n                      const schm = MuxerHelper.findBox(sinf, ['schm'])[0];\n                      if (schm) {\n                          const scheme = MuxerHelper.bin2str(schm.subarray(4, 8));\n                          if (scheme === 'cbcs' || scheme === 'cenc') {\n                              const frma = MuxerHelper.findBox(sinf, ['frma'])[0];\n                              if (frma) {\n                                  // for encrypted content baseCodecType will be in frma\n                                  baseCodecType = MuxerHelper.bin2str(frma);\n                              }\n                              const tenc = MuxerHelper.findBox(sinf, ['schi', 'tenc'])[0];\n                              if (tenc) {\n                                  defaultPerSampleIVSize = tenc[7];\n                              }\n                          }\n                      }\n                  });\n              }\n              let codecConfig;\n              const sampleEntriesEnd = sampleEntries.subarray(86);\n              switch (baseCodecType) {\n                  case 'mp4a':\n                      codec = 'mp4a.40.5';\n                      break;\n                  case 'ac-3':\n                  case 'ec-3':\n                  case 'alac':\n                  case 'fLaC':\n                      codec = baseCodecType;\n                      break;\n                  case 'avc1':\n                  case 'avc3':\n                      codec = baseCodecType + '.640028';\n                      break;\n                  case 'hvc1':\n                  case 'hev1':\n                      const hvcCBox = MuxerHelper.findBox(sampleEntriesEnd, ['hvcC'])[0]; // There may be other atoms right after sampleEntries\n                      codecConfig = MP4Demuxer.parseHvcC(hvcCBox);\n                      codec = codecConfig ? MP4Demuxer.hvcCToCodecString(baseCodecType, codecConfig) : baseCodecType + '.2.4.H150.B0';\n                      break;\n                  case 'dvh1':\n                  case 'dvhe':\n                      const dvcCBox = MuxerHelper.findBox(sampleEntriesEnd, ['dvcC'])[0];\n                      codecConfig = MP4Demuxer.parseDvcC(dvcCBox);\n                      codec = codecConfig ? MP4Demuxer.dvcCToCodecString(baseCodecType, codecConfig) : baseCodecType + '.05.01';\n                      break;\n                  case 'c608':\n                      codec = baseCodecType;\n                      break;\n                  case 'vp09':\n                      const vpcCBox = MuxerHelper.findBox(sampleEntriesEnd, ['vpcC'])[0];\n                      codecConfig = MP4Demuxer.parseVpcC(vpcCBox);\n                      codec = MP4Demuxer.vpcCToCodecString(baseCodecType, codecConfig);\n                      break;\n                  default:\n                      codec = baseCodecType;\n                      break;\n              }\n              return { codec, encrypted, defaultPerSampleIVSize };\n          }\n          static has32BitTfdts(fragment) {\n              const tfdts = MuxerHelper.findBox(fragment, ['moof', 'traf', 'tfdt']);\n              let found = false;\n              tfdts.forEach((tfdt) => {\n                  if (tfdt[0] === 0) {\n                      // version 0 means 32 bit tfdt\n                      found = true;\n                  }\n              });\n              return found;\n          }\n          /**\n           * Determine the base media decode start time, in seconds, for an MP4\n           * fragment. If multiple fragments are specified, the earliest time is\n           * returned.\n           *\n           * The base media decode time can be parsed from track fragment\n           * metadata:\n           * ```\n           * moof > traf > tfdt.baseMediaDecodeTime\n           * ```\n           * It requires the timescale value from the mdhd to interpret.\n           *\n           * @param timescale {object} a hash of track ids to timescale values.\n           * @return {number} the earliest base media decode start time for the\n           * fragment, in seconds\n           */\n          static getStartDtsTs(initData, fragment) {\n              // we need info from two childrend of each track fragment box\n              const trafs = MuxerHelper.findBox(fragment, ['moof', 'traf']);\n              let minTime = Number.MAX_SAFE_INTEGER;\n              let result;\n              // determine the start times for each track\n              trafs.map(function (traf) {\n                  return MuxerHelper.findBox(traf, ['tfhd']).forEach((tfhd) => {\n                      // get the track id from the tfhd\n                      const id = MuxerHelper.readUint32(tfhd, 4);\n                      const parsedTrak = initData.tracksById[id];\n                      let timescale;\n                      if (!parsedTrak) {\n                          return;\n                      }\n                      if (parsedTrak.isTimingTrack) {\n                          // assume a 90kHz clock if no timescale was specified\n                          timescale = parsedTrak.timescale || 90000;\n                      }\n                      else {\n                          return Infinity; // Should just not be considered for time calculation\n                      }\n                      // get the base media decode time from the tfdt\n                      const tfdtTimes = MuxerHelper.findBox(traf, ['tfdt']).map(function (tfdt) {\n                          let result;\n                          const version = tfdt[0];\n                          result = MuxerHelper.readUint32(tfdt, 4);\n                          if (version === 1) {\n                              if (result > MAX_UPPER_32_VALUE) {\n                                  getLogger().warn(loggerName$c, `Value larger than can be represented by float for upper 32 bits ${result}`);\n                              }\n                              result *= Math.pow(2, 32);\n                              result += MuxerHelper.readUint32(tfdt, 8);\n                          }\n                          return result;\n                      });\n                      const baseTime = tfdtTimes.length > 0 ? tfdtTimes[0] : Infinity;\n                      if (isFinite(baseTime) && baseTime / timescale < minTime) {\n                          minTime = baseTime / timescale;\n                          result = { baseTime, timescale };\n                      }\n                  });\n              });\n              return result;\n          }\n          static offsetStartDTS(initData, fragment, timeOffsetTs, audioPrimingDelaySec) {\n              MuxerHelper.findBox(fragment, ['moof', 'traf']).map(function (traf) {\n                  return MuxerHelper.findBox(traf, ['tfhd']).map(function (tfhd) {\n                      // get the track id from the tfhd\n                      const id = MuxerHelper.readUint32(tfhd, 4);\n                      const parsedTrak = initData.tracksById[id];\n                      if (!parsedTrak) {\n                          return;\n                      }\n                      // assume a 90kHz clock if no timescale was specified\n                      const timescale = parsedTrak.timescale || 90000;\n                      const audioPrimingOffset = parsedTrak.type === 'caption' ? 0 : audioPrimingDelaySec;\n                      // get the base media decode time from the tfdt\n                      MuxerHelper.findBox(traf, ['tfdt']).map(function (tfdt) {\n                          const version = tfdt[0];\n                          const mediaType = parsedTrak.type;\n                          if (version === 0) {\n                              const baseMediaDecodeTime = MuxerHelper.readUint32(tfdt, 4);\n                              let offsetBaseMediaDecodeTime = baseMediaDecodeTime - Math.round((timeOffsetTs.baseTime * timescale) / timeOffsetTs.timescale);\n                              // need to make sure video doesn't go negative after timestampOffset is applied\n                              if (mediaType === 'video' && offsetBaseMediaDecodeTime < 0) {\n                                  getLogger().warn(loggerName$c, `video tdft would have gone negative by ${offsetBaseMediaDecodeTime / timescale} seconds`);\n                                  offsetBaseMediaDecodeTime = 0;\n                              }\n                              offsetBaseMediaDecodeTime = offsetBaseMediaDecodeTime + Math.round(audioPrimingOffset * timescale);\n                              offsetBaseMediaDecodeTime = Math.max(offsetBaseMediaDecodeTime, 0);\n                              MuxerHelper.writeUint32(tfdt, 4, offsetBaseMediaDecodeTime);\n                          }\n                          else {\n                              const baseMediaDecodeTime = MuxerHelper.readUint32(tfdt, 4);\n                              if (baseMediaDecodeTime > MAX_UPPER_32_VALUE) {\n                                  getLogger().error(loggerName$c, `baseMediaDecodeTime larger than can be represented by float for upper 32 bits ${baseMediaDecodeTime}`);\n                              }\n                              let offsetBaseMediaDecodeTime = baseMediaDecodeTime;\n                              offsetBaseMediaDecodeTime *= Math.pow(2, 32);\n                              offsetBaseMediaDecodeTime += MuxerHelper.readUint32(tfdt, 8);\n                              offsetBaseMediaDecodeTime = offsetBaseMediaDecodeTime - Math.round((timeOffsetTs.baseTime * timescale) / timeOffsetTs.timescale);\n                              // need to make sure video doesn't go negative after timestampOffset is applied\n                              if (mediaType === 'video' && offsetBaseMediaDecodeTime < 0) {\n                                  getLogger().warn(loggerName$c, `video tdft would have gone negative by ${offsetBaseMediaDecodeTime / timescale} seconds`);\n                                  offsetBaseMediaDecodeTime = 0;\n                              }\n                              offsetBaseMediaDecodeTime = offsetBaseMediaDecodeTime + Math.round(audioPrimingOffset * timescale);\n                              offsetBaseMediaDecodeTime = Math.max(offsetBaseMediaDecodeTime, 0);\n                              const upper = Math.floor(offsetBaseMediaDecodeTime / (UINT32_MAX + 1));\n                              const lower = Math.floor(offsetBaseMediaDecodeTime % (UINT32_MAX + 1));\n                              MuxerHelper.writeUint32(tfdt, 4, upper);\n                              MuxerHelper.writeUint32(tfdt, 8, lower);\n                          }\n                      });\n                  });\n              });\n          }\n          static writeStartDTS(initData, fragmentData, startDTS) {\n              MuxerHelper.findBox(fragmentData, ['moof', 'traf']).map(function (traf) {\n                  return MuxerHelper.findBox(traf, ['tfhd']).map(function (tfhd) {\n                      // get the track id from the tfhd\n                      const id = MuxerHelper.readUint32(tfhd, 4);\n                      const parsedTrak = initData.tracksById[id];\n                      if (!parsedTrak) {\n                          return;\n                      }\n                      // assume a 90kHz clock if no timescale was specified\n                      const timescale = parsedTrak.timescale || 90000;\n                      // everything is in decimal seconds, so we need round timestamps or they'll get truncated and lose accuracy\n                      const roundedStartDTS = Math.round(startDTS * timescale) / timescale;\n                      if (Math.abs(roundedStartDTS - startDTS) > 0.01) {\n                          // the rounding errors should be very small since we snap durations to the timescale\n                          getLogger().warn(loggerName$c, `[iframes] large rounding error when adjusting timestamps, startDTS: ${startDTS}, roundedStartDTS: ${roundedStartDTS}`);\n                      }\n                      // get the base media decode time from the tfdt\n                      MuxerHelper.findBox(traf, ['tfdt']).map(function (tfdt) {\n                          const version = tfdt[0];\n                          if (version === 0) {\n                              MuxerHelper.writeUint32(tfdt, 4, roundedStartDTS * timescale);\n                          }\n                          else {\n                              let baseMediaDecodeTime = roundedStartDTS * timescale;\n                              baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n                              const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n                              const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n                              MuxerHelper.writeUint32(tfdt, 4, upper);\n                              MuxerHelper.writeUint32(tfdt, 8, lower);\n                          }\n                      });\n                  });\n              });\n          }\n          static parseSAIO(saio) {\n              let subsampleOffset = 0;\n              let offset = 0;\n              const version = saio[0];\n              const flags = MuxerHelper.readUint32(saio, 0) & 16777215;\n              offset += 4;\n              if ((flags & 1) !== 0) {\n                  offset += 8;\n              }\n              const entryCount = MuxerHelper.readUint32(saio, offset) & 16777215;\n              if (entryCount === 1) {\n                  offset += 4;\n                  subsampleOffset = MuxerHelper.readUint32(saio, offset);\n                  if (version === 1) {\n                      offset += 4;\n                      subsampleOffset *= Math.pow(2, 32);\n                      subsampleOffset += MuxerHelper.readUint32(saio, offset);\n                  }\n              }\n              else {\n                  getLogger().error(loggerName$c, `saio entry count error, count is: ${entryCount}`);\n              }\n              return subsampleOffset;\n          }\n          static parseSAIZ(saiz) {\n              let sampleSize = 0;\n              let offset = 0;\n              const flags = MuxerHelper.readUint32(saiz, 0) & 16777215;\n              offset += 4;\n              if ((flags & 1) !== 0) {\n                  offset += 8;\n              }\n              sampleSize = saiz[offset];\n              offset++;\n              // let sampleCount = MP4Demuxer.readUint32(saiz, offset);\n              offset += 4; // just get the first sample\n              if (sampleSize === 0) {\n                  sampleSize = saiz[offset];\n              }\n              return sampleSize;\n          }\n          static parseSubsample(perSampleIVSize, entry) {\n              const sampleAuxInfo = { subsamples: [] };\n              let offset = 0;\n              if (perSampleIVSize) {\n                  sampleAuxInfo.iv = entry.subarray(0, perSampleIVSize);\n                  offset += perSampleIVSize;\n              }\n              offset += 2; // skip entry length\n              // need at least 6 bytes to read a subsample entry\n              while (offset + 6 <= entry.byteLength) {\n                  const bytesClear = MuxerHelper.readUint16(entry, offset);\n                  offset += 2;\n                  const bytesEncrypted = MuxerHelper.readUint32(entry, offset);\n                  offset += 4;\n                  sampleAuxInfo.subsamples.push([bytesClear, bytesEncrypted]);\n              }\n              return sampleAuxInfo;\n          }\n          static isSEIMessage(isHEVCFlavor, naluType) {\n              return isHEVCFlavor ? naluType === 39 || naluType === 40 : naluType === 6;\n          }\n          static parseCLCPSample(fragment, startSampleOffset, sampleSize) {\n              let sampleIndex = 0;\n              const samples = [];\n              let totalSize = 0;\n              while (sampleIndex < sampleSize) {\n                  let sampleOffset = startSampleOffset + sampleIndex;\n                  const cdatSize = MuxerHelper.readUint32(fragment, sampleOffset); // get actual cdat size\n                  sampleOffset += 4;\n                  const cdatType = MuxerHelper.bin2str(fragment.subarray(sampleOffset, sampleOffset + 4));\n                  sampleOffset += 4;\n                  if (cdatType === 'cdat') {\n                      if (cdatSize !== sampleSize) {\n                          getLogger().debug(loggerName$c, `clcp track: cdatSize ${cdatSize} @ offset ${sampleOffset}; sampleSize ${sampleSize}`);\n                      }\n                      const actualDataSize = cdatSize - 8;\n                      const rawData = fragment.subarray(sampleOffset, sampleOffset + actualDataSize);\n                      totalSize += actualDataSize;\n                      samples.push(rawData);\n                      sampleIndex += cdatSize; // actualDataSize + 8\n                  }\n                  else {\n                      getLogger().debug(loggerName$c, `clcp track: unknown atom type ${cdatType}`);\n                      break;\n                  }\n              }\n              return { cdatList: samples, cdatTotalSize: totalSize };\n          }\n          // TODOs:\n          // * Parse cdt2 data\n          // * Handle 64-bit length in tfhd > baseDataOffset\n          static parseSamples(startDTS, fragment, track, iframeDuration, useSEICaptions, maxSamples) {\n              const timescale = track.timescale;\n              const trackId = track.id;\n              let pts = startDTS;\n              let parsedSampleCount = 0;\n              let sampleAuxInfo;\n              let isHEVCFlavor = false;\n              const moofs = MuxerHelper.findBoxWithOffset(fragment, 0, ['moof']);\n              moofs.map(function (moofTuple) {\n                  const moof = moofTuple.data;\n                  const moofOffset = moofTuple.offset;\n                  const trafs = MuxerHelper.findBox(moof, ['traf']);\n                  trafs.map(function (traf) {\n                      // get the base media decode time from the tfdt\n                      const baseTime = MuxerHelper.findBox(traf, ['tfdt']).map(function (tfdt) {\n                          let result;\n                          const version = tfdt[0];\n                          result = MuxerHelper.readUint32(tfdt, 4);\n                          if (version === 1) {\n                              result *= Math.pow(2, 32);\n                              result += MuxerHelper.readUint32(tfdt, 8);\n                          }\n                          return result / timescale;\n                      })[0];\n                      if (baseTime !== undefined) {\n                          pts = baseTime;\n                      }\n                      return MuxerHelper.findBox(traf, ['tfhd']).map(function (tfhd) {\n                          // tfhd default values\n                          const id = MuxerHelper.readUint32(tfhd, 4);\n                          const tfhdFlags = MuxerHelper.readUint32(tfhd, 0) & 16777215;\n                          const baseDataOffsetPresent = (tfhdFlags & 1) !== 0;\n                          const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0;\n                          const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0;\n                          let defaultSampleDuration = 0;\n                          const defaultSampleSizePresent = (tfhdFlags & 16) !== 0;\n                          let defaultSampleSize = 0;\n                          const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0;\n                          // let durationIsEmpty = (tfhdFlags & 0x010000) !== 0;\n                          // let defaultBaseIsMoof = (tfhdFlags & 0x020000) !== 0;\n                          let tfhdOffset = 8;\n                          if (isFiniteNumber(track.defaultSampleSize)) {\n                              defaultSampleSize = track.defaultSampleSize;\n                          }\n                          if (id === trackId) {\n                              if (baseDataOffsetPresent) {\n                                  MuxerHelper.readUint32(tfhd, tfhdOffset); // Should be 64-bit\n                                  tfhdOffset += 4;\n                                  const mustBeZeroes = MuxerHelper.readUint32(tfhd, tfhdOffset);\n                                  tfhdOffset += 4;\n                                  if (mustBeZeroes !== 0) {\n                                      getLogger().info(loggerName$c, 'tfhd baseDataOffset has 64-bit value. Caption should be turned off');\n                                  }\n                              }\n                              if (sampleDescriptionIndexPresent) {\n                                  MuxerHelper.readUint32(tfhd, tfhdOffset);\n                                  tfhdOffset += 4;\n                              }\n                              if (defaultSampleDurationPresent) {\n                                  defaultSampleDuration = MuxerHelper.readUint32(tfhd, tfhdOffset);\n                                  tfhdOffset += 4;\n                              }\n                              if (defaultSampleSizePresent) {\n                                  defaultSampleSize = MuxerHelper.readUint32(tfhd, tfhdOffset);\n                                  tfhdOffset += 4;\n                              }\n                              if (defaultSampleFlagsPresent) {\n                                  MuxerHelper.readUint32(tfhd, tfhdOffset);\n                                  tfhdOffset += 4;\n                              }\n                              if (track.type === 'video') {\n                                  let subsampleOffset = 0, subsampleSize = 0;\n                                  // only use the first one\n                                  MuxerHelper.findBox(traf, ['saio']).map(function (saio) {\n                                      subsampleOffset = MP4Demuxer.parseSAIO(saio);\n                                  });\n                                  MuxerHelper.findBox(traf, ['saiz']).map(function (saiz) {\n                                      subsampleSize = MP4Demuxer.parseSAIZ(saiz);\n                                  });\n                                  if (subsampleOffset && subsampleSize) {\n                                      sampleAuxInfo = MP4Demuxer.parseSubsample(track.defaultPerSampleIVSize, fragment.subarray(subsampleOffset, subsampleOffset + subsampleSize));\n                                  }\n                                  isHEVCFlavor = MP4Demuxer.isHEVCFlavor(track.codec);\n                              }\n                              MuxerHelper.findBox(traf, ['trun']).map(function (trun) {\n                                  // trun specific values\n                                  const version = trun[0];\n                                  const flags = MuxerHelper.readUint32(trun, 0) & 16777215;\n                                  const dataOffsetPresent = (flags & 1) !== 0;\n                                  let dataOffset = 0;\n                                  const firstSampleFlagsPresent = (flags & 4) !== 0;\n                                  const sampleDurationPresent = (flags & 256) !== 0;\n                                  let sampleDuration = 0;\n                                  const sampleSizePresent = (flags & 512) !== 0;\n                                  let sampleSize = 0;\n                                  const sampleFlagsPresent = (flags & 1024) !== 0;\n                                  const sampleCompositionOffsetsPresent = (flags & 2048) !== 0;\n                                  let compositionOffset = 0;\n                                  const sampleCount = MuxerHelper.readUint32(trun, 4);\n                                  let trunOffset = 8; // past version, flags, and sample count\n                                  if (dataOffsetPresent) {\n                                      dataOffset = MuxerHelper.readUint32(trun, trunOffset);\n                                      trunOffset += 4;\n                                  }\n                                  if (firstSampleFlagsPresent) {\n                                      trunOffset += 4;\n                                  }\n                                  let sampleOffset = dataOffset + moofOffset;\n                                  for (let ix = 0; ix < sampleCount && (maxSamples < 0 || parsedSampleCount < maxSamples); ix++) {\n                                      if (sampleDurationPresent) {\n                                          sampleDuration = MuxerHelper.readUint32(trun, trunOffset);\n                                          trunOffset += 4;\n                                      }\n                                      else {\n                                          sampleDuration = defaultSampleDuration;\n                                      }\n                                      if (sampleSizePresent) {\n                                          sampleSize = MuxerHelper.readUint32(trun, trunOffset);\n                                          trunOffset += 4;\n                                      }\n                                      else {\n                                          sampleSize = defaultSampleSize;\n                                      }\n                                      if (sampleFlagsPresent) {\n                                          trunOffset += 4;\n                                      }\n                                      if (sampleCompositionOffsetsPresent) {\n                                          if (version === 0) {\n                                              compositionOffset = MuxerHelper.readUint32(trun, trunOffset);\n                                          }\n                                          else {\n                                              compositionOffset = MuxerHelper.readSint32(trun, trunOffset);\n                                          }\n                                          trunOffset += 4;\n                                      }\n                                      // TODO: make this more generic\n                                      if (track.type === 'video') {\n                                          if (!isFiniteNumber(iframeDuration)) {\n                                              // non iframe\n                                              track.fragmentDuration += sampleDuration;\n                                              if (useSEICaptions) {\n                                                  let naluTotalSize = 0;\n                                                  // hijacking sei parsing to get video duration\n                                                  while (naluTotalSize < sampleSize) {\n                                                      const naluSize = MuxerHelper.readUint32(fragment, sampleOffset);\n                                                      sampleOffset += 4;\n                                                      const naluType = fragment[sampleOffset] & 31;\n                                                      if (!track.seiSamples) {\n                                                          track.seiSamples = [];\n                                                      }\n                                                      if (MP4Demuxer.isSEIMessage(isHEVCFlavor, naluType)) {\n                                                          const sampleData = fragment.subarray(sampleOffset, sampleOffset + naluSize);\n                                                          track.seiSamples.push({ pts: pts + compositionOffset / timescale, type: naluType, data: sampleData, sampleOffset: sampleOffset, naluSize: naluSize });\n                                                      }\n                                                      sampleOffset += naluSize;\n                                                      naluTotalSize += naluSize + 4;\n                                                  }\n                                              }\n                                          }\n                                          else {\n                                              // iframe\n                                              track.samples.push({\n                                                  data: fragment.subarray(sampleOffset, sampleOffset + sampleSize),\n                                                  size: sampleSize,\n                                                  duration: iframeDuration * timescale,\n                                                  cts: 0,\n                                                  flags: {\n                                                      isLeading: 0,\n                                                      isDependedOn: 0,\n                                                      hasRedundancy: 0,\n                                                      degradPrio: 0,\n                                                      dependsOn: 2,\n                                                      isNonSync: 0,\n                                                      paddingValue: 0,\n                                                  },\n                                                  subsamples: sampleAuxInfo ? sampleAuxInfo.subsamples : [],\n                                                  iv: sampleAuxInfo ? sampleAuxInfo.iv : undefined,\n                                              });\n                                          }\n                                      }\n                                      else if (track.type === 'audio') {\n                                          track.fragmentDuration += sampleDuration;\n                                      }\n                                      else if (track.type === 'caption') {\n                                          const { cdatList, cdatTotalSize } = MP4Demuxer.parseCLCPSample(fragment, sampleOffset, sampleSize);\n                                          sampleOffset += sampleSize;\n                                          if (cdatList.length) {\n                                              let cdatArray;\n                                              if (cdatList.length === 1) {\n                                                  cdatArray = new Uint8Array(cdatList[0]);\n                                              }\n                                              else if (cdatList.length > 1) {\n                                                  let offset = 0;\n                                                  cdatArray = new Uint8Array(cdatTotalSize);\n                                                  for (const arr of cdatList) {\n                                                      cdatArray.set(arr, offset);\n                                                      offset += arr.length;\n                                                  }\n                                              }\n                                              track.captionSamples.push({ type: 3, pts: pts, bytes: cdatArray });\n                                          }\n                                      }\n                                      parsedSampleCount++;\n                                      pts += sampleDuration / timescale;\n                                  } // for ix\n                              }); // trun map\n                          } // if (id == trackId)\n                      }); // tfhd map\n                  }); // traf map\n              }); // moof map\n          }\n          static parseEmsg(data) {\n              const version = data[0];\n              let schemeIdUri = '';\n              let value = '';\n              let timeScale;\n              let presentationTimeDelta;\n              let presentationTime;\n              let eventDuration;\n              let id;\n              let offset = 0;\n              if (version === 0) {\n                  while (MuxerHelper.bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n                      schemeIdUri += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                      offset += 1;\n                  }\n                  schemeIdUri += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                  offset += 1;\n                  while (MuxerHelper.bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n                      value += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                      offset += 1;\n                  }\n                  value += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                  offset += 1;\n                  timeScale = MuxerHelper.readUint32(data, 12);\n                  presentationTimeDelta = MuxerHelper.readUint32(data, 16);\n                  eventDuration = MuxerHelper.readUint32(data, 20);\n                  id = MuxerHelper.readUint32(data, 24);\n                  offset = 28;\n              }\n              else {\n                  offset += 4;\n                  timeScale = MuxerHelper.readUint32(data, offset);\n                  offset += 4;\n                  const leftPresentationTime = MuxerHelper.readUint32(data, offset);\n                  offset += 4;\n                  const rightPresentationTime = MuxerHelper.readUint32(data, offset);\n                  offset += 4;\n                  presentationTime = Math.pow(2, 32) * leftPresentationTime + rightPresentationTime;\n                  if (!Number.isSafeInteger(presentationTime)) {\n                      presentationTime = Number.MAX_SAFE_INTEGER;\n                      getLogger().warn(loggerName$c, 'Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');\n                  }\n                  eventDuration = MuxerHelper.readUint32(data, offset);\n                  offset += 4;\n                  id = MuxerHelper.readUint32(data, offset);\n                  offset += 4;\n                  while (MuxerHelper.bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n                      schemeIdUri += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                      offset += 1;\n                  }\n                  schemeIdUri += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                  offset += 1;\n                  while (MuxerHelper.bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n                      value += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                      offset += 1;\n                  }\n                  value += MuxerHelper.bin2str(data.subarray(offset, offset + 1));\n                  offset += 1;\n              }\n              const payload = data.subarray(offset, data.byteLength);\n              return { schemeIdUri, value, timeScale, presentationTime, presentationTimeDelta, eventDuration, id, payload };\n          }\n          static extractID3PayloadCreateID3Track(emsgInfo, timeOffset, id3Track, logger) {\n              const id3 = new ID3$1(emsgInfo.payload, logger);\n              const data = new Uint8Array(emsgInfo.payload);\n              const length = data.byteLength;\n              let frameIndex = 0;\n              let offset = 0;\n              const pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;\n              if (!isFiniteNumber(pts)) {\n                  getLogger().error(loggerName$c, 'No pts found in emsg info when extracting ID3 payload');\n                  return;\n              }\n              const frameDuration = emsgInfo.eventDuration;\n              const header = data.subarray(0, 10);\n              const fileIdentifier = MuxerHelper.bin2str(header.subarray(offset, offset + 3));\n              offset += 3;\n              if (fileIdentifier !== 'ID3') {\n                  getLogger().error(loggerName$c, 'No ID3 tag found when extracting ID3 payload');\n              }\n              // skip versions\n              offset += 2;\n              const flags = data.subarray(offset, offset + 1);\n              const extendedHeader = flags[0] & 64;\n              const footerPresent = flags[0] & 16;\n              offset += 1;\n              ID3$1.readSynchSafeUint32(data.subarray(offset, offset + 4));\n              offset += 4;\n              if (extendedHeader) {\n                  const extHeaderSize = ID3$1.readSynchSafeUint32(data.subarray(offset, offset + 4));\n                  offset += 4;\n                  offset += extHeaderSize;\n              }\n              while (offset + 2 < length) {\n                  let frameId = '';\n                  frameId += MuxerHelper.bin2str(data.subarray(offset, offset + 4));\n                  offset += 4;\n                  const frameLength = ID3$1.readSynchSafeUint32(data.subarray(offset, offset + 4));\n                  offset += 4;\n                  const stamp = pts + frameIndex * frameDuration;\n                  const id3Sample = { data: data, pts: stamp, dts: stamp, keyTagInfo: undefined, frames: id3.frames };\n                  id3Track.id3Samples.push(id3Sample);\n                  offset += frameLength;\n                  frameIndex++;\n                  if (footerPresent) {\n                      const di3 = MuxerHelper.bin2str(data.subarray(offset, offset + 3));\n                      if (di3 !== 'DI3') {\n                          getLogger().error(loggerName$c, 'End should be DI3 if footer present in extracting ID3 payload');\n                      }\n                      offset += 3;\n                      // skip remaining 7 bits\n                      offset += 7;\n                  }\n              }\n              if (offset + 2 === length) {\n                  const padding = MuxerHelper.readUint16(data, offset);\n                  if (padding !== 0) {\n                      getLogger().warn(loggerName$c, 'Padding should be 0 when extracting ID3 payload');\n                  }\n              }\n          }\n          /**\n           * @param data\n           * @param timeOffset  The position in the media element corresponding to this fragment at rate 1\n           * @param contiguous  Contiguous with previously appeneded fragment\n           * @param keyTagInfo Object describing information about the key that was used to encrypt data\n           * @param iframeMediaStart  If remuxing for iframe, the time in media element to remux fragment to\n           * @param iframeDuration    If remuxing for iframe, the duration to remux fragment to\n           */\n          append(data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo, iframeMediaStart, iframeDuration) {\n              let initData = this.initData;\n              let videoDuration = 0, audioDuration = 0;\n              let hasVideo = false, hasAudio = false;\n              if (typeof initData === 'undefined') {\n                  this.resetInitSegment(data, 0);\n                  initData = this.initData;\n              }\n              let initPtsTs = this.initPtsTs;\n              let startDtsTs;\n              if (!initPtsTs) {\n                  startDtsTs = MP4Demuxer.getStartDtsTs(initData, data);\n                  this.initPtsTs = initPtsTs = { baseTime: startDtsTs.baseTime - Math.round(timeOffset * startDtsTs.timescale), timescale: startDtsTs.timescale };\n                  this.observer.trigger(DemuxerEvent.INIT_PTS_FOUND, { initPTS: initPtsTs });\n              }\n              if (initData.foundLargeTimescale && MP4Demuxer.has32BitTfdts(data) && !iframeDuration) {\n                  data = MP4EncryptionRemuxer.remuxOverflowSegment(data, this.logger);\n              }\n              // Don't remux start DTS, will be adjusted in source buffer timestampOffset instead\n              startDtsTs = MP4Demuxer.getStartDtsTs(initData, data);\n              const emsgs = MuxerHelper.findBox(data, ['emsg']);\n              if (initData.video && initData.video.encrypted) {\n                  // Check for 'senc' or 'saiz' && 'saio'\n                  const trafs = MuxerHelper.findBox(data, ['moof', 'traf']);\n                  const gotSubsamples = trafs.find(function (traf) {\n                      return Boolean(MuxerHelper.findBox(traf, ['senc'])[0] || (MuxerHelper.findBox(traf, ['saiz'])[0] && MuxerHelper.findBox(traf, ['saio'])[0]));\n                  });\n                  if (!gotSubsamples) {\n                      this.logger.warn(loggerName$c, `Missing subsample information for encrypted content codec=${initData.videoCodec}`);\n                  }\n              }\n              if (iframeDuration) {\n                  const timescale = this._videoTrack.timescale;\n                  // snap the iframe durations so added the durations will result in timestamps that are always accurately representable when converted to uints\n                  // we want to use ceil so durations aren't reduced, otherwise the same iframe could get chosen in the next round.\n                  iframeDuration = Math.ceil(iframeDuration * timescale) / timescale;\n                  // iframe timestamps are written directly, not offset, so we have to add the audioPrimingDelay since it'll\n                  // still be shifted by the sourceBuffer.timestampOffset\n                  const startDtsSec = (startDtsTs.baseTime + this.audioPrimingDelay * startDtsTs.timescale) / startDtsTs.timescale;\n                  if (this._videoTrack && this._audioTrack && !this._silentAudioTrack) {\n                      const silentTrackBase = SilentAudio.getTrack(this.observer, this._audioTrack.id, this._audioTrack.codec, 2, this.logger);\n                      if (!silentTrackBase) {\n                          throw `unable to create silent audio track for codec ${this._audioTrack.codec}`;\n                      }\n                      this._silentAudioTrack = Object.assign(Object.assign({}, silentTrackBase), { sequenceNumber: 0 });\n                      const iframeInitSegment = MP4$1.initSegment([this._videoTrack, this._silentAudioTrack]);\n                      this.remuxedInitDataTrack = { type: 'audiovideo', container: 'video/mp4', codec: this._silentAudioTrack.config.codec + ',' + this._videoTrack.codec, initSegment: iframeInitSegment };\n                      const data = { track: this.remuxedInitDataTrack };\n                      this.observer.trigger(DemuxerEvent.FRAG_PARSING_INIT_SEGMENT, data);\n                  }\n                  MP4Demuxer.parseSamples(startDtsSec, data, this._videoTrack, iframeDuration, false, 1);\n                  this.mp4Remuxer.remuxIFrame(startDtsSec, this._videoTrack, this._silentAudioTrack, iframeDuration, this.remuxedInitDataTrack);\n                  this._videoTrack.samples = [];\n              }\n              else {\n                  let startDtsSec = (startDtsTs.baseTime - this.audioPrimingDelay * startDtsTs.timescale) / startDtsTs.timescale;\n                  startDtsSec = Math.max(0, startDtsSec);\n                  if (emsgs && emsgs.length > 0) {\n                      const emsgsInfos = emsgs.map((emsg) => {\n                          const emsgInfo = MP4Demuxer.parseEmsg(emsg);\n                          // HLSJS only processes id3 tags in emsgs\n                          if (emsgInfo.schemeIdUri === 'https://aomedia.org/emsg/ID3\\0' && !this._id3Track) {\n                              this._id3Track = { id3Samples: [], inputTimescale: 90000 };\n                          }\n                          return emsgInfo;\n                      });\n                      if (this._id3Track) {\n                          emsgsInfos.map((emsgInfo) => {\n                              MP4Demuxer.extractID3PayloadCreateID3Track(emsgInfo, timeOffset, this._id3Track, this.logger);\n                          });\n                      }\n                  }\n                  if (this._videoTrack) {\n                      MP4Demuxer.parseSamples(startDtsSec, data, this._videoTrack, undefined, this.trySEICaptions, -1);\n                      videoDuration = this._videoTrack.fragmentDuration / this._videoTrack.timescale;\n                      hasVideo = true;\n                      this._videoTrack.fragmentDuration = 0;\n                      this.logger.info(loggerName$c, `frag video duration: ${videoDuration}`);\n                      if (this.trySEICaptions) {\n                          MP4Demuxer.extractSEICaptionsFromNALu(this._videoTrack.seiSamples, this._captionTrack);\n                          this._videoTrack.seiSamples = [];\n                          this.logger.info(loggerName$c, `sei samples: ${this._captionTrack.captionSamples.length}`);\n                      }\n                      else if (this._captionTrack) {\n                          // clcp text track\n                          MP4Demuxer.parseSamples(startDtsSec, data, this._captionTrack, undefined, false, Number.MAX_SAFE_INTEGER);\n                      }\n                  }\n                  if (this._audioTrack) {\n                      MP4Demuxer.parseSamples(startDtsSec, data, this._audioTrack, undefined, false, -1);\n                      audioDuration = this._audioTrack.fragmentDuration / this._audioTrack.timescale;\n                      hasAudio = true;\n                      this._audioTrack.fragmentDuration = 0;\n                  }\n                  this.mp4Remuxer.remuxEmsgAndRawData(audioDuration, hasAudio, videoDuration, hasVideo, this._captionTrack, this._id3Track, startDtsSec, startDtsTs.timescale, data, this.remuxedInitDataTrack);\n                  if (this._id3Track) {\n                      this._id3Track.id3Samples = [];\n                  }\n              }\n          }\n          static extractSEICaptionsFromNALu(units, textTrack) {\n              if (!units) {\n                  return;\n              }\n              for (let u = 0; u < units.length; ++u) {\n                  const unit = units[u];\n                  const pts = unit.pts;\n                  let seiPtr = 0;\n                  seiPtr++;\n                  let payloadType = 0;\n                  let payloadSize = 0;\n                  let endOfCaptions = false;\n                  let b = 0;\n                  while (!endOfCaptions && seiPtr < unit.data.length) {\n                      payloadType = 0;\n                      do {\n                          if (seiPtr >= unit.data.length) {\n                              break;\n                          }\n                          b = unit.data[seiPtr++];\n                          payloadType += b;\n                      } while (b === 255);\n                      // Parse payload size.\n                      payloadSize = 0;\n                      do {\n                          if (seiPtr >= unit.data.length) {\n                              break;\n                          }\n                          b = unit.data[seiPtr++];\n                          payloadSize += b;\n                      } while (b === 255);\n                      const leftOver = unit.data.length - seiPtr;\n                      if (payloadType === 4 && seiPtr < unit.data.length) {\n                          endOfCaptions = true;\n                          const countryCode = unit.data[seiPtr++];\n                          if (countryCode === 181) {\n                              const providerCode = MuxerHelper.readUint16(unit.data, seiPtr);\n                              seiPtr += 2;\n                              if (providerCode === 49) {\n                                  const userStructure = MuxerHelper.readUint32(unit.data, seiPtr);\n                                  seiPtr += 4;\n                                  if (userStructure === 1195456820) {\n                                      const userDataType = unit.data[seiPtr++];\n                                      // Raw CEA-608 bytes wrapped in CEA-708 packet\n                                      if (userDataType === 3) {\n                                          const firstByte = unit.data[seiPtr++];\n                                          seiPtr++; // skip second byte\n                                          const totalCCs = 31 & firstByte;\n                                          const enabled = 64 & firstByte;\n                                          const byteArray = [];\n                                          if (enabled) {\n                                              for (let i = 0; i < totalCCs; i++) {\n                                                  const ccData = unit.data[seiPtr++];\n                                                  const ccDataChecked = ccData & 252;\n                                                  if (ccData === ccDataChecked) {\n                                                      // valid ccData\n                                                      const ccType = ccData & 3;\n                                                      if (0 === ccType || 1 === ccType) {\n                                                          // Exclude CEA708 CC data.\n                                                          const b1 = unit.data[seiPtr++];\n                                                          const b2 = unit.data[seiPtr++];\n                                                          byteArray.push(b1);\n                                                          byteArray.push(b2);\n                                                      }\n                                                  }\n                                                  else {\n                                                      seiPtr += 2; // Skip byte pair too\n                                                  }\n                                              }\n                                          }\n                                          if (byteArray.length > 0) {\n                                              textTrack.captionSamples.push({ type: 3, pts: pts, bytes: byteArray });\n                                          }\n                                      }\n                                  }\n                              }\n                          }\n                      }\n                      else if (payloadSize < leftOver) {\n                          seiPtr += payloadSize;\n                      }\n                      else if (payloadSize > leftOver) {\n                          break;\n                      }\n                  }\n              }\n              return textTrack;\n          }\n      }\n    \n      \n      const loggerName$b = { name: 'ExpGolomb' };\n      class ExpGolomb {\n          constructor(data, logger) {\n              this.data = data;\n              this.logger = logger;\n              // the number of bytes left to examine in this.data\n              this._bytesAvailable = data.byteLength;\n              // the current word being examined\n              this.word = 0; // :uint\n              // the number of bits left to examine in the current word\n              this.bitsAvailable = 0; // :uint\n          }\n          get bytesAvailable() {\n              return this._bytesAvailable;\n          }\n          loadWord() {\n              const data = this.data, bytesAvailable = this._bytesAvailable, position = data.byteLength - bytesAvailable, workingBytes = new Uint8Array(4), availableBytes = Math.min(4, bytesAvailable);\n              if (availableBytes === 0) {\n                  throw new Error('no bytes available');\n              }\n              workingBytes.set(data.subarray(position, position + availableBytes));\n              this.word = new DataView(workingBytes.buffer).getUint32(0);\n              // track the amount of this.data that has been processed\n              this.bitsAvailable = availableBytes * 8;\n              this._bytesAvailable -= availableBytes;\n          }\n          skipBits(count) {\n              let skipBytes; // :int\n              if (this.bitsAvailable > count) {\n                  this.word <<= count;\n                  this.bitsAvailable -= count;\n              }\n              else {\n                  count -= this.bitsAvailable;\n                  skipBytes = count >> 3;\n                  count -= skipBytes >> 3;\n                  this._bytesAvailable -= skipBytes;\n                  this.loadWord();\n                  this.word <<= count;\n                  this.bitsAvailable -= count;\n              }\n          }\n          readBits(size) {\n              let bits = Math.min(this.bitsAvailable, size); // :uint\n              const valu = this.word >>> (32 - bits); // :uint\n              if (size > 32) {\n                  this.logger.error(loggerName$b, 'Cannot read more than 32 bits at a time');\n              }\n              this.bitsAvailable -= bits;\n              if (this.bitsAvailable > 0) {\n                  this.word <<= bits;\n              }\n              else if (this._bytesAvailable > 0) {\n                  this.loadWord();\n              }\n              bits = size - bits;\n              if (bits > 0 && this.bitsAvailable) {\n                  return (valu << bits) | this.readBits(bits);\n              }\n              else {\n                  return valu;\n              }\n          }\n          // ():uint\n          skipLZ() {\n              let leadingZeroCount; // :uint\n              for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n                  if (0 !== (this.word & (2147483648 >>> leadingZeroCount))) {\n                      // the first bit of working word is 1\n                      this.word <<= leadingZeroCount;\n                      this.bitsAvailable -= leadingZeroCount;\n                      return leadingZeroCount;\n                  }\n              }\n              // we exhausted word and still have not found a 1\n              this.loadWord();\n              return leadingZeroCount + this.skipLZ();\n          }\n          // ():void\n          skipUEG() {\n              this.skipBits(1 + this.skipLZ());\n          }\n          // ():void\n          skipEG() {\n              this.skipBits(1 + this.skipLZ());\n          }\n          // ():uint\n          readUEG() {\n              const clz = this.skipLZ(); // :uint\n              return this.readBits(clz + 1) - 1;\n          }\n          // ():int\n          readEG() {\n              const valu = this.readUEG(); // :int\n              if (1 & valu) {\n                  // the number is odd if the low order bit is set\n                  return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n              }\n              else {\n                  return -1 * (valu >>> 1); // divide by two then make it negative\n              }\n          }\n          // Some convenience functions\n          // :Boolean\n          readBoolean() {\n              return 1 === this.readBits(1);\n          }\n          // ():int\n          readUByte() {\n              return this.readBits(8);\n          }\n          // ():int\n          readUShort() {\n              return this.readBits(16);\n          }\n          // ():int\n          readUInt() {\n              return this.readBits(32);\n          }\n          /**\n           * Advance the ExpGolomb decoder past a scaling list. The scaling\n           * list is optionally transmitted as part of a sequence parameter\n           * set and is not relevant to transmuxing.\n           * @param count {number} the number of entries in this scaling list\n           * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n           */\n          skipScalingList(count) {\n              let lastScale = 8, nextScale = 8, j, deltaScale;\n              for (j = 0; j < count; j++) {\n                  if (nextScale !== 0) {\n                      deltaScale = this.readEG();\n                      nextScale = (lastScale + deltaScale + 256) % 256;\n                  }\n                  lastScale = nextScale === 0 ? lastScale : nextScale;\n              }\n          }\n          /**\n           * Read a sequence parameter set and return some interesting video\n           * properties. A sequence parameter set is the H264 metadata that\n           * describes the properties of upcoming video frames.\n           * @param data {Uint8Array} the bytes of a sequence parameter set\n           * @return {object} an object with configuration parsed from the\n           * sequence parameter set, including the dimensions of the\n           * associated video frames.\n           */\n          readSPS() {\n              let frameCropLeftOffset = 0, frameCropRightOffset = 0, frameCropTopOffset = 0, frameCropBottomOffset = 0, numRefFramesInPicOrderCntCycle, scalingListCount, i;\n              const readUByte = this.readUByte.bind(this), readBits = this.readBits.bind(this), readUEG = this.readUEG.bind(this), readBoolean = this.readBoolean.bind(this), skipBits = this.skipBits.bind(this), skipEG = this.skipEG.bind(this), skipUEG = this.skipUEG.bind(this), skipScalingList = this.skipScalingList.bind(this);\n              readUByte();\n              const profileIdc = readUByte(); // profile_idc\n              readBits(5); // constraint_set[0-4]_flag, u(5)\n              skipBits(3); // reserved_zero_3bits u(3),\n              readUByte(); // level_idc u(8)\n              skipUEG(); // seq_parameter_set_id\n              // some profiles have more optional data we don't need\n              if (profileIdc === 100 ||\n                  profileIdc === 110 ||\n                  profileIdc === 122 ||\n                  profileIdc === 244 ||\n                  profileIdc === 44 ||\n                  profileIdc === 83 ||\n                  profileIdc === 86 ||\n                  profileIdc === 118 ||\n                  profileIdc === 128) {\n                  const chromaFormatIdc = readUEG();\n                  if (chromaFormatIdc === 3) {\n                      skipBits(1); // separate_colour_plane_flag\n                  }\n                  skipUEG(); // bit_depth_luma_minus8\n                  skipUEG(); // bit_depth_chroma_minus8\n                  skipBits(1); // qpprime_y_zero_transform_bypass_flag\n                  if (readBoolean()) {\n                      // seq_scaling_matrix_present_flag\n                      scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n                      for (i = 0; i < scalingListCount; i++) {\n                          if (readBoolean()) {\n                              // seq_scaling_list_present_flag[ i ]\n                              if (i < 6) {\n                                  skipScalingList(16);\n                              }\n                              else {\n                                  skipScalingList(64);\n                              }\n                          }\n                      }\n                  }\n              }\n              skipUEG(); // log2_max_frame_num_minus4\n              const picOrderCntType = readUEG();\n              if (picOrderCntType === 0) {\n                  readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n              }\n              else if (picOrderCntType === 1) {\n                  skipBits(1); // delta_pic_order_always_zero_flag\n                  skipEG(); // offset_for_non_ref_pic\n                  skipEG(); // offset_for_top_to_bottom_field\n                  numRefFramesInPicOrderCntCycle = readUEG();\n                  for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n                      skipEG(); // offset_for_ref_frame[ i ]\n                  }\n              }\n              skipUEG(); // max_num_ref_frames\n              skipBits(1); // gaps_in_frame_num_value_allowed_flag\n              const picWidthInMbsMinus1 = readUEG();\n              const picHeightInMapUnitsMinus1 = readUEG();\n              const frameMbsOnlyFlag = readBits(1);\n              if (frameMbsOnlyFlag === 0) {\n                  skipBits(1); // mb_adaptive_frame_field_flag\n              }\n              skipBits(1); // direct_8x8_inference_flag\n              if (readBoolean()) {\n                  // frame_cropping_flag\n                  frameCropLeftOffset = readUEG();\n                  frameCropRightOffset = readUEG();\n                  frameCropTopOffset = readUEG();\n                  frameCropBottomOffset = readUEG();\n              }\n              let pixelRatio = [1, 1];\n              if (readBoolean()) {\n                  // vui_parameters_present_flag\n                  if (readBoolean()) {\n                      // aspect_ratio_info_present_flag\n                      const aspectRatioIdc = readUByte();\n                      switch (aspectRatioIdc) {\n                          case 1:\n                              pixelRatio = [1, 1];\n                              break;\n                          case 2:\n                              pixelRatio = [12, 11];\n                              break;\n                          case 3:\n                              pixelRatio = [10, 11];\n                              break;\n                          case 4:\n                              pixelRatio = [16, 11];\n                              break;\n                          case 5:\n                              pixelRatio = [40, 33];\n                              break;\n                          case 6:\n                              pixelRatio = [24, 11];\n                              break;\n                          case 7:\n                              pixelRatio = [20, 11];\n                              break;\n                          case 8:\n                              pixelRatio = [32, 11];\n                              break;\n                          case 9:\n                              pixelRatio = [80, 33];\n                              break;\n                          case 10:\n                              pixelRatio = [18, 11];\n                              break;\n                          case 11:\n                              pixelRatio = [15, 11];\n                              break;\n                          case 12:\n                              pixelRatio = [64, 33];\n                              break;\n                          case 13:\n                              pixelRatio = [160, 99];\n                              break;\n                          case 14:\n                              pixelRatio = [4, 3];\n                              break;\n                          case 15:\n                              pixelRatio = [3, 2];\n                              break;\n                          case 16:\n                              pixelRatio = [2, 1];\n                              break;\n                          case 255: {\n                              pixelRatio = [(readUByte() << 8) | readUByte(), (readUByte() << 8) | readUByte()];\n                              break;\n                          }\n                      }\n                  }\n              }\n              return {\n                  width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),\n                  height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),\n                  pixelRatio: pixelRatio,\n              };\n          }\n          readSliceType() {\n              // skip NALu type\n              this.readUByte();\n              // discard first_mb_in_slice\n              this.readUEG();\n              // return slice_type\n              return this.readUEG();\n          }\n      }\n    \n      \n      const TIMESCALE = 90000;\n      const loggerName$a = { name: 'TS Demuxer' };\n      function isCompleteVideoConfig(config) {\n          const is = typeof config.codec === 'string' &&\n              Array.isArray(config.sps) &&\n              Array.isArray(config.pps) &&\n              typeof config.width === 'number' &&\n              typeof config.height === 'number' &&\n              Array.isArray(config.pixelRatio);\n          return is;\n      }\n      class TsDemuxer extends EsDemuxer {\n          constructor(observer, remuxer, config, typeSupported, logger) {\n              super(observer, remuxer, config, typeSupported, logger);\n          }\n          static probe(data, logger) {\n              // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n              if (data.length >= 564 && data[0] === 71 && data[188] === 71 && data[376] === 71) {\n                  return true;\n              }\n              else {\n                  return false;\n              }\n          }\n          resetInitSegment(initSegment, duration, keyTagInfo) {\n              this.pmtParsed = false;\n              this._pmtId = -1;\n              const baseInfo = { id: -1, inputTimescale: TIMESCALE, timescale: NaN, duration: 0, encrypted: keyTagInfo && keyTagInfo.isEncrypted, keyTagInfo };\n              const baseParsingInfo = { len: 0, sequenceNumber: 0 };\n              this._avcContext = { info: Object.assign({}, baseInfo), parsingData: Object.assign(Object.assign({}, baseParsingInfo), { esSamples: new Array(), dropped: 0 }), config: {}, container: 'video/mp2t', type: 'video' };\n              this._audioContext = { info: Object.assign({}, baseInfo), parsingData: Object.assign(Object.assign({}, baseParsingInfo), { esSamples: new Array() }), container: 'video/mp2t', type: 'audio' };\n              this._id3Track = { id: -1, inputTimescale: TIMESCALE, id3Samples: [] };\n              this._txtTrack = { inputTimescale: TIMESCALE, captionSamples: [] };\n              this._duration = duration;\n              this._initSegment = initSegment;\n          }\n          // feed incoming data to the front of the parsing pipeline\n          append(data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo, iframeMediaStart, iframeDuration) {\n              let start, stt, pid, atf, offset, pes, unknownPIDs = false;\n              this.contiguous = contiguous;\n              const avcContext = this._avcContext, audioContext = this._audioContext, id3Track = this._id3Track;\n              let pmtParsed = this.pmtParsed, avcId = avcContext.info.id, audioId = audioContext.info.id, id3Id = id3Track.id, pmtId = this._pmtId, avcData = avcContext.pesData, audioData = audioContext.pesData, id3Data = id3Track.pesData;\n              this.iframeMode = typeof iframeDuration !== 'undefined';\n              if (this._initSegment && this._initSegment.byteLength > 0) {\n                  // if there's an init segment then it needs to be prepended to the first data\n                  const newData = new Uint8Array(this._initSegment.byteLength + data.byteLength);\n                  newData.set(this._initSegment);\n                  newData.set(data, this._initSegment.byteLength);\n                  this._initSegment = undefined;\n                  // make sure its still valid TS\n                  if (newData[0] === 71) {\n                      data = newData;\n                  }\n              }\n              let len = data.length;\n              // don't parse last TS packet if incomplete\n              len -= len % 188;\n              // loop through TS packets\n              for (start = 0; start < len; start += 188) {\n                  if (data[start] === 71) {\n                      // payload unit start indicator - pes immediately follows the ts header\n                      stt = !!(data[start + 1] & 64);\n                      // pid is a 13-bit field starting at the last bit of TS[1]\n                      pid = ((data[start + 1] & 31) << 8) + data[start + 2];\n                      atf = (data[start + 3] & 48) >> 4;\n                      // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n                      if (atf > 1) {\n                          offset = start + 5 + data[start + 4];\n                          // continue if there is only adaptation field\n                          if (offset === start + 188) {\n                              continue;\n                          }\n                      }\n                      else {\n                          offset = start + 4;\n                      }\n                      switch (pid) {\n                          case avcId:\n                              if (stt) {\n                                  if (avcData && (pes = this._parsePES(avcData))) {\n                                      // new pes is starting and we have an current one, therefore the current pes is complete, so lets parse it\n                                      this._parseAVCPES(pes, false);\n                                  }\n                                  // reset the current pes data\n                                  avcData = { data: [], size: 0, keyTagInfo: keyTagInfo };\n                              }\n                              if (avcData) {\n                                  avcData.data.push(data.subarray(offset, start + 188));\n                                  avcData.size += start + 188 - offset;\n                              }\n                              break;\n                          case audioId:\n                              if (stt && !this.iframeMode) {\n                                  if (audioData && (pes = this._parsePES(audioData))) {\n                                      switch (audioContext.segmentCodec) {\n                                          case 'aac':\n                                              this._parseAACPES(pes);\n                                              break;\n                                          case 'mp3':\n                                              this._parseMPEGPES(pes);\n                                              break;\n                                          case 'ac3':\n                                          case 'ec3':\n                                              this._parseDolbyPES(pes);\n                                              break;\n                                      }\n                                  }\n                                  audioData = { data: [], size: 0, keyTagInfo: keyTagInfo };\n                              }\n                              if (audioData) {\n                                  audioData.data.push(data.subarray(offset, start + 188));\n                                  audioData.size += start + 188 - offset;\n                              }\n                              break;\n                          case id3Id:\n                              if (stt) {\n                                  if (id3Data && (pes = this._parsePES(id3Data))) {\n                                      id3Track.id3Samples.push(pes);\n                                  }\n                                  id3Data = { data: [], size: 0 };\n                              }\n                              if (id3Data) {\n                                  id3Data.data.push(data.subarray(offset, start + 188));\n                                  id3Data.size += start + 188 - offset;\n                              }\n                              break;\n                          case 0:\n                              if (stt) {\n                                  offset += data[offset] + 1;\n                              }\n                              pmtId = this._pmtId = this._parsePAT(data, offset);\n                              break;\n                          case pmtId:\n                              if (stt) {\n                                  offset += data[offset] + 1;\n                              }\n                              const parsedPIDs = this._parsePMT(data, offset, this.typeSupported);\n                              // only update track id if track PID found while parsing PMT\n                              // this is to avoid resetting the PID to -1 in case\n                              // track PID transiently disappears from the stream\n                              // this could happen in case of transient missing audio samples for example\n                              avcId = parsedPIDs.avcId;\n                              if (avcId > 0) {\n                                  avcContext.info.id = avcId;\n                                  avcContext.info.encrypted = parsedPIDs.videoEncrypted;\n                              }\n                              audioId = parsedPIDs.audioId;\n                              if (audioId > 0) {\n                                  audioContext.info.id = audioId;\n                                  audioContext.segmentCodec = parsedPIDs.audioSegmentCodec;\n                                  audioContext.info.encrypted = parsedPIDs.audioEncrypted;\n                              }\n                              id3Id = parsedPIDs.id3Id;\n                              if (id3Id > 0) {\n                                  id3Track.id = id3Id;\n                              }\n                              if (unknownPIDs && !pmtParsed) {\n                                  this.logger.info(loggerName$a, 'reparse from beginning');\n                                  unknownPIDs = false;\n                                  // we set it to -188, the += 188 in the for loop will reset start to 0\n                                  start = -188;\n                              }\n                              pmtParsed = this.pmtParsed = true;\n                              break;\n                          case 17: // eslint-disable-line\n                          case 8191:\n                              break;\n                          default:\n                              unknownPIDs = true;\n                              break;\n                      }\n                  }\n                  else {\n                      const payload = new FragParsingError(false, 'TS packet did not start with 0x47', ErrorResponses.NoTSSyncByteFound);\n                      this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return;\n                  }\n              }\n              // try to parse last PES packets\n              if (avcData && (pes = this._parsePES(avcData))) {\n                  this._parseAVCPES(pes, true);\n                  avcContext.pesData = undefined;\n              }\n              else {\n                  // either avcData null or PES truncated, keep it for next frag parsing\n                  avcContext.pesData = avcData;\n              }\n              if (audioData && (pes = this._parsePES(audioData))) {\n                  switch (audioContext.segmentCodec) {\n                      case 'aac':\n                          this._parseAACPES(pes);\n                          break;\n                      case 'mp3':\n                          this._parseMPEGPES(pes);\n                          break;\n                      case 'ac3':\n                      case 'ec3':\n                          this._parseDolbyPES(pes);\n                          break;\n                  }\n                  audioContext.pesData = undefined;\n              }\n              else {\n                  if (audioData && audioData.size) {\n                      this.logger.warn(loggerName$a, 'last AAC PES packet truncated,might overlap between fragments');\n                  }\n                  // either audioData null or PES truncated, keep it for next frag parsing\n                  audioContext.pesData = audioData;\n              }\n              if (id3Data && (pes = this._parsePES(id3Data))) {\n                  id3Track.id3Samples.push(pes);\n                  id3Track.pesData = undefined;\n              }\n              else {\n                  // either id3Data null or PES truncated, keep it for next frag parsing\n                  id3Track.pesData = id3Data;\n              }\n              let audioTrack;\n              if (audioContext.config && audioContext.segmentCodec) {\n                  audioTrack = { type: 'audio', info: audioContext.info, config: audioContext.config, parsingData: audioContext.parsingData };\n              }\n              let videoTrack;\n              const pc = avcContext.config;\n              if (isCompleteVideoConfig(pc)) {\n                  videoTrack = { type: 'video', info: avcContext.info, config: pc, parsingData: avcContext.parsingData };\n              }\n              this.esRemuxer.remuxEsTracks(audioTrack, videoTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset, keyTagInfo, iframeMediaStart, iframeDuration);\n          }\n          destroy() {\n              this._duration = 0;\n          }\n          _parsePAT(data, offset) {\n              // skip the PSI header and parse the first PMT entry\n              return ((data[offset + 10] & 31) << 8) | data[offset + 11];\n          }\n          _parsePMT(data, offset, typeSupported) {\n              let pid; // result = { audio : -1, avc : -1, id3 : -1, segmentCodec : 'aac', videoEncrypted : false, audioEncrypted :false };\n              const result = {\n                  audioId: -1,\n                  avcId: -1,\n                  id3Id: -1,\n                  audioEncrypted: false,\n                  videoEncrypted: false,\n              };\n              const sectionLength = ((data[offset + 1] & 15) << 8) | data[offset + 2];\n              const tableEnd = offset + 3 + sectionLength - 4;\n              // to determine where the table is, we have to figure out how\n              // long the program info descriptors are\n              const programInfoLength = ((data[offset + 10] & 15) << 8) | data[offset + 11];\n              // advance the offset to the first entry in the mapping table\n              offset += 12 + programInfoLength;\n              while (offset < tableEnd) {\n                  pid = ((data[offset + 1] & 31) << 8) | data[offset + 2];\n                  switch (data[offset]) {\n                      case 207:\n                          result.audioEncrypted = true;\n                      /* falls through */\n                      // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n                      case 15:\n                          // logger.info('AAC PID:'  + pid);\n                          if (result.audioId === -1) {\n                              result.audioId = pid;\n                              result.audioSegmentCodec = 'aac';\n                          }\n                          break;\n                      // Packetized metadata (ID3)\n                      case 21:\n                          // logger.info('ID3 PID:'  + pid);\n                          if (result.id3Id === -1) {\n                              result.id3Id = pid;\n                          }\n                          break;\n                      case 219:\n                          result.videoEncrypted = true;\n                      /* falls through */\n                      // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n                      case 27:\n                          // logger.info('AVC PID:'  + pid);\n                          if (result.avcId === -1) {\n                              result.avcId = pid;\n                          }\n                          break;\n                      // ISO/IEC 11172-3 (MPEG-1 audio)\n                      // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n                      case 3:\n                      case 4:\n                          // logger.info('MPEG PID:'  + pid);\n                          if (typeSupported.mpeg !== true && typeSupported.mp3 !== true) {\n                              this.logger.warn(loggerName$a, 'MPEG audio found, not supported in this browser for now');\n                          }\n                          else if (result.audioId === -1) {\n                              result.audioId = pid;\n                              result.audioSegmentCodec = 'mp3';\n                          }\n                          break;\n                      case 193:\n                          result.audioEncrypted = true;\n                          this.logger.info(loggerName$a, 'TS encrypted AC-3 audio found');\n                      /* falls through */\n                      case 129:\n                          if (typeSupported.ac3 !== true) {\n                              this.logger.warn(loggerName$a, 'AC-3 audio found, not supported in this browser for now');\n                          }\n                          else if (result.audioId === -1) {\n                              result.audioId = pid;\n                              result.audioSegmentCodec = 'ac3';\n                          }\n                          break;\n                      case 194:\n                          result.audioEncrypted = true;\n                          this.logger.info(loggerName$a, 'TS encrypted EC-3 audio found');\n                      /* falls through */\n                      case 135:\n                          if (typeSupported.ec3 !== true) {\n                              this.logger.warn(loggerName$a, 'EC-3 audio found, not supported in this browser for now');\n                          }\n                          else if (result.audioId === -1) {\n                              result.audioId = pid;\n                              result.audioSegmentCodec = 'ec3';\n                          }\n                          break;\n                      case 36:\n                          this.logger.warn(loggerName$a, 'HEVC stream type found, not supported for now');\n                          break;\n                      default:\n                          this.logger.warn(loggerName$a, 'unkown stream type:' + data[offset]);\n                          break;\n                  }\n                  // move to the next table entry\n                  // skip past the elementary stream descriptors, if present\n                  offset += (((data[offset + 3] & 15) << 8) | data[offset + 4]) + 5;\n              }\n              return result;\n          }\n          _parsePES(stream) {\n              let i = 0, frag, pesFlags, pesLen, pesHdrLen, pesData, payloadStartOffset;\n              const data = stream.data, keyTagInfo = stream.keyTagInfo;\n              let pesPts = NaN, pesDts = NaN;\n              // safety check\n              if (!stream || stream.size === 0) {\n                  return undefined;\n              }\n              // we might need up to 19 bytes to read PES header\n              // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n              // usually only one merge is needed (and this is rare ...)\n              while (data[0].length < 19 && data.length > 1) {\n                  const newData = new Uint8Array(data[0].length + data[1].length);\n                  newData.set(data[0]);\n                  newData.set(data[1], data[0].length);\n                  data[0] = newData;\n                  data.splice(1, 1);\n              }\n              // retrieve PTS/DTS from first fragment\n              frag = data[0];\n              const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n              if (pesPrefix === 1) {\n                  pesLen = (frag[4] << 8) + frag[5];\n                  // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n                  // minus 6 : PES header size\n                  if (pesLen && pesLen > stream.size - 6) {\n                      return undefined;\n                  }\n                  pesFlags = frag[7];\n                  if (pesFlags & 192) {\n                      /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n                         as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n                         as Bitwise operators treat their operands as a sequence of 32 bits */\n                      pesPts =\n                          (frag[9] & 14) * 536870912 + // 1 << 29\n                              (frag[10] & 255) * 4194304 + // 1 << 22\n                              (frag[11] & 254) * 16384 + // 1 << 14\n                              (frag[12] & 255) * 128 + // 1 << 7\n                              (frag[13] & 254) / 2;\n                      if (pesFlags & 64) {\n                          pesDts =\n                              (frag[14] & 14) * 536870912 + // 1 << 29\n                                  (frag[15] & 255) * 4194304 + // 1 << 22\n                                  (frag[16] & 254) * 16384 + // 1 << 14\n                                  (frag[17] & 255) * 128 + // 1 << 7\n                                  (frag[18] & 254) / 2;\n                          if (pesPts - pesDts > 5400000) {\n                              this.logger.warn(loggerName$a, `${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);\n                              pesPts = pesDts;\n                          }\n                      }\n                      else {\n                          pesDts = pesPts;\n                      }\n                  }\n                  pesHdrLen = frag[8];\n                  // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n                  payloadStartOffset = pesHdrLen + 9;\n                  stream.size -= payloadStartOffset;\n                  // reassemble PES packet\n                  pesData = new Uint8Array(stream.size);\n                  for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n                      frag = data[j];\n                      let len = frag.byteLength;\n                      if (payloadStartOffset) {\n                          if (payloadStartOffset > len) {\n                              // trim full frag if PES header bigger than frag\n                              payloadStartOffset -= len;\n                              continue;\n                          }\n                          else {\n                              // trim partial frag if PES header smaller than frag\n                              frag = frag.subarray(payloadStartOffset);\n                              len -= payloadStartOffset;\n                              payloadStartOffset = 0;\n                          }\n                      }\n                      pesData.set(frag, i);\n                      i += len;\n                  }\n                  if (pesLen) {\n                      // payload size : remove PES header + PES extension\n                      pesLen -= pesHdrLen + 3;\n                  }\n                  return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen, keyTagInfo: keyTagInfo };\n              }\n              else {\n                  return undefined;\n              }\n          }\n          pushAccesUnit(avcContext, keyTagInfo) {\n              const avcSample = avcContext.avcSample;\n              if (avcSample && avcSample.units.length && avcSample.frame) {\n                  const samples = avcContext.parsingData.esSamples;\n                  const nbSamples = samples.length;\n                  if (avcSample.key === true || (avcContext.config.sps && (nbSamples || this.contiguous))) {\n                      avcSample.id = nbSamples;\n                      avcSample.keyTagInfo = keyTagInfo;\n                      if (avcContext.info.encrypted) {\n                          const units = avcSample.units;\n                          units.forEach((unit) => {\n                              if (unit.data.byteLength > 48) {\n                                  switch (unit.type) {\n                                      case 1:\n                                      case 5:\n                                          // need to remove EPBs from encrypted NALs now that they're parsed into units\n                                          unit.data = this.discardEPB(unit.data);\n                                          break;\n                                  }\n                              }\n                          });\n                      }\n                  }\n                  if (!nbSamples && !isFinite(avcSample.pts)) {\n                      // dropping samples, no timestamp found\n                      avcContext.parsingData.dropped++;\n                      return;\n                  }\n                  samples.push(avcSample);\n              }\n              if (avcSample && avcSample.debug.length) {\n                  this.logger.info(loggerName$a, avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n              }\n          }\n          _parseAVCPES(pes, last) {\n              if (!pes.data) {\n                  throw 'invalid pes data';\n              }\n              const avcContext = this._avcContext, units = this._parseAVCNALu(pes.data);\n              let expGolombDecoder, avcSample = avcContext.avcSample, push, i;\n              const keyTagInfo = pes.keyTagInfo;\n              // free pes.data to save up some memory\n              pes.data = undefined;\n              units.forEach((unit) => {\n                  switch (unit.type) {\n                      // NDR\n                      case 1:\n                          if (avcSample && !this.iframeMode) {\n                              // TODO: demuxer needs better support for partial nal units\n                              push = true;\n                              avcSample.frame = true;\n                              // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n                              const data = unit.data;\n                              if (data.length > 4) {\n                                  const sliceType = new ExpGolomb(data, this.logger).readSliceType();\n                                  // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n                                  // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n                                  // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n                                  // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n                                  // if (sliceType === 2 || sliceType === 7) {\n                                  if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n                                      avcSample.key = true;\n                                  }\n                              }\n                          }\n                          break;\n                      // IDR\n                      case 5:\n                          push = true;\n                          if (avcSample) {\n                              // handle PES not starting with AUD\n                              if (!avcSample) {\n                                  avcSample = avcContext.avcSample = this._createAVCSample(true, pes.pts, pes.dts, '');\n                              }\n                              avcSample.key = true;\n                              avcSample.frame = true;\n                          }\n                          break;\n                      // SEI\n                      case 6:\n                          push = true;\n                          expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data), this.logger);\n                          // skip frameType\n                          expGolombDecoder.readUByte();\n                          let payloadType = 0;\n                          let payloadSize = 0;\n                          let endOfCaptions = false;\n                          let b = 0;\n                          while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n                              payloadType = 0;\n                              do {\n                                  b = expGolombDecoder.readUByte();\n                                  payloadType += b;\n                              } while (b === 255);\n                              // Parse payload size.\n                              payloadSize = 0;\n                              do {\n                                  b = expGolombDecoder.readUByte();\n                                  payloadSize += b;\n                              } while (b === 255);\n                              // TODO: there can be more than one payload in an SEI packet...\n                              // TODO: need to read type and size in a while loop to get them all\n                              if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n                                  endOfCaptions = true;\n                                  const countryCode = expGolombDecoder.readUByte();\n                                  if (countryCode === 181) {\n                                      const providerCode = expGolombDecoder.readUShort();\n                                      if (providerCode === 49) {\n                                          const userStructure = expGolombDecoder.readUInt();\n                                          if (userStructure === 1195456820) {\n                                              const userDataType = expGolombDecoder.readUByte();\n                                              // Raw CEA-608 bytes wrapped in CEA-708 packet\n                                              if (userDataType === 3) {\n                                                  const firstByte = expGolombDecoder.readUByte();\n                                                  const secondByte = expGolombDecoder.readUByte();\n                                                  const totalCCs = 31 & firstByte;\n                                                  const byteArray = [firstByte, secondByte];\n                                                  for (i = 0; i < totalCCs; i++) {\n                                                      // 3 bytes per CC\n                                                      byteArray.push(expGolombDecoder.readUByte());\n                                                      byteArray.push(expGolombDecoder.readUByte());\n                                                      byteArray.push(expGolombDecoder.readUByte());\n                                                  }\n                                                  this._insertSampleInOrder(this._txtTrack.captionSamples, { type: 3, pts: pes.pts, bytes: byteArray });\n                                              }\n                                          }\n                                      }\n                                  }\n                              }\n                              else if (payloadSize < expGolombDecoder.bytesAvailable) {\n                                  for (i = 0; i < payloadSize; i++) {\n                                      expGolombDecoder.readUByte();\n                                  }\n                              }\n                          }\n                          break;\n                      // SPS\n                      case 7:\n                          push = true;\n                          if (!avcContext.config.sps) {\n                              expGolombDecoder = new ExpGolomb(unit.data, this.logger);\n                              const config = expGolombDecoder.readSPS();\n                              avcContext.config.width = config.width;\n                              avcContext.config.height = config.height;\n                              avcContext.config.pixelRatio = config.pixelRatio;\n                              avcContext.config.sps = [unit.data];\n                              avcContext.info.duration = this._duration;\n                              const codecarray = unit.data.subarray(1, 4);\n                              let codecstring = 'avc1.';\n                              for (i = 0; i < 3; i++) {\n                                  let h = codecarray[i].toString(16);\n                                  if (h.length < 2) {\n                                      h = '0' + h;\n                                  }\n                                  codecstring += h;\n                              }\n                              avcContext.config.codec = codecstring;\n                          }\n                          break;\n                      // PPS\n                      case 8:\n                          push = true;\n                          if (!avcContext.config.pps) {\n                              avcContext.config.pps = [unit.data];\n                          }\n                          break;\n                      // AUD\n                      case 9:\n                          push = false;\n                          if (avcSample) {\n                              this.pushAccesUnit(avcContext, keyTagInfo);\n                          }\n                          avcSample = avcContext.avcSample = this._createAVCSample(false, pes.pts, pes.dts, '');\n                          break;\n                      // Filler Data\n                      case 12:\n                          push = false;\n                          break;\n                      default:\n                          push = false;\n                          if (avcSample) {\n                              avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n                          }\n                          break;\n                  }\n                  if (avcSample && push) {\n                      const units = avcSample.units;\n                      units.push(unit);\n                  }\n              });\n              // if last PES packet, push samples\n              if (last && avcSample) {\n                  this.pushAccesUnit(avcContext, keyTagInfo);\n                  avcContext.avcSample = undefined;\n              }\n          }\n          _createAVCSample(key, pts, dts, debug) {\n              return { id: NaN, key: key, pts: pts, dts: dts, units: new Array(), debug: debug };\n          }\n          _insertSampleInOrder(arr, data) {\n              const len = arr.length;\n              if (len > 0) {\n                  if (data.pts >= arr[len - 1].pts) {\n                      arr.push(data);\n                  }\n                  else {\n                      for (let pos = len - 1; pos >= 0; pos--) {\n                          if (data.pts < arr[pos].pts) {\n                              arr.splice(pos, 0, data);\n                              break;\n                          }\n                      }\n                  }\n              }\n              else {\n                  arr.push(data);\n              }\n          }\n          _getLastNalUnit() {\n              const avcContext = this._avcContext;\n              let avcSample = avcContext.avcSample, lastUnit;\n              // try to fallback to previous sample if current one is empty\n              if (!avcSample || avcSample.units.length === 0) {\n                  const samples = avcContext.parsingData.esSamples;\n                  avcSample = samples[samples.length - 1];\n              }\n              if (avcSample) {\n                  const units = avcSample.units;\n                  lastUnit = units[units.length - 1];\n              }\n              return lastUnit;\n          }\n          _parseAVCNALu(array) {\n              const len = array.byteLength;\n              let i = 0, value, overflow;\n              const avcContext = this._avcContext;\n              let state = avcContext.naluState || 0;\n              const lastState = state;\n              const units = [];\n              let unit, unitType, lastUnitStart = -1, lastUnitType;\n              if (state === -1) {\n                  // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n                  lastUnitStart = 0;\n                  // NALu type is value read from offset 0\n                  lastUnitType = array[0] & 31;\n                  state = 0;\n                  i = 1;\n              }\n              while (i < len) {\n                  value = array[i++];\n                  // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n                  if (!state) {\n                      state = value ? 0 : 1;\n                      continue;\n                  }\n                  if (state === 1) {\n                      state = value ? 0 : 2;\n                      continue;\n                  }\n                  // here we have state either equal to 2 or 3\n                  if (!value) {\n                      state = 3;\n                  }\n                  else if (value === 1) {\n                      if (lastUnitStart >= 0) {\n                          unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };\n                          units.push(unit);\n                      }\n                      else {\n                          // lastUnitStart is -1 => this is the first start code found in this PES packet\n                          // first check if start code delimiter is overlapping between 2 PES packets,\n                          // ie it started in last packet (lastState not zero)\n                          // and ended at the beginning of this PES packet (i <= 4 - lastState)\n                          const lastUnit = this._getLastNalUnit();\n                          if (lastUnit) {\n                              if (lastState && i <= 4 - lastState) {\n                                  // start delimiter overlapping between PES packets\n                                  // strip start delimiter bytes from the end of last NAL unit\n                                  // check if lastUnit had a state different from zero\n                                  if (lastUnit.state) {\n                                      // strip last bytes\n                                      lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);\n                                  }\n                              }\n                              // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n                              overflow = i - state - 1;\n                              if (overflow > 0) {\n                                  const tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n                                  tmp.set(lastUnit.data, 0);\n                                  tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n                                  lastUnit.data = tmp;\n                                  lastUnit.state = 0;\n                              }\n                          }\n                      }\n                      // check if we can read unit type\n                      if (i < len) {\n                          unitType = array[i] & 31;\n                          lastUnitStart = i;\n                          lastUnitType = unitType;\n                          state = 0;\n                      }\n                      else {\n                          // not enough byte to read unit type. let's read it on next PES parsing\n                          state = -1;\n                      }\n                  }\n                  else {\n                      state = 0;\n                  }\n              }\n              if (lastUnitStart >= 0 && state >= 0) {\n                  unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state };\n                  units.push(unit);\n              }\n              // no NALu found\n              if (units.length === 0) {\n                  // append pes.data to previous NAL unit\n                  const lastUnit = this._getLastNalUnit();\n                  if (lastUnit) {\n                      const tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n                      tmp.set(lastUnit.data, 0);\n                      tmp.set(array, lastUnit.data.byteLength);\n                      lastUnit.data = tmp;\n                  }\n              }\n              avcContext.naluState = state;\n              return units;\n          }\n          /**\n           * remove Emulation Prevention bytes from a RBSP\n           */\n          discardEPB(data) {\n              const length = data.byteLength, EPBPositions = [];\n              let i = 1;\n              // Find all `Emulation Prevention Bytes`\n              while (i < length - 2) {\n                  if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 3) {\n                      EPBPositions.push(i + 2);\n                      i += 2;\n                  }\n                  else {\n                      i++;\n                  }\n              }\n              // If no Emulation Prevention Bytes were found just return the original\n              // array\n              if (EPBPositions.length === 0) {\n                  return data;\n              }\n              // Create a new array to hold the NAL unit data\n              const newLength = length - EPBPositions.length;\n              const newData = new Uint8Array(newLength);\n              let sourceIndex = 0;\n              for (i = 0; i < newLength; sourceIndex++, i++) {\n                  if (sourceIndex === EPBPositions[0]) {\n                      // Skip this byte\n                      sourceIndex++;\n                      // Remove this position index\n                      EPBPositions.shift();\n                  }\n                  newData[i] = data[sourceIndex];\n              }\n              return newData;\n          }\n          _parseAACPES(pes) {\n              const audioContext = this._audioContext, audioLastPTS = audioContext.audioLastPTS, startOffset = 0, keyTagInfo = pes.keyTagInfo;\n              let data = pes.data, pts = pes.pts, audioOverFlow = audioContext.audioOverFlow, frameLength, frameIndex, offset, headerLength, stamp, len, aacSample;\n              if (audioOverFlow) {\n                  const tmp = new Uint8Array(audioOverFlow.byteLength + data.byteLength);\n                  tmp.set(audioOverFlow, 0);\n                  tmp.set(data, audioOverFlow.byteLength);\n                  data = tmp;\n              }\n              // look for ADTS header (0xFFFx)\n              for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n                  if (data[offset] === 255 && (data[offset + 1] & 240) === 240) {\n                      break;\n                  }\n              }\n              // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n              if (offset) {\n                  let reason, fatal, response;\n                  if (offset < len - 1) {\n                      reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n                      fatal = false;\n                      response = ErrorResponses.PESDidNotStartWithADTS;\n                  }\n                  else {\n                      reason = 'no ADTS header found in AAC PES';\n                      fatal = true;\n                      response = ErrorResponses.NoADTSHeaderInPES;\n                  }\n                  this.logger.warn(loggerName$a, `parsing error:${reason}`);\n                  const payload = new FragParsingError(fatal, reason, response);\n                  this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                  if (fatal) {\n                      return;\n                  }\n              }\n              if (!audioContext.config) {\n                  const config = ADTS.getAudioConfig(this.observer, data, offset, undefined, this.logger);\n                  if (!config) {\n                      throw 'unable to parse adts header';\n                  }\n                  audioContext.config = config;\n                  this.logger.info(loggerName$a, `parsed codec:${config.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n              }\n              frameIndex = 0;\n              const frameDuration = 92160000 / audioContext.config.samplerate;\n              // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n              // first sample PTS should be equal to last sample PTS + frameDuration\n              if (audioOverFlow && audioLastPTS) {\n                  const newPTS = audioLastPTS + frameDuration;\n                  if (Math.abs(newPTS - pts) > 1) {\n                      this.logger.info(loggerName$a, `AAC: align PTS for overlapping frames by ${Math.round((newPTS - pts) / 90)}`);\n                      pts = newPTS;\n                  }\n              }\n              while (offset + 5 < len) {\n                  // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n                  headerLength = data[offset + 1] & 1 ? 7 : 9;\n                  // retrieve frame size\n                  frameLength = ((data[offset + 3] & 3) << 11) | (data[offset + 4] << 3) | ((data[offset + 5] & 224) >>> 5);\n                  frameLength -= headerLength;\n                  if (frameLength > 0 && offset + headerLength + frameLength <= len) {\n                      stamp = pts + frameIndex * frameDuration;\n                      aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp, keyTagInfo: keyTagInfo };\n                      audioContext.parsingData.esSamples.push(aacSample);\n                      audioContext.parsingData.len += frameLength;\n                      offset += frameLength + headerLength;\n                      frameIndex++;\n                      // look for ADTS header (0xFFFx)\n                      for (; offset < len - 1; offset++) {\n                          if (data[offset] === 255 && (data[offset + 1] & 240) === 240) {\n                              break;\n                          }\n                      }\n                  }\n                  else {\n                      break;\n                  }\n              }\n              if (offset < len) {\n                  audioOverFlow = data.subarray(offset, len);\n              }\n              else {\n                  audioOverFlow = undefined;\n              }\n              audioContext.audioOverFlow = audioOverFlow;\n              audioContext.audioLastPTS = stamp;\n          }\n          _parseMPEGPES(pes) {\n              if (this._audioContext.segmentCodec === 'mp3') {\n                  MpegAudio$1.parse(this._audioContext.parsingData, pes.data, 0, pes.pts, this.logger);\n              }\n          }\n          _parseDolbyPES(pes) {\n              const audioContext = this._audioContext;\n              let data = pes.data;\n              let pts = pes.pts;\n              const keyTagInfo = pes.keyTagInfo;\n              let frameIndex = 0;\n              let offset = 0;\n              let audioOverFlow = audioContext.audioOverFlow;\n              const audioLastPTS = audioContext.audioLastPTS;\n              if (!audioContext.config) {\n                  let config;\n                  if (audioContext.segmentCodec === 'ac3') {\n                      config = Dolby.getAudioConfig(this.observer, data, offset, this.logger);\n                  }\n                  else if (audioContext.segmentCodec === 'ec3') {\n                      config = DDPlus$1.getAudioConfig(this.observer, data, offset, this.logger);\n                  }\n                  if (!config) {\n                      throw 'unable to parse dolby header';\n                  }\n                  audioContext.config = config;\n              }\n              if (audioContext.config.segmentCodec !== 'ac3' && audioContext.config.segmentCodec !== 'ec3') {\n                  throw 'unexpected config type';\n              }\n              const frameDuration = (1536 / audioContext.config.samplerate) * audioContext.info.inputTimescale;\n              if (audioOverFlow) {\n                  const tmp = new Uint8Array(audioOverFlow.byteLength + data.byteLength);\n                  tmp.set(audioOverFlow, 0);\n                  tmp.set(data, audioOverFlow.byteLength);\n                  data = tmp;\n              }\n              const length = data.length;\n              if (audioOverFlow && audioLastPTS) {\n                  const newPTS = audioLastPTS + frameDuration;\n                  if (Math.abs(newPTS - pts) > 1) {\n                      pts = newPTS;\n                  }\n              }\n              let frameLength = 0;\n              while (offset + frameLength <= length) {\n                  if (data[offset] !== 11 || data[offset + 1] !== 119) {\n                      const payload = new FragParsingError(true, 'invalid dolby audio magic', ErrorResponses.InvalidDolbyAudioMagic);\n                      this.observer.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return;\n                  }\n                  if (audioContext.segmentCodec === 'ac3') {\n                      frameLength = Dolby.getFrameLength(this.observer, data, offset);\n                  }\n                  else if (audioContext.segmentCodec === 'ec3') {\n                      frameLength = DDPlus$1.getFrameLength(this.observer, data, offset, this.logger);\n                  }\n                  const stamp = pts + frameIndex * frameDuration;\n                  audioContext.audioLastPTS = stamp;\n                  const dolbySample = { unit: data.subarray(offset, offset + frameLength), pts: stamp, dts: stamp, keyTagInfo: keyTagInfo };\n                  audioContext.parsingData.esSamples.push(dolbySample);\n                  audioContext.info.duration = this._duration;\n                  audioContext.parsingData.len += frameLength;\n                  offset += frameLength;\n                  frameIndex++;\n              }\n              if (offset < length) {\n                  audioOverFlow = data.subarray(offset, length);\n              }\n              else {\n                  audioOverFlow = undefined;\n              }\n              audioContext.audioOverFlow = audioOverFlow;\n          }\n      }\n      var TsDemuxer$1 = TsDemuxer;\n    \n      \n      class DemuxerInline extends Observer {\n          constructor(typeSupported, config, vendor, logger) {\n              super();\n              this.typeSupported = typeSupported;\n              this.config = config;\n              this.vendor = vendor;\n              this.logger = logger;\n          }\n          destroy() {\n              this.removeAllListeners();\n              const demuxer = this.demuxer;\n              const remuxer = this.remuxer;\n              if (demuxer) {\n                  demuxer.destroy();\n              }\n              if (remuxer) {\n                  remuxer.destroy();\n              }\n          }\n          push(data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration) {\n              if (!data) {\n                  // if data is undefined and this.probeFn exists,\n                  // all the demuxers will fail probing. We will still end up with the old probeFn.\n                  // We will push Uint8Array(undefined) to the demuxer that owns this.probeFn, which will be fatal\n                  return;\n              }\n              let demuxer = this.demuxer;\n              const _data = new Uint8Array(data);\n              if (!demuxer ||\n                  // in case of continuity change, we might switch from content type (AAC container to TS container for example). this is signaled through the discontinuity argument.\n                  // also a variant switch can also change the content type (TS container to fMP4 contaner for example). this is signaled through the trackSwitch argument.\n                  // so let's check that current demuxer is still valid\n                  ((discontinuity || trackSwitch) && !this.probeFn(_data, this.logger))) {\n                  const { typeSupported, config } = this;\n                  const muxConfig = [\n                      { demux: MP4Demuxer, remux: MP4EncryptionRemuxer },\n                      { demux: TsDemuxer$1, remux: EsRemuxer },\n                      { demux: EC3Demuxer, remux: EsRemuxer },\n                      { demux: AC3Demuxer, remux: EsRemuxer },\n                      { demux: AACDemuxer, remux: EsRemuxer },\n                      { demux: MP3Demuxer, remux: EsRemuxer },\n                  ]; // move MP3Demuxer to last to avoid false positive mp3 detection.\n                  // probe for content type\n                  for (const mux of muxConfig) {\n                      const { probe } = mux.demux;\n                      if (probe(_data, this.logger)) {\n                          this.remuxer = new mux.remux(this, config, typeSupported, this.vendor, this.logger);\n                          demuxer = new mux.demux(this, this.remuxer, config, typeSupported, this.logger);\n                          this.probeFn = probe;\n                          break;\n                      }\n                  }\n                  if (!demuxer) {\n                      const payload = new FragParsingError(true, 'no demux matching with content found', ErrorResponses.DemuxerNotFound);\n                      this.trigger(HlsEvent$1.INTERNAL_ERROR, payload);\n                      return;\n                  }\n                  this.demuxer = demuxer;\n              }\n              const remuxer = this.remuxer;\n              const keyChange = !this.lastKeyTagInfo || (keyTagInfo && keyTagInfo.method !== 'NONE' && this.lastKeyTagInfo.uri !== keyTagInfo.uri);\n              this.lastKeyTagInfo = keyTagInfo;\n              if (discontinuity || trackSwitch || keyChange) {\n                  // resetInitSegment error handling may need to know if we are in a discontinuity or track switch\n                  demuxer.resetInitSegment(new Uint8Array(initSegment), duration, keyTagInfo, discontinuity);\n                  remuxer.resetInitSegment();\n              }\n              if (discontinuity) {\n                  const pts = defaultInitPTS ? convertTimestampToSeconds(defaultInitPTS) : undefined;\n                  demuxer.resetTimeStamp(pts);\n                  remuxer.resetTimeStamp(pts);\n              }\n              demuxer.append(_data, timeOffset, contiguous, accurateTimeOffset, keyTagInfo, iframeMediaStart, iframeDuration);\n          }\n      }\n    \n      function generateUniqueID() {\n          let id = `${Date.now()}-${Math.random()}`;\n          if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n              id += `-${performance.now()}`;\n          }\n          return id;\n      }\n    \n      class DemuxRPCServer {\n          constructor(rpc, logger) {\n              this.rpc = rpc;\n              this.logger = logger;\n              this.init = (typeSupported, config, vendor) => callback => {\n                  const demuxSessionID = generateUniqueID();\n                  const demuxer = (this.demuxers[demuxSessionID] = new DemuxerInline(typeSupported, config, vendor, this.logger));\n                  [\n                      DemuxerEvent.INIT_PTS_FOUND,\n                      DemuxerEvent.FRAG_PARSING_INIT_SEGMENT,\n                      DemuxerEvent.FRAG_PARSING_DATA,\n                      DemuxerEvent.FRAG_PARSED,\n                      HlsEvent$1.INTERNAL_ERROR\n                  ].forEach(event => {\n                      demuxer.on(event, (data) => this.rpc.invoke('demuxer.event', [demuxSessionID, event, data])(() => { }));\n                  });\n                  callback(demuxSessionID);\n              };\n              this.push = (id, data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration) => callback => {\n                  const demuxer = this.demuxers[id];\n                  if (!demuxer) {\n                      callback(undefined, `Demuxer with id \"${id}\" does not exist on push`);\n                      return;\n                  }\n                  demuxer.push(data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration);\n                  callback();\n              };\n              this.destroy = (id) => callback => {\n                  const demuxer = this.demuxers[id];\n                  if (!demuxer) {\n                      this.logger.error(`Demuxer with id \"${id}\" does not exist on destroy`);\n                      return;\n                  }\n                  demuxer.destroy();\n                  delete this.demuxers[id];\n                  callback();\n              };\n              this.demuxers = {};\n              rpc.register('demuxer.init', this.init);\n              rpc.register('demuxer.push', this.push);\n              rpc.register('demuxer.destroy', this.destroy);\n          }\n      }\n    \n      // RPCWorkerService has client and server counterparts, where the service server\n      // runs in a Web Worker process, while the client remains in the main process.\n      class RPCWorkerService {\n          constructor(worker) {\n              this.worker = worker;\n              this.handlers = {};\n              this.deferers = {};\n              this._messageHandler = (event) => {\n                  const { type, id, command, args, result, error } = event.data;\n                  if (type === RPCWorkerMessageType.Invoke) {\n                      try {\n                          if (this.handlers[command] == null) {\n                              throw new Error(`command ${command} not found`);\n                          }\n                          this.handlers[command](...args)(this._respond.bind(this, id, command));\n                      }\n                      catch (error) {\n                          this._respond(id, command, null, new Error(`command ${command} not found`));\n                      }\n                  }\n                  else if (type === RPCWorkerMessageType.Result) {\n                      if (this.deferers[id] == null) {\n                          return;\n                      }\n                      this.deferers[id](result, error);\n                      delete this.deferers[id];\n                  }\n              };\n              worker.addEventListener('message', this._messageHandler);\n          }\n          register(command, handler) {\n              if (this.handlers[command] != null) {\n                  return false;\n              }\n              this.handlers[command] = handler;\n          }\n          unregister(command) {\n              if (this.handlers[command] != null) {\n                  return false;\n              }\n              delete this.handlers[command];\n          }\n          invoke(command, args, transfer) {\n              return (callback = RPCWorkerService._fallbackCallback) => {\n                  const id = generateUniqueID();\n                  this.deferers[id] = callback;\n                  const message = {\n                      type: RPCWorkerMessageType.Invoke,\n                      id,\n                      command,\n                      args,\n                  };\n                  this._send(message, transfer);\n              };\n          }\n          teardown(done) {\n              this.worker.removeEventListener('message', this._messageHandler);\n              done();\n          }\n          _respond(id, command, result, error, transfer) {\n              if (error instanceof Error) {\n                  error = `[${error.name}] ${error.message}\\n${error.stack}`;\n              }\n              const message = {\n                  type: RPCWorkerMessageType.Result,\n                  id,\n                  command,\n                  result,\n                  error,\n              };\n              this._send(message, transfer);\n          }\n          _send(message, transfer = []) {\n              this.worker.postMessage(message, transfer.map((value) => (ArrayBuffer.isView(value) ? value.buffer : value)).filter((value) => value !== undefined));\n          }\n      }\n      RPCWorkerService._fallbackCallback = (result, error) => {\n          if (error != null) {\n              throw error;\n          }\n      };\n      var RPCWorkerMessageType;\n      (function (RPCWorkerMessageType) {\n          RPCWorkerMessageType[RPCWorkerMessageType[\"Invoke\"] = 0] = \"Invoke\";\n          RPCWorkerMessageType[RPCWorkerMessageType[\"Result\"] = 1] = \"Result\";\n      })(RPCWorkerMessageType || (RPCWorkerMessageType = {}));\n      // Minimal polyfill\n      // ArrayBuffer.isView() is relatively new\n      // https://caniuse.com/?search=arraybuffer\n      if (!ArrayBuffer['isView']) {\n          ArrayBuffer.isView = function isView(a) {\n              return a !== null && typeof a === 'object' && a['buffer'] instanceof ArrayBuffer;\n          };\n      }\n    \n      const startWorker = () => {\n          const ctx = global$1;\n          const rpcService = new RPCWorkerService(ctx);\n          const logger = LoggerRPCClient(rpcService);\n          new CryptoRPCServer(rpcService, logger);\n          new DemuxRPCServer(rpcService, logger);\n          logger.info('WebWorker RPCService has started');\n      };\n    \n      if (hasUMDWorker() && typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {\n          startWorker();\n      }\n    \n      /*! *****************************************************************************\n      Copyright (c) Microsoft Corporation.\n    \n      Permission to use, copy, modify, and/or distribute this software for any\n      purpose with or without fee is hereby granted.\n    \n      THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n      REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n      AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n      INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n      LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n      OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n      PERFORMANCE OF THIS SOFTWARE.\n      ***************************************************************************** */\n      /* global Reflect, Promise */\n    \n      var extendStatics = function(d, b) {\n          extendStatics = Object.setPrototypeOf ||\n              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n              function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n          return extendStatics(d, b);\n      };\n    \n      function __extends(d, b) {\n          if (typeof b !== \"function\" && b !== null)\n              throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n          extendStatics(d, b);\n          function __() { this.constructor = d; }\n          d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n      }\n    \n      var __assign = function() {\n          __assign = Object.assign || function __assign(t) {\n              for (var s, i = 1, n = arguments.length; i < n; i++) {\n                  s = arguments[i];\n                  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n              }\n              return t;\n          };\n          return __assign.apply(this, arguments);\n      };\n    \n      function __rest(s, e) {\n          var t = {};\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n              t[p] = s[p];\n          if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n              for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n                  if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n                      t[p[i]] = s[p[i]];\n              }\n          return t;\n      }\n    \n      function __decorate$2(decorators, target, key, desc) {\n          var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n          if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n          else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n          return c > 3 && r && Object.defineProperty(target, key, r), r;\n      }\n    \n      function __metadata(metadataKey, metadataValue) {\n          if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n      }\n    \n      function __values(o) {\n          var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n          if (m) return m.call(o);\n          if (o && typeof o.length === \"number\") return {\n              next: function () {\n                  if (o && i >= o.length) o = void 0;\n                  return { value: o && o[i++], done: !o };\n              }\n          };\n          throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n      }\n    \n      function __read(o, n) {\n          var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n          if (!m) return o;\n          var i = m.call(o), r, ar = [], e;\n          try {\n              while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n          }\n          catch (error) { e = { error: error }; }\n          finally {\n              try {\n                  if (r && !r.done && (m = i[\"return\"])) m.call(i);\n              }\n              finally { if (e) throw e.error; }\n          }\n          return ar;\n      }\n    \n      /** @deprecated */\n      function __spread() {\n          for (var ar = [], i = 0; i < arguments.length; i++)\n              ar = ar.concat(__read(arguments[i]));\n          return ar;\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function isFunction$1(x) {\n          return typeof x === 'function';\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var _enable_super_gross_mode_that_will_cause_bad_things = false;\n      var config = {\n          Promise: undefined,\n          set useDeprecatedSynchronousErrorHandling(value) {\n              _enable_super_gross_mode_that_will_cause_bad_things = value;\n          },\n          get useDeprecatedSynchronousErrorHandling() {\n              return _enable_super_gross_mode_that_will_cause_bad_things;\n          },\n      };\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function hostReportError(err) {\n          setTimeout(function () { throw err; }, 0);\n      }\n    \n      /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */\n      var empty$1 = {\n          closed: true,\n          next: function (value) { },\n          error: function (err) {\n              if (config.useDeprecatedSynchronousErrorHandling) {\n                  throw err;\n              }\n              else {\n                  hostReportError(err);\n              }\n          },\n          complete: function () { }\n      };\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var isArray$1 = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function isObject$1(x) {\n          return x !== null && typeof x === 'object';\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {\n          function UnsubscriptionErrorImpl(errors) {\n              Error.call(this);\n              this.message = errors ?\n                  errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n  ') : '';\n              this.name = 'UnsubscriptionError';\n              this.errors = errors;\n              return this;\n          }\n          UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n          return UnsubscriptionErrorImpl;\n      })();\n      var UnsubscriptionError = UnsubscriptionErrorImpl;\n    \n      /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */\n      var Subscription = /*@__PURE__*/ (function () {\n          function Subscription(unsubscribe) {\n              this.closed = false;\n              this._parentOrParents = null;\n              this._subscriptions = null;\n              if (unsubscribe) {\n                  this._ctorUnsubscribe = true;\n                  this._unsubscribe = unsubscribe;\n              }\n          }\n          Subscription.prototype.unsubscribe = function () {\n              var errors;\n              if (this.closed) {\n                  return;\n              }\n              var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;\n              this.closed = true;\n              this._parentOrParents = null;\n              this._subscriptions = null;\n              if (_parentOrParents instanceof Subscription) {\n                  _parentOrParents.remove(this);\n              }\n              else if (_parentOrParents !== null) {\n                  for (var index = 0; index < _parentOrParents.length; ++index) {\n                      var parent_1 = _parentOrParents[index];\n                      parent_1.remove(this);\n                  }\n              }\n              if (isFunction$1(_unsubscribe)) {\n                  if (_ctorUnsubscribe) {\n                      this._unsubscribe = undefined;\n                  }\n                  try {\n                      _unsubscribe.call(this);\n                  }\n                  catch (e) {\n                      errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n                  }\n              }\n              if (isArray$1(_subscriptions)) {\n                  var index = -1;\n                  var len = _subscriptions.length;\n                  while (++index < len) {\n                      var sub = _subscriptions[index];\n                      if (isObject$1(sub)) {\n                          try {\n                              sub.unsubscribe();\n                          }\n                          catch (e) {\n                              errors = errors || [];\n                              if (e instanceof UnsubscriptionError) {\n                                  errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n                              }\n                              else {\n                                  errors.push(e);\n                              }\n                          }\n                      }\n                  }\n              }\n              if (errors) {\n                  throw new UnsubscriptionError(errors);\n              }\n          };\n          Subscription.prototype.add = function (teardown) {\n              var subscription = teardown;\n              if (!teardown) {\n                  return Subscription.EMPTY;\n              }\n              switch (typeof teardown) {\n                  case 'function':\n                      subscription = new Subscription(teardown);\n                  case 'object':\n                      if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n                          return subscription;\n                      }\n                      else if (this.closed) {\n                          subscription.unsubscribe();\n                          return subscription;\n                      }\n                      else if (!(subscription instanceof Subscription)) {\n                          var tmp = subscription;\n                          subscription = new Subscription();\n                          subscription._subscriptions = [tmp];\n                      }\n                      break;\n                  default: {\n                      throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n                  }\n              }\n              var _parentOrParents = subscription._parentOrParents;\n              if (_parentOrParents === null) {\n                  subscription._parentOrParents = this;\n              }\n              else if (_parentOrParents instanceof Subscription) {\n                  if (_parentOrParents === this) {\n                      return subscription;\n                  }\n                  subscription._parentOrParents = [_parentOrParents, this];\n              }\n              else if (_parentOrParents.indexOf(this) === -1) {\n                  _parentOrParents.push(this);\n              }\n              else {\n                  return subscription;\n              }\n              var subscriptions = this._subscriptions;\n              if (subscriptions === null) {\n                  this._subscriptions = [subscription];\n              }\n              else {\n                  subscriptions.push(subscription);\n              }\n              return subscription;\n          };\n          Subscription.prototype.remove = function (subscription) {\n              var subscriptions = this._subscriptions;\n              if (subscriptions) {\n                  var subscriptionIndex = subscriptions.indexOf(subscription);\n                  if (subscriptionIndex !== -1) {\n                      subscriptions.splice(subscriptionIndex, 1);\n                  }\n              }\n          };\n          Subscription.EMPTY = (function (empty) {\n              empty.closed = true;\n              return empty;\n          }(new Subscription()));\n          return Subscription;\n      }());\n      function flattenUnsubscriptionErrors(errors) {\n          return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var rxSubscriber = /*@__PURE__*/ (function () {\n          return typeof Symbol === 'function'\n              ? /*@__PURE__*/ Symbol('rxSubscriber')\n              : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();\n      })();\n    \n      /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */\n      var Subscriber = /*@__PURE__*/ (function (_super) {\n          __extends(Subscriber, _super);\n          function Subscriber(destinationOrNext, error, complete) {\n              var _this = _super.call(this) || this;\n              _this.syncErrorValue = null;\n              _this.syncErrorThrown = false;\n              _this.syncErrorThrowable = false;\n              _this.isStopped = false;\n              switch (arguments.length) {\n                  case 0:\n                      _this.destination = empty$1;\n                      break;\n                  case 1:\n                      if (!destinationOrNext) {\n                          _this.destination = empty$1;\n                          break;\n                      }\n                      if (typeof destinationOrNext === 'object') {\n                          if (destinationOrNext instanceof Subscriber) {\n                              _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n                              _this.destination = destinationOrNext;\n                              destinationOrNext.add(_this);\n                          }\n                          else {\n                              _this.syncErrorThrowable = true;\n                              _this.destination = new SafeSubscriber(_this, destinationOrNext);\n                          }\n                          break;\n                      }\n                  default:\n                      _this.syncErrorThrowable = true;\n                      _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);\n                      break;\n              }\n              return _this;\n          }\n          Subscriber.prototype[rxSubscriber] = function () { return this; };\n          Subscriber.create = function (next, error, complete) {\n              var subscriber = new Subscriber(next, error, complete);\n              subscriber.syncErrorThrowable = false;\n              return subscriber;\n          };\n          Subscriber.prototype.next = function (value) {\n              if (!this.isStopped) {\n                  this._next(value);\n              }\n          };\n          Subscriber.prototype.error = function (err) {\n              if (!this.isStopped) {\n                  this.isStopped = true;\n                  this._error(err);\n              }\n          };\n          Subscriber.prototype.complete = function () {\n              if (!this.isStopped) {\n                  this.isStopped = true;\n                  this._complete();\n              }\n          };\n          Subscriber.prototype.unsubscribe = function () {\n              if (this.closed) {\n                  return;\n              }\n              this.isStopped = true;\n              _super.prototype.unsubscribe.call(this);\n          };\n          Subscriber.prototype._next = function (value) {\n              this.destination.next(value);\n          };\n          Subscriber.prototype._error = function (err) {\n              this.destination.error(err);\n              this.unsubscribe();\n          };\n          Subscriber.prototype._complete = function () {\n              this.destination.complete();\n              this.unsubscribe();\n          };\n          Subscriber.prototype._unsubscribeAndRecycle = function () {\n              var _parentOrParents = this._parentOrParents;\n              this._parentOrParents = null;\n              this.unsubscribe();\n              this.closed = false;\n              this.isStopped = false;\n              this._parentOrParents = _parentOrParents;\n              return this;\n          };\n          return Subscriber;\n      }(Subscription));\n      var SafeSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SafeSubscriber, _super);\n          function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {\n              var _this = _super.call(this) || this;\n              _this._parentSubscriber = _parentSubscriber;\n              var next;\n              var context = _this;\n              if (isFunction$1(observerOrNext)) {\n                  next = observerOrNext;\n              }\n              else if (observerOrNext) {\n                  next = observerOrNext.next;\n                  error = observerOrNext.error;\n                  complete = observerOrNext.complete;\n                  if (observerOrNext !== empty$1) {\n                      context = Object.create(observerOrNext);\n                      if (isFunction$1(context.unsubscribe)) {\n                          _this.add(context.unsubscribe.bind(context));\n                      }\n                      context.unsubscribe = _this.unsubscribe.bind(_this);\n                  }\n              }\n              _this._context = context;\n              _this._next = next;\n              _this._error = error;\n              _this._complete = complete;\n              return _this;\n          }\n          SafeSubscriber.prototype.next = function (value) {\n              if (!this.isStopped && this._next) {\n                  var _parentSubscriber = this._parentSubscriber;\n                  if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n                      this.__tryOrUnsub(this._next, value);\n                  }\n                  else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n                      this.unsubscribe();\n                  }\n              }\n          };\n          SafeSubscriber.prototype.error = function (err) {\n              if (!this.isStopped) {\n                  var _parentSubscriber = this._parentSubscriber;\n                  var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;\n                  if (this._error) {\n                      if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n                          this.__tryOrUnsub(this._error, err);\n                          this.unsubscribe();\n                      }\n                      else {\n                          this.__tryOrSetError(_parentSubscriber, this._error, err);\n                          this.unsubscribe();\n                      }\n                  }\n                  else if (!_parentSubscriber.syncErrorThrowable) {\n                      this.unsubscribe();\n                      if (useDeprecatedSynchronousErrorHandling) {\n                          throw err;\n                      }\n                      hostReportError(err);\n                  }\n                  else {\n                      if (useDeprecatedSynchronousErrorHandling) {\n                          _parentSubscriber.syncErrorValue = err;\n                          _parentSubscriber.syncErrorThrown = true;\n                      }\n                      else {\n                          hostReportError(err);\n                      }\n                      this.unsubscribe();\n                  }\n              }\n          };\n          SafeSubscriber.prototype.complete = function () {\n              var _this = this;\n              if (!this.isStopped) {\n                  var _parentSubscriber = this._parentSubscriber;\n                  if (this._complete) {\n                      var wrappedComplete = function () { return _this._complete.call(_this._context); };\n                      if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n                          this.__tryOrUnsub(wrappedComplete);\n                          this.unsubscribe();\n                      }\n                      else {\n                          this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n                          this.unsubscribe();\n                      }\n                  }\n                  else {\n                      this.unsubscribe();\n                  }\n              }\n          };\n          SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {\n              try {\n                  fn.call(this._context, value);\n              }\n              catch (err) {\n                  this.unsubscribe();\n                  if (config.useDeprecatedSynchronousErrorHandling) {\n                      throw err;\n                  }\n                  else {\n                      hostReportError(err);\n                  }\n              }\n          };\n          SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {\n              if (!config.useDeprecatedSynchronousErrorHandling) {\n                  throw new Error('bad call');\n              }\n              try {\n                  fn.call(this._context, value);\n              }\n              catch (err) {\n                  if (config.useDeprecatedSynchronousErrorHandling) {\n                      parent.syncErrorValue = err;\n                      parent.syncErrorThrown = true;\n                      return true;\n                  }\n                  else {\n                      hostReportError(err);\n                      return true;\n                  }\n              }\n              return false;\n          };\n          SafeSubscriber.prototype._unsubscribe = function () {\n              var _parentSubscriber = this._parentSubscriber;\n              this._context = null;\n              this._parentSubscriber = null;\n              _parentSubscriber.unsubscribe();\n          };\n          return SafeSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */\n      function canReportError(observer) {\n          while (observer) {\n              var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;\n              if (closed_1 || isStopped) {\n                  return false;\n              }\n              else if (destination && destination instanceof Subscriber) {\n                  observer = destination;\n              }\n              else {\n                  observer = null;\n              }\n          }\n          return true;\n      }\n    \n      /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */\n      function toSubscriber(nextOrObserver, error, complete) {\n          if (nextOrObserver) {\n              if (nextOrObserver instanceof Subscriber) {\n                  return nextOrObserver;\n              }\n              if (nextOrObserver[rxSubscriber]) {\n                  return nextOrObserver[rxSubscriber]();\n              }\n          }\n          if (!nextOrObserver && !error && !complete) {\n              return new Subscriber(empty$1);\n          }\n          return new Subscriber(nextOrObserver, error, complete);\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function identity(x) {\n          return x;\n      }\n    \n      /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */\n      function pipe() {\n          var fns = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              fns[_i] = arguments[_i];\n          }\n          return pipeFromArray(fns);\n      }\n      function pipeFromArray(fns) {\n          if (fns.length === 0) {\n              return identity;\n          }\n          if (fns.length === 1) {\n              return fns[0];\n          }\n          return function piped(input) {\n              return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n          };\n      }\n    \n      /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */\n      var Observable = /*@__PURE__*/ (function () {\n          function Observable(subscribe) {\n              this._isScalar = false;\n              if (subscribe) {\n                  this._subscribe = subscribe;\n              }\n          }\n          Observable.prototype.lift = function (operator) {\n              var observable = new Observable();\n              observable.source = this;\n              observable.operator = operator;\n              return observable;\n          };\n          Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n              var operator = this.operator;\n              var sink = toSubscriber(observerOrNext, error, complete);\n              if (operator) {\n                  sink.add(operator.call(sink, this.source));\n              }\n              else {\n                  sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n                      this._subscribe(sink) :\n                      this._trySubscribe(sink));\n              }\n              if (config.useDeprecatedSynchronousErrorHandling) {\n                  if (sink.syncErrorThrowable) {\n                      sink.syncErrorThrowable = false;\n                      if (sink.syncErrorThrown) {\n                          throw sink.syncErrorValue;\n                      }\n                  }\n              }\n              return sink;\n          };\n          Observable.prototype._trySubscribe = function (sink) {\n              try {\n                  return this._subscribe(sink);\n              }\n              catch (err) {\n                  if (config.useDeprecatedSynchronousErrorHandling) {\n                      sink.syncErrorThrown = true;\n                      sink.syncErrorValue = err;\n                  }\n                  if (canReportError(sink)) {\n                      sink.error(err);\n                  }\n                  else {\n                      console.warn(err);\n                  }\n              }\n          };\n          Observable.prototype.forEach = function (next, promiseCtor) {\n              var _this = this;\n              promiseCtor = getPromiseCtor(promiseCtor);\n              return new promiseCtor(function (resolve, reject) {\n                  var subscription;\n                  subscription = _this.subscribe(function (value) {\n                      try {\n                          next(value);\n                      }\n                      catch (err) {\n                          reject(err);\n                          if (subscription) {\n                              subscription.unsubscribe();\n                          }\n                      }\n                  }, reject, resolve);\n              });\n          };\n          Observable.prototype._subscribe = function (subscriber) {\n              var source = this.source;\n              return source && source.subscribe(subscriber);\n          };\n          Observable.prototype[observable] = function () {\n              return this;\n          };\n          Observable.prototype.pipe = function () {\n              var operations = [];\n              for (var _i = 0; _i < arguments.length; _i++) {\n                  operations[_i] = arguments[_i];\n              }\n              if (operations.length === 0) {\n                  return this;\n              }\n              return pipeFromArray(operations)(this);\n          };\n          Observable.prototype.toPromise = function (promiseCtor) {\n              var _this = this;\n              promiseCtor = getPromiseCtor(promiseCtor);\n              return new promiseCtor(function (resolve, reject) {\n                  var value;\n                  _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });\n              });\n          };\n          Observable.create = function (subscribe) {\n              return new Observable(subscribe);\n          };\n          return Observable;\n      }());\n      function getPromiseCtor(promiseCtor) {\n          if (!promiseCtor) {\n              promiseCtor = config.Promise || Promise;\n          }\n          if (!promiseCtor) {\n              throw new Error('no Promise impl found');\n          }\n          return promiseCtor;\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () {\n          function ObjectUnsubscribedErrorImpl() {\n              Error.call(this);\n              this.message = 'object unsubscribed';\n              this.name = 'ObjectUnsubscribedError';\n              return this;\n          }\n          ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n          return ObjectUnsubscribedErrorImpl;\n      })();\n      var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;\n    \n      /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */\n      var SubjectSubscription = /*@__PURE__*/ (function (_super) {\n          __extends(SubjectSubscription, _super);\n          function SubjectSubscription(subject, subscriber) {\n              var _this = _super.call(this) || this;\n              _this.subject = subject;\n              _this.subscriber = subscriber;\n              _this.closed = false;\n              return _this;\n          }\n          SubjectSubscription.prototype.unsubscribe = function () {\n              if (this.closed) {\n                  return;\n              }\n              this.closed = true;\n              var subject = this.subject;\n              var observers = subject.observers;\n              this.subject = null;\n              if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {\n                  return;\n              }\n              var subscriberIndex = observers.indexOf(this.subscriber);\n              if (subscriberIndex !== -1) {\n                  observers.splice(subscriberIndex, 1);\n              }\n          };\n          return SubjectSubscription;\n      }(Subscription));\n    \n      /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */\n      var SubjectSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SubjectSubscriber, _super);\n          function SubjectSubscriber(destination) {\n              var _this = _super.call(this, destination) || this;\n              _this.destination = destination;\n              return _this;\n          }\n          return SubjectSubscriber;\n      }(Subscriber));\n      var Subject = /*@__PURE__*/ (function (_super) {\n          __extends(Subject, _super);\n          function Subject() {\n              var _this = _super.call(this) || this;\n              _this.observers = [];\n              _this.closed = false;\n              _this.isStopped = false;\n              _this.hasError = false;\n              _this.thrownError = null;\n              return _this;\n          }\n          Subject.prototype[rxSubscriber] = function () {\n              return new SubjectSubscriber(this);\n          };\n          Subject.prototype.lift = function (operator) {\n              var subject = new AnonymousSubject(this, this);\n              subject.operator = operator;\n              return subject;\n          };\n          Subject.prototype.next = function (value) {\n              if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              if (!this.isStopped) {\n                  var observers = this.observers;\n                  var len = observers.length;\n                  var copy = observers.slice();\n                  for (var i = 0; i < len; i++) {\n                      copy[i].next(value);\n                  }\n              }\n          };\n          Subject.prototype.error = function (err) {\n              if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              this.hasError = true;\n              this.thrownError = err;\n              this.isStopped = true;\n              var observers = this.observers;\n              var len = observers.length;\n              var copy = observers.slice();\n              for (var i = 0; i < len; i++) {\n                  copy[i].error(err);\n              }\n              this.observers.length = 0;\n          };\n          Subject.prototype.complete = function () {\n              if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              this.isStopped = true;\n              var observers = this.observers;\n              var len = observers.length;\n              var copy = observers.slice();\n              for (var i = 0; i < len; i++) {\n                  copy[i].complete();\n              }\n              this.observers.length = 0;\n          };\n          Subject.prototype.unsubscribe = function () {\n              this.isStopped = true;\n              this.closed = true;\n              this.observers = null;\n          };\n          Subject.prototype._trySubscribe = function (subscriber) {\n              if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              else {\n                  return _super.prototype._trySubscribe.call(this, subscriber);\n              }\n          };\n          Subject.prototype._subscribe = function (subscriber) {\n              if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              else if (this.hasError) {\n                  subscriber.error(this.thrownError);\n                  return Subscription.EMPTY;\n              }\n              else if (this.isStopped) {\n                  subscriber.complete();\n                  return Subscription.EMPTY;\n              }\n              else {\n                  this.observers.push(subscriber);\n                  return new SubjectSubscription(this, subscriber);\n              }\n          };\n          Subject.prototype.asObservable = function () {\n              var observable = new Observable();\n              observable.source = this;\n              return observable;\n          };\n          Subject.create = function (destination, source) {\n              return new AnonymousSubject(destination, source);\n          };\n          return Subject;\n      }(Observable));\n      var AnonymousSubject = /*@__PURE__*/ (function (_super) {\n          __extends(AnonymousSubject, _super);\n          function AnonymousSubject(destination, source) {\n              var _this = _super.call(this) || this;\n              _this.destination = destination;\n              _this.source = source;\n              return _this;\n          }\n          AnonymousSubject.prototype.next = function (value) {\n              var destination = this.destination;\n              if (destination && destination.next) {\n                  destination.next(value);\n              }\n          };\n          AnonymousSubject.prototype.error = function (err) {\n              var destination = this.destination;\n              if (destination && destination.error) {\n                  this.destination.error(err);\n              }\n          };\n          AnonymousSubject.prototype.complete = function () {\n              var destination = this.destination;\n              if (destination && destination.complete) {\n                  this.destination.complete();\n              }\n          };\n          AnonymousSubject.prototype._subscribe = function (subscriber) {\n              var source = this.source;\n              if (source) {\n                  return this.source.subscribe(subscriber);\n              }\n              else {\n                  return Subscription.EMPTY;\n              }\n          };\n          return AnonymousSubject;\n      }(Subject));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function refCount() {\n          return function refCountOperatorFunction(source) {\n              return source.lift(new RefCountOperator(source));\n          };\n      }\n      var RefCountOperator = /*@__PURE__*/ (function () {\n          function RefCountOperator(connectable) {\n              this.connectable = connectable;\n          }\n          RefCountOperator.prototype.call = function (subscriber, source) {\n              var connectable = this.connectable;\n              connectable._refCount++;\n              var refCounter = new RefCountSubscriber(subscriber, connectable);\n              var subscription = source.subscribe(refCounter);\n              if (!refCounter.closed) {\n                  refCounter.connection = connectable.connect();\n              }\n              return subscription;\n          };\n          return RefCountOperator;\n      }());\n      var RefCountSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(RefCountSubscriber, _super);\n          function RefCountSubscriber(destination, connectable) {\n              var _this = _super.call(this, destination) || this;\n              _this.connectable = connectable;\n              return _this;\n          }\n          RefCountSubscriber.prototype._unsubscribe = function () {\n              var connectable = this.connectable;\n              if (!connectable) {\n                  this.connection = null;\n                  return;\n              }\n              this.connectable = null;\n              var refCount = connectable._refCount;\n              if (refCount <= 0) {\n                  this.connection = null;\n                  return;\n              }\n              connectable._refCount = refCount - 1;\n              if (refCount > 1) {\n                  this.connection = null;\n                  return;\n              }\n              var connection = this.connection;\n              var sharedConnection = connectable._connection;\n              this.connection = null;\n              if (sharedConnection && (!connection || sharedConnection === connection)) {\n                  sharedConnection.unsubscribe();\n              }\n          };\n          return RefCountSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */\n      var ConnectableObservable = /*@__PURE__*/ (function (_super) {\n          __extends(ConnectableObservable, _super);\n          function ConnectableObservable(source, subjectFactory) {\n              var _this = _super.call(this) || this;\n              _this.source = source;\n              _this.subjectFactory = subjectFactory;\n              _this._refCount = 0;\n              _this._isComplete = false;\n              return _this;\n          }\n          ConnectableObservable.prototype._subscribe = function (subscriber) {\n              return this.getSubject().subscribe(subscriber);\n          };\n          ConnectableObservable.prototype.getSubject = function () {\n              var subject = this._subject;\n              if (!subject || subject.isStopped) {\n                  this._subject = this.subjectFactory();\n              }\n              return this._subject;\n          };\n          ConnectableObservable.prototype.connect = function () {\n              var connection = this._connection;\n              if (!connection) {\n                  this._isComplete = false;\n                  connection = this._connection = new Subscription();\n                  connection.add(this.source\n                      .subscribe(new ConnectableSubscriber(this.getSubject(), this)));\n                  if (connection.closed) {\n                      this._connection = null;\n                      connection = Subscription.EMPTY;\n                  }\n              }\n              return connection;\n          };\n          ConnectableObservable.prototype.refCount = function () {\n              return refCount()(this);\n          };\n          return ConnectableObservable;\n      }(Observable));\n      var connectableObservableDescriptor = /*@__PURE__*/ (function () {\n          var connectableProto = ConnectableObservable.prototype;\n          return {\n              operator: { value: null },\n              _refCount: { value: 0, writable: true },\n              _subject: { value: null, writable: true },\n              _connection: { value: null, writable: true },\n              _subscribe: { value: connectableProto._subscribe },\n              _isComplete: { value: connectableProto._isComplete, writable: true },\n              getSubject: { value: connectableProto.getSubject },\n              connect: { value: connectableProto.connect },\n              refCount: { value: connectableProto.refCount }\n          };\n      })();\n      var ConnectableSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(ConnectableSubscriber, _super);\n          function ConnectableSubscriber(destination, connectable) {\n              var _this = _super.call(this, destination) || this;\n              _this.connectable = connectable;\n              return _this;\n          }\n          ConnectableSubscriber.prototype._error = function (err) {\n              this._unsubscribe();\n              _super.prototype._error.call(this, err);\n          };\n          ConnectableSubscriber.prototype._complete = function () {\n              this.connectable._isComplete = true;\n              this._unsubscribe();\n              _super.prototype._complete.call(this);\n          };\n          ConnectableSubscriber.prototype._unsubscribe = function () {\n              var connectable = this.connectable;\n              if (connectable) {\n                  this.connectable = null;\n                  var connection = connectable._connection;\n                  connectable._refCount = 0;\n                  connectable._subject = null;\n                  connectable._connection = null;\n                  if (connection) {\n                      connection.unsubscribe();\n                  }\n              }\n          };\n          return ConnectableSubscriber;\n      }(SubjectSubscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */\n      var BehaviorSubject = /*@__PURE__*/ (function (_super) {\n          __extends(BehaviorSubject, _super);\n          function BehaviorSubject(_value) {\n              var _this = _super.call(this) || this;\n              _this._value = _value;\n              return _this;\n          }\n          Object.defineProperty(BehaviorSubject.prototype, \"value\", {\n              get: function () {\n                  return this.getValue();\n              },\n              enumerable: true,\n              configurable: true\n          });\n          BehaviorSubject.prototype._subscribe = function (subscriber) {\n              var subscription = _super.prototype._subscribe.call(this, subscriber);\n              if (subscription && !subscription.closed) {\n                  subscriber.next(this._value);\n              }\n              return subscription;\n          };\n          BehaviorSubject.prototype.getValue = function () {\n              if (this.hasError) {\n                  throw this.thrownError;\n              }\n              else if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              else {\n                  return this._value;\n              }\n          };\n          BehaviorSubject.prototype.next = function (value) {\n              _super.prototype.next.call(this, this._value = value);\n          };\n          return BehaviorSubject;\n      }(Subject));\n    \n      /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */\n      var Action = /*@__PURE__*/ (function (_super) {\n          __extends(Action, _super);\n          function Action(scheduler, work) {\n              return _super.call(this) || this;\n          }\n          Action.prototype.schedule = function (state, delay) {\n              return this;\n          };\n          return Action;\n      }(Subscription));\n    \n      /** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */\n      var AsyncAction = /*@__PURE__*/ (function (_super) {\n          __extends(AsyncAction, _super);\n          function AsyncAction(scheduler, work) {\n              var _this = _super.call(this, scheduler, work) || this;\n              _this.scheduler = scheduler;\n              _this.work = work;\n              _this.pending = false;\n              return _this;\n          }\n          AsyncAction.prototype.schedule = function (state, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              if (this.closed) {\n                  return this;\n              }\n              this.state = state;\n              var id = this.id;\n              var scheduler = this.scheduler;\n              if (id != null) {\n                  this.id = this.recycleAsyncId(scheduler, id, delay);\n              }\n              this.pending = true;\n              this.delay = delay;\n              this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);\n              return this;\n          };\n          AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              return setInterval(scheduler.flush.bind(scheduler, this), delay);\n          };\n          AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              if (delay !== null && this.delay === delay && this.pending === false) {\n                  return id;\n              }\n              clearInterval(id);\n              return undefined;\n          };\n          AsyncAction.prototype.execute = function (state, delay) {\n              if (this.closed) {\n                  return new Error('executing a cancelled action');\n              }\n              this.pending = false;\n              var error = this._execute(state, delay);\n              if (error) {\n                  return error;\n              }\n              else if (this.pending === false && this.id != null) {\n                  this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n              }\n          };\n          AsyncAction.prototype._execute = function (state, delay) {\n              var errored = false;\n              var errorValue = undefined;\n              try {\n                  this.work(state);\n              }\n              catch (e) {\n                  errored = true;\n                  errorValue = !!e && e || new Error(e);\n              }\n              if (errored) {\n                  this.unsubscribe();\n                  return errorValue;\n              }\n          };\n          AsyncAction.prototype._unsubscribe = function () {\n              var id = this.id;\n              var scheduler = this.scheduler;\n              var actions = scheduler.actions;\n              var index = actions.indexOf(this);\n              this.work = null;\n              this.state = null;\n              this.pending = false;\n              this.scheduler = null;\n              if (index !== -1) {\n                  actions.splice(index, 1);\n              }\n              if (id != null) {\n                  this.id = this.recycleAsyncId(scheduler, id, null);\n              }\n              this.delay = null;\n          };\n          return AsyncAction;\n      }(Action));\n    \n      /** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */\n      var QueueAction = /*@__PURE__*/ (function (_super) {\n          __extends(QueueAction, _super);\n          function QueueAction(scheduler, work) {\n              var _this = _super.call(this, scheduler, work) || this;\n              _this.scheduler = scheduler;\n              _this.work = work;\n              return _this;\n          }\n          QueueAction.prototype.schedule = function (state, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              if (delay > 0) {\n                  return _super.prototype.schedule.call(this, state, delay);\n              }\n              this.delay = delay;\n              this.state = state;\n              this.scheduler.flush(this);\n              return this;\n          };\n          QueueAction.prototype.execute = function (state, delay) {\n              return (delay > 0 || this.closed) ?\n                  _super.prototype.execute.call(this, state, delay) :\n                  this._execute(state, delay);\n          };\n          QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {\n                  return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);\n              }\n              return scheduler.flush(this);\n          };\n          return QueueAction;\n      }(AsyncAction));\n    \n      var Scheduler = /*@__PURE__*/ (function () {\n          function Scheduler(SchedulerAction, now) {\n              if (now === void 0) {\n                  now = Scheduler.now;\n              }\n              this.SchedulerAction = SchedulerAction;\n              this.now = now;\n          }\n          Scheduler.prototype.schedule = function (work, delay, state) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              return new this.SchedulerAction(this, work).schedule(state, delay);\n          };\n          Scheduler.now = function () { return Date.now(); };\n          return Scheduler;\n      }());\n    \n      /** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */\n      var AsyncScheduler = /*@__PURE__*/ (function (_super) {\n          __extends(AsyncScheduler, _super);\n          function AsyncScheduler(SchedulerAction, now) {\n              if (now === void 0) {\n                  now = Scheduler.now;\n              }\n              var _this = _super.call(this, SchedulerAction, function () {\n                  if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) {\n                      return AsyncScheduler.delegate.now();\n                  }\n                  else {\n                      return now();\n                  }\n              }) || this;\n              _this.actions = [];\n              _this.active = false;\n              _this.scheduled = undefined;\n              return _this;\n          }\n          AsyncScheduler.prototype.schedule = function (work, delay, state) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n                  return AsyncScheduler.delegate.schedule(work, delay, state);\n              }\n              else {\n                  return _super.prototype.schedule.call(this, work, delay, state);\n              }\n          };\n          AsyncScheduler.prototype.flush = function (action) {\n              var actions = this.actions;\n              if (this.active) {\n                  actions.push(action);\n                  return;\n              }\n              var error;\n              this.active = true;\n              do {\n                  if (error = action.execute(action.state, action.delay)) {\n                      break;\n                  }\n              } while (action = actions.shift());\n              this.active = false;\n              if (error) {\n                  while (action = actions.shift()) {\n                      action.unsubscribe();\n                  }\n                  throw error;\n              }\n          };\n          return AsyncScheduler;\n      }(Scheduler));\n    \n      /** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */\n      var QueueScheduler = /*@__PURE__*/ (function (_super) {\n          __extends(QueueScheduler, _super);\n          function QueueScheduler() {\n              return _super !== null && _super.apply(this, arguments) || this;\n          }\n          return QueueScheduler;\n      }(AsyncScheduler));\n    \n      /** PURE_IMPORTS_START _QueueAction,_QueueScheduler PURE_IMPORTS_END */\n      var queueScheduler = /*@__PURE__*/ new QueueScheduler(QueueAction);\n      var queue = queueScheduler;\n    \n      /** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */\n      var EMPTY = /*@__PURE__*/ new Observable(function (subscriber) { return subscriber.complete(); });\n      function empty(scheduler) {\n          return scheduler ? emptyScheduled(scheduler) : EMPTY;\n      }\n      function emptyScheduled(scheduler) {\n          return new Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function isScheduler(value) {\n          return value && typeof value.schedule === 'function';\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var subscribeToArray = function (array) {\n          return function (subscriber) {\n              for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n                  subscriber.next(array[i]);\n              }\n              subscriber.complete();\n          };\n      };\n    \n      /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */\n      function scheduleArray(input, scheduler) {\n          return new Observable(function (subscriber) {\n              var sub = new Subscription();\n              var i = 0;\n              sub.add(scheduler.schedule(function () {\n                  if (i === input.length) {\n                      subscriber.complete();\n                      return;\n                  }\n                  subscriber.next(input[i++]);\n                  if (!subscriber.closed) {\n                      sub.add(this.schedule());\n                  }\n              }));\n              return sub;\n          });\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */\n      function fromArray(input, scheduler) {\n          if (!scheduler) {\n              return new Observable(subscribeToArray(input));\n          }\n          else {\n              return scheduleArray(input, scheduler);\n          }\n      }\n    \n      /** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */\n      function of() {\n          var args = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              args[_i] = arguments[_i];\n          }\n          var scheduler = args[args.length - 1];\n          if (isScheduler(scheduler)) {\n              args.pop();\n              return scheduleArray(args, scheduler);\n          }\n          else {\n              return fromArray(args);\n          }\n      }\n    \n      /** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */\n      function throwError(error, scheduler) {\n          if (!scheduler) {\n              return new Observable(function (subscriber) { return subscriber.error(error); });\n          }\n          else {\n              return new Observable(function (subscriber) { return scheduler.schedule(dispatch$1, 0, { error: error, subscriber: subscriber }); });\n          }\n      }\n      function dispatch$1(_a) {\n          var error = _a.error, subscriber = _a.subscriber;\n          subscriber.error(error);\n      }\n    \n      /** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */\n      var Notification = /*@__PURE__*/ (function () {\n          function Notification(kind, value, error) {\n              this.kind = kind;\n              this.value = value;\n              this.error = error;\n              this.hasValue = kind === 'N';\n          }\n          Notification.prototype.observe = function (observer) {\n              switch (this.kind) {\n                  case 'N':\n                      return observer.next && observer.next(this.value);\n                  case 'E':\n                      return observer.error && observer.error(this.error);\n                  case 'C':\n                      return observer.complete && observer.complete();\n              }\n          };\n          Notification.prototype.do = function (next, error, complete) {\n              var kind = this.kind;\n              switch (kind) {\n                  case 'N':\n                      return next && next(this.value);\n                  case 'E':\n                      return error && error(this.error);\n                  case 'C':\n                      return complete && complete();\n              }\n          };\n          Notification.prototype.accept = function (nextOrObserver, error, complete) {\n              if (nextOrObserver && typeof nextOrObserver.next === 'function') {\n                  return this.observe(nextOrObserver);\n              }\n              else {\n                  return this.do(nextOrObserver, error, complete);\n              }\n          };\n          Notification.prototype.toObservable = function () {\n              var kind = this.kind;\n              switch (kind) {\n                  case 'N':\n                      return of(this.value);\n                  case 'E':\n                      return throwError(this.error);\n                  case 'C':\n                      return empty();\n              }\n              throw new Error('unexpected notification kind value');\n          };\n          Notification.createNext = function (value) {\n              if (typeof value !== 'undefined') {\n                  return new Notification('N', value);\n              }\n              return Notification.undefinedValueNotification;\n          };\n          Notification.createError = function (err) {\n              return new Notification('E', undefined, err);\n          };\n          Notification.createComplete = function () {\n              return Notification.completeNotification;\n          };\n          Notification.completeNotification = new Notification('C');\n          Notification.undefinedValueNotification = new Notification('N', undefined);\n          return Notification;\n      }());\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */\n      function observeOn(scheduler, delay) {\n          if (delay === void 0) {\n              delay = 0;\n          }\n          return function observeOnOperatorFunction(source) {\n              return source.lift(new ObserveOnOperator(scheduler, delay));\n          };\n      }\n      var ObserveOnOperator = /*@__PURE__*/ (function () {\n          function ObserveOnOperator(scheduler, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              this.scheduler = scheduler;\n              this.delay = delay;\n          }\n          ObserveOnOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));\n          };\n          return ObserveOnOperator;\n      }());\n      var ObserveOnSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(ObserveOnSubscriber, _super);\n          function ObserveOnSubscriber(destination, scheduler, delay) {\n              if (delay === void 0) {\n                  delay = 0;\n              }\n              var _this = _super.call(this, destination) || this;\n              _this.scheduler = scheduler;\n              _this.delay = delay;\n              return _this;\n          }\n          ObserveOnSubscriber.dispatch = function (arg) {\n              var notification = arg.notification, destination = arg.destination;\n              notification.observe(destination);\n              this.unsubscribe();\n          };\n          ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {\n              var destination = this.destination;\n              destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));\n          };\n          ObserveOnSubscriber.prototype._next = function (value) {\n              this.scheduleMessage(Notification.createNext(value));\n          };\n          ObserveOnSubscriber.prototype._error = function (err) {\n              this.scheduleMessage(Notification.createError(err));\n              this.unsubscribe();\n          };\n          ObserveOnSubscriber.prototype._complete = function () {\n              this.scheduleMessage(Notification.createComplete());\n              this.unsubscribe();\n          };\n          return ObserveOnSubscriber;\n      }(Subscriber));\n      var ObserveOnMessage = /*@__PURE__*/ (function () {\n          function ObserveOnMessage(notification, destination) {\n              this.notification = notification;\n              this.destination = destination;\n          }\n          return ObserveOnMessage;\n      }());\n    \n      /** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */\n      var ReplaySubject = /*@__PURE__*/ (function (_super) {\n          __extends(ReplaySubject, _super);\n          function ReplaySubject(bufferSize, windowTime, scheduler) {\n              if (bufferSize === void 0) {\n                  bufferSize = Number.POSITIVE_INFINITY;\n              }\n              if (windowTime === void 0) {\n                  windowTime = Number.POSITIVE_INFINITY;\n              }\n              var _this = _super.call(this) || this;\n              _this.scheduler = scheduler;\n              _this._events = [];\n              _this._infiniteTimeWindow = false;\n              _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;\n              _this._windowTime = windowTime < 1 ? 1 : windowTime;\n              if (windowTime === Number.POSITIVE_INFINITY) {\n                  _this._infiniteTimeWindow = true;\n                  _this.next = _this.nextInfiniteTimeWindow;\n              }\n              else {\n                  _this.next = _this.nextTimeWindow;\n              }\n              return _this;\n          }\n          ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) {\n              if (!this.isStopped) {\n                  var _events = this._events;\n                  _events.push(value);\n                  if (_events.length > this._bufferSize) {\n                      _events.shift();\n                  }\n              }\n              _super.prototype.next.call(this, value);\n          };\n          ReplaySubject.prototype.nextTimeWindow = function (value) {\n              if (!this.isStopped) {\n                  this._events.push(new ReplayEvent(this._getNow(), value));\n                  this._trimBufferThenGetEvents();\n              }\n              _super.prototype.next.call(this, value);\n          };\n          ReplaySubject.prototype._subscribe = function (subscriber) {\n              var _infiniteTimeWindow = this._infiniteTimeWindow;\n              var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();\n              var scheduler = this.scheduler;\n              var len = _events.length;\n              var subscription;\n              if (this.closed) {\n                  throw new ObjectUnsubscribedError();\n              }\n              else if (this.isStopped || this.hasError) {\n                  subscription = Subscription.EMPTY;\n              }\n              else {\n                  this.observers.push(subscriber);\n                  subscription = new SubjectSubscription(this, subscriber);\n              }\n              if (scheduler) {\n                  subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));\n              }\n              if (_infiniteTimeWindow) {\n                  for (var i = 0; i < len && !subscriber.closed; i++) {\n                      subscriber.next(_events[i]);\n                  }\n              }\n              else {\n                  for (var i = 0; i < len && !subscriber.closed; i++) {\n                      subscriber.next(_events[i].value);\n                  }\n              }\n              if (this.hasError) {\n                  subscriber.error(this.thrownError);\n              }\n              else if (this.isStopped) {\n                  subscriber.complete();\n              }\n              return subscription;\n          };\n          ReplaySubject.prototype._getNow = function () {\n              return (this.scheduler || queue).now();\n          };\n          ReplaySubject.prototype._trimBufferThenGetEvents = function () {\n              var now = this._getNow();\n              var _bufferSize = this._bufferSize;\n              var _windowTime = this._windowTime;\n              var _events = this._events;\n              var eventsCount = _events.length;\n              var spliceCount = 0;\n              while (spliceCount < eventsCount) {\n                  if ((now - _events[spliceCount].time) < _windowTime) {\n                      break;\n                  }\n                  spliceCount++;\n              }\n              if (eventsCount > _bufferSize) {\n                  spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);\n              }\n              if (spliceCount > 0) {\n                  _events.splice(0, spliceCount);\n              }\n              return _events;\n          };\n          return ReplaySubject;\n      }(Subject));\n      var ReplayEvent = /*@__PURE__*/ (function () {\n          function ReplayEvent(time, value) {\n              this.time = time;\n              this.value = value;\n          }\n          return ReplayEvent;\n      }());\n    \n      /** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */\n      var AsyncSubject = /*@__PURE__*/ (function (_super) {\n          __extends(AsyncSubject, _super);\n          function AsyncSubject() {\n              var _this = _super !== null && _super.apply(this, arguments) || this;\n              _this.value = null;\n              _this.hasNext = false;\n              _this.hasCompleted = false;\n              return _this;\n          }\n          AsyncSubject.prototype._subscribe = function (subscriber) {\n              if (this.hasError) {\n                  subscriber.error(this.thrownError);\n                  return Subscription.EMPTY;\n              }\n              else if (this.hasCompleted && this.hasNext) {\n                  subscriber.next(this.value);\n                  subscriber.complete();\n                  return Subscription.EMPTY;\n              }\n              return _super.prototype._subscribe.call(this, subscriber);\n          };\n          AsyncSubject.prototype.next = function (value) {\n              if (!this.hasCompleted) {\n                  this.value = value;\n                  this.hasNext = true;\n              }\n          };\n          AsyncSubject.prototype.error = function (error) {\n              if (!this.hasCompleted) {\n                  _super.prototype.error.call(this, error);\n              }\n          };\n          AsyncSubject.prototype.complete = function () {\n              this.hasCompleted = true;\n              if (this.hasNext) {\n                  _super.prototype.next.call(this, this.value);\n              }\n              _super.prototype.complete.call(this);\n          };\n          return AsyncSubject;\n      }(Subject));\n    \n      /** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */\n      var asyncScheduler = /*@__PURE__*/ new AsyncScheduler(AsyncAction);\n      var async = asyncScheduler;\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function noop() { }\n    \n      /** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */\n      function isObservable(obj) {\n          return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));\n      }\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var ArgumentOutOfRangeErrorImpl = /*@__PURE__*/ (function () {\n          function ArgumentOutOfRangeErrorImpl() {\n              Error.call(this);\n              this.message = 'argument out of range';\n              this.name = 'ArgumentOutOfRangeError';\n              return this;\n          }\n          ArgumentOutOfRangeErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n          return ArgumentOutOfRangeErrorImpl;\n      })();\n      var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var TimeoutErrorImpl = /*@__PURE__*/ (function () {\n          function TimeoutErrorImpl() {\n              Error.call(this);\n              this.message = 'Timeout has occurred';\n              this.name = 'TimeoutError';\n              return this;\n          }\n          TimeoutErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n          return TimeoutErrorImpl;\n      })();\n      var TimeoutError = TimeoutErrorImpl;\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function map(project, thisArg) {\n          return function mapOperation(source) {\n              if (typeof project !== 'function') {\n                  throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n              }\n              return source.lift(new MapOperator(project, thisArg));\n          };\n      }\n      var MapOperator = /*@__PURE__*/ (function () {\n          function MapOperator(project, thisArg) {\n              this.project = project;\n              this.thisArg = thisArg;\n          }\n          MapOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n          };\n          return MapOperator;\n      }());\n      var MapSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(MapSubscriber, _super);\n          function MapSubscriber(destination, project, thisArg) {\n              var _this = _super.call(this, destination) || this;\n              _this.project = project;\n              _this.count = 0;\n              _this.thisArg = thisArg || _this;\n              return _this;\n          }\n          MapSubscriber.prototype._next = function (value) {\n              var result;\n              try {\n                  result = this.project.call(this.thisArg, value, this.count++);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.destination.next(result);\n          };\n          return MapSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      var OuterSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(OuterSubscriber, _super);\n          function OuterSubscriber() {\n              return _super !== null && _super.apply(this, arguments) || this;\n          }\n          OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n              this.destination.next(innerValue);\n          };\n          OuterSubscriber.prototype.notifyError = function (error, innerSub) {\n              this.destination.error(error);\n          };\n          OuterSubscriber.prototype.notifyComplete = function (innerSub) {\n              this.destination.complete();\n          };\n          return OuterSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      var InnerSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(InnerSubscriber, _super);\n          function InnerSubscriber(parent, outerValue, outerIndex) {\n              var _this = _super.call(this) || this;\n              _this.parent = parent;\n              _this.outerValue = outerValue;\n              _this.outerIndex = outerIndex;\n              _this.index = 0;\n              return _this;\n          }\n          InnerSubscriber.prototype._next = function (value) {\n              this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);\n          };\n          InnerSubscriber.prototype._error = function (error) {\n              this.parent.notifyError(error, this);\n              this.unsubscribe();\n          };\n          InnerSubscriber.prototype._complete = function () {\n              this.parent.notifyComplete(this);\n              this.unsubscribe();\n          };\n          return InnerSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */\n      var subscribeToPromise = function (promise) {\n          return function (subscriber) {\n              promise.then(function (value) {\n                  if (!subscriber.closed) {\n                      subscriber.next(value);\n                      subscriber.complete();\n                  }\n              }, function (err) { return subscriber.error(err); })\n                  .then(null, hostReportError);\n              return subscriber;\n          };\n      };\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function getSymbolIterator() {\n          if (typeof Symbol !== 'function' || !Symbol.iterator) {\n              return '@@iterator';\n          }\n          return Symbol.iterator;\n      }\n      var iterator = /*@__PURE__*/ getSymbolIterator();\n    \n      /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */\n      var subscribeToIterable = function (iterable) {\n          return function (subscriber) {\n              var iterator$1 = iterable[iterator]();\n              do {\n                  var item = void 0;\n                  try {\n                      item = iterator$1.next();\n                  }\n                  catch (err) {\n                      subscriber.error(err);\n                      return subscriber;\n                  }\n                  if (item.done) {\n                      subscriber.complete();\n                      break;\n                  }\n                  subscriber.next(item.value);\n                  if (subscriber.closed) {\n                      break;\n                  }\n              } while (true);\n              if (typeof iterator$1.return === 'function') {\n                  subscriber.add(function () {\n                      if (iterator$1.return) {\n                          iterator$1.return();\n                      }\n                  });\n              }\n              return subscriber;\n          };\n      };\n    \n      /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */\n      var subscribeToObservable = function (obj) {\n          return function (subscriber) {\n              var obs = obj[observable]();\n              if (typeof obs.subscribe !== 'function') {\n                  throw new TypeError('Provided object does not correctly implement Symbol.observable');\n              }\n              else {\n                  return obs.subscribe(subscriber);\n              }\n          };\n      };\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function isPromise(value) {\n          return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';\n      }\n    \n      /** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */\n      var subscribeTo = function (result) {\n          if (!!result && typeof result[observable] === 'function') {\n              return subscribeToObservable(result);\n          }\n          else if (isArrayLike(result)) {\n              return subscribeToArray(result);\n          }\n          else if (isPromise(result)) {\n              return subscribeToPromise(result);\n          }\n          else if (!!result && typeof result[iterator] === 'function') {\n              return subscribeToIterable(result);\n          }\n          else {\n              var value = isObject$1(result) ? 'an invalid object' : \"'\" + result + \"'\";\n              var msg = \"You provided \" + value + \" where a stream was expected.\"\n                  + ' You can provide an Observable, Promise, Array, or Iterable.';\n              throw new TypeError(msg);\n          }\n      };\n    \n      /** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */\n      function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) {\n          if (innerSubscriber === void 0) {\n              innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex);\n          }\n          if (innerSubscriber.closed) {\n              return undefined;\n          }\n          if (result instanceof Observable) {\n              return result.subscribe(innerSubscriber);\n          }\n          return subscribeTo(result)(innerSubscriber);\n      }\n    \n      /** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */\n      var NONE = {};\n      function combineLatest() {\n          var observables = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              observables[_i] = arguments[_i];\n          }\n          var resultSelector = undefined;\n          var scheduler = undefined;\n          if (isScheduler(observables[observables.length - 1])) {\n              scheduler = observables.pop();\n          }\n          if (typeof observables[observables.length - 1] === 'function') {\n              resultSelector = observables.pop();\n          }\n          if (observables.length === 1 && isArray$1(observables[0])) {\n              observables = observables[0];\n          }\n          return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));\n      }\n      var CombineLatestOperator = /*@__PURE__*/ (function () {\n          function CombineLatestOperator(resultSelector) {\n              this.resultSelector = resultSelector;\n          }\n          CombineLatestOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));\n          };\n          return CombineLatestOperator;\n      }());\n      var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(CombineLatestSubscriber, _super);\n          function CombineLatestSubscriber(destination, resultSelector) {\n              var _this = _super.call(this, destination) || this;\n              _this.resultSelector = resultSelector;\n              _this.active = 0;\n              _this.values = [];\n              _this.observables = [];\n              return _this;\n          }\n          CombineLatestSubscriber.prototype._next = function (observable) {\n              this.values.push(NONE);\n              this.observables.push(observable);\n          };\n          CombineLatestSubscriber.prototype._complete = function () {\n              var observables = this.observables;\n              var len = observables.length;\n              if (len === 0) {\n                  this.destination.complete();\n              }\n              else {\n                  this.active = len;\n                  this.toRespond = len;\n                  for (var i = 0; i < len; i++) {\n                      var observable = observables[i];\n                      this.add(subscribeToResult(this, observable, undefined, i));\n                  }\n              }\n          };\n          CombineLatestSubscriber.prototype.notifyComplete = function (unused) {\n              if ((this.active -= 1) === 0) {\n                  this.destination.complete();\n              }\n          };\n          CombineLatestSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) {\n              var values = this.values;\n              var oldVal = values[outerIndex];\n              var toRespond = !this.toRespond\n                  ? 0\n                  : oldVal === NONE ? --this.toRespond : this.toRespond;\n              values[outerIndex] = innerValue;\n              if (toRespond === 0) {\n                  if (this.resultSelector) {\n                      this._tryResultSelector(values);\n                  }\n                  else {\n                      this.destination.next(values.slice());\n                  }\n              }\n          };\n          CombineLatestSubscriber.prototype._tryResultSelector = function (values) {\n              var result;\n              try {\n                  result = this.resultSelector.apply(this, values);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.destination.next(result);\n          };\n          return CombineLatestSubscriber;\n      }(OuterSubscriber));\n    \n      /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */\n      function scheduleObservable(input, scheduler) {\n          return new Observable(function (subscriber) {\n              var sub = new Subscription();\n              sub.add(scheduler.schedule(function () {\n                  var observable$1 = input[observable]();\n                  sub.add(observable$1.subscribe({\n                      next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },\n                      error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },\n                      complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },\n                  }));\n              }));\n              return sub;\n          });\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */\n      function schedulePromise(input, scheduler) {\n          return new Observable(function (subscriber) {\n              var sub = new Subscription();\n              sub.add(scheduler.schedule(function () {\n                  return input.then(function (value) {\n                      sub.add(scheduler.schedule(function () {\n                          subscriber.next(value);\n                          sub.add(scheduler.schedule(function () { return subscriber.complete(); }));\n                      }));\n                  }, function (err) {\n                      sub.add(scheduler.schedule(function () { return subscriber.error(err); }));\n                  });\n              }));\n              return sub;\n          });\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */\n      function scheduleIterable(input, scheduler) {\n          if (!input) {\n              throw new Error('Iterable cannot be null');\n          }\n          return new Observable(function (subscriber) {\n              var sub = new Subscription();\n              var iterator$1;\n              sub.add(function () {\n                  if (iterator$1 && typeof iterator$1.return === 'function') {\n                      iterator$1.return();\n                  }\n              });\n              sub.add(scheduler.schedule(function () {\n                  iterator$1 = input[iterator]();\n                  sub.add(scheduler.schedule(function () {\n                      if (subscriber.closed) {\n                          return;\n                      }\n                      var value;\n                      var done;\n                      try {\n                          var result = iterator$1.next();\n                          value = result.value;\n                          done = result.done;\n                      }\n                      catch (err) {\n                          subscriber.error(err);\n                          return;\n                      }\n                      if (done) {\n                          subscriber.complete();\n                      }\n                      else {\n                          subscriber.next(value);\n                          this.schedule();\n                      }\n                  }));\n              }));\n              return sub;\n          });\n      }\n    \n      /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */\n      function isInteropObservable(input) {\n          return input && typeof input[observable] === 'function';\n      }\n    \n      /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */\n      function isIterable(input) {\n          return input && typeof input[iterator] === 'function';\n      }\n    \n      /** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */\n      function scheduled(input, scheduler) {\n          if (input != null) {\n              if (isInteropObservable(input)) {\n                  return scheduleObservable(input, scheduler);\n              }\n              else if (isPromise(input)) {\n                  return schedulePromise(input, scheduler);\n              }\n              else if (isArrayLike(input)) {\n                  return scheduleArray(input, scheduler);\n              }\n              else if (isIterable(input) || typeof input === 'string') {\n                  return scheduleIterable(input, scheduler);\n              }\n          }\n          throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */\n      function from(input, scheduler) {\n          if (!scheduler) {\n              if (input instanceof Observable) {\n                  return input;\n              }\n              return new Observable(subscribeTo(input));\n          }\n          else {\n              return scheduled(input, scheduler);\n          }\n      }\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_util_subscribeTo PURE_IMPORTS_END */\n      var SimpleInnerSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SimpleInnerSubscriber, _super);\n          function SimpleInnerSubscriber(parent) {\n              var _this = _super.call(this) || this;\n              _this.parent = parent;\n              return _this;\n          }\n          SimpleInnerSubscriber.prototype._next = function (value) {\n              this.parent.notifyNext(value);\n          };\n          SimpleInnerSubscriber.prototype._error = function (error) {\n              this.parent.notifyError(error);\n              this.unsubscribe();\n          };\n          SimpleInnerSubscriber.prototype._complete = function () {\n              this.parent.notifyComplete();\n              this.unsubscribe();\n          };\n          return SimpleInnerSubscriber;\n      }(Subscriber));\n      var SimpleOuterSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SimpleOuterSubscriber, _super);\n          function SimpleOuterSubscriber() {\n              return _super !== null && _super.apply(this, arguments) || this;\n          }\n          SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) {\n              this.destination.next(innerValue);\n          };\n          SimpleOuterSubscriber.prototype.notifyError = function (err) {\n              this.destination.error(err);\n          };\n          SimpleOuterSubscriber.prototype.notifyComplete = function () {\n              this.destination.complete();\n          };\n          return SimpleOuterSubscriber;\n      }(Subscriber));\n      function innerSubscribe(result, innerSubscriber) {\n          if (innerSubscriber.closed) {\n              return undefined;\n          }\n          if (result instanceof Observable) {\n              return result.subscribe(innerSubscriber);\n          }\n          return subscribeTo(result)(innerSubscriber);\n      }\n    \n      /** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */\n      function mergeMap(project, resultSelector, concurrent) {\n          if (concurrent === void 0) {\n              concurrent = Number.POSITIVE_INFINITY;\n          }\n          if (typeof resultSelector === 'function') {\n              return function (source) { return source.pipe(mergeMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); };\n          }\n          else if (typeof resultSelector === 'number') {\n              concurrent = resultSelector;\n          }\n          return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };\n      }\n      var MergeMapOperator = /*@__PURE__*/ (function () {\n          function MergeMapOperator(project, concurrent) {\n              if (concurrent === void 0) {\n                  concurrent = Number.POSITIVE_INFINITY;\n              }\n              this.project = project;\n              this.concurrent = concurrent;\n          }\n          MergeMapOperator.prototype.call = function (observer, source) {\n              return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));\n          };\n          return MergeMapOperator;\n      }());\n      var MergeMapSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(MergeMapSubscriber, _super);\n          function MergeMapSubscriber(destination, project, concurrent) {\n              if (concurrent === void 0) {\n                  concurrent = Number.POSITIVE_INFINITY;\n              }\n              var _this = _super.call(this, destination) || this;\n              _this.project = project;\n              _this.concurrent = concurrent;\n              _this.hasCompleted = false;\n              _this.buffer = [];\n              _this.active = 0;\n              _this.index = 0;\n              return _this;\n          }\n          MergeMapSubscriber.prototype._next = function (value) {\n              if (this.active < this.concurrent) {\n                  this._tryNext(value);\n              }\n              else {\n                  this.buffer.push(value);\n              }\n          };\n          MergeMapSubscriber.prototype._tryNext = function (value) {\n              var result;\n              var index = this.index++;\n              try {\n                  result = this.project(value, index);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.active++;\n              this._innerSub(result);\n          };\n          MergeMapSubscriber.prototype._innerSub = function (ish) {\n              var innerSubscriber = new SimpleInnerSubscriber(this);\n              var destination = this.destination;\n              destination.add(innerSubscriber);\n              var innerSubscription = innerSubscribe(ish, innerSubscriber);\n              if (innerSubscription !== innerSubscriber) {\n                  destination.add(innerSubscription);\n              }\n          };\n          MergeMapSubscriber.prototype._complete = function () {\n              this.hasCompleted = true;\n              if (this.active === 0 && this.buffer.length === 0) {\n                  this.destination.complete();\n              }\n              this.unsubscribe();\n          };\n          MergeMapSubscriber.prototype.notifyNext = function (innerValue) {\n              this.destination.next(innerValue);\n          };\n          MergeMapSubscriber.prototype.notifyComplete = function () {\n              var buffer = this.buffer;\n              this.active--;\n              if (buffer.length > 0) {\n                  this._next(buffer.shift());\n              }\n              else if (this.active === 0 && this.hasCompleted) {\n                  this.destination.complete();\n              }\n          };\n          return MergeMapSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */\n      function mergeAll(concurrent) {\n          if (concurrent === void 0) {\n              concurrent = Number.POSITIVE_INFINITY;\n          }\n          return mergeMap(identity, concurrent);\n      }\n    \n      /** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */\n      function concatAll() {\n          return mergeAll(1);\n      }\n    \n      /** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */\n      function concat() {\n          var observables = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              observables[_i] = arguments[_i];\n          }\n          return concatAll()(of.apply(void 0, observables));\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */\n      function defer(observableFactory) {\n          return new Observable(function (subscriber) {\n              var input;\n              try {\n                  input = observableFactory();\n              }\n              catch (err) {\n                  subscriber.error(err);\n                  return undefined;\n              }\n              var source = input ? from(input) : empty();\n              return source.subscribe(subscriber);\n          });\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */\n      function forkJoin() {\n          var sources = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              sources[_i] = arguments[_i];\n          }\n          if (sources.length === 1) {\n              var first_1 = sources[0];\n              if (isArray$1(first_1)) {\n                  return forkJoinInternal(first_1, null);\n              }\n              if (isObject$1(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) {\n                  var keys = Object.keys(first_1);\n                  return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys);\n              }\n          }\n          if (typeof sources[sources.length - 1] === 'function') {\n              var resultSelector_1 = sources.pop();\n              sources = (sources.length === 1 && isArray$1(sources[0])) ? sources[0] : sources;\n              return forkJoinInternal(sources, null).pipe(map(function (args) { return resultSelector_1.apply(void 0, args); }));\n          }\n          return forkJoinInternal(sources, null);\n      }\n      function forkJoinInternal(sources, keys) {\n          return new Observable(function (subscriber) {\n              var len = sources.length;\n              if (len === 0) {\n                  subscriber.complete();\n                  return;\n              }\n              var values = new Array(len);\n              var completed = 0;\n              var emitted = 0;\n              var _loop_1 = function (i) {\n                  var source = from(sources[i]);\n                  var hasValue = false;\n                  subscriber.add(source.subscribe({\n                      next: function (value) {\n                          if (!hasValue) {\n                              hasValue = true;\n                              emitted++;\n                          }\n                          values[i] = value;\n                      },\n                      error: function (err) { return subscriber.error(err); },\n                      complete: function () {\n                          completed++;\n                          if (completed === len || !hasValue) {\n                              if (emitted === len) {\n                                  subscriber.next(keys ?\n                                      keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) :\n                                      values);\n                              }\n                              subscriber.complete();\n                          }\n                      }\n                  }));\n              };\n              for (var i = 0; i < len; i++) {\n                  _loop_1(i);\n              }\n          });\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */\n      function fromEvent(target, eventName, options, resultSelector) {\n          if (isFunction$1(options)) {\n              resultSelector = options;\n              options = undefined;\n          }\n          if (resultSelector) {\n              return fromEvent(target, eventName, options).pipe(map(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));\n          }\n          return new Observable(function (subscriber) {\n              function handler(e) {\n                  if (arguments.length > 1) {\n                      subscriber.next(Array.prototype.slice.call(arguments));\n                  }\n                  else {\n                      subscriber.next(e);\n                  }\n              }\n              setupSubscription(target, eventName, handler, subscriber, options);\n          });\n      }\n      function setupSubscription(sourceObj, eventName, handler, subscriber, options) {\n          var unsubscribe;\n          if (isEventTarget(sourceObj)) {\n              var source_1 = sourceObj;\n              sourceObj.addEventListener(eventName, handler, options);\n              unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };\n          }\n          else if (isJQueryStyleEventEmitter(sourceObj)) {\n              var source_2 = sourceObj;\n              sourceObj.on(eventName, handler);\n              unsubscribe = function () { return source_2.off(eventName, handler); };\n          }\n          else if (isNodeStyleEventEmitter(sourceObj)) {\n              var source_3 = sourceObj;\n              sourceObj.addListener(eventName, handler);\n              unsubscribe = function () { return source_3.removeListener(eventName, handler); };\n          }\n          else if (sourceObj && sourceObj.length) {\n              for (var i = 0, len = sourceObj.length; i < len; i++) {\n                  setupSubscription(sourceObj[i], eventName, handler, subscriber, options);\n              }\n          }\n          else {\n              throw new TypeError('Invalid event target');\n          }\n          subscriber.add(unsubscribe);\n      }\n      function isNodeStyleEventEmitter(sourceObj) {\n          return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';\n      }\n      function isJQueryStyleEventEmitter(sourceObj) {\n          return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';\n      }\n      function isEventTarget(sourceObj) {\n          return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';\n      }\n    \n      /** PURE_IMPORTS_START _defer,_empty PURE_IMPORTS_END */\n      function iif(condition, trueResult, falseResult) {\n          if (trueResult === void 0) {\n              trueResult = EMPTY;\n          }\n          if (falseResult === void 0) {\n              falseResult = EMPTY;\n          }\n          return defer(function () { return condition() ? trueResult : falseResult; });\n      }\n    \n      /** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */\n      function isNumeric(val) {\n          return !isArray$1(val) && (val - parseFloat(val) + 1) >= 0;\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */\n      function merge() {\n          var observables = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              observables[_i] = arguments[_i];\n          }\n          var concurrent = Number.POSITIVE_INFINITY;\n          var scheduler = null;\n          var last = observables[observables.length - 1];\n          if (isScheduler(last)) {\n              scheduler = observables.pop();\n              if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {\n                  concurrent = observables.pop();\n              }\n          }\n          else if (typeof last === 'number') {\n              concurrent = observables.pop();\n          }\n          if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {\n              return observables[0];\n          }\n          return mergeAll(concurrent)(fromArray(observables, scheduler));\n      }\n    \n      /** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */\n      var NEVER = /*@__PURE__*/ new Observable(noop);\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function filter(predicate, thisArg) {\n          return function filterOperatorFunction(source) {\n              return source.lift(new FilterOperator(predicate, thisArg));\n          };\n      }\n      var FilterOperator = /*@__PURE__*/ (function () {\n          function FilterOperator(predicate, thisArg) {\n              this.predicate = predicate;\n              this.thisArg = thisArg;\n          }\n          FilterOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n          };\n          return FilterOperator;\n      }());\n      var FilterSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(FilterSubscriber, _super);\n          function FilterSubscriber(destination, predicate, thisArg) {\n              var _this = _super.call(this, destination) || this;\n              _this.predicate = predicate;\n              _this.thisArg = thisArg;\n              _this.count = 0;\n              return _this;\n          }\n          FilterSubscriber.prototype._next = function (value) {\n              var result;\n              try {\n                  result = this.predicate.call(this.thisArg, value, this.count++);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              if (result) {\n                  this.destination.next(value);\n              }\n          };\n          return FilterSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */\n      function race() {\n          var observables = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              observables[_i] = arguments[_i];\n          }\n          if (observables.length === 1) {\n              if (isArray$1(observables[0])) {\n                  observables = observables[0];\n              }\n              else {\n                  return observables[0];\n              }\n          }\n          return fromArray(observables, undefined).lift(new RaceOperator());\n      }\n      var RaceOperator = /*@__PURE__*/ (function () {\n          function RaceOperator() {\n          }\n          RaceOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new RaceSubscriber(subscriber));\n          };\n          return RaceOperator;\n      }());\n      var RaceSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(RaceSubscriber, _super);\n          function RaceSubscriber(destination) {\n              var _this = _super.call(this, destination) || this;\n              _this.hasFirst = false;\n              _this.observables = [];\n              _this.subscriptions = [];\n              return _this;\n          }\n          RaceSubscriber.prototype._next = function (observable) {\n              this.observables.push(observable);\n          };\n          RaceSubscriber.prototype._complete = function () {\n              var observables = this.observables;\n              var len = observables.length;\n              if (len === 0) {\n                  this.destination.complete();\n              }\n              else {\n                  for (var i = 0; i < len && !this.hasFirst; i++) {\n                      var observable = observables[i];\n                      var subscription = subscribeToResult(this, observable, undefined, i);\n                      if (this.subscriptions) {\n                          this.subscriptions.push(subscription);\n                      }\n                      this.add(subscription);\n                  }\n                  this.observables = null;\n              }\n          };\n          RaceSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) {\n              if (!this.hasFirst) {\n                  this.hasFirst = true;\n                  for (var i = 0; i < this.subscriptions.length; i++) {\n                      if (i !== outerIndex) {\n                          var subscription = this.subscriptions[i];\n                          subscription.unsubscribe();\n                          this.remove(subscription);\n                      }\n                  }\n                  this.subscriptions = null;\n              }\n              this.destination.next(innerValue);\n          };\n          return RaceSubscriber;\n      }(OuterSubscriber));\n    \n      /** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */\n      function timer(dueTime, periodOrScheduler, scheduler) {\n          if (dueTime === void 0) {\n              dueTime = 0;\n          }\n          var period = -1;\n          if (isNumeric(periodOrScheduler)) {\n              period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);\n          }\n          else if (isScheduler(periodOrScheduler)) {\n              scheduler = periodOrScheduler;\n          }\n          if (!isScheduler(scheduler)) {\n              scheduler = async;\n          }\n          return new Observable(function (subscriber) {\n              var due = isNumeric(dueTime)\n                  ? dueTime\n                  : (+dueTime - scheduler.now());\n              return scheduler.schedule(dispatch, due, {\n                  index: 0, period: period, subscriber: subscriber\n              });\n          });\n      }\n      function dispatch(state) {\n          var index = state.index, period = state.period, subscriber = state.subscriber;\n          subscriber.next(index);\n          if (subscriber.closed) {\n              return;\n          }\n          else if (period === -1) {\n              return subscriber.complete();\n          }\n          state.index = index + 1;\n          this.schedule(state, period);\n      }\n    \n      /** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_.._internal_symbol_iterator,_innerSubscribe PURE_IMPORTS_END */\n      function zip() {\n          var observables = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              observables[_i] = arguments[_i];\n          }\n          var resultSelector = observables[observables.length - 1];\n          if (typeof resultSelector === 'function') {\n              observables.pop();\n          }\n          return fromArray(observables, undefined).lift(new ZipOperator(resultSelector));\n      }\n      var ZipOperator = /*@__PURE__*/ (function () {\n          function ZipOperator(resultSelector) {\n              this.resultSelector = resultSelector;\n          }\n          ZipOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));\n          };\n          return ZipOperator;\n      }());\n      var ZipSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(ZipSubscriber, _super);\n          function ZipSubscriber(destination, resultSelector, values) {\n              var _this = _super.call(this, destination) || this;\n              _this.resultSelector = resultSelector;\n              _this.iterators = [];\n              _this.active = 0;\n              _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : undefined;\n              return _this;\n          }\n          ZipSubscriber.prototype._next = function (value) {\n              var iterators = this.iterators;\n              if (isArray$1(value)) {\n                  iterators.push(new StaticArrayIterator(value));\n              }\n              else if (typeof value[iterator] === 'function') {\n                  iterators.push(new StaticIterator(value[iterator]()));\n              }\n              else {\n                  iterators.push(new ZipBufferIterator(this.destination, this, value));\n              }\n          };\n          ZipSubscriber.prototype._complete = function () {\n              var iterators = this.iterators;\n              var len = iterators.length;\n              this.unsubscribe();\n              if (len === 0) {\n                  this.destination.complete();\n                  return;\n              }\n              this.active = len;\n              for (var i = 0; i < len; i++) {\n                  var iterator = iterators[i];\n                  if (iterator.stillUnsubscribed) {\n                      var destination = this.destination;\n                      destination.add(iterator.subscribe());\n                  }\n                  else {\n                      this.active--;\n                  }\n              }\n          };\n          ZipSubscriber.prototype.notifyInactive = function () {\n              this.active--;\n              if (this.active === 0) {\n                  this.destination.complete();\n              }\n          };\n          ZipSubscriber.prototype.checkIterators = function () {\n              var iterators = this.iterators;\n              var len = iterators.length;\n              var destination = this.destination;\n              for (var i = 0; i < len; i++) {\n                  var iterator = iterators[i];\n                  if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {\n                      return;\n                  }\n              }\n              var shouldComplete = false;\n              var args = [];\n              for (var i = 0; i < len; i++) {\n                  var iterator = iterators[i];\n                  var result = iterator.next();\n                  if (iterator.hasCompleted()) {\n                      shouldComplete = true;\n                  }\n                  if (result.done) {\n                      destination.complete();\n                      return;\n                  }\n                  args.push(result.value);\n              }\n              if (this.resultSelector) {\n                  this._tryresultSelector(args);\n              }\n              else {\n                  destination.next(args);\n              }\n              if (shouldComplete) {\n                  destination.complete();\n              }\n          };\n          ZipSubscriber.prototype._tryresultSelector = function (args) {\n              var result;\n              try {\n                  result = this.resultSelector.apply(this, args);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.destination.next(result);\n          };\n          return ZipSubscriber;\n      }(Subscriber));\n      var StaticIterator = /*@__PURE__*/ (function () {\n          function StaticIterator(iterator) {\n              this.iterator = iterator;\n              this.nextResult = iterator.next();\n          }\n          StaticIterator.prototype.hasValue = function () {\n              return true;\n          };\n          StaticIterator.prototype.next = function () {\n              var result = this.nextResult;\n              this.nextResult = this.iterator.next();\n              return result;\n          };\n          StaticIterator.prototype.hasCompleted = function () {\n              var nextResult = this.nextResult;\n              return Boolean(nextResult && nextResult.done);\n          };\n          return StaticIterator;\n      }());\n      var StaticArrayIterator = /*@__PURE__*/ (function () {\n          function StaticArrayIterator(array) {\n              this.array = array;\n              this.index = 0;\n              this.length = 0;\n              this.length = array.length;\n          }\n          StaticArrayIterator.prototype[iterator] = function () {\n              return this;\n          };\n          StaticArrayIterator.prototype.next = function (value) {\n              var i = this.index++;\n              var array = this.array;\n              return i < this.length ? { value: array[i], done: false } : { value: null, done: true };\n          };\n          StaticArrayIterator.prototype.hasValue = function () {\n              return this.array.length > this.index;\n          };\n          StaticArrayIterator.prototype.hasCompleted = function () {\n              return this.array.length === this.index;\n          };\n          return StaticArrayIterator;\n      }());\n      var ZipBufferIterator = /*@__PURE__*/ (function (_super) {\n          __extends(ZipBufferIterator, _super);\n          function ZipBufferIterator(destination, parent, observable) {\n              var _this = _super.call(this, destination) || this;\n              _this.parent = parent;\n              _this.observable = observable;\n              _this.stillUnsubscribed = true;\n              _this.buffer = [];\n              _this.isComplete = false;\n              return _this;\n          }\n          ZipBufferIterator.prototype[iterator] = function () {\n              return this;\n          };\n          ZipBufferIterator.prototype.next = function () {\n              var buffer = this.buffer;\n              if (buffer.length === 0 && this.isComplete) {\n                  return { value: null, done: true };\n              }\n              else {\n                  return { value: buffer.shift(), done: false };\n              }\n          };\n          ZipBufferIterator.prototype.hasValue = function () {\n              return this.buffer.length > 0;\n          };\n          ZipBufferIterator.prototype.hasCompleted = function () {\n              return this.buffer.length === 0 && this.isComplete;\n          };\n          ZipBufferIterator.prototype.notifyComplete = function () {\n              if (this.buffer.length > 0) {\n                  this.isComplete = true;\n                  this.parent.notifyInactive();\n              }\n              else {\n                  this.destination.complete();\n              }\n          };\n          ZipBufferIterator.prototype.notifyNext = function (innerValue) {\n              this.buffer.push(innerValue);\n              this.parent.checkIterators();\n          };\n          ZipBufferIterator.prototype.subscribe = function () {\n              return innerSubscribe(this.observable, new SimpleInnerSubscriber(this));\n          };\n          return ZipBufferIterator;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */\n      function audit(durationSelector) {\n          return function auditOperatorFunction(source) {\n              return source.lift(new AuditOperator(durationSelector));\n          };\n      }\n      var AuditOperator = /*@__PURE__*/ (function () {\n          function AuditOperator(durationSelector) {\n              this.durationSelector = durationSelector;\n          }\n          AuditOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));\n          };\n          return AuditOperator;\n      }());\n      var AuditSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(AuditSubscriber, _super);\n          function AuditSubscriber(destination, durationSelector) {\n              var _this = _super.call(this, destination) || this;\n              _this.durationSelector = durationSelector;\n              _this.hasValue = false;\n              return _this;\n          }\n          AuditSubscriber.prototype._next = function (value) {\n              this.value = value;\n              this.hasValue = true;\n              if (!this.throttled) {\n                  var duration = void 0;\n                  try {\n                      var durationSelector = this.durationSelector;\n                      duration = durationSelector(value);\n                  }\n                  catch (err) {\n                      return this.destination.error(err);\n                  }\n                  var innerSubscription = innerSubscribe(duration, new SimpleInnerSubscriber(this));\n                  if (!innerSubscription || innerSubscription.closed) {\n                      this.clearThrottle();\n                  }\n                  else {\n                      this.add(this.throttled = innerSubscription);\n                  }\n              }\n          };\n          AuditSubscriber.prototype.clearThrottle = function () {\n              var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;\n              if (throttled) {\n                  this.remove(throttled);\n                  this.throttled = undefined;\n                  throttled.unsubscribe();\n              }\n              if (hasValue) {\n                  this.value = undefined;\n                  this.hasValue = false;\n                  this.destination.next(value);\n              }\n          };\n          AuditSubscriber.prototype.notifyNext = function () {\n              this.clearThrottle();\n          };\n          AuditSubscriber.prototype.notifyComplete = function () {\n              this.clearThrottle();\n          };\n          return AuditSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */\n      function auditTime(duration, scheduler) {\n          if (scheduler === void 0) {\n              scheduler = async;\n          }\n          return audit(function () { return timer(duration, scheduler); });\n      }\n    \n      /** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */\n      function catchError(selector) {\n          return function catchErrorOperatorFunction(source) {\n              var operator = new CatchOperator(selector);\n              var caught = source.lift(operator);\n              return (operator.caught = caught);\n          };\n      }\n      var CatchOperator = /*@__PURE__*/ (function () {\n          function CatchOperator(selector) {\n              this.selector = selector;\n          }\n          CatchOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));\n          };\n          return CatchOperator;\n      }());\n      var CatchSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(CatchSubscriber, _super);\n          function CatchSubscriber(destination, selector, caught) {\n              var _this = _super.call(this, destination) || this;\n              _this.selector = selector;\n              _this.caught = caught;\n              return _this;\n          }\n          CatchSubscriber.prototype.error = function (err) {\n              if (!this.isStopped) {\n                  var result = void 0;\n                  try {\n                      result = this.selector(err, this.caught);\n                  }\n                  catch (err2) {\n                      _super.prototype.error.call(this, err2);\n                      return;\n                  }\n                  this._unsubscribeAndRecycle();\n                  var innerSubscriber = new SimpleInnerSubscriber(this);\n                  this.add(innerSubscriber);\n                  var innerSubscription = innerSubscribe(result, innerSubscriber);\n                  if (innerSubscription !== innerSubscriber) {\n                      this.add(innerSubscription);\n                  }\n              }\n          };\n          return CatchSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */\n      function concatMap(project, resultSelector) {\n          return mergeMap(project, resultSelector, 1);\n      }\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */\n      function debounceTime(dueTime, scheduler) {\n          if (scheduler === void 0) {\n              scheduler = async;\n          }\n          return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };\n      }\n      var DebounceTimeOperator = /*@__PURE__*/ (function () {\n          function DebounceTimeOperator(dueTime, scheduler) {\n              this.dueTime = dueTime;\n              this.scheduler = scheduler;\n          }\n          DebounceTimeOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));\n          };\n          return DebounceTimeOperator;\n      }());\n      var DebounceTimeSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(DebounceTimeSubscriber, _super);\n          function DebounceTimeSubscriber(destination, dueTime, scheduler) {\n              var _this = _super.call(this, destination) || this;\n              _this.dueTime = dueTime;\n              _this.scheduler = scheduler;\n              _this.debouncedSubscription = null;\n              _this.lastValue = null;\n              _this.hasValue = false;\n              return _this;\n          }\n          DebounceTimeSubscriber.prototype._next = function (value) {\n              this.clearDebounce();\n              this.lastValue = value;\n              this.hasValue = true;\n              this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext$1, this.dueTime, this));\n          };\n          DebounceTimeSubscriber.prototype._complete = function () {\n              this.debouncedNext();\n              this.destination.complete();\n          };\n          DebounceTimeSubscriber.prototype.debouncedNext = function () {\n              this.clearDebounce();\n              if (this.hasValue) {\n                  var lastValue = this.lastValue;\n                  this.lastValue = null;\n                  this.hasValue = false;\n                  this.destination.next(lastValue);\n              }\n          };\n          DebounceTimeSubscriber.prototype.clearDebounce = function () {\n              var debouncedSubscription = this.debouncedSubscription;\n              if (debouncedSubscription !== null) {\n                  this.remove(debouncedSubscription);\n                  debouncedSubscription.unsubscribe();\n                  this.debouncedSubscription = null;\n              }\n          };\n          return DebounceTimeSubscriber;\n      }(Subscriber));\n      function dispatchNext$1(subscriber) {\n          subscriber.debouncedNext();\n      }\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function defaultIfEmpty(defaultValue) {\n          if (defaultValue === void 0) {\n              defaultValue = null;\n          }\n          return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };\n      }\n      var DefaultIfEmptyOperator = /*@__PURE__*/ (function () {\n          function DefaultIfEmptyOperator(defaultValue) {\n              this.defaultValue = defaultValue;\n          }\n          DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));\n          };\n          return DefaultIfEmptyOperator;\n      }());\n      var DefaultIfEmptySubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(DefaultIfEmptySubscriber, _super);\n          function DefaultIfEmptySubscriber(destination, defaultValue) {\n              var _this = _super.call(this, destination) || this;\n              _this.defaultValue = defaultValue;\n              _this.isEmpty = true;\n              return _this;\n          }\n          DefaultIfEmptySubscriber.prototype._next = function (value) {\n              this.isEmpty = false;\n              this.destination.next(value);\n          };\n          DefaultIfEmptySubscriber.prototype._complete = function () {\n              if (this.isEmpty) {\n                  this.destination.next(this.defaultValue);\n              }\n              this.destination.complete();\n          };\n          return DefaultIfEmptySubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START  PURE_IMPORTS_END */\n      function isDate(value) {\n          return value instanceof Date && !isNaN(+value);\n      }\n    \n      /** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */\n      function delay(delay, scheduler) {\n          if (scheduler === void 0) {\n              scheduler = async;\n          }\n          var absoluteDelay = isDate(delay);\n          var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);\n          return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };\n      }\n      var DelayOperator = /*@__PURE__*/ (function () {\n          function DelayOperator(delay, scheduler) {\n              this.delay = delay;\n              this.scheduler = scheduler;\n          }\n          DelayOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));\n          };\n          return DelayOperator;\n      }());\n      var DelaySubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(DelaySubscriber, _super);\n          function DelaySubscriber(destination, delay, scheduler) {\n              var _this = _super.call(this, destination) || this;\n              _this.delay = delay;\n              _this.scheduler = scheduler;\n              _this.queue = [];\n              _this.active = false;\n              _this.errored = false;\n              return _this;\n          }\n          DelaySubscriber.dispatch = function (state) {\n              var source = state.source;\n              var queue = source.queue;\n              var scheduler = state.scheduler;\n              var destination = state.destination;\n              while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {\n                  queue.shift().notification.observe(destination);\n              }\n              if (queue.length > 0) {\n                  var delay_1 = Math.max(0, queue[0].time - scheduler.now());\n                  this.schedule(state, delay_1);\n              }\n              else {\n                  this.unsubscribe();\n                  source.active = false;\n              }\n          };\n          DelaySubscriber.prototype._schedule = function (scheduler) {\n              this.active = true;\n              var destination = this.destination;\n              destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {\n                  source: this, destination: this.destination, scheduler: scheduler\n              }));\n          };\n          DelaySubscriber.prototype.scheduleNotification = function (notification) {\n              if (this.errored === true) {\n                  return;\n              }\n              var scheduler = this.scheduler;\n              var message = new DelayMessage(scheduler.now() + this.delay, notification);\n              this.queue.push(message);\n              if (this.active === false) {\n                  this._schedule(scheduler);\n              }\n          };\n          DelaySubscriber.prototype._next = function (value) {\n              this.scheduleNotification(Notification.createNext(value));\n          };\n          DelaySubscriber.prototype._error = function (err) {\n              this.errored = true;\n              this.queue = [];\n              this.destination.error(err);\n              this.unsubscribe();\n          };\n          DelaySubscriber.prototype._complete = function () {\n              this.scheduleNotification(Notification.createComplete());\n              this.unsubscribe();\n          };\n          return DelaySubscriber;\n      }(Subscriber));\n      var DelayMessage = /*@__PURE__*/ (function () {\n          function DelayMessage(time, notification) {\n              this.time = time;\n              this.notification = notification;\n          }\n          return DelayMessage;\n      }());\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */\n      function delayWhen(delayDurationSelector, subscriptionDelay) {\n          if (subscriptionDelay) {\n              return function (source) {\n                  return new SubscriptionDelayObservable(source, subscriptionDelay)\n                      .lift(new DelayWhenOperator(delayDurationSelector));\n              };\n          }\n          return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); };\n      }\n      var DelayWhenOperator = /*@__PURE__*/ (function () {\n          function DelayWhenOperator(delayDurationSelector) {\n              this.delayDurationSelector = delayDurationSelector;\n          }\n          DelayWhenOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));\n          };\n          return DelayWhenOperator;\n      }());\n      var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(DelayWhenSubscriber, _super);\n          function DelayWhenSubscriber(destination, delayDurationSelector) {\n              var _this = _super.call(this, destination) || this;\n              _this.delayDurationSelector = delayDurationSelector;\n              _this.completed = false;\n              _this.delayNotifierSubscriptions = [];\n              _this.index = 0;\n              return _this;\n          }\n          DelayWhenSubscriber.prototype.notifyNext = function (outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) {\n              this.destination.next(outerValue);\n              this.removeSubscription(innerSub);\n              this.tryComplete();\n          };\n          DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) {\n              this._error(error);\n          };\n          DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) {\n              var value = this.removeSubscription(innerSub);\n              if (value) {\n                  this.destination.next(value);\n              }\n              this.tryComplete();\n          };\n          DelayWhenSubscriber.prototype._next = function (value) {\n              var index = this.index++;\n              try {\n                  var delayNotifier = this.delayDurationSelector(value, index);\n                  if (delayNotifier) {\n                      this.tryDelay(delayNotifier, value);\n                  }\n              }\n              catch (err) {\n                  this.destination.error(err);\n              }\n          };\n          DelayWhenSubscriber.prototype._complete = function () {\n              this.completed = true;\n              this.tryComplete();\n              this.unsubscribe();\n          };\n          DelayWhenSubscriber.prototype.removeSubscription = function (subscription) {\n              subscription.unsubscribe();\n              var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);\n              if (subscriptionIdx !== -1) {\n                  this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);\n              }\n              return subscription.outerValue;\n          };\n          DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) {\n              var notifierSubscription = subscribeToResult(this, delayNotifier, value);\n              if (notifierSubscription && !notifierSubscription.closed) {\n                  var destination = this.destination;\n                  destination.add(notifierSubscription);\n                  this.delayNotifierSubscriptions.push(notifierSubscription);\n              }\n          };\n          DelayWhenSubscriber.prototype.tryComplete = function () {\n              if (this.completed && this.delayNotifierSubscriptions.length === 0) {\n                  this.destination.complete();\n              }\n          };\n          return DelayWhenSubscriber;\n      }(OuterSubscriber));\n      var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) {\n          __extends(SubscriptionDelayObservable, _super);\n          function SubscriptionDelayObservable(source, subscriptionDelay) {\n              var _this = _super.call(this) || this;\n              _this.source = source;\n              _this.subscriptionDelay = subscriptionDelay;\n              return _this;\n          }\n          SubscriptionDelayObservable.prototype._subscribe = function (subscriber) {\n              this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));\n          };\n          return SubscriptionDelayObservable;\n      }(Observable));\n      var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SubscriptionDelaySubscriber, _super);\n          function SubscriptionDelaySubscriber(parent, source) {\n              var _this = _super.call(this) || this;\n              _this.parent = parent;\n              _this.source = source;\n              _this.sourceSubscribed = false;\n              return _this;\n          }\n          SubscriptionDelaySubscriber.prototype._next = function (unused) {\n              this.subscribeToSource();\n          };\n          SubscriptionDelaySubscriber.prototype._error = function (err) {\n              this.unsubscribe();\n              this.parent.error(err);\n          };\n          SubscriptionDelaySubscriber.prototype._complete = function () {\n              this.unsubscribe();\n              this.subscribeToSource();\n          };\n          SubscriptionDelaySubscriber.prototype.subscribeToSource = function () {\n              if (!this.sourceSubscribed) {\n                  this.sourceSubscribed = true;\n                  this.unsubscribe();\n                  this.source.subscribe(this.parent);\n              }\n          };\n          return SubscriptionDelaySubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function distinctUntilChanged(compare, keySelector) {\n          return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };\n      }\n      var DistinctUntilChangedOperator = /*@__PURE__*/ (function () {\n          function DistinctUntilChangedOperator(compare, keySelector) {\n              this.compare = compare;\n              this.keySelector = keySelector;\n          }\n          DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));\n          };\n          return DistinctUntilChangedOperator;\n      }());\n      var DistinctUntilChangedSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(DistinctUntilChangedSubscriber, _super);\n          function DistinctUntilChangedSubscriber(destination, compare, keySelector) {\n              var _this = _super.call(this, destination) || this;\n              _this.keySelector = keySelector;\n              _this.hasKey = false;\n              if (typeof compare === 'function') {\n                  _this.compare = compare;\n              }\n              return _this;\n          }\n          DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {\n              return x === y;\n          };\n          DistinctUntilChangedSubscriber.prototype._next = function (value) {\n              var key;\n              try {\n                  var keySelector = this.keySelector;\n                  key = keySelector ? keySelector(value) : value;\n              }\n              catch (err) {\n                  return this.destination.error(err);\n              }\n              var result = false;\n              if (this.hasKey) {\n                  try {\n                      var compare = this.compare;\n                      result = compare(this.key, key);\n                  }\n                  catch (err) {\n                      return this.destination.error(err);\n                  }\n              }\n              else {\n                  this.hasKey = true;\n              }\n              if (!result) {\n                  this.key = key;\n                  this.destination.next(value);\n              }\n          };\n          return DistinctUntilChangedSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */\n      function take(count) {\n          return function (source) {\n              if (count === 0) {\n                  return empty();\n              }\n              else {\n                  return source.lift(new TakeOperator(count));\n              }\n          };\n      }\n      var TakeOperator = /*@__PURE__*/ (function () {\n          function TakeOperator(total) {\n              this.total = total;\n              if (this.total < 0) {\n                  throw new ArgumentOutOfRangeError;\n              }\n          }\n          TakeOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new TakeSubscriber(subscriber, this.total));\n          };\n          return TakeOperator;\n      }());\n      var TakeSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(TakeSubscriber, _super);\n          function TakeSubscriber(destination, total) {\n              var _this = _super.call(this, destination) || this;\n              _this.total = total;\n              _this.count = 0;\n              return _this;\n          }\n          TakeSubscriber.prototype._next = function (value) {\n              var total = this.total;\n              var count = ++this.count;\n              if (count <= total) {\n                  this.destination.next(value);\n                  if (count === total) {\n                      this.destination.complete();\n                      this.unsubscribe();\n                  }\n              }\n          };\n          return TakeSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */\n      function exhaustMap(project, resultSelector) {\n          if (resultSelector) {\n              return function (source) { return source.pipe(exhaustMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };\n          }\n          return function (source) {\n              return source.lift(new ExhaustMapOperator(project));\n          };\n      }\n      var ExhaustMapOperator = /*@__PURE__*/ (function () {\n          function ExhaustMapOperator(project) {\n              this.project = project;\n          }\n          ExhaustMapOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));\n          };\n          return ExhaustMapOperator;\n      }());\n      var ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(ExhaustMapSubscriber, _super);\n          function ExhaustMapSubscriber(destination, project) {\n              var _this = _super.call(this, destination) || this;\n              _this.project = project;\n              _this.hasSubscription = false;\n              _this.hasCompleted = false;\n              _this.index = 0;\n              return _this;\n          }\n          ExhaustMapSubscriber.prototype._next = function (value) {\n              if (!this.hasSubscription) {\n                  this.tryNext(value);\n              }\n          };\n          ExhaustMapSubscriber.prototype.tryNext = function (value) {\n              var result;\n              var index = this.index++;\n              try {\n                  result = this.project(value, index);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.hasSubscription = true;\n              this._innerSub(result);\n          };\n          ExhaustMapSubscriber.prototype._innerSub = function (result) {\n              var innerSubscriber = new SimpleInnerSubscriber(this);\n              var destination = this.destination;\n              destination.add(innerSubscriber);\n              var innerSubscription = innerSubscribe(result, innerSubscriber);\n              if (innerSubscription !== innerSubscriber) {\n                  destination.add(innerSubscription);\n              }\n          };\n          ExhaustMapSubscriber.prototype._complete = function () {\n              this.hasCompleted = true;\n              if (!this.hasSubscription) {\n                  this.destination.complete();\n              }\n              this.unsubscribe();\n          };\n          ExhaustMapSubscriber.prototype.notifyNext = function (innerValue) {\n              this.destination.next(innerValue);\n          };\n          ExhaustMapSubscriber.prototype.notifyError = function (err) {\n              this.destination.error(err);\n          };\n          ExhaustMapSubscriber.prototype.notifyComplete = function () {\n              this.hasSubscription = false;\n              if (this.hasCompleted) {\n                  this.destination.complete();\n              }\n          };\n          return ExhaustMapSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_Subscription PURE_IMPORTS_END */\n      function finalize$1(callback) {\n          return function (source) { return source.lift(new FinallyOperator(callback)); };\n      }\n      var FinallyOperator = /*@__PURE__*/ (function () {\n          function FinallyOperator(callback) {\n              this.callback = callback;\n          }\n          FinallyOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new FinallySubscriber(subscriber, this.callback));\n          };\n          return FinallyOperator;\n      }());\n      var FinallySubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(FinallySubscriber, _super);\n          function FinallySubscriber(destination, callback) {\n              var _this = _super.call(this, destination) || this;\n              _this.add(new Subscription(callback));\n              return _this;\n          }\n          return FinallySubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */\n      function takeLast(count) {\n          return function takeLastOperatorFunction(source) {\n              if (count === 0) {\n                  return empty();\n              }\n              else {\n                  return source.lift(new TakeLastOperator(count));\n              }\n          };\n      }\n      var TakeLastOperator = /*@__PURE__*/ (function () {\n          function TakeLastOperator(total) {\n              this.total = total;\n              if (this.total < 0) {\n                  throw new ArgumentOutOfRangeError;\n              }\n          }\n          TakeLastOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new TakeLastSubscriber(subscriber, this.total));\n          };\n          return TakeLastOperator;\n      }());\n      var TakeLastSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(TakeLastSubscriber, _super);\n          function TakeLastSubscriber(destination, total) {\n              var _this = _super.call(this, destination) || this;\n              _this.total = total;\n              _this.ring = new Array();\n              _this.count = 0;\n              return _this;\n          }\n          TakeLastSubscriber.prototype._next = function (value) {\n              var ring = this.ring;\n              var total = this.total;\n              var count = this.count++;\n              if (ring.length < total) {\n                  ring.push(value);\n              }\n              else {\n                  var index = count % total;\n                  ring[index] = value;\n              }\n          };\n          TakeLastSubscriber.prototype._complete = function () {\n              var destination = this.destination;\n              var count = this.count;\n              if (count > 0) {\n                  var total = this.count >= this.total ? this.total : this.count;\n                  var ring = this.ring;\n                  for (var i = 0; i < total; i++) {\n                      var idx = (count++) % total;\n                      destination.next(ring[idx]);\n                  }\n              }\n              destination.complete();\n          };\n          return TakeLastSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function mapTo(value) {\n          return function (source) { return source.lift(new MapToOperator(value)); };\n      }\n      var MapToOperator = /*@__PURE__*/ (function () {\n          function MapToOperator(value) {\n              this.value = value;\n          }\n          MapToOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new MapToSubscriber(subscriber, this.value));\n          };\n          return MapToOperator;\n      }());\n      var MapToSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(MapToSubscriber, _super);\n          function MapToSubscriber(destination, value) {\n              var _this = _super.call(this, destination) || this;\n              _this.value = value;\n              return _this;\n          }\n          MapToSubscriber.prototype._next = function (x) {\n              this.destination.next(this.value);\n          };\n          return MapToSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function scan(accumulator, seed) {\n          var hasSeed = false;\n          if (arguments.length >= 2) {\n              hasSeed = true;\n          }\n          return function scanOperatorFunction(source) {\n              return source.lift(new ScanOperator(accumulator, seed, hasSeed));\n          };\n      }\n      var ScanOperator = /*@__PURE__*/ (function () {\n          function ScanOperator(accumulator, seed, hasSeed) {\n              if (hasSeed === void 0) {\n                  hasSeed = false;\n              }\n              this.accumulator = accumulator;\n              this.seed = seed;\n              this.hasSeed = hasSeed;\n          }\n          ScanOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));\n          };\n          return ScanOperator;\n      }());\n      var ScanSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(ScanSubscriber, _super);\n          function ScanSubscriber(destination, accumulator, _seed, hasSeed) {\n              var _this = _super.call(this, destination) || this;\n              _this.accumulator = accumulator;\n              _this._seed = _seed;\n              _this.hasSeed = hasSeed;\n              _this.index = 0;\n              return _this;\n          }\n          Object.defineProperty(ScanSubscriber.prototype, \"seed\", {\n              get: function () {\n                  return this._seed;\n              },\n              set: function (value) {\n                  this.hasSeed = true;\n                  this._seed = value;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          ScanSubscriber.prototype._next = function (value) {\n              if (!this.hasSeed) {\n                  this.seed = value;\n                  this.destination.next(value);\n              }\n              else {\n                  return this._tryNext(value);\n              }\n          };\n          ScanSubscriber.prototype._tryNext = function (value) {\n              var index = this.index++;\n              var result;\n              try {\n                  result = this.accumulator(this.seed, value, index);\n              }\n              catch (err) {\n                  this.destination.error(err);\n              }\n              this.seed = result;\n              this.destination.next(result);\n          };\n          return ScanSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */\n      function reduce(accumulator, seed) {\n          if (arguments.length >= 2) {\n              return function reduceOperatorFunctionWithSeed(source) {\n                  return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source);\n              };\n          }\n          return function reduceOperatorFunction(source) {\n              return pipe(scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast(1))(source);\n          };\n      }\n    \n      /** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */\n      function multicast(subjectOrSubjectFactory, selector) {\n          return function multicastOperatorFunction(source) {\n              var subjectFactory;\n              if (typeof subjectOrSubjectFactory === 'function') {\n                  subjectFactory = subjectOrSubjectFactory;\n              }\n              else {\n                  subjectFactory = function subjectFactory() {\n                      return subjectOrSubjectFactory;\n                  };\n              }\n              if (typeof selector === 'function') {\n                  return source.lift(new MulticastOperator(subjectFactory, selector));\n              }\n              var connectable = Object.create(source, connectableObservableDescriptor);\n              connectable.source = source;\n              connectable.subjectFactory = subjectFactory;\n              return connectable;\n          };\n      }\n      var MulticastOperator = /*@__PURE__*/ (function () {\n          function MulticastOperator(subjectFactory, selector) {\n              this.subjectFactory = subjectFactory;\n              this.selector = selector;\n          }\n          MulticastOperator.prototype.call = function (subscriber, source) {\n              var selector = this.selector;\n              var subject = this.subjectFactory();\n              var subscription = selector(subject).subscribe(subscriber);\n              subscription.add(source.subscribe(subject));\n              return subscription;\n          };\n          return MulticastOperator;\n      }());\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function pairwise() {\n          return function (source) { return source.lift(new PairwiseOperator()); };\n      }\n      var PairwiseOperator = /*@__PURE__*/ (function () {\n          function PairwiseOperator() {\n          }\n          PairwiseOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new PairwiseSubscriber(subscriber));\n          };\n          return PairwiseOperator;\n      }());\n      var PairwiseSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(PairwiseSubscriber, _super);\n          function PairwiseSubscriber(destination) {\n              var _this = _super.call(this, destination) || this;\n              _this.hasPrev = false;\n              return _this;\n          }\n          PairwiseSubscriber.prototype._next = function (value) {\n              var pair;\n              if (this.hasPrev) {\n                  pair = [this.prev, value];\n              }\n              else {\n                  this.hasPrev = true;\n              }\n              this.prev = value;\n              if (pair) {\n                  this.destination.next(pair);\n              }\n          };\n          return PairwiseSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */\n      function retryWhen(notifier) {\n          return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };\n      }\n      var RetryWhenOperator = /*@__PURE__*/ (function () {\n          function RetryWhenOperator(notifier, source) {\n              this.notifier = notifier;\n              this.source = source;\n          }\n          RetryWhenOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));\n          };\n          return RetryWhenOperator;\n      }());\n      var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(RetryWhenSubscriber, _super);\n          function RetryWhenSubscriber(destination, notifier, source) {\n              var _this = _super.call(this, destination) || this;\n              _this.notifier = notifier;\n              _this.source = source;\n              return _this;\n          }\n          RetryWhenSubscriber.prototype.error = function (err) {\n              if (!this.isStopped) {\n                  var errors = this.errors;\n                  var retries = this.retries;\n                  var retriesSubscription = this.retriesSubscription;\n                  if (!retries) {\n                      errors = new Subject();\n                      try {\n                          var notifier = this.notifier;\n                          retries = notifier(errors);\n                      }\n                      catch (e) {\n                          return _super.prototype.error.call(this, e);\n                      }\n                      retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this));\n                  }\n                  else {\n                      this.errors = undefined;\n                      this.retriesSubscription = undefined;\n                  }\n                  this._unsubscribeAndRecycle();\n                  this.errors = errors;\n                  this.retries = retries;\n                  this.retriesSubscription = retriesSubscription;\n                  errors.next(err);\n              }\n          };\n          RetryWhenSubscriber.prototype._unsubscribe = function () {\n              var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;\n              if (errors) {\n                  errors.unsubscribe();\n                  this.errors = undefined;\n              }\n              if (retriesSubscription) {\n                  retriesSubscription.unsubscribe();\n                  this.retriesSubscription = undefined;\n              }\n              this.retries = undefined;\n          };\n          RetryWhenSubscriber.prototype.notifyNext = function () {\n              var _unsubscribe = this._unsubscribe;\n              this._unsubscribe = null;\n              this._unsubscribeAndRecycle();\n              this._unsubscribe = _unsubscribe;\n              this.source.subscribe(this);\n          };\n          return RetryWhenSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */\n      function shareSubjectFactory() {\n          return new Subject();\n      }\n      function share() {\n          return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); };\n      }\n    \n      /** PURE_IMPORTS_START _ReplaySubject PURE_IMPORTS_END */\n      function shareReplay(configOrBufferSize, windowTime, scheduler) {\n          var config;\n          if (configOrBufferSize && typeof configOrBufferSize === 'object') {\n              config = configOrBufferSize;\n          }\n          else {\n              config = {\n                  bufferSize: configOrBufferSize,\n                  windowTime: windowTime,\n                  refCount: false,\n                  scheduler: scheduler,\n              };\n          }\n          return function (source) { return source.lift(shareReplayOperator(config)); };\n      }\n      function shareReplayOperator(_a) {\n          var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler;\n          var subject;\n          var refCount = 0;\n          var subscription;\n          var hasError = false;\n          var isComplete = false;\n          return function shareReplayOperation(source) {\n              refCount++;\n              var innerSub;\n              if (!subject || hasError) {\n                  hasError = false;\n                  subject = new ReplaySubject(bufferSize, windowTime, scheduler);\n                  innerSub = subject.subscribe(this);\n                  subscription = source.subscribe({\n                      next: function (value) {\n                          subject.next(value);\n                      },\n                      error: function (err) {\n                          hasError = true;\n                          subject.error(err);\n                      },\n                      complete: function () {\n                          isComplete = true;\n                          subscription = undefined;\n                          subject.complete();\n                      },\n                  });\n                  if (isComplete) {\n                      subscription = undefined;\n                  }\n              }\n              else {\n                  innerSub = subject.subscribe(this);\n              }\n              this.add(function () {\n                  refCount--;\n                  innerSub.unsubscribe();\n                  innerSub = undefined;\n                  if (subscription && !isComplete && useRefCount && refCount === 0) {\n                      subscription.unsubscribe();\n                      subscription = undefined;\n                      subject = undefined;\n                  }\n              });\n          };\n      }\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function skip(count) {\n          return function (source) { return source.lift(new SkipOperator(count)); };\n      }\n      var SkipOperator = /*@__PURE__*/ (function () {\n          function SkipOperator(total) {\n              this.total = total;\n          }\n          SkipOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new SkipSubscriber(subscriber, this.total));\n          };\n          return SkipOperator;\n      }());\n      var SkipSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SkipSubscriber, _super);\n          function SkipSubscriber(destination, total) {\n              var _this = _super.call(this, destination) || this;\n              _this.total = total;\n              _this.count = 0;\n              return _this;\n          }\n          SkipSubscriber.prototype._next = function (x) {\n              if (++this.count > this.total) {\n                  this.destination.next(x);\n              }\n          };\n          return SkipSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */\n      function startWith() {\n          var array = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              array[_i] = arguments[_i];\n          }\n          var scheduler = array[array.length - 1];\n          if (isScheduler(scheduler)) {\n              array.pop();\n              return function (source) { return concat(array, source, scheduler); };\n          }\n          else {\n              return function (source) { return concat(array, source); };\n          }\n      }\n    \n      /** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */\n      function switchMap(project, resultSelector) {\n          if (typeof resultSelector === 'function') {\n              return function (source) { return source.pipe(switchMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };\n          }\n          return function (source) { return source.lift(new SwitchMapOperator(project)); };\n      }\n      var SwitchMapOperator = /*@__PURE__*/ (function () {\n          function SwitchMapOperator(project) {\n              this.project = project;\n          }\n          SwitchMapOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));\n          };\n          return SwitchMapOperator;\n      }());\n      var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(SwitchMapSubscriber, _super);\n          function SwitchMapSubscriber(destination, project) {\n              var _this = _super.call(this, destination) || this;\n              _this.project = project;\n              _this.index = 0;\n              return _this;\n          }\n          SwitchMapSubscriber.prototype._next = function (value) {\n              var result;\n              var index = this.index++;\n              try {\n                  result = this.project(value, index);\n              }\n              catch (error) {\n                  this.destination.error(error);\n                  return;\n              }\n              this._innerSub(result);\n          };\n          SwitchMapSubscriber.prototype._innerSub = function (result) {\n              var innerSubscription = this.innerSubscription;\n              if (innerSubscription) {\n                  innerSubscription.unsubscribe();\n              }\n              var innerSubscriber = new SimpleInnerSubscriber(this);\n              var destination = this.destination;\n              destination.add(innerSubscriber);\n              this.innerSubscription = innerSubscribe(result, innerSubscriber);\n              if (this.innerSubscription !== innerSubscriber) {\n                  destination.add(this.innerSubscription);\n              }\n          };\n          SwitchMapSubscriber.prototype._complete = function () {\n              var innerSubscription = this.innerSubscription;\n              if (!innerSubscription || innerSubscription.closed) {\n                  _super.prototype._complete.call(this);\n              }\n              this.unsubscribe();\n          };\n          SwitchMapSubscriber.prototype._unsubscribe = function () {\n              this.innerSubscription = undefined;\n          };\n          SwitchMapSubscriber.prototype.notifyComplete = function () {\n              this.innerSubscription = undefined;\n              if (this.isStopped) {\n                  _super.prototype._complete.call(this);\n              }\n          };\n          SwitchMapSubscriber.prototype.notifyNext = function (innerValue) {\n              this.destination.next(innerValue);\n          };\n          return SwitchMapSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START _switchMap PURE_IMPORTS_END */\n      function switchMapTo(innerObservable, resultSelector) {\n          return resultSelector ? switchMap(function () { return innerObservable; }, resultSelector) : switchMap(function () { return innerObservable; });\n      }\n    \n      /** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */\n      function takeUntil(notifier) {\n          return function (source) { return source.lift(new TakeUntilOperator(notifier)); };\n      }\n      var TakeUntilOperator = /*@__PURE__*/ (function () {\n          function TakeUntilOperator(notifier) {\n              this.notifier = notifier;\n          }\n          TakeUntilOperator.prototype.call = function (subscriber, source) {\n              var takeUntilSubscriber = new TakeUntilSubscriber(subscriber);\n              var notifierSubscription = innerSubscribe(this.notifier, new SimpleInnerSubscriber(takeUntilSubscriber));\n              if (notifierSubscription && !takeUntilSubscriber.seenValue) {\n                  takeUntilSubscriber.add(notifierSubscription);\n                  return source.subscribe(takeUntilSubscriber);\n              }\n              return takeUntilSubscriber;\n          };\n          return TakeUntilOperator;\n      }());\n      var TakeUntilSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(TakeUntilSubscriber, _super);\n          function TakeUntilSubscriber(destination) {\n              var _this = _super.call(this, destination) || this;\n              _this.seenValue = false;\n              return _this;\n          }\n          TakeUntilSubscriber.prototype.notifyNext = function () {\n              this.seenValue = true;\n              this.complete();\n          };\n          TakeUntilSubscriber.prototype.notifyComplete = function () {\n          };\n          return TakeUntilSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\n      function takeWhile(predicate, inclusive) {\n          if (inclusive === void 0) {\n              inclusive = false;\n          }\n          return function (source) {\n              return source.lift(new TakeWhileOperator(predicate, inclusive));\n          };\n      }\n      var TakeWhileOperator = /*@__PURE__*/ (function () {\n          function TakeWhileOperator(predicate, inclusive) {\n              this.predicate = predicate;\n              this.inclusive = inclusive;\n          }\n          TakeWhileOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive));\n          };\n          return TakeWhileOperator;\n      }());\n      var TakeWhileSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(TakeWhileSubscriber, _super);\n          function TakeWhileSubscriber(destination, predicate, inclusive) {\n              var _this = _super.call(this, destination) || this;\n              _this.predicate = predicate;\n              _this.inclusive = inclusive;\n              _this.index = 0;\n              return _this;\n          }\n          TakeWhileSubscriber.prototype._next = function (value) {\n              var destination = this.destination;\n              var result;\n              try {\n                  result = this.predicate(value, this.index++);\n              }\n              catch (err) {\n                  destination.error(err);\n                  return;\n              }\n              this.nextOrComplete(value, result);\n          };\n          TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {\n              var destination = this.destination;\n              if (Boolean(predicateResult)) {\n                  destination.next(value);\n              }\n              else {\n                  if (this.inclusive) {\n                      destination.next(value);\n                  }\n                  destination.complete();\n              }\n          };\n          return TakeWhileSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */\n      function tap(nextOrObserver, error, complete) {\n          return function tapOperatorFunction(source) {\n              return source.lift(new DoOperator(nextOrObserver, error, complete));\n          };\n      }\n      var DoOperator = /*@__PURE__*/ (function () {\n          function DoOperator(nextOrObserver, error, complete) {\n              this.nextOrObserver = nextOrObserver;\n              this.error = error;\n              this.complete = complete;\n          }\n          DoOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));\n          };\n          return DoOperator;\n      }());\n      var TapSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(TapSubscriber, _super);\n          function TapSubscriber(destination, observerOrNext, error, complete) {\n              var _this = _super.call(this, destination) || this;\n              _this._tapNext = noop;\n              _this._tapError = noop;\n              _this._tapComplete = noop;\n              _this._tapError = error || noop;\n              _this._tapComplete = complete || noop;\n              if (isFunction$1(observerOrNext)) {\n                  _this._context = _this;\n                  _this._tapNext = observerOrNext;\n              }\n              else if (observerOrNext) {\n                  _this._context = observerOrNext;\n                  _this._tapNext = observerOrNext.next || noop;\n                  _this._tapError = observerOrNext.error || noop;\n                  _this._tapComplete = observerOrNext.complete || noop;\n              }\n              return _this;\n          }\n          TapSubscriber.prototype._next = function (value) {\n              try {\n                  this._tapNext.call(this._context, value);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.destination.next(value);\n          };\n          TapSubscriber.prototype._error = function (err) {\n              try {\n                  this._tapError.call(this._context, err);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.destination.error(err);\n          };\n          TapSubscriber.prototype._complete = function () {\n              try {\n                  this._tapComplete.call(this._context);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              return this.destination.complete();\n          };\n          return TapSubscriber;\n      }(Subscriber));\n    \n      /** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */\n      var defaultThrottleConfig = {\n          leading: true,\n          trailing: false\n      };\n    \n      /** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async,_throttle PURE_IMPORTS_END */\n      function throttleTime(duration, scheduler, config) {\n          if (scheduler === void 0) {\n              scheduler = async;\n          }\n          if (config === void 0) {\n              config = defaultThrottleConfig;\n          }\n          return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };\n      }\n      var ThrottleTimeOperator = /*@__PURE__*/ (function () {\n          function ThrottleTimeOperator(duration, scheduler, leading, trailing) {\n              this.duration = duration;\n              this.scheduler = scheduler;\n              this.leading = leading;\n              this.trailing = trailing;\n          }\n          ThrottleTimeOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));\n          };\n          return ThrottleTimeOperator;\n      }());\n      var ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(ThrottleTimeSubscriber, _super);\n          function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {\n              var _this = _super.call(this, destination) || this;\n              _this.duration = duration;\n              _this.scheduler = scheduler;\n              _this.leading = leading;\n              _this.trailing = trailing;\n              _this._hasTrailingValue = false;\n              _this._trailingValue = null;\n              return _this;\n          }\n          ThrottleTimeSubscriber.prototype._next = function (value) {\n              if (this.throttled) {\n                  if (this.trailing) {\n                      this._trailingValue = value;\n                      this._hasTrailingValue = true;\n                  }\n              }\n              else {\n                  this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));\n                  if (this.leading) {\n                      this.destination.next(value);\n                  }\n                  else if (this.trailing) {\n                      this._trailingValue = value;\n                      this._hasTrailingValue = true;\n                  }\n              }\n          };\n          ThrottleTimeSubscriber.prototype._complete = function () {\n              if (this._hasTrailingValue) {\n                  this.destination.next(this._trailingValue);\n                  this.destination.complete();\n              }\n              else {\n                  this.destination.complete();\n              }\n          };\n          ThrottleTimeSubscriber.prototype.clearThrottle = function () {\n              var throttled = this.throttled;\n              if (throttled) {\n                  if (this.trailing && this._hasTrailingValue) {\n                      this.destination.next(this._trailingValue);\n                      this._trailingValue = null;\n                      this._hasTrailingValue = false;\n                  }\n                  throttled.unsubscribe();\n                  this.remove(throttled);\n                  this.throttled = null;\n              }\n          };\n          return ThrottleTimeSubscriber;\n      }(Subscriber));\n      function dispatchNext(arg) {\n          var subscriber = arg.subscriber;\n          subscriber.clearThrottle();\n      }\n    \n      /** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_innerSubscribe PURE_IMPORTS_END */\n      function timeoutWith(due, withObservable, scheduler) {\n          if (scheduler === void 0) {\n              scheduler = async;\n          }\n          return function (source) {\n              var absoluteTimeout = isDate(due);\n              var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);\n              return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));\n          };\n      }\n      var TimeoutWithOperator = /*@__PURE__*/ (function () {\n          function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {\n              this.waitFor = waitFor;\n              this.absoluteTimeout = absoluteTimeout;\n              this.withObservable = withObservable;\n              this.scheduler = scheduler;\n          }\n          TimeoutWithOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));\n          };\n          return TimeoutWithOperator;\n      }());\n      var TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(TimeoutWithSubscriber, _super);\n          function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {\n              var _this = _super.call(this, destination) || this;\n              _this.absoluteTimeout = absoluteTimeout;\n              _this.waitFor = waitFor;\n              _this.withObservable = withObservable;\n              _this.scheduler = scheduler;\n              _this.scheduleTimeout();\n              return _this;\n          }\n          TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {\n              var withObservable = subscriber.withObservable;\n              subscriber._unsubscribeAndRecycle();\n              subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber)));\n          };\n          TimeoutWithSubscriber.prototype.scheduleTimeout = function () {\n              var action = this.action;\n              if (action) {\n                  this.action = action.schedule(this, this.waitFor);\n              }\n              else {\n                  this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));\n              }\n          };\n          TimeoutWithSubscriber.prototype._next = function (value) {\n              if (!this.absoluteTimeout) {\n                  this.scheduleTimeout();\n              }\n              _super.prototype._next.call(this, value);\n          };\n          TimeoutWithSubscriber.prototype._unsubscribe = function () {\n              this.action = undefined;\n              this.scheduler = null;\n              this.withObservable = null;\n          };\n          return TimeoutWithSubscriber;\n      }(SimpleOuterSubscriber));\n    \n      /** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */\n      function timeout(due, scheduler) {\n          if (scheduler === void 0) {\n              scheduler = async;\n          }\n          return timeoutWith(due, throwError(new TimeoutError()), scheduler);\n      }\n    \n      /** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */\n      function withLatestFrom() {\n          var args = [];\n          for (var _i = 0; _i < arguments.length; _i++) {\n              args[_i] = arguments[_i];\n          }\n          return function (source) {\n              var project;\n              if (typeof args[args.length - 1] === 'function') {\n                  project = args.pop();\n              }\n              var observables = args;\n              return source.lift(new WithLatestFromOperator(observables, project));\n          };\n      }\n      var WithLatestFromOperator = /*@__PURE__*/ (function () {\n          function WithLatestFromOperator(observables, project) {\n              this.observables = observables;\n              this.project = project;\n          }\n          WithLatestFromOperator.prototype.call = function (subscriber, source) {\n              return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));\n          };\n          return WithLatestFromOperator;\n      }());\n      var WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) {\n          __extends(WithLatestFromSubscriber, _super);\n          function WithLatestFromSubscriber(destination, observables, project) {\n              var _this = _super.call(this, destination) || this;\n              _this.observables = observables;\n              _this.project = project;\n              _this.toRespond = [];\n              var len = observables.length;\n              _this.values = new Array(len);\n              for (var i = 0; i < len; i++) {\n                  _this.toRespond.push(i);\n              }\n              for (var i = 0; i < len; i++) {\n                  var observable = observables[i];\n                  _this.add(subscribeToResult(_this, observable, undefined, i));\n              }\n              return _this;\n          }\n          WithLatestFromSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) {\n              this.values[outerIndex] = innerValue;\n              var toRespond = this.toRespond;\n              if (toRespond.length > 0) {\n                  var found = toRespond.indexOf(outerIndex);\n                  if (found !== -1) {\n                      toRespond.splice(found, 1);\n                  }\n              }\n          };\n          WithLatestFromSubscriber.prototype.notifyComplete = function () {\n          };\n          WithLatestFromSubscriber.prototype._next = function (value) {\n              if (this.toRespond.length === 0) {\n                  var args = [value].concat(this.values);\n                  if (this.project) {\n                      this._tryProject(args);\n                  }\n                  else {\n                      this.destination.next(args);\n                  }\n              }\n          };\n          WithLatestFromSubscriber.prototype._tryProject = function (args) {\n              var result;\n              try {\n                  result = this.project.apply(this, args);\n              }\n              catch (err) {\n                  this.destination.error(err);\n                  return;\n              }\n              this.destination.next(result);\n          };\n          return WithLatestFromSubscriber;\n      }(OuterSubscriber));\n    \n      var currentAction = {\n          type: null,\n          entityIds: null,\n          skip: false,\n      };\n      var customActionActive = false;\n      function resetCustomAction() {\n          customActionActive = false;\n      }\n      // public API for custom actions. Custom action always wins\n      function logAction(type, entityIds) {\n          setAction(type, entityIds);\n          customActionActive = true;\n      }\n      function setAction(type, entityIds) {\n          if (customActionActive === false) {\n              currentAction.type = type;\n              currentAction.entityIds = entityIds;\n          }\n      }\n      function action(action, entityIds) {\n          return function (target, propertyKey, descriptor) {\n              var originalMethod = descriptor.value;\n              descriptor.value = function () {\n                  var args = [];\n                  for (var _i = 0; _i < arguments.length; _i++) {\n                      args[_i] = arguments[_i];\n                  }\n                  logAction(action, entityIds);\n                  return originalMethod.apply(this, args);\n              };\n              return descriptor;\n          };\n      }\n    \n      // @internal\n      function hasEntity(entities, id) {\n          return entities.hasOwnProperty(id);\n      }\n    \n      // @internal\n      function addEntities(_a) {\n          var state = _a.state, entities = _a.entities, idKey = _a.idKey, _b = _a.options, options = _b === void 0 ? {} : _b, preAddEntity = _a.preAddEntity;\n          var e_1, _c;\n          var newEntities = {};\n          var newIds = [];\n          var hasNewEntities = false;\n          try {\n              for (var entities_1 = __values(entities), entities_1_1 = entities_1.next(); !entities_1_1.done; entities_1_1 = entities_1.next()) {\n                  var entity = entities_1_1.value;\n                  if (hasEntity(state.entities, entity[idKey]) === false) {\n                      // evaluate the middleware first to support dynamic ids\n                      var current = preAddEntity(entity);\n                      var entityId = current[idKey];\n                      newEntities[entityId] = current;\n                      if (options.prepend)\n                          newIds.unshift(entityId);\n                      else\n                          newIds.push(entityId);\n                      hasNewEntities = true;\n                  }\n              }\n          }\n          catch (e_1_1) { e_1 = { error: e_1_1 }; }\n          finally {\n              try {\n                  if (entities_1_1 && !entities_1_1.done && (_c = entities_1.return)) _c.call(entities_1);\n              }\n              finally { if (e_1) throw e_1.error; }\n          }\n          return hasNewEntities\n              ? {\n                  newState: __assign({}, state, { entities: __assign({}, state.entities, newEntities), ids: options.prepend ? __spread(newIds, state.ids) : __spread(state.ids, newIds) }),\n                  newIds: newIds\n              }\n              : null;\n      }\n    \n      // @internal\n      function isNil(v) {\n          return v === null || v === undefined;\n      }\n    \n      // @internal\n      function coerceArray(value) {\n          if (isNil(value)) {\n              return [];\n          }\n          return Array.isArray(value) ? value : [value];\n      }\n    \n      var DEFAULT_ID_KEY = 'id';\n    \n      var EntityActions;\n      (function (EntityActions) {\n          EntityActions[\"Set\"] = \"Set\";\n          EntityActions[\"Add\"] = \"Add\";\n          EntityActions[\"Update\"] = \"Update\";\n          EntityActions[\"Remove\"] = \"Remove\";\n      })(EntityActions || (EntityActions = {}));\n    \n      var isBrowser = typeof window !== 'undefined';\n    \n      // @internal\n      function isObject(value) {\n          var type = typeof value;\n          return value != null && (type == 'object' || type == 'function');\n      }\n    \n      // @internal\n      function isArray(value) {\n          return Array.isArray(value);\n      }\n    \n      // @internal\n      function getActiveEntities(idOrOptions, ids, currentActive) {\n          var result;\n          if (isArray(idOrOptions)) {\n              result = idOrOptions;\n          }\n          else {\n              if (isObject(idOrOptions)) {\n                  if (isNil(currentActive))\n                      return;\n                  idOrOptions = Object.assign({ wrap: true }, idOrOptions);\n                  var currentIdIndex = ids.indexOf(currentActive);\n                  if (idOrOptions.prev) {\n                      var isFirst = currentIdIndex === 0;\n                      if (isFirst && !idOrOptions.wrap)\n                          return;\n                      result = isFirst ? ids[ids.length - 1] : ids[currentIdIndex - 1];\n                  }\n                  else if (idOrOptions.next) {\n                      var isLast = ids.length === currentIdIndex + 1;\n                      if (isLast && !idOrOptions.wrap)\n                          return;\n                      result = isLast ? ids[0] : ids[currentIdIndex + 1];\n                  }\n              }\n              else {\n                  if (idOrOptions === currentActive)\n                      return;\n                  result = idOrOptions;\n              }\n          }\n          return result;\n      }\n    \n      // @internal\n      var getInitialEntitiesState = function () {\n          return ({\n              entities: {},\n              ids: [],\n              loading: true,\n              error: null\n          });\n      };\n    \n      // @internal\n      function isDefined(val) {\n          return isNil(val) === false;\n      }\n    \n      // @internal\n      function isEmpty(arr) {\n          if (isArray(arr)) {\n              return arr.length === 0;\n          }\n          return false;\n      }\n    \n      // @internal\n      function isFunction(value) {\n          return typeof value === 'function';\n      }\n    \n      // @internal\n      function isUndefined(value) {\n          return value === undefined;\n      }\n    \n      // @internal\n      function hasActiveState(state) {\n          return state.hasOwnProperty('active');\n      }\n      // @internal\n      function isMultiActiveState(active) {\n          return isArray(active);\n      }\n      // @internal\n      function resolveActiveEntity(_a) {\n          var active = _a.active, ids = _a.ids, entities = _a.entities;\n          if (isMultiActiveState(active)) {\n              return getExitingActives(active, ids);\n          }\n          if (hasEntity(entities, active) === false) {\n              return null;\n          }\n          return active;\n      }\n      // @internal\n      function getExitingActives(currentActivesIds, newIds) {\n          var filtered = currentActivesIds.filter(function (id) { return newIds.indexOf(id) > -1; });\n          /** Return the same reference if nothing has changed */\n          if (filtered.length === currentActivesIds.length) {\n              return currentActivesIds;\n          }\n          return filtered;\n      }\n    \n      // @internal\n      function removeEntities(_a) {\n          var state = _a.state, ids = _a.ids;\n          var e_1, _b;\n          if (isNil(ids))\n              return removeAllEntities(state);\n          var entities = state.entities;\n          var newEntities = {};\n          try {\n              for (var _c = __values(state.ids), _d = _c.next(); !_d.done; _d = _c.next()) {\n                  var id = _d.value;\n                  if (ids.includes(id) === false) {\n                      newEntities[id] = entities[id];\n                  }\n              }\n          }\n          catch (e_1_1) { e_1 = { error: e_1_1 }; }\n          finally {\n              try {\n                  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);\n              }\n              finally { if (e_1) throw e_1.error; }\n          }\n          var newState = __assign({}, state, { entities: newEntities, ids: state.ids.filter(function (current) { return ids.includes(current) === false; }) });\n          if (hasActiveState(state)) {\n              newState.active = resolveActiveEntity(newState);\n          }\n          return newState;\n      }\n      // @internal\n      function removeAllEntities(state) {\n          return __assign({}, state, { entities: {}, ids: [], active: isMultiActiveState(state.active) ? [] : null });\n      }\n    \n      // @internal\n      function toEntitiesObject(entities, idKey, preAddEntity) {\n          var e_1, _a;\n          var acc = {\n              entities: {},\n              ids: []\n          };\n          try {\n              for (var entities_1 = __values(entities), entities_1_1 = entities_1.next(); !entities_1_1.done; entities_1_1 = entities_1.next()) {\n                  var entity = entities_1_1.value;\n                  // evaluate the middleware first to support dynamic ids\n                  var current = preAddEntity(entity);\n                  acc.entities[current[idKey]] = current;\n                  acc.ids.push(current[idKey]);\n              }\n          }\n          catch (e_1_1) { e_1 = { error: e_1_1 }; }\n          finally {\n              try {\n                  if (entities_1_1 && !entities_1_1.done && (_a = entities_1.return)) _a.call(entities_1);\n              }\n              finally { if (e_1) throw e_1.error; }\n          }\n          return acc;\n      }\n    \n      // @internal\n      function isEntityState(state) {\n          return state.entities && state.ids;\n      }\n      // @internal\n      function applyMiddleware(entities, preAddEntity) {\n          var e_1, _a;\n          var mapped = {};\n          try {\n              for (var _b = __values(Object.keys(entities)), _c = _b.next(); !_c.done; _c = _b.next()) {\n                  var id = _c.value;\n                  mapped[id] = preAddEntity(entities[id]);\n              }\n          }\n          catch (e_1_1) { e_1 = { error: e_1_1 }; }\n          finally {\n              try {\n                  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n              }\n              finally { if (e_1) throw e_1.error; }\n          }\n          return mapped;\n      }\n      // @internal\n      function setEntities(_a) {\n          var state = _a.state, entities = _a.entities, idKey = _a.idKey, preAddEntity = _a.preAddEntity, isNativePreAdd = _a.isNativePreAdd;\n          var newEntities;\n          var newIds;\n          if (isArray(entities)) {\n              var resolve = toEntitiesObject(entities, idKey, preAddEntity);\n              newEntities = resolve.entities;\n              newIds = resolve.ids;\n          }\n          else if (isEntityState(entities)) {\n              newEntities = isNativePreAdd ? entities.entities : applyMiddleware(entities.entities, preAddEntity);\n              newIds = entities.ids;\n          }\n          else {\n              // it's an object\n              newEntities = isNativePreAdd ? entities : applyMiddleware(entities, preAddEntity);\n              newIds = Object.keys(newEntities).map(function (id) { return (isNaN(id) ? id : Number(id)); });\n          }\n          var newState = __assign({}, state, { entities: newEntities, ids: newIds, loading: false });\n          if (hasActiveState(state)) {\n              newState.active = resolveActiveEntity(newState);\n          }\n          return newState;\n      }\n    \n      var CONFIG = {\n          resettable: false,\n          ttl: null,\n          producerFn: undefined\n      };\n      // @internal\n      function getAkitaConfig() {\n          return CONFIG;\n      }\n      function getGlobalProducerFn() {\n          return CONFIG.producerFn;\n      }\n    \n      // @internal\n      function deepFreeze(o) {\n          Object.freeze(o);\n          var oIsFunction = typeof o === 'function';\n          var hasOwnProp = Object.prototype.hasOwnProperty;\n          Object.getOwnPropertyNames(o).forEach(function (prop) {\n              if (hasOwnProp.call(o, prop) &&\n                  (oIsFunction ? prop !== 'caller' && prop !== 'callee' && prop !== 'arguments' : true) &&\n                  o[prop] !== null &&\n                  (typeof o[prop] === 'object' || typeof o[prop] === 'function') &&\n                  !Object.isFrozen(o[prop])) {\n                  deepFreeze(o[prop]);\n              }\n          });\n          return o;\n      }\n    \n      // @internal\n      var $$deleteStore = new Subject();\n      // @internal\n      var $$addStore = new ReplaySubject(50, 5000);\n      // @internal\n      var $$updateStore = new Subject();\n      // @internal\n      function dispatchDeleted(storeName) {\n          $$deleteStore.next(storeName);\n      }\n      // @internal\n      function dispatchAdded(storeName) {\n          $$addStore.next(storeName);\n      }\n      // @internal\n      function dispatchUpdate(storeName, action) {\n          $$updateStore.next({ storeName: storeName, action: action });\n      }\n    \n      // @internal\n      /** @class */ ((function (_super) {\n          __extends(AkitaError, _super);\n          function AkitaError(message) {\n              return _super.call(this, message) || this;\n          }\n          return AkitaError;\n      })(Error));\n      // @internal\n      function assertStoreHasName(name, className) {\n          if (!name) {\n              console.error(\"@StoreConfig({ name }) is missing in \" + className);\n          }\n      }\n    \n      // @internal\n      function toBoolean(value) {\n          return value != null && \"\" + value !== 'false';\n      }\n    \n      // @internal\n      function isPlainObject$1(value) {\n          return toBoolean(value) && value.constructor.name === 'Object';\n      }\n    \n      var configKey = 'akitaConfig';\n    \n      // @internal\n      var __stores__ = {};\n      // @internal\n      var __queries__ = {};\n      if (isBrowser) {\n          window.$$stores = __stores__;\n          window.$$queries = __queries__;\n      }\n    \n      // @internal\n      var transactionFinished = new Subject();\n      // @internal\n      var transactionInProcess = new BehaviorSubject(false);\n      // @internal\n      var transactionManager = {\n          activeTransactions: 0,\n          batchTransaction: null\n      };\n      // @internal\n      function startBatch() {\n          if (!isTransactionInProcess()) {\n              transactionManager.batchTransaction = new Subject();\n          }\n          transactionManager.activeTransactions++;\n          transactionInProcess.next(true);\n      }\n      // @internal\n      function endBatch() {\n          if (--transactionManager.activeTransactions === 0) {\n              transactionManager.batchTransaction.next(true);\n              transactionManager.batchTransaction.complete();\n              transactionInProcess.next(false);\n              transactionFinished.next(true);\n          }\n      }\n      // @internal\n      function isTransactionInProcess() {\n          return transactionManager.activeTransactions > 0;\n      }\n      // @internal\n      function commit() {\n          return transactionManager.batchTransaction ? transactionManager.batchTransaction.asObservable() : of(true);\n      }\n      /**\n       *  A logical transaction.\n       *  Use this transaction to optimize the dispatch of all the stores.\n       *  The following code will update the store, BUT  emits only once\n       *\n       *  @example\n       *  applyTransaction(() => {\n       *    this.todosStore.add(new Todo(1, title));\n       *    this.todosStore.add(new Todo(2, title));\n       *  });\n       *\n       */\n      function applyTransaction(action, thisArg) {\n          if (thisArg === void 0) { thisArg = undefined; }\n          startBatch();\n          try {\n              return action.apply(thisArg);\n          }\n          finally {\n              logAction('@Transaction');\n              endBatch();\n          }\n      }\n      /**\n       *  A logical transaction.\n       *  Use this transaction to optimize the dispatch of all the stores.\n       *\n       *  The following code will update the store, BUT  emits only once.\n       *\n       *  @example\n       *  @transaction\n       *  addTodos() {\n       *    this.todosStore.add(new Todo(1, title));\n       *    this.todosStore.add(new Todo(2, title));\n       *  }\n       *\n       *\n       */\n      function transaction() {\n          return function (target, propertyKey, descriptor) {\n              var originalMethod = descriptor.value;\n              descriptor.value = function () {\n                  var _this = this;\n                  var args = [];\n                  for (var _i = 0; _i < arguments.length; _i++) {\n                      args[_i] = arguments[_i];\n                  }\n                  return applyTransaction(function () {\n                      return originalMethod.apply(_this, args);\n                  }, this);\n              };\n              return descriptor;\n          };\n      }\n      /**\n       *\n       * RxJS custom operator that wraps the callback inside transaction\n       *\n       * @example\n       *\n       * return http.get().pipe(\n       *    withTransaction(response > {\n       *      store.setActive(1);\n       *      store.update();\n       *      store.updateEntity(1, {});\n       *    })\n       * )\n       *\n       */\n      function withTransaction(next) {\n          return function (source) {\n              return source.pipe(tap(function (value) { return applyTransaction(function () { return next(value); }); }));\n          };\n      }\n    \n      /**\n       *\n       * Store for managing any type of data\n       *\n       * @example\n       *\n       * export interface SessionState {\n       *   token: string;\n       *   userDetails: UserDetails\n       * }\n       *\n       * export function createInitialState(): SessionState {\n       *  return {\n       *    token: '',\n       *    userDetails: null\n       *  };\n       * }\n       *\n       * @StoreConfig({ name: 'session' })\n       * export class SessionStore extends Store<SessionState> {\n       *   constructor() {\n       *    super(createInitialState());\n       *   }\n       * }\n       */\n      var Store = /** @class */ (function () {\n          function Store(initialState, options) {\n              if (options === void 0) { options = {}; }\n              this.options = options;\n              this.inTransaction = false;\n              this.cache = {\n                  active: new BehaviorSubject(false),\n                  ttl: null,\n              };\n              this.onInit(initialState);\n          }\n          /**\n           *  Set the loading state\n           *\n           *  @example\n           *\n           *  store.setLoading(true)\n           *\n           */\n          Store.prototype.setLoading = function (loading) {\n              if (loading === void 0) { loading = false; }\n              if (loading !== this._value().loading) {\n                  setAction('Set Loading');\n                  this._setState(function (state) { return (__assign({}, state, { loading: loading })); });\n              }\n          };\n          /**\n           *\n           * Set whether the data is cached\n           *\n           * @example\n           *\n           * store.setHasCache(true)\n           * store.setHasCache(false)\n           * store.setHasCache(true, { restartTTL: true })\n           *\n           */\n          Store.prototype.setHasCache = function (hasCache, options) {\n              var _this = this;\n              if (options === void 0) { options = { restartTTL: false }; }\n              if (hasCache !== this.cache.active.value) {\n                  this.cache.active.next(hasCache);\n              }\n              if (options.restartTTL) {\n                  var ttlConfig = this.getCacheTTL();\n                  if (ttlConfig) {\n                      if (this.cache.ttl !== null) {\n                          clearTimeout(this.cache.ttl);\n                      }\n                      this.cache.ttl = setTimeout(function () { return _this.setHasCache(false); }, ttlConfig);\n                  }\n              }\n          };\n          /**\n           *\n           * Sometimes we need to access the store value from a store\n           *\n           * @example middleware\n           *\n           */\n          Store.prototype.getValue = function () {\n              return this.storeValue;\n          };\n          /**\n           *  Set the error state\n           *\n           *  @example\n           *\n           *  store.setError({text: 'unable to load data' })\n           *\n           */\n          Store.prototype.setError = function (error) {\n              if (error !== this._value().error) {\n                  setAction('Set Error');\n                  this._setState(function (state) { return (__assign({}, state, { error: error })); });\n              }\n          };\n          // @internal\n          Store.prototype._select = function (project) {\n              return this.store.asObservable().pipe(map(function (snapshot) { return project(snapshot.state); }), distinctUntilChanged());\n          };\n          // @internal\n          Store.prototype._value = function () {\n              return this.storeValue;\n          };\n          // @internal\n          Store.prototype._cache = function () {\n              return this.cache.active;\n          };\n          Object.defineProperty(Store.prototype, \"config\", {\n              // @internal\n              get: function () {\n                  return this.constructor[configKey] || {};\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(Store.prototype, \"storeName\", {\n              // @internal\n              get: function () {\n                  return this.config.storeName || this.options.storeName || this.options.name;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(Store.prototype, \"deepFreeze\", {\n              // @internal\n              get: function () {\n                  return this.config.deepFreezeFn || this.options.deepFreezeFn || deepFreeze;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(Store.prototype, \"cacheConfig\", {\n              // @internal\n              get: function () {\n                  return this.config.cache || this.options.cache;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(Store.prototype, \"_producerFn\", {\n              get: function () {\n                  return this.config.producerFn || this.options.producerFn || getGlobalProducerFn();\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(Store.prototype, \"resettable\", {\n              // @internal\n              get: function () {\n                  return isDefined(this.config.resettable) ? this.config.resettable : this.options.resettable;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          // @internal\n          Store.prototype._setState = function (newState, _dispatchAction) {\n              var _this = this;\n              if (_dispatchAction === void 0) { _dispatchAction = true; }\n              if (isFunction(newState)) {\n                  var _newState = newState(this._value());\n                  this.storeValue = this.deepFreeze(_newState) ;\n              }\n              else {\n                  this.storeValue = newState;\n              }\n              if (!this.store) {\n                  this.store = new BehaviorSubject({ state: this.storeValue });\n                  {\n                      this.store.subscribe(function (_a) {\n                          var action = _a.action;\n                          if (action) {\n                              dispatchUpdate(_this.storeName, action);\n                          }\n                      });\n                  }\n                  return;\n              }\n              if (isTransactionInProcess()) {\n                  this.handleTransaction();\n                  return;\n              }\n              this.dispatch(this.storeValue, _dispatchAction);\n          };\n          /**\n           *\n           * Reset the current store back to the initial value\n           *\n           * @example\n           *\n           * store.reset()\n           *\n           */\n          Store.prototype.reset = function () {\n              var _this = this;\n              if (this.isResettable()) {\n                  setAction('Reset');\n                  this._setState(function () { return Object.assign({}, _this._initialState); });\n                  this.setHasCache(false);\n              }\n              else {\n                  console.warn(\"You need to enable the reset functionality\");\n              }\n          };\n          Store.prototype.update = function (stateOrCallback) {\n              setAction('Update');\n              var newState;\n              var currentState = this._value();\n              if (isFunction(stateOrCallback)) {\n                  newState = isFunction(this._producerFn) ? this._producerFn(currentState, stateOrCallback) : stateOrCallback(currentState);\n              }\n              else {\n                  newState = stateOrCallback;\n              }\n              var withHook = this.akitaPreUpdate(currentState, __assign({}, currentState, newState));\n              var resolved = isPlainObject$1(currentState) ? withHook : new currentState.constructor(withHook);\n              this._setState(resolved);\n          };\n          Store.prototype.updateStoreConfig = function (newOptions) {\n              this.options = __assign({}, this.options, newOptions);\n          };\n          // @internal\n          Store.prototype.akitaPreUpdate = function (_, nextState) {\n              return nextState;\n          };\n          Store.prototype.ngOnDestroy = function () {\n              this.destroy();\n          };\n          /**\n           *\n           * Destroy the store\n           *\n           * @example\n           *\n           * store.destroy()\n           *\n           */\n          Store.prototype.destroy = function () {\n              var hmrEnabled = isBrowser ? window.hmrEnabled : false;\n              if (!hmrEnabled && this === __stores__[this.storeName]) {\n                  delete __stores__[this.storeName];\n                  dispatchDeleted(this.storeName);\n                  this.setHasCache(false);\n                  this.cache.active.complete();\n                  this.store.complete();\n              }\n          };\n          Store.prototype.onInit = function (initialState) {\n              __stores__[this.storeName] = this;\n              this._setState(function () { return initialState; });\n              dispatchAdded(this.storeName);\n              if (this.isResettable()) {\n                  this._initialState = initialState;\n              }\n              assertStoreHasName(this.storeName, this.constructor.name);\n          };\n          Store.prototype.dispatch = function (state, _dispatchAction) {\n              if (_dispatchAction === void 0) { _dispatchAction = true; }\n              var action = undefined;\n              if (_dispatchAction) {\n                  action = currentAction;\n                  resetCustomAction();\n              }\n              this.store.next({ state: state, action: action });\n          };\n          Store.prototype.watchTransaction = function () {\n              var _this = this;\n              commit().subscribe(function () {\n                  _this.inTransaction = false;\n                  _this.dispatch(_this._value());\n              });\n          };\n          Store.prototype.isResettable = function () {\n              if (this.resettable === false) {\n                  return false;\n              }\n              return this.resettable || getAkitaConfig().resettable;\n          };\n          Store.prototype.handleTransaction = function () {\n              if (!this.inTransaction) {\n                  this.watchTransaction();\n                  this.inTransaction = true;\n              }\n          };\n          Store.prototype.getCacheTTL = function () {\n              return (this.cacheConfig && this.cacheConfig.ttl) || getAkitaConfig().ttl;\n          };\n          return Store;\n      }());\n    \n      // @internal\n      function updateEntities(_a) {\n          var state = _a.state, ids = _a.ids, idKey = _a.idKey, newStateOrFn = _a.newStateOrFn, preUpdateEntity = _a.preUpdateEntity, producerFn = _a.producerFn, onEntityIdChanges = _a.onEntityIdChanges;\n          var e_1, _b;\n          var updatedEntities = {};\n          var isUpdatingIdKey = false;\n          var idToUpdate;\n          try {\n              for (var ids_1 = __values(ids), ids_1_1 = ids_1.next(); !ids_1_1.done; ids_1_1 = ids_1.next()) {\n                  var id = ids_1_1.value;\n                  // if the entity doesn't exist don't do anything\n                  if (hasEntity(state.entities, id) === false) {\n                      continue;\n                  }\n                  var oldEntity = state.entities[id];\n                  var newState = void 0;\n                  if (isFunction(newStateOrFn)) {\n                      newState = isFunction(producerFn) ? producerFn(oldEntity, newStateOrFn) : newStateOrFn(oldEntity);\n                  }\n                  else {\n                      newState = newStateOrFn;\n                  }\n                  var isIdChanged = newState.hasOwnProperty(idKey) && newState[idKey] !== oldEntity[idKey];\n                  var newEntity = void 0;\n                  idToUpdate = id;\n                  if (isIdChanged) {\n                      isUpdatingIdKey = true;\n                      idToUpdate = newState[idKey];\n                  }\n                  var merged = __assign({}, oldEntity, newState);\n                  if (isPlainObject$1(oldEntity)) {\n                      newEntity = merged;\n                  }\n                  else {\n                      /**\n                       * In case that new state is class of it's own, there's\n                       * a possibility that it will be different than the old\n                       * class.\n                       * For example, Old state is an instance of animal class\n                       * and new state is instance of person class.\n                       * To avoid run over new person class with the old animal\n                       * class we check if the new state is a class of it's own.\n                       * If so, use it. Otherwise, use the old state class\n                       */\n                      if (isPlainObject$1(newState)) {\n                          newEntity = new oldEntity.constructor(merged);\n                      }\n                      else {\n                          newEntity = new newState.constructor(merged);\n                      }\n                  }\n                  updatedEntities[idToUpdate] = preUpdateEntity(oldEntity, newEntity);\n              }\n          }\n          catch (e_1_1) { e_1 = { error: e_1_1 }; }\n          finally {\n              try {\n                  if (ids_1_1 && !ids_1_1.done && (_b = ids_1.return)) _b.call(ids_1);\n              }\n              finally { if (e_1) throw e_1.error; }\n          }\n          var updatedIds = state.ids;\n          var stateEntities = state.entities;\n          if (isUpdatingIdKey) {\n              var _c = __read(ids, 1), id_1 = _c[0];\n              var _d = state.entities, _e = id_1, rest = __rest(_d, [typeof _e === \"symbol\" ? _e : _e + \"\"]);\n              stateEntities = rest;\n              updatedIds = state.ids.map(function (current) { return (current === id_1 ? idToUpdate : current); });\n              onEntityIdChanges(id_1, idToUpdate);\n          }\n          return __assign({}, state, { entities: __assign({}, stateEntities, updatedEntities), ids: updatedIds });\n      }\n    \n      /**\n       *\n       * Store for managing a collection of entities\n       *\n       * @example\n       *\n       * export interface WidgetsState extends EntityState<Widget> { }\n       *\n       * @StoreConfig({ name: 'widgets' })\n       *  export class WidgetsStore extends EntityStore<WidgetsState> {\n       *   constructor() {\n       *     super();\n       *   }\n       * }\n       *\n       *\n       */\n      var EntityStore = /** @class */ (function (_super) {\n          __extends(EntityStore, _super);\n          function EntityStore(initialState, options) {\n              if (initialState === void 0) { initialState = {}; }\n              if (options === void 0) { options = {}; }\n              var _this = _super.call(this, __assign({}, getInitialEntitiesState(), initialState), options) || this;\n              _this.options = options;\n              _this.entityActions = new Subject();\n              _this.entityIdChanges = new Subject();\n              return _this;\n          }\n          Object.defineProperty(EntityStore.prototype, \"selectEntityAction$\", {\n              // @internal\n              get: function () {\n                  return this.entityActions.asObservable();\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(EntityStore.prototype, \"selectEntityIdChanges$\", {\n              // @internal\n              get: function () {\n                  return this.entityIdChanges.asObservable();\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(EntityStore.prototype, \"idKey\", {\n              // @internal\n              get: function () {\n                  return this.config.idKey || this.options.idKey || DEFAULT_ID_KEY;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          /**\n           *\n           * Replace current collection with provided collection\n           *\n           * @example\n           *\n           * this.store.set([Entity, Entity])\n           * this.store.set({ids: [], entities: {}})\n           * this.store.set({ 1: {}, 2: {}})\n           *\n           */\n          EntityStore.prototype.set = function (entities, options) {\n              var _this = this;\n              if (options === void 0) { options = {}; }\n              if (isNil(entities))\n                  return;\n              setAction('Set Entity');\n              var isNativePreAdd = this.akitaPreAddEntity === EntityStore.prototype.akitaPreAddEntity;\n              this.setHasCache(true, { restartTTL: true });\n              this._setState(function (state) {\n                  var newState = setEntities({\n                      state: state,\n                      entities: entities,\n                      idKey: _this.idKey,\n                      preAddEntity: _this.akitaPreAddEntity,\n                      isNativePreAdd: isNativePreAdd,\n                  });\n                  if (isUndefined(options.activeId) === false) {\n                      newState.active = options.activeId;\n                  }\n                  return newState;\n              });\n              if (this.hasInitialUIState()) {\n                  this.handleUICreation();\n              }\n              this.entityActions.next({ type: EntityActions.Set, ids: this.ids });\n          };\n          /**\n           * Add entities\n           *\n           * @example\n           *\n           * this.store.add([Entity, Entity])\n           * this.store.add(Entity)\n           * this.store.add(Entity, { prepend: true })\n           *\n           * this.store.add(Entity, { loading: false })\n           */\n          EntityStore.prototype.add = function (entities, options) {\n              if (options === void 0) { options = { loading: false }; }\n              var collection = coerceArray(entities);\n              if (isEmpty(collection))\n                  return;\n              var data = addEntities({\n                  state: this._value(),\n                  preAddEntity: this.akitaPreAddEntity,\n                  entities: collection,\n                  idKey: this.idKey,\n                  options: options,\n              });\n              if (data) {\n                  setAction('Add Entity');\n                  data.newState.loading = options.loading;\n                  this._setState(function () { return data.newState; });\n                  if (this.hasInitialUIState()) {\n                      this.handleUICreation(true);\n                  }\n                  this.entityActions.next({ type: EntityActions.Add, ids: data.newIds });\n              }\n          };\n          EntityStore.prototype.update = function (idsOrFnOrState, newStateOrFn) {\n              var _this = this;\n              if (isUndefined(newStateOrFn)) {\n                  _super.prototype.update.call(this, idsOrFnOrState);\n                  return;\n              }\n              var ids = [];\n              if (isFunction(idsOrFnOrState)) {\n                  // We need to filter according the predicate function\n                  ids = this.ids.filter(function (id) { return idsOrFnOrState(_this.entities[id]); });\n              }\n              else {\n                  // If it's nil we want all of them\n                  ids = isNil(idsOrFnOrState) ? this.ids : coerceArray(idsOrFnOrState);\n              }\n              if (isEmpty(ids))\n                  return;\n              setAction('Update Entity', ids);\n              var entityIdChanged;\n              this._setState(function (state) {\n                  return updateEntities({\n                      idKey: _this.idKey,\n                      ids: ids,\n                      preUpdateEntity: _this.akitaPreUpdateEntity,\n                      state: state,\n                      newStateOrFn: newStateOrFn,\n                      producerFn: _this._producerFn,\n                      onEntityIdChanges: function (oldId, newId) {\n                          entityIdChanged = { oldId: oldId, newId: newId };\n                          _this.entityIdChanges.next(__assign({}, entityIdChanged, { pending: true }));\n                      },\n                  });\n              });\n              if (entityIdChanged) {\n                  this.entityIdChanges.next(__assign({}, entityIdChanged, { pending: false }));\n              }\n              this.entityActions.next({ type: EntityActions.Update, ids: ids });\n          };\n          EntityStore.prototype.upsert = function (ids, newState, onCreate, options) {\n              var _this = this;\n              if (options === void 0) { options = {}; }\n              var toArray = coerceArray(ids);\n              var predicate = function (isUpdate) { return function (id) { return hasEntity(_this.entities, id) === isUpdate; }; };\n              var baseClass = isFunction(onCreate) ? options.baseClass : onCreate ? onCreate.baseClass : undefined;\n              var isClassBased = isFunction(baseClass);\n              var updateIds = toArray.filter(predicate(true));\n              var newEntities = toArray.filter(predicate(false)).map(function (id) {\n                  var _a;\n                  var newStateObj = typeof newState === 'function' ? newState({}) : newState;\n                  var entity = isFunction(onCreate) ? onCreate(id, newStateObj) : newStateObj;\n                  var withId = __assign({}, entity, (_a = {}, _a[_this.idKey] = id, _a));\n                  if (isClassBased) {\n                      return new baseClass(withId);\n                  }\n                  return withId;\n              });\n              // it can be any of the three types\n              this.update(updateIds, newState);\n              this.add(newEntities);\n              logAction('Upsert Entity');\n          };\n          /**\n           *\n           * Upsert entity collection (idKey must be present)\n           *\n           * @example\n           *\n           * store.upsertMany([ { id: 1 }, { id: 2 }]);\n           *\n           * store.upsertMany([ { id: 1 }, { id: 2 }], { loading: true  });\n           * store.upsertMany([ { id: 1 }, { id: 2 }], { baseClass: Todo  });\n           *\n           */\n          EntityStore.prototype.upsertMany = function (entities, options) {\n              if (options === void 0) { options = {}; }\n              var e_1, _a;\n              var addedIds = [];\n              var updatedIds = [];\n              var updatedEntities = {};\n              try {\n                  // Update the state directly to optimize performance\n                  for (var entities_1 = __values(entities), entities_1_1 = entities_1.next(); !entities_1_1.done; entities_1_1 = entities_1.next()) {\n                      var entity = entities_1_1.value;\n                      var withPreCheckHook = this.akitaPreCheckEntity(entity);\n                      var id = withPreCheckHook[this.idKey];\n                      if (hasEntity(this.entities, id)) {\n                          var prev = this._value().entities[id];\n                          var merged = __assign({}, this._value().entities[id], withPreCheckHook);\n                          var next = options.baseClass ? new options.baseClass(merged) : merged;\n                          var withHook = this.akitaPreUpdateEntity(prev, next);\n                          var nextId = withHook[this.idKey];\n                          updatedEntities[nextId] = withHook;\n                          updatedIds.push(nextId);\n                      }\n                      else {\n                          var newEntity = options.baseClass ? new options.baseClass(withPreCheckHook) : withPreCheckHook;\n                          var withHook = this.akitaPreAddEntity(newEntity);\n                          var nextId = withHook[this.idKey];\n                          addedIds.push(nextId);\n                          updatedEntities[nextId] = withHook;\n                      }\n                  }\n              }\n              catch (e_1_1) { e_1 = { error: e_1_1 }; }\n              finally {\n                  try {\n                      if (entities_1_1 && !entities_1_1.done && (_a = entities_1.return)) _a.call(entities_1);\n                  }\n                  finally { if (e_1) throw e_1.error; }\n              }\n              logAction('Upsert Many');\n              this._setState(function (state) { return (__assign({}, state, { ids: addedIds.length ? __spread(state.ids, addedIds) : state.ids, entities: __assign({}, state.entities, updatedEntities), loading: !!options.loading })); });\n              updatedIds.length && this.entityActions.next({ type: EntityActions.Update, ids: updatedIds });\n              addedIds.length && this.entityActions.next({ type: EntityActions.Add, ids: addedIds });\n              if (addedIds.length && this.hasUIStore()) {\n                  this.handleUICreation(true);\n              }\n          };\n          /**\n           *\n           * Replace one or more entities (except the id property)\n           *\n           *\n           * @example\n           *\n           * this.store.replace(5, newEntity)\n           * this.store.replace([1,2,3], newEntity)\n           */\n          EntityStore.prototype.replace = function (ids, newState) {\n              var e_2, _a;\n              var toArray = coerceArray(ids);\n              if (isEmpty(toArray))\n                  return;\n              var replaced = {};\n              try {\n                  for (var toArray_1 = __values(toArray), toArray_1_1 = toArray_1.next(); !toArray_1_1.done; toArray_1_1 = toArray_1.next()) {\n                      var id = toArray_1_1.value;\n                      newState[this.idKey] = id;\n                      replaced[id] = newState;\n                  }\n              }\n              catch (e_2_1) { e_2 = { error: e_2_1 }; }\n              finally {\n                  try {\n                      if (toArray_1_1 && !toArray_1_1.done && (_a = toArray_1.return)) _a.call(toArray_1);\n                  }\n                  finally { if (e_2) throw e_2.error; }\n              }\n              setAction('Replace Entity', ids);\n              this._setState(function (state) { return (__assign({}, state, { entities: __assign({}, state.entities, replaced) })); });\n          };\n          /**\n           *\n           * Move entity inside the collection\n           *\n           *\n           * @example\n           *\n           * this.store.move(fromIndex, toIndex)\n           */\n          EntityStore.prototype.move = function (from, to) {\n              var ids = this.ids.slice();\n              ids.splice(to < 0 ? ids.length + to : to, 0, ids.splice(from, 1)[0]);\n              setAction('Move Entity');\n              this._setState(function (state) { return (__assign({}, state, { \n                  // Change the entities reference so that selectAll emit\n                  entities: __assign({}, state.entities), ids: ids })); });\n          };\n          EntityStore.prototype.remove = function (idsOrFn) {\n              var _this = this;\n              if (isEmpty(this.ids))\n                  return;\n              var idPassed = isDefined(idsOrFn);\n              // null means remove all\n              var ids = [];\n              if (isFunction(idsOrFn)) {\n                  ids = this.ids.filter(function (entityId) { return idsOrFn(_this.entities[entityId]); });\n              }\n              else {\n                  ids = idPassed ? coerceArray(idsOrFn) : this.ids;\n              }\n              if (isEmpty(ids))\n                  return;\n              setAction('Remove Entity', ids);\n              this._setState(function (state) { return removeEntities({ state: state, ids: ids }); });\n              if (!idPassed) {\n                  this.setHasCache(false);\n              }\n              this.handleUIRemove(ids);\n              this.entityActions.next({ type: EntityActions.Remove, ids: ids });\n          };\n          /**\n           *\n           * Update the active entity\n           *\n           * @example\n           *\n           * this.store.updateActive({ completed: true })\n           * this.store.updateActive(active => {\n           *   return {\n           *     config: {\n           *      ..active.config,\n           *      date\n           *     }\n           *   }\n           * })\n           */\n          EntityStore.prototype.updateActive = function (newStateOrCallback) {\n              var ids = coerceArray(this.active);\n              setAction('Update Active', ids);\n              this.update(ids, newStateOrCallback);\n          };\n          EntityStore.prototype.setActive = function (idOrOptions) {\n              var active = getActiveEntities(idOrOptions, this.ids, this.active);\n              if (active === undefined) {\n                  return;\n              }\n              setAction('Set Active', active);\n              this._setActive(active);\n          };\n          /**\n           * Add active entities\n           *\n           * @example\n           *\n           * store.addActive(2);\n           * store.addActive([3, 4, 5]);\n           */\n          EntityStore.prototype.addActive = function (ids) {\n              var _this = this;\n              var toArray = coerceArray(ids);\n              if (isEmpty(toArray))\n                  return;\n              var everyExist = toArray.every(function (id) { return _this.active.indexOf(id) > -1; });\n              if (everyExist)\n                  return;\n              setAction('Add Active', ids);\n              this._setState(function (state) {\n                  /** Protect against case that one of the items in the array exist */\n                  var uniques = Array.from(new Set(__spread(state.active, toArray)));\n                  return __assign({}, state, { active: uniques });\n              });\n          };\n          /**\n           * Remove active entities\n           *\n           * @example\n           *\n           * store.removeActive(2)\n           * store.removeActive([3, 4, 5])\n           */\n          EntityStore.prototype.removeActive = function (ids) {\n              var _this = this;\n              var toArray = coerceArray(ids);\n              if (isEmpty(toArray))\n                  return;\n              var someExist = toArray.some(function (id) { return _this.active.indexOf(id) > -1; });\n              if (!someExist)\n                  return;\n              setAction('Remove Active', ids);\n              this._setState(function (state) {\n                  return __assign({}, state, { active: Array.isArray(state.active) ? state.active.filter(function (currentId) { return toArray.indexOf(currentId) === -1; }) : null });\n              });\n          };\n          /**\n           * Toggle active entities\n           *\n           * @example\n           *\n           * store.toggle(2)\n           * store.toggle([3, 4, 5])\n           */\n          EntityStore.prototype.toggleActive = function (ids) {\n              var _this = this;\n              var toArray = coerceArray(ids);\n              var filterExists = function (remove) { return function (id) { return _this.active.includes(id) === remove; }; };\n              var remove = toArray.filter(filterExists(true));\n              var add = toArray.filter(filterExists(false));\n              this.removeActive(remove);\n              this.addActive(add);\n              logAction('Toggle Active');\n          };\n          /**\n           *\n           * Create sub UI store for managing Entity's UI state\n           *\n           * @example\n           *\n           * export type ProductUI = {\n           *   isLoading: boolean;\n           *   isOpen: boolean\n           * }\n           *\n           * interface ProductsUIState extends EntityState<ProductUI> {}\n           *\n           * export class ProductsStore EntityStore<ProductsState, Product> {\n           *   ui: EntityUIStore<ProductsUIState, ProductUI>;\n           *\n           *   constructor() {\n           *     super();\n           *     this.createUIStore();\n           *   }\n           *\n           * }\n           */\n          EntityStore.prototype.createUIStore = function (initialState, storeConfig) {\n              if (initialState === void 0) { initialState = {}; }\n              if (storeConfig === void 0) { storeConfig = {}; }\n              var defaults = { name: \"UI/\" + this.storeName, idKey: this.idKey };\n              this.ui = new EntityUIStore(initialState, __assign({}, defaults, storeConfig));\n              return this.ui;\n          };\n          // @internal\n          EntityStore.prototype.destroy = function () {\n              _super.prototype.destroy.call(this);\n              if (this.ui instanceof EntityStore) {\n                  this.ui.destroy();\n              }\n              this.entityActions.complete();\n          };\n          // @internal\n          EntityStore.prototype.akitaPreUpdateEntity = function (_, nextEntity) {\n              return nextEntity;\n          };\n          // @internal\n          EntityStore.prototype.akitaPreAddEntity = function (newEntity) {\n              return newEntity;\n          };\n          // @internal\n          EntityStore.prototype.akitaPreCheckEntity = function (newEntity) {\n              return newEntity;\n          };\n          Object.defineProperty(EntityStore.prototype, \"ids\", {\n              get: function () {\n                  return this._value().ids;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(EntityStore.prototype, \"entities\", {\n              get: function () {\n                  return this._value().entities;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(EntityStore.prototype, \"active\", {\n              get: function () {\n                  return this._value().active;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          EntityStore.prototype._setActive = function (ids) {\n              this._setState(function (state) {\n                  return __assign({}, state, { active: ids });\n              });\n          };\n          EntityStore.prototype.handleUICreation = function (add) {\n              var _this = this;\n              if (add === void 0) { add = false; }\n              var ids = this.ids;\n              var isFunc = isFunction(this.ui._akitaCreateEntityFn);\n              var uiEntities;\n              var createFn = function (id) {\n                  var _a;\n                  var current = _this.entities[id];\n                  var ui = isFunc ? _this.ui._akitaCreateEntityFn(current) : _this.ui._akitaCreateEntityFn;\n                  return __assign((_a = {}, _a[_this.idKey] = current[_this.idKey], _a), ui);\n              };\n              if (add) {\n                  uiEntities = this.ids.filter(function (id) { return isUndefined(_this.ui.entities[id]); }).map(createFn);\n              }\n              else {\n                  uiEntities = ids.map(createFn);\n              }\n              add ? this.ui.add(uiEntities) : this.ui.set(uiEntities);\n          };\n          EntityStore.prototype.hasInitialUIState = function () {\n              return this.hasUIStore() && isUndefined(this.ui._akitaCreateEntityFn) === false;\n          };\n          EntityStore.prototype.handleUIRemove = function (ids) {\n              if (this.hasUIStore()) {\n                  this.ui.remove(ids);\n              }\n          };\n          EntityStore.prototype.hasUIStore = function () {\n              return this.ui instanceof EntityUIStore;\n          };\n          var _b;\n          __decorate$2([\n              transaction(),\n              __metadata(\"design:type\", Function),\n              __metadata(\"design:paramtypes\", [Object, Object, Object, Object]),\n              __metadata(\"design:returntype\", void 0)\n          ], EntityStore.prototype, \"upsert\", null);\n          __decorate$2([\n              transaction(),\n              __metadata(\"design:type\", Function),\n              __metadata(\"design:paramtypes\", [typeof (_b = typeof T !== \"undefined\" && T) === \"function\" ? _b : Object]),\n              __metadata(\"design:returntype\", void 0)\n          ], EntityStore.prototype, \"toggleActive\", null);\n          return EntityStore;\n      }(Store));\n      // @internal\n      var EntityUIStore = /** @class */ (function (_super) {\n          __extends(EntityUIStore, _super);\n          function EntityUIStore(initialState, storeConfig) {\n              if (initialState === void 0) { initialState = {}; }\n              if (storeConfig === void 0) { storeConfig = {}; }\n              return _super.call(this, initialState, storeConfig) || this;\n          }\n          /**\n           *\n           * Set the initial UI entity state. This function will determine the entity's\n           * initial state when we call `set()` or `add()`.\n           *\n           * @example\n           *\n           * constructor() {\n           *   super();\n           *   this.createUIStore().setInitialEntityState(entity => ({ isLoading: false, isOpen: true }));\n           *   this.createUIStore().setInitialEntityState({ isLoading: false, isOpen: true });\n           * }\n           *\n           */\n          EntityUIStore.prototype.setInitialEntityState = function (createFn) {\n              this._akitaCreateEntityFn = createFn;\n          };\n          return EntityUIStore;\n      }(EntityStore));\n      // @internal\n      function distinctUntilArrayItemChanged() {\n          return distinctUntilChanged(function (prevCollection, currentCollection) {\n              if (prevCollection === currentCollection) {\n                  return true;\n              }\n              if (isArray(prevCollection) === false || isArray(currentCollection) === false) {\n                  return false;\n              }\n              if (isEmpty(prevCollection) && isEmpty(currentCollection)) {\n                  return true;\n              }\n              // if item is new in the current collection but not exist in the prev collection\n              var hasNewItem = hasChange(currentCollection, prevCollection);\n              if (hasNewItem) {\n                  return false;\n              }\n              var isOneOfItemReferenceChanged = hasChange(prevCollection, currentCollection);\n              // return false means there is a change and we want to call next()\n              return isOneOfItemReferenceChanged === false;\n          });\n      }\n      // @internal\n      function hasChange(first, second) {\n          var hasChange = second.some(function (currentItem) {\n              var oldItem = first.find(function (prevItem) { return prevItem === currentItem; });\n              return oldItem === undefined;\n          });\n          return hasChange;\n      }\n    \n      var Order;\n      (function (Order) {\n          Order[\"ASC\"] = \"asc\";\n          Order[\"DESC\"] = \"desc\";\n      })(Order || (Order = {}));\n      // @internal\n      function compareValues(key, order) {\n          if (order === void 0) { order = Order.ASC; }\n          return function (a, b) {\n              if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {\n                  return 0;\n              }\n              var varA = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key];\n              var varB = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key];\n              var comparison = 0;\n              if (varA > varB) {\n                  comparison = 1;\n              }\n              else if (varA < varB) {\n                  comparison = -1;\n              }\n              return order == Order.DESC ? comparison * -1 : comparison;\n          };\n      }\n    \n      // @internal\n      function entitiesToArray(state, options) {\n          var arr = [];\n          var ids = state.ids, entities = state.entities;\n          var filterBy = options.filterBy, limitTo = options.limitTo, sortBy = options.sortBy, sortByOrder = options.sortByOrder;\n          var _loop_1 = function (i) {\n              var entity = entities[ids[i]];\n              if (!filterBy) {\n                  arr.push(entity);\n                  return \"continue\";\n              }\n              var toArray = coerceArray(filterBy);\n              var allPass = toArray.every(function (fn) { return fn(entity, i); });\n              if (allPass) {\n                  arr.push(entity);\n              }\n          };\n          for (var i = 0; i < ids.length; i++) {\n              _loop_1(i);\n          }\n          if (sortBy) {\n              var _sortBy_1 = isFunction(sortBy) ? sortBy : compareValues(sortBy, sortByOrder);\n              arr = arr.sort(function (a, b) { return _sortBy_1(a, b, state); });\n          }\n          var length = Math.min(limitTo || arr.length, arr.length);\n          return length === arr.length ? arr : arr.slice(0, length);\n      }\n    \n      // @internal\n      function entitiesToMap(state, options) {\n          var map = {};\n          var filterBy = options.filterBy, limitTo = options.limitTo;\n          var ids = state.ids, entities = state.entities;\n          if (!filterBy && !limitTo) {\n              return entities;\n          }\n          var hasLimit = isNil(limitTo) === false;\n          if (filterBy && hasLimit) {\n              var count = 0;\n              var _loop_1 = function (i, length_1) {\n                  if (count === limitTo)\n                      return \"break\";\n                  var id = ids[i];\n                  var entity = entities[id];\n                  var allPass = coerceArray(filterBy).every(function (fn) { return fn(entity, i); });\n                  if (allPass) {\n                      map[id] = entity;\n                      count++;\n                  }\n              };\n              for (var i = 0, length_1 = ids.length; i < length_1; i++) {\n                  var state_1 = _loop_1(i, length_1);\n                  if (state_1 === \"break\")\n                      break;\n              }\n          }\n          else {\n              var finalLength = Math.min(limitTo || ids.length, ids.length);\n              var _loop_2 = function (i) {\n                  var id = ids[i];\n                  var entity = entities[id];\n                  if (!filterBy) {\n                      map[id] = entity;\n                      return \"continue\";\n                  }\n                  var allPass = coerceArray(filterBy).every(function (fn) { return fn(entity, i); });\n                  if (allPass) {\n                      map[id] = entity;\n                  }\n              };\n              for (var i = 0; i < finalLength; i++) {\n                  _loop_2(i);\n              }\n          }\n          return map;\n      }\n    \n      // @internal\n      function isString(value) {\n          return typeof value === 'string';\n      }\n    \n      // @internal\n      function findEntityByPredicate(predicate, entities) {\n          var e_1, _a;\n          try {\n              for (var _b = __values(Object.keys(entities)), _c = _b.next(); !_c.done; _c = _b.next()) {\n                  var entityId = _c.value;\n                  if (predicate(entities[entityId]) === true) {\n                      return entityId;\n                  }\n              }\n          }\n          catch (e_1_1) { e_1 = { error: e_1_1 }; }\n          finally {\n              try {\n                  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n              }\n              finally { if (e_1) throw e_1.error; }\n          }\n          return undefined;\n      }\n      // @internal\n      function getEntity(id, project) {\n          return function (entities) {\n              var entity = entities[id];\n              if (isUndefined(entity)) {\n                  return undefined;\n              }\n              if (!project) {\n                  return entity;\n              }\n              if (isString(project)) {\n                  return entity[project];\n              }\n              return project(entity);\n          };\n      }\n    \n      // @internal\n      function mapSkipUndefined(arr, callbackFn) {\n          return arr.reduce(function (result, value, index, array) {\n              var val = callbackFn(value, index, array);\n              if (val !== undefined) {\n                  result.push(val);\n              }\n              return result;\n          }, []);\n      }\n    \n      var queryConfigKey = 'akitaQueryConfig';\n    \n      function compareKeys(keysOrFuncs) {\n          return function (prevState, currState) {\n              var isFns = isFunction(keysOrFuncs[0]);\n              // Return when they are NOT changed\n              return keysOrFuncs.some(function (keyOrFunc) {\n                  if (isFns) {\n                      return keyOrFunc(prevState) !== keyOrFunc(currState);\n                  }\n                  return prevState[keyOrFunc] !== currState[keyOrFunc];\n              }) === false;\n          };\n      }\n    \n      var Query = /** @class */ (function () {\n          function Query(store) {\n              this.store = store;\n              this.__store__ = store;\n              {\n                  // @internal\n                  __queries__[store.storeName] = this;\n              }\n          }\n          Query.prototype.select = function (project) {\n              var mapFn;\n              if (isFunction(project)) {\n                  mapFn = project;\n              }\n              else if (isString(project)) {\n                  mapFn = function (state) { return state[project]; };\n              }\n              else if (Array.isArray(project)) {\n                  return this.store\n                      ._select(function (state) { return state; })\n                      .pipe(distinctUntilChanged(compareKeys(project)), map(function (state) {\n                      if (isFunction(project[0])) {\n                          return project.map(function (func) { return func(state); });\n                      }\n                      return project.reduce(function (acc, k) {\n                          acc[k] = state[k];\n                          return acc;\n                      }, {});\n                  }));\n              }\n              else {\n                  mapFn = function (state) { return state; };\n              }\n              return this.store._select(mapFn);\n          };\n          /**\n           * Select the loading state\n           *\n           * @example\n           *\n           * this.query.selectLoading().subscribe(isLoading => {})\n           */\n          Query.prototype.selectLoading = function () {\n              return this.select(function (state) { return state.loading; });\n          };\n          /**\n           * Select the error state\n           *\n           * @example\n           *\n           * this.query.selectError().subscribe(error => {})\n           */\n          Query.prototype.selectError = function () {\n              return this.select(function (state) { return state.error; });\n          };\n          /**\n           * Get the store's value\n           *\n           * @example\n           *\n           * this.query.getValue()\n           *\n           */\n          Query.prototype.getValue = function () {\n              return this.store._value();\n          };\n          /**\n           * Select the cache state\n           *\n           * @example\n           *\n           * this.query.selectHasCache().pipe(\n           *   switchMap(hasCache => {\n           *     return hasCache ? of() : http().pipe(res => store.set(res))\n           *   })\n           * )\n           */\n          Query.prototype.selectHasCache = function () {\n              return this.store._cache().asObservable();\n          };\n          /**\n           * Whether we've cached data\n           *\n           * @example\n           *\n           * this.query.getHasCache()\n           *\n           */\n          Query.prototype.getHasCache = function () {\n              return this.store._cache().value;\n          };\n          Object.defineProperty(Query.prototype, \"config\", {\n              // @internal\n              get: function () {\n                  return this.constructor[queryConfigKey];\n              },\n              enumerable: true,\n              configurable: true\n          });\n          return Query;\n      }());\n    \n      // @internal\n      function sortByOptions(options, config) {\n          options.sortBy = options.sortBy || (config && config.sortBy);\n          options.sortByOrder = options.sortByOrder || (config && config.sortByOrder);\n      }\n    \n      /**\n       *\n       *  The Entity Query is similar to the general Query, with additional functionality tailored for EntityStores.\n       *\n       *  class WidgetsQuery extends QueryEntity<WidgetsState> {\n       *     constructor(protected store: WidgetsStore) {\n       *       super(store);\n       *     }\n       *  }\n       *\n       *\n       *\n       */\n      var QueryEntity = /** @class */ (function (_super) {\n          __extends(QueryEntity, _super);\n          function QueryEntity(store, options) {\n              if (options === void 0) { options = {}; }\n              var _this = _super.call(this, store) || this;\n              _this.options = options;\n              _this.__store__ = store;\n              return _this;\n          }\n          QueryEntity.prototype.selectAll = function (options) {\n              var _this = this;\n              if (options === void 0) { options = {\n                  asObject: false,\n              }; }\n              return this.select(function (state) { return state.entities; }).pipe(map(function () { return _this.getAll(options); }));\n          };\n          QueryEntity.prototype.getAll = function (options) {\n              if (options === void 0) { options = { asObject: false, filterBy: undefined, limitTo: undefined }; }\n              if (options.asObject) {\n                  return entitiesToMap(this.getValue(), options);\n              }\n              sortByOptions(options, this.config || this.options);\n              return entitiesToArray(this.getValue(), options);\n          };\n          QueryEntity.prototype.selectMany = function (ids, project) {\n              if (!ids || !ids.length)\n                  return of([]);\n              return this.select(function (state) { return state.entities; }).pipe(map(function (entities) { return mapSkipUndefined(ids, function (id) { return getEntity(id, project)(entities); }); }), distinctUntilArrayItemChanged());\n          };\n          QueryEntity.prototype.selectEntity = function (idOrPredicate, project) {\n              var id = idOrPredicate;\n              if (isFunction(idOrPredicate)) {\n                  // For performance reason we expect the entity to be in the store\n                  id = findEntityByPredicate(idOrPredicate, this.getValue().entities);\n              }\n              return this.select(function (state) { return state.entities; }).pipe(map(getEntity(id, project)), distinctUntilChanged());\n          };\n          /**\n           * Get an entity by id\n           *\n           * @example\n           *\n           * this.query.getEntity(1);\n           */\n          QueryEntity.prototype.getEntity = function (id) {\n              return this.getValue().entities[id];\n          };\n          /**\n           * Select the active entity's id\n           *\n           * @example\n           *\n           * this.query.selectActiveId()\n           */\n          QueryEntity.prototype.selectActiveId = function () {\n              return this.select(function (state) { return state.active; });\n          };\n          /**\n           * Get the active id\n           *\n           * @example\n           *\n           * this.query.getActiveId()\n           */\n          QueryEntity.prototype.getActiveId = function () {\n              return this.getValue().active;\n          };\n          QueryEntity.prototype.selectActive = function (project) {\n              var _this = this;\n              if (isArray(this.getActive())) {\n                  return this.selectActiveId().pipe(switchMap(function (ids) { return _this.selectMany(ids, project); }));\n              }\n              return this.selectActiveId().pipe(switchMap(function (ids) { return _this.selectEntity(ids, project); }));\n          };\n          QueryEntity.prototype.getActive = function () {\n              var _this = this;\n              var activeId = this.getActiveId();\n              if (isArray(activeId)) {\n                  return activeId.map(function (id) { return _this.getValue().entities[id]; });\n              }\n              return toBoolean(activeId) ? this.getEntity(activeId) : undefined;\n          };\n          /**\n           * Select the store's entity collection length\n           *\n           * @example\n           *\n           * this.query.selectCount()\n           * this.query.selectCount(entity => entity.completed)\n           */\n          QueryEntity.prototype.selectCount = function (predicate) {\n              var _this = this;\n              return this.select(function (state) { return state.entities; }).pipe(map(function () { return _this.getCount(predicate); }));\n          };\n          /**\n           * Get the store's entity collection length\n           *\n           * @example\n           *\n           * this.query.getCount()\n           * this.query.getCount(entity => entity.completed)\n           */\n          QueryEntity.prototype.getCount = function (predicate) {\n              if (isFunction(predicate)) {\n                  return this.getAll().filter(predicate).length;\n              }\n              return this.getValue().ids.length;\n          };\n          QueryEntity.prototype.selectLast = function (project) {\n              return this.selectAt(function (ids) { return ids[ids.length - 1]; }, project);\n          };\n          QueryEntity.prototype.selectFirst = function (project) {\n              return this.selectAt(function (ids) { return ids[0]; }, project);\n          };\n          QueryEntity.prototype.selectEntityAction = function (actionOrActions) {\n              if (isNil(actionOrActions)) {\n                  return this.store.selectEntityAction$;\n              }\n              var project = isArray(actionOrActions) ? function (action) { return action; } : function (_a) {\n                  var ids = _a.ids;\n                  return ids;\n              };\n              var actions = coerceArray(actionOrActions);\n              return this.store.selectEntityAction$.pipe(filter(function (_a) {\n                  var type = _a.type;\n                  return actions.includes(type);\n              }), map(function (action) { return project(action); }));\n          };\n          QueryEntity.prototype.hasEntity = function (projectOrIds) {\n              var _this = this;\n              if (isNil(projectOrIds)) {\n                  return this.getValue().ids.length > 0;\n              }\n              if (isFunction(projectOrIds)) {\n                  return this.getAll().some(projectOrIds);\n              }\n              if (isArray(projectOrIds)) {\n                  return projectOrIds.every(function (id) { return id in _this.getValue().entities; });\n              }\n              return projectOrIds in this.getValue().entities;\n          };\n          /**\n           * Returns whether entity store has an active entity\n           *\n           * @example\n           *\n           * this.query.hasActive()\n           * this.query.hasActive(3)\n           *\n           */\n          QueryEntity.prototype.hasActive = function (id) {\n              var active = this.getValue().active;\n              var isIdProvided = isDefined(id);\n              if (Array.isArray(active)) {\n                  if (isIdProvided) {\n                      return active.includes(id);\n                  }\n                  return active.length > 0;\n              }\n              return isIdProvided ? active === id : isDefined(active);\n          };\n          /**\n           *\n           * Create sub UI query for querying Entity's UI state\n           *\n           * @example\n           *\n           *\n           * export class ProductsQuery extends QueryEntity<ProductsState> {\n           *   ui: EntityUIQuery<ProductsUIState>;\n           *\n           *   constructor(protected store: ProductsStore) {\n           *     super(store);\n           *     this.createUIQuery();\n           *   }\n           *\n           * }\n           */\n          QueryEntity.prototype.createUIQuery = function () {\n              this.ui = new EntityUIQuery(this.__store__.ui);\n          };\n          QueryEntity.prototype.selectAt = function (mapFn, project) {\n              var _this = this;\n              return this.select(function (state) { return state.ids; }).pipe(map(mapFn), distinctUntilChanged(), switchMap(function (id) { return _this.selectEntity(id, project); }));\n          };\n          return QueryEntity;\n      }(Query));\n      // @internal\n      var EntityUIQuery = /** @class */ (function (_super) {\n          __extends(EntityUIQuery, _super);\n          function EntityUIQuery(store) {\n              return _super.call(this, store) || this;\n          }\n          return EntityUIQuery;\n      }(QueryEntity));\n    \n      /**\n       * @example\n       *\n       * query.selectEntity(2).pipe(filterNil)\n       */\n      var filterNil = function (source) { return source.pipe(filter(function (value) { return value !== null && typeof value !== 'undefined'; })); };\n    \n      /**\n       * @internal\n       *\n       * @example\n       *\n       * getValue(state, 'todos.ui')\n       *\n       */\n      function getValue(obj, prop) {\n          /** return the whole state  */\n          if (prop.split('.').length === 1) {\n              return obj;\n          }\n          var removeStoreName = prop\n              .split('.')\n              .slice(1)\n              .join('.');\n          return removeStoreName.split('.').reduce(function (acc, part) { return acc && acc[part]; }, obj);\n      }\n    \n      /**\n       * @internal\n       *\n       * @example\n       * setValue(state, 'todos.ui', { filter: {} })\n       */\n      function setValue(obj, prop, val) {\n          var split = prop.split('.');\n          if (split.length === 1) {\n              return __assign({}, obj, val);\n          }\n          obj = __assign({}, obj);\n          var lastIndex = split.length - 2;\n          var removeStoreName = prop.split('.').slice(1);\n          removeStoreName.reduce(function (acc, part, index) {\n              if (index !== lastIndex) {\n                  acc[part] = __assign({}, acc[part]);\n                  return acc && acc[part];\n              }\n              acc[part] = Array.isArray(acc[part]) || !isObject(acc[part]) ? val : __assign({}, acc[part], val);\n              return acc && acc[part];\n          }, obj);\n          return obj;\n      }\n      new ReplaySubject(1);\n    \n      var AkitaPlugin = /** @class */ (function () {\n          function AkitaPlugin(query, config) {\n              this.query = query;\n          }\n          /** This method is responsible for getting access to the query. */\n          AkitaPlugin.prototype.getQuery = function () {\n              return this.query;\n          };\n          /** This method is responsible for getting access to the store. */\n          AkitaPlugin.prototype.getStore = function () {\n              return this.getQuery().__store__;\n          };\n          /** This method is responsible tells whether the plugin is entityBased or not.  */\n          AkitaPlugin.prototype.isEntityBased = function (entityId) {\n              return toBoolean(entityId);\n          };\n          /** This method is responsible for selecting the source; it can be the whole store or one entity. */\n          AkitaPlugin.prototype.selectSource = function (entityId, property) {\n              var _this = this;\n              if (this.isEntityBased(entityId)) {\n                  return this.getQuery().selectEntity(entityId).pipe(filterNil);\n              }\n              if (property) {\n                  return this.getQuery().select(function (state) { return getValue(state, _this.withStoreName(property)); });\n              }\n              return this.getQuery().select();\n          };\n          AkitaPlugin.prototype.getSource = function (entityId, property) {\n              if (this.isEntityBased(entityId)) {\n                  return this.getQuery().getEntity(entityId);\n              }\n              var state = this.getQuery().getValue();\n              if (property) {\n                  return getValue(state, this.withStoreName(property));\n              }\n              return state;\n          };\n          AkitaPlugin.prototype.withStoreName = function (prop) {\n              return this.storeName + \".\" + prop;\n          };\n          Object.defineProperty(AkitaPlugin.prototype, \"storeName\", {\n              get: function () {\n                  return this.getStore().storeName;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          /** This method is responsible for updating the store or one entity; it can be the whole store or one entity. */\n          AkitaPlugin.prototype.updateStore = function (newState, entityId, property) {\n              var _this = this;\n              if (this.isEntityBased(entityId)) {\n                  this.getStore().update(entityId, newState);\n              }\n              else {\n                  if (property) {\n                      this.getStore()._setState(function (state) {\n                          return setValue(state, _this.withStoreName(property), newState);\n                      });\n                      return;\n                  }\n                  this.getStore()._setState(function (state) { return (__assign({}, state, newState)); });\n              }\n          };\n          /**\n           * Function to invoke upon reset\n           */\n          AkitaPlugin.prototype.onReset = function (fn) {\n              var _this = this;\n              var original = this.getStore().reset;\n              this.getStore().reset = function () {\n                  var params = [];\n                  for (var _i = 0; _i < arguments.length; _i++) {\n                      params[_i] = arguments[_i];\n                  }\n                  /** It should run after the plugin destroy method */\n                  setTimeout(function () {\n                      original.apply(_this.getStore(), params);\n                      fn();\n                  });\n              };\n          };\n          return AkitaPlugin;\n      }());\n    \n      var paginatorDefaults = {\n          pagesControls: false,\n          range: false,\n          startWith: 1,\n          cacheTimeout: undefined,\n          clearStoreWithCache: true\n      };\n      /** @class */ ((function (_super) {\n          __extends(PaginatorPlugin, _super);\n          function PaginatorPlugin(query, config) {\n              if (config === void 0) { config = {}; }\n              var _this = _super.call(this, query, {\n                  resetFn: function () {\n                      _this.initial = false;\n                      _this.destroy({ clearCache: true, currentPage: 1 });\n                  }\n              }) || this;\n              _this.query = query;\n              _this.config = config;\n              /** Save current filters, sorting, etc. in cache */\n              _this.metadata = new Map();\n              _this.pages = new Map();\n              _this.pagination = {\n                  currentPage: 1,\n                  perPage: 0,\n                  total: 0,\n                  lastPage: 0,\n                  data: []\n              };\n              /**\n               * When the user navigates to a different page and return\n               * we don't want to call `clearCache` on first time.\n               */\n              _this.initial = true;\n              /**\n               * Proxy to the query loading\n               */\n              _this.isLoading$ = _this.query.selectLoading().pipe(delay(0));\n              _this.config = Object.assign(paginatorDefaults, config);\n              var _a = _this.config, startWith = _a.startWith, cacheTimeout = _a.cacheTimeout;\n              _this.page = new BehaviorSubject(startWith);\n              if (isObservable(cacheTimeout)) {\n                  _this.clearCacheSubscription = cacheTimeout.subscribe(function () { return _this.clearCache(); });\n              }\n              return _this;\n          }\n          Object.defineProperty(PaginatorPlugin.prototype, \"pageChanges\", {\n              /**\n               * Listen to page changes\n               */\n              get: function () {\n                  return this.page.asObservable();\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(PaginatorPlugin.prototype, \"currentPage\", {\n              /**\n               * Get the current page number\n               */\n              get: function () {\n                  return this.pagination.currentPage;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(PaginatorPlugin.prototype, \"isFirst\", {\n              /**\n               * Check if current page is the first one\n               */\n              get: function () {\n                  return this.currentPage === 1;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(PaginatorPlugin.prototype, \"isLast\", {\n              /**\n               * Check if current page is the last one\n               */\n              get: function () {\n                  return this.currentPage === this.pagination.lastPage;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          /**\n           * Whether to generate an array of pages for *ngFor\n           * [1, 2, 3, 4]\n           */\n          PaginatorPlugin.prototype.withControls = function () {\n              this.config.pagesControls = true;\n              return this;\n          };\n          /**\n           * Whether to generate the `from` and `to` keys\n           * [1, 2, 3, 4]\n           */\n          PaginatorPlugin.prototype.withRange = function () {\n              this.config.range = true;\n              return this;\n          };\n          /**\n           * Set the loading state\n           */\n          PaginatorPlugin.prototype.setLoading = function (value) {\n              if (value === void 0) { value = true; }\n              this.getStore().setLoading(value);\n          };\n          /**\n           * Update the pagination object and add the page\n           */\n          PaginatorPlugin.prototype.update = function (response) {\n              this.pagination = response;\n              this.addPage(response.data);\n          };\n          /**\n           *\n           * Set the ids and add the page to store\n           */\n          PaginatorPlugin.prototype.addPage = function (data) {\n              var _this = this;\n              this.pages.set(this.currentPage, { ids: data.map(function (entity) { return entity[_this.getStore().idKey]; }) });\n              this.getStore().upsertMany(data);\n          };\n          /**\n           * Clear the cache.\n           */\n          PaginatorPlugin.prototype.clearCache = function (options) {\n              if (options === void 0) { options = {}; }\n              if (!this.initial) {\n                  logAction('@Pagination - Clear Cache');\n                  if (options.clearStore !== false && (this.config.clearStoreWithCache || options.clearStore)) {\n                      this.getStore().remove();\n                  }\n                  this.pages = new Map();\n                  this.metadata = new Map();\n              }\n              this.initial = false;\n          };\n          PaginatorPlugin.prototype.clearPage = function (page) {\n              this.pages.delete(page);\n          };\n          /**\n           * Clear the cache timeout and optionally the pages\n           */\n          PaginatorPlugin.prototype.destroy = function (_a) {\n              var _b = _a === void 0 ? {} : _a, clearCache = _b.clearCache, currentPage = _b.currentPage;\n              if (this.clearCacheSubscription) {\n                  this.clearCacheSubscription.unsubscribe();\n              }\n              if (clearCache) {\n                  this.clearCache();\n              }\n              if (!isUndefined(currentPage)) {\n                  this.setPage(currentPage);\n              }\n              this.initial = true;\n          };\n          /**\n           * Whether the provided page is active\n           */\n          PaginatorPlugin.prototype.isPageActive = function (page) {\n              return this.currentPage === page;\n          };\n          /**\n           * Set the current page\n           */\n          PaginatorPlugin.prototype.setPage = function (page) {\n              if (page !== this.currentPage || !this.hasPage(page)) {\n                  this.page.next((this.pagination.currentPage = page));\n              }\n          };\n          /**\n           * Increment current page\n           */\n          PaginatorPlugin.prototype.nextPage = function () {\n              if (this.currentPage !== this.pagination.lastPage) {\n                  this.setPage(this.pagination.currentPage + 1);\n              }\n          };\n          /**\n           * Decrement current page\n           */\n          PaginatorPlugin.prototype.prevPage = function () {\n              if (this.pagination.currentPage > 1) {\n                  this.setPage(this.pagination.currentPage - 1);\n              }\n          };\n          /**\n           * Set current page to last\n           */\n          PaginatorPlugin.prototype.setLastPage = function () {\n              this.setPage(this.pagination.lastPage);\n          };\n          /**\n           * Set current page to first\n           */\n          PaginatorPlugin.prototype.setFirstPage = function () {\n              this.setPage(1);\n          };\n          /**\n           * Check if page exists in cache\n           */\n          PaginatorPlugin.prototype.hasPage = function (page) {\n              return this.pages.has(page);\n          };\n          /**\n           * Get the current page if it's in cache, otherwise invoke the request\n           */\n          PaginatorPlugin.prototype.getPage = function (req) {\n              var _this = this;\n              var page = this.pagination.currentPage;\n              if (this.hasPage(page)) {\n                  return this.selectPage(page);\n              }\n              else {\n                  this.setLoading(true);\n                  return from(req()).pipe(switchMap(function (config) {\n                      page = config.currentPage;\n                      applyTransaction(function () {\n                          _this.setLoading(false);\n                          _this.update(config);\n                      });\n                      return _this.selectPage(page);\n                  }));\n              }\n          };\n          PaginatorPlugin.prototype.getQuery = function () {\n              return this.query;\n          };\n          PaginatorPlugin.prototype.refreshCurrentPage = function () {\n              if (isNil(this.currentPage) === false) {\n                  this.clearPage(this.currentPage);\n                  this.setPage(this.currentPage);\n              }\n          };\n          PaginatorPlugin.prototype.getFrom = function () {\n              if (this.isFirst) {\n                  return 1;\n              }\n              return (this.currentPage - 1) * this.pagination.perPage + 1;\n          };\n          PaginatorPlugin.prototype.getTo = function () {\n              if (this.isLast) {\n                  return this.pagination.total;\n              }\n              return this.currentPage * this.pagination.perPage;\n          };\n          /**\n           * Select the page\n           */\n          PaginatorPlugin.prototype.selectPage = function (page) {\n              var _this = this;\n              return this.query.selectAll({ asObject: true }).pipe(take(1), map(function (entities) {\n                  var response = __assign({}, _this.pagination, { data: _this.pages.get(page).ids.map(function (id) { return entities[id]; }) });\n                  var _a = _this.config, range = _a.range, pagesControls = _a.pagesControls;\n                  /** If no total - calc it */\n                  if (isNaN(_this.pagination.total)) {\n                      if (response.lastPage === 1) {\n                          response.total = response.data ? response.data.length : 0;\n                      }\n                      else {\n                          response.total = response.perPage * response.lastPage;\n                      }\n                      _this.pagination.total = response.total;\n                  }\n                  if (range) {\n                      response.from = _this.getFrom();\n                      response.to = _this.getTo();\n                  }\n                  if (pagesControls) {\n                      response.pageControls = generatePages(_this.pagination.total, _this.pagination.perPage);\n                  }\n                  return response;\n              }));\n          };\n          __decorate$2([\n              action('@Pagination - New Page'),\n              __metadata(\"design:type\", Function),\n              __metadata(\"design:paramtypes\", [Object]),\n              __metadata(\"design:returntype\", void 0)\n          ], PaginatorPlugin.prototype, \"update\", null);\n          return PaginatorPlugin;\n      })(AkitaPlugin));\n      /**\n       * Generate an array so we can ngFor them to navigate between pages\n       */\n      function generatePages(total, perPage) {\n          var len = Math.ceil(total / perPage);\n          var arr = [];\n          for (var i = 0; i < len; i++) {\n              arr.push(i + 1);\n          }\n          return arr;\n      }\n    \n      /** @class */ ((function (_super) {\n          __extends(PersistNgFormPlugin, _super);\n          function PersistNgFormPlugin(query, factoryFnOrPath, params) {\n              if (params === void 0) { params = {}; }\n              var _this = _super.call(this, query) || this;\n              _this.query = query;\n              _this.factoryFnOrPath = factoryFnOrPath;\n              _this.params = params;\n              _this.params = __assign({ debounceTime: 300, formKey: 'akitaForm', emitEvent: false, arrControlFactory: function (v) { return _this.builder.control(v); } }, params);\n              _this.isRootKeys = toBoolean(factoryFnOrPath) === false;\n              _this.isKeyBased = isString(factoryFnOrPath) || _this.isRootKeys;\n              return _this;\n          }\n          PersistNgFormPlugin.prototype.setForm = function (form, builder) {\n              this.form = form;\n              this.builder = builder;\n              this.activate();\n              return this;\n          };\n          PersistNgFormPlugin.prototype.reset = function (initialState) {\n              var _this = this;\n              var _a;\n              var value;\n              if (initialState) {\n                  value = initialState;\n              }\n              else {\n                  value = this.isKeyBased ? this.initialValue : this.factoryFnOrPath();\n              }\n              if (this.isKeyBased) {\n                  Object.keys(this.initialValue).forEach(function (stateKey) {\n                      var value = _this.initialValue[stateKey];\n                      if (Array.isArray(value) && _this.builder) {\n                          var formArray = _this.form.controls[stateKey];\n                          _this.cleanArray(formArray);\n                          value.forEach(function (v, i) {\n                              _this.form.get(stateKey).insert(i, _this.params.arrControlFactory(v));\n                          });\n                      }\n                  });\n              }\n              this.form.patchValue(value, { emitEvent: this.params.emitEvent });\n              var storeValue = this.isKeyBased ? setValue(this.getQuery().getValue(), this.getStore().storeName + \".\" + this.factoryFnOrPath, value) : (_a = {}, _a[this.params.formKey] = value, _a);\n              this.updateStore(storeValue);\n          };\n          PersistNgFormPlugin.prototype.cleanArray = function (control) {\n              while (control.length !== 0) {\n                  control.removeAt(0);\n              }\n          };\n          PersistNgFormPlugin.prototype.resolveInitialValue = function (formValue, root) {\n              var _this = this;\n              if (!formValue)\n                  return;\n              return Object.keys(formValue).reduce(function (acc, stateKey) {\n                  var value = root[stateKey];\n                  if (Array.isArray(value) && _this.builder) {\n                      var factory_1 = _this.params.arrControlFactory;\n                      _this.cleanArray(_this.form.get(stateKey));\n                      value.forEach(function (v, i) {\n                          _this.form.get(stateKey).insert(i, factory_1(v));\n                      });\n                  }\n                  acc[stateKey] = root[stateKey];\n                  return acc;\n              }, {});\n          };\n          PersistNgFormPlugin.prototype.activate = function () {\n              var _this = this;\n              var _a;\n              var path;\n              if (this.isKeyBased) {\n                  if (this.isRootKeys) {\n                      this.initialValue = this.resolveInitialValue(this.form.value, this.getQuery().getValue());\n                      this.form.patchValue(this.initialValue, { emitEvent: this.params.emitEvent });\n                  }\n                  else {\n                      path = this.getStore().storeName + \".\" + this.factoryFnOrPath;\n                      var root = getValue(this.getQuery().getValue(), path);\n                      this.initialValue = this.resolveInitialValue(root, root);\n                      this.form.patchValue(this.initialValue, { emitEvent: this.params.emitEvent });\n                  }\n              }\n              else {\n                  if (!this.getQuery().getValue()[this.params.formKey]) {\n                      logAction('@PersistNgFormPlugin activate');\n                      this.updateStore((_a = {}, _a[this.params.formKey] = this.factoryFnOrPath(), _a));\n                  }\n                  var value = this.getQuery().getValue()[this.params.formKey];\n                  this.form.patchValue(value);\n              }\n              this.formChanges = this.form.valueChanges.pipe(debounceTime(this.params.debounceTime)).subscribe(function (value) {\n                  logAction('@PersistForm - Update');\n                  var newState;\n                  if (_this.isKeyBased) {\n                      if (_this.isRootKeys) {\n                          newState = function (state) { return (__assign({}, state, value)); };\n                      }\n                      else {\n                          newState = function (state) { return setValue(state, path, value); };\n                      }\n                  }\n                  else {\n                      newState = function () {\n                          var _a;\n                          return (_a = {}, _a[_this.params.formKey] = value, _a);\n                      };\n                  }\n                  _this.updateStore(newState(_this.getQuery().getValue()));\n              });\n          };\n          PersistNgFormPlugin.prototype.destroy = function () {\n              this.formChanges && this.formChanges.unsubscribe();\n              this.form = null;\n              this.builder = null;\n          };\n          return PersistNgFormPlugin;\n      })(AkitaPlugin));\n    \n      /**\n       * Each plugin that wants to add support for entities should extend this interface.\n       */\n      var EntityCollectionPlugin = /** @class */ (function () {\n          function EntityCollectionPlugin(query, entityIds) {\n              this.query = query;\n              this.entityIds = entityIds;\n              this.entities = new Map();\n          }\n          /**\n           * Get the entity plugin instance.\n           */\n          EntityCollectionPlugin.prototype.getEntity = function (id) {\n              return this.entities.get(id);\n          };\n          /**\n           * Whether the entity plugin exist.\n           */\n          EntityCollectionPlugin.prototype.hasEntity = function (id) {\n              return this.entities.has(id);\n          };\n          /**\n           * Remove the entity plugin instance.\n           */\n          EntityCollectionPlugin.prototype.removeEntity = function (id) {\n              this.destroy(id);\n              return this.entities.delete(id);\n          };\n          /**\n           * Set the entity plugin instance.\n           */\n          EntityCollectionPlugin.prototype.createEntity = function (id, plugin) {\n              return this.entities.set(id, plugin);\n          };\n          /**\n           * If the user passes `entityIds` we take them; otherwise, we take all.\n           */\n          EntityCollectionPlugin.prototype.getIds = function () {\n              return isUndefined(this.entityIds) ? this.query.getValue().ids : coerceArray(this.entityIds);\n          };\n          /**\n           * When you call one of the plugin methods, you can pass id/ids or undefined which means all.\n           */\n          EntityCollectionPlugin.prototype.resolvedIds = function (ids) {\n              return isUndefined(ids) ? this.getIds() : coerceArray(ids);\n          };\n          /**\n           * Call this method when you want to activate the plugin on init or when you need to listen to add/remove of entities dynamically.\n           *\n           * For example in your plugin you may do the following:\n           *\n           * this.query.select(state => state.ids).pipe(skip(1)).subscribe(ids => this.activate(ids));\n           */\n          EntityCollectionPlugin.prototype.rebase = function (ids, actions) {\n              var _this = this;\n              if (actions === void 0) { actions = {}; }\n              /**\n               *\n               * If the user passes `entityIds` & we have new ids check if we need to add/remove instances.\n               *\n               * This phase will be called only upon update.\n               */\n              if (toBoolean(ids)) {\n                  /**\n                   * Which means all\n                   */\n                  if (isUndefined(this.entityIds)) {\n                      for (var i = 0, len = ids.length; i < len; i++) {\n                          var entityId = ids[i];\n                          if (this.hasEntity(entityId) === false) {\n                              isFunction(actions.beforeAdd) && actions.beforeAdd(entityId);\n                              var plugin = this.instantiatePlugin(entityId);\n                              this.entities.set(entityId, plugin);\n                              isFunction(actions.afterAdd) && actions.afterAdd(plugin);\n                          }\n                      }\n                      this.entities.forEach(function (plugin, entityId) {\n                          if (ids.indexOf(entityId) === -1) {\n                              isFunction(actions.beforeRemove) && actions.beforeRemove(plugin);\n                              _this.removeEntity(entityId);\n                          }\n                      });\n                  }\n                  else {\n                      /**\n                       * Which means the user passes specific ids\n                       */\n                      var _ids = coerceArray(this.entityIds);\n                      for (var i = 0, len = _ids.length; i < len; i++) {\n                          var entityId = _ids[i];\n                          /** The Entity in current ids and doesn't exist, add it. */\n                          if (ids.indexOf(entityId) > -1 && this.hasEntity(entityId) === false) {\n                              isFunction(actions.beforeAdd) && actions.beforeAdd(entityId);\n                              var plugin = this.instantiatePlugin(entityId);\n                              this.entities.set(entityId, plugin);\n                              isFunction(actions.afterAdd) && actions.afterAdd(plugin);\n                          }\n                          else {\n                              this.entities.forEach(function (plugin, entityId) {\n                                  /** The Entity not in current ids and exists, remove it. */\n                                  if (ids.indexOf(entityId) === -1 && _this.hasEntity(entityId) === true) {\n                                      isFunction(actions.beforeRemove) && actions.beforeRemove(plugin);\n                                      _this.removeEntity(entityId);\n                                  }\n                              });\n                          }\n                      }\n                  }\n              }\n              else {\n                  /**\n                   * Otherwise, start with the provided ids or all.\n                   */\n                  this.getIds().forEach(function (id) {\n                      if (!_this.hasEntity(id))\n                          _this.createEntity(id, _this.instantiatePlugin(id));\n                  });\n              }\n          };\n          /**\n           * Listen for add/remove entities.\n           */\n          EntityCollectionPlugin.prototype.selectIds = function () {\n              return this.query.select(function (state) { return state.ids; });\n          };\n          /**\n           * Base method for activation, you can override it if you need to.\n           */\n          EntityCollectionPlugin.prototype.activate = function (ids) {\n              this.rebase(ids);\n          };\n          /**\n           * Loop over each id and invoke the plugin method.\n           */\n          EntityCollectionPlugin.prototype.forEachId = function (ids, cb) {\n              var _ids = this.resolvedIds(ids);\n              for (var i = 0, len = _ids.length; i < len; i++) {\n                  var id = _ids[i];\n                  if (this.hasEntity(id)) {\n                      cb(this.getEntity(id));\n                  }\n              }\n          };\n          return EntityCollectionPlugin;\n      }());\n    \n      var StateHistoryPlugin = /** @class */ (function (_super) {\n          __extends(StateHistoryPlugin, _super);\n          function StateHistoryPlugin(query, params, _entityId) {\n              if (params === void 0) { params = {}; }\n              var _this = _super.call(this, query, {\n                  resetFn: function () { return _this.clear(); }\n              }) || this;\n              _this.query = query;\n              _this.params = params;\n              _this._entityId = _entityId;\n              /** Allow skipping an update from outside */\n              _this.skip = false;\n              _this.history = {\n                  past: [],\n                  present: null,\n                  future: []\n              };\n              /** Skip the update when redo/undo */\n              _this.skipUpdate = false;\n              params.maxAge = !!params.maxAge ? params.maxAge : 10;\n              params.comparator = params.comparator || (function () { return true; });\n              _this.activate();\n              return _this;\n          }\n          Object.defineProperty(StateHistoryPlugin.prototype, \"hasPast$\", {\n              /**\n               * Observable stream representing whether the history plugin has an available past\n               *\n               */\n              get: function () {\n                  return this._hasPast$;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(StateHistoryPlugin.prototype, \"hasFuture$\", {\n              /**\n               * Observable stream representing whether the history plugin has an available future\n               *\n               */\n              get: function () {\n                  return this._hasFuture$;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(StateHistoryPlugin.prototype, \"hasPast\", {\n              get: function () {\n                  return this.history.past.length > 0;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(StateHistoryPlugin.prototype, \"hasFuture\", {\n              get: function () {\n                  return this.history.future.length > 0;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          Object.defineProperty(StateHistoryPlugin.prototype, \"property\", {\n              get: function () {\n                  return this.params.watchProperty;\n              },\n              enumerable: true,\n              configurable: true\n          });\n          /* Updates the hasPast$ hasFuture$ observables*/\n          StateHistoryPlugin.prototype.updateHasHistory = function () {\n              this.hasFutureSubject.next(this.hasFuture);\n              this.hasPastSubject.next(this.hasPast);\n          };\n          StateHistoryPlugin.prototype.activate = function () {\n              var _this = this;\n              this.hasPastSubject = new BehaviorSubject(false);\n              this._hasPast$ = this.hasPastSubject.asObservable().pipe(distinctUntilChanged());\n              this.hasFutureSubject = new BehaviorSubject(false);\n              this._hasFuture$ = this.hasFutureSubject.asObservable().pipe(distinctUntilChanged());\n              this.history.present = this.getSource(this._entityId, this.property);\n              this.subscription = this\n                  .selectSource(this._entityId, this.property)\n                  .pipe(pairwise())\n                  .subscribe(function (_a) {\n                  var _b = __read(_a, 2), past = _b[0], present = _b[1];\n                  if (_this.skip) {\n                      _this.skip = false;\n                      return;\n                  }\n                  /**\n                   *  comparator: (prev, current) => isEqual(prev, current) === false\n                   */\n                  var shouldUpdate = _this.params.comparator(past, present);\n                  if (!_this.skipUpdate && shouldUpdate) {\n                      if (_this.history.past.length === _this.params.maxAge) {\n                          _this.history.past = _this.history.past.slice(1);\n                      }\n                      _this.history.past = __spread(_this.history.past, [past]);\n                      _this.history.present = present;\n                      _this.updateHasHistory();\n                  }\n              });\n          };\n          StateHistoryPlugin.prototype.undo = function () {\n              if (this.history.past.length > 0) {\n                  var _a = this.history, past = _a.past, present = _a.present;\n                  var previous = past[past.length - 1];\n                  this.history.past = past.slice(0, past.length - 1);\n                  this.history.present = previous;\n                  this.history.future = __spread([present], this.history.future);\n                  this.update();\n              }\n          };\n          StateHistoryPlugin.prototype.redo = function () {\n              if (this.history.future.length > 0) {\n                  var _a = this.history, past = _a.past, present = _a.present;\n                  var next = this.history.future[0];\n                  var newFuture = this.history.future.slice(1);\n                  this.history.past = __spread(past, [present]);\n                  this.history.present = next;\n                  this.history.future = newFuture;\n                  this.update('Redo');\n              }\n          };\n          StateHistoryPlugin.prototype.jumpToPast = function (index) {\n              if (index < 0 || index >= this.history.past.length)\n                  return;\n              var _a = this.history, past = _a.past, future = _a.future, present = _a.present;\n              /**\n               *\n               * const past = [1, 2, 3, 4, 5];\n               * const present = 6;\n               * const future = [7, 8, 9];\n               * const index = 2;\n               *\n               * newPast = past.slice(0, index) = [1, 2];\n               * newPresent = past[index] = 3;\n               * newFuture = [...past.slice(index + 1),present, ...future] = [4, 5, 6, 7, 8, 9];\n               *\n               */\n              var newPast = past.slice(0, index);\n              var newFuture = __spread(past.slice(index + 1), [present], future);\n              var newPresent = past[index];\n              this.history.past = newPast;\n              this.history.present = newPresent;\n              this.history.future = newFuture;\n              this.update();\n          };\n          StateHistoryPlugin.prototype.jumpToFuture = function (index) {\n              if (index < 0 || index >= this.history.future.length)\n                  return;\n              var _a = this.history, past = _a.past, future = _a.future, present = _a.present;\n              /**\n               *\n               * const past = [1, 2, 3, 4, 5];\n               * const present = 6;\n               * const future = [7, 8, 9, 10]\n               * const index = 1\n               *\n               * newPast = [...past, present, ...future.slice(0, index) = [1, 2, 3, 4, 5, 6, 7];\n               * newPresent = future[index] = 8;\n               * newFuture = futrue.slice(index+1) = [9, 10];\n               *\n               */\n              var newPast = __spread(past, [present], future.slice(0, index));\n              var newPresent = future[index];\n              var newFuture = future.slice(index + 1);\n              this.history.past = newPast;\n              this.history.present = newPresent;\n              this.history.future = newFuture;\n              this.update('Redo');\n          };\n          /**\n           *\n           * jump n steps in the past or forward\n           *\n           */\n          StateHistoryPlugin.prototype.jump = function (n) {\n              if (n > 0)\n                  return this.jumpToFuture(n - 1);\n              if (n < 0)\n                  return this.jumpToPast(this.history.past.length + n);\n          };\n          /**\n           * Clear the history\n           *\n           * @param customUpdateFn Callback function for only clearing part of the history\n           *\n           * @example\n           *\n           * stateHistory.clear((history) => {\n           *  return {\n           *    past: history.past,\n           *    present: history.present,\n           *    future: []\n           *  };\n           * });\n           */\n          StateHistoryPlugin.prototype.clear = function (customUpdateFn) {\n              this.history = isFunction(customUpdateFn)\n                  ? customUpdateFn(this.history)\n                  : {\n                      past: [],\n                      present: null,\n                      future: []\n                  };\n              this.updateHasHistory();\n          };\n          StateHistoryPlugin.prototype.destroy = function (clearHistory) {\n              if (clearHistory === void 0) { clearHistory = false; }\n              if (clearHistory) {\n                  this.clear();\n              }\n              this.subscription.unsubscribe();\n          };\n          StateHistoryPlugin.prototype.ignoreNext = function () {\n              this.skip = true;\n          };\n          StateHistoryPlugin.prototype.update = function (action) {\n              if (action === void 0) { action = 'Undo'; }\n              this.skipUpdate = true;\n              logAction(\"@StateHistory - \" + action);\n              this.updateStore(this.history.present, this._entityId, this.property);\n              this.updateHasHistory();\n              this.skipUpdate = false;\n          };\n          return StateHistoryPlugin;\n      }(AkitaPlugin));\n    \n      /** @class */ ((function (_super) {\n          __extends(EntityStateHistoryPlugin, _super);\n          function EntityStateHistoryPlugin(query, params) {\n              if (params === void 0) { params = {}; }\n              var _this = _super.call(this, query, params.entityIds) || this;\n              _this.query = query;\n              _this.params = params;\n              params.maxAge = toBoolean(params.maxAge) ? params.maxAge : 10;\n              _this.activate();\n              _this.selectIds()\n                  .pipe(skip(1))\n                  .subscribe(function (ids) { return _this.activate(ids); });\n              return _this;\n          }\n          EntityStateHistoryPlugin.prototype.redo = function (ids) {\n              this.forEachId(ids, function (e) { return e.redo(); });\n          };\n          EntityStateHistoryPlugin.prototype.undo = function (ids) {\n              this.forEachId(ids, function (e) { return e.undo(); });\n          };\n          EntityStateHistoryPlugin.prototype.hasPast = function (id) {\n              if (this.hasEntity(id)) {\n                  return this.getEntity(id).hasPast;\n              }\n          };\n          EntityStateHistoryPlugin.prototype.hasFuture = function (id) {\n              if (this.hasEntity(id)) {\n                  return this.getEntity(id).hasFuture;\n              }\n          };\n          EntityStateHistoryPlugin.prototype.jumpToFuture = function (ids, index) {\n              this.forEachId(ids, function (e) { return e.jumpToFuture(index); });\n          };\n          EntityStateHistoryPlugin.prototype.jumpToPast = function (ids, index) {\n              this.forEachId(ids, function (e) { return e.jumpToPast(index); });\n          };\n          EntityStateHistoryPlugin.prototype.clear = function (ids) {\n              this.forEachId(ids, function (e) { return e.clear(); });\n          };\n          EntityStateHistoryPlugin.prototype.destroy = function (ids, clearHistory) {\n              if (clearHistory === void 0) { clearHistory = false; }\n              this.forEachId(ids, function (e) { return e.destroy(clearHistory); });\n          };\n          EntityStateHistoryPlugin.prototype.ignoreNext = function (ids) {\n              this.forEachId(ids, function (e) { return e.ignoreNext(); });\n          };\n          EntityStateHistoryPlugin.prototype.instantiatePlugin = function (id) {\n              return new StateHistoryPlugin(this.query, this.params, id);\n          };\n          return EntityStateHistoryPlugin;\n      })(EntityCollectionPlugin));\n    \n      var Éµ0 = function (head, current) { return JSON.stringify(head) !== JSON.stringify(current); };\n      var dirtyCheckDefaultParams = {\n          comparator: Éµ0\n      };\n      function getNestedPath(nestedObj, path) {\n          var pathAsArray = path.split('.');\n          return pathAsArray.reduce(function (obj, key) { return (obj && obj[key] !== 'undefined' ? obj[key] : undefined); }, nestedObj);\n      }\n      var DirtyCheckPlugin = /** @class */ (function (_super) {\n          __extends(DirtyCheckPlugin, _super);\n          function DirtyCheckPlugin(query, params, _entityId) {\n              var _this = _super.call(this, query) || this;\n              _this.query = query;\n              _this.params = params;\n              _this._entityId = _entityId;\n              _this.dirty = new BehaviorSubject(false);\n              _this.active = false;\n              _this._reset = new Subject();\n              _this.isDirty$ = _this.dirty.asObservable().pipe(distinctUntilChanged());\n              _this.reset$ = _this._reset.asObservable();\n              _this.params = __assign({}, dirtyCheckDefaultParams, params);\n              if (_this.params.watchProperty) {\n                  var watchProp = coerceArray(_this.params.watchProperty);\n                  if (query instanceof QueryEntity && watchProp.includes('entities') && !watchProp.includes('ids')) {\n                      watchProp.push('ids');\n                  }\n                  _this.params.watchProperty = watchProp;\n              }\n              return _this;\n          }\n          DirtyCheckPlugin.prototype.reset = function (params) {\n              if (params === void 0) { params = {}; }\n              var currentValue = this.head;\n              if (isFunction(params.updateFn)) {\n                  if (this.isEntityBased(this._entityId)) {\n                      currentValue = params.updateFn(this.head, this.getQuery().getEntity(this._entityId));\n                  }\n                  else {\n                      currentValue = params.updateFn(this.head, this.getQuery().getValue());\n                  }\n              }\n              logAction(\"@DirtyCheck - Revert\");\n              this.updateStore(currentValue, this._entityId);\n              this._reset.next();\n          };\n          DirtyCheckPlugin.prototype.setHead = function () {\n              if (!this.active) {\n                  this.activate();\n                  this.active = true;\n              }\n              else {\n                  this.head = this._getHead();\n              }\n              this.updateDirtiness(false);\n              return this;\n          };\n          DirtyCheckPlugin.prototype.isDirty = function () {\n              return !!this.dirty.value;\n          };\n          DirtyCheckPlugin.prototype.hasHead = function () {\n              return !!this.getHead();\n          };\n          DirtyCheckPlugin.prototype.destroy = function () {\n              this.head = null;\n              this.subscription && this.subscription.unsubscribe();\n              this._reset && this._reset.complete();\n          };\n          DirtyCheckPlugin.prototype.isPathDirty = function (path) {\n              var head = this.getHead();\n              var current = this.getQuery().getValue();\n              var currentPathValue = getNestedPath(current, path);\n              var headPathValue = getNestedPath(head, path);\n              return this.params.comparator(currentPathValue, headPathValue);\n          };\n          DirtyCheckPlugin.prototype.getHead = function () {\n              return this.head;\n          };\n          DirtyCheckPlugin.prototype.activate = function () {\n              var _this = this;\n              this.head = this._getHead();\n              /** if we are tracking specific properties select only the relevant ones */\n              var source = this.params.watchProperty\n                  ? this.params.watchProperty.map(function (prop) {\n                      return _this.query\n                          .select(function (state) { return state[prop]; })\n                          .pipe(map(function (val) { return ({\n                          val: val,\n                          __akitaKey: prop\n                      }); }));\n                  })\n                  : [this.selectSource(this._entityId)];\n              this.subscription = combineLatest.apply(void 0, __spread(source)).pipe(skip(1))\n                  .subscribe(function (currentState) {\n                  if (isUndefined(_this.head))\n                      return;\n                  /** __akitaKey is used to determine if we are tracking a specific property or a store change */\n                  var isChange = currentState.some(function (state) {\n                      var head = state.__akitaKey ? _this.head[state.__akitaKey] : _this.head;\n                      var compareTo = state.__akitaKey ? state.val : state;\n                      return _this.params.comparator(head, compareTo);\n                  });\n                  _this.updateDirtiness(isChange);\n              });\n          };\n          DirtyCheckPlugin.prototype.updateDirtiness = function (isDirty) {\n              this.dirty.next(isDirty);\n          };\n          DirtyCheckPlugin.prototype._getHead = function () {\n              var head = this.getSource(this._entityId);\n              if (this.params.watchProperty) {\n                  head = this.getWatchedValues(head);\n              }\n              return head;\n          };\n          DirtyCheckPlugin.prototype.getWatchedValues = function (source) {\n              return this.params.watchProperty.reduce(function (watched, prop) {\n                  watched[prop] = source[prop];\n                  return watched;\n              }, {});\n          };\n          return DirtyCheckPlugin;\n      }(AkitaPlugin));\n    \n      /** @class */ ((function (_super) {\n          __extends(EntityDirtyCheckPlugin, _super);\n          function EntityDirtyCheckPlugin(query, params) {\n              if (params === void 0) { params = {}; }\n              var _this = _super.call(this, query, params.entityIds) || this;\n              _this.query = query;\n              _this.params = params;\n              _this._someDirty = new Subject();\n              _this.someDirty$ = merge(_this.query.select(function (state) { return state.entities; }), _this._someDirty.asObservable()).pipe(auditTime(0), map(function () { return _this.checkSomeDirty(); }));\n              _this.params = __assign({}, dirtyCheckDefaultParams, params);\n              // TODO lazy activate?\n              _this.activate();\n              _this.selectIds()\n                  .pipe(skip(1))\n                  .subscribe(function (ids) {\n                  _super.prototype.rebase.call(_this, ids, { afterAdd: function (plugin) { return plugin.setHead(); } });\n              });\n              return _this;\n          }\n          EntityDirtyCheckPlugin.prototype.setHead = function (ids) {\n              if (this.params.entityIds && ids) {\n                  var toArray_1 = coerceArray(ids);\n                  var someAreWatched = coerceArray(this.params.entityIds).some(function (id) { return toArray_1.indexOf(id) > -1; });\n                  if (someAreWatched === false) {\n                      return this;\n                  }\n              }\n              this.forEachId(ids, function (e) { return e.setHead(); });\n              this._someDirty.next();\n              return this;\n          };\n          EntityDirtyCheckPlugin.prototype.hasHead = function (id) {\n              if (this.entities.has(id)) {\n                  var entity = this.getEntity(id);\n                  return entity.hasHead();\n              }\n              return false;\n          };\n          EntityDirtyCheckPlugin.prototype.reset = function (ids, params) {\n              if (params === void 0) { params = {}; }\n              this.forEachId(ids, function (e) { return e.reset(params); });\n          };\n          EntityDirtyCheckPlugin.prototype.isDirty = function (id, asObservable) {\n              if (asObservable === void 0) { asObservable = true; }\n              if (this.entities.has(id)) {\n                  var entity = this.getEntity(id);\n                  return asObservable ? entity.isDirty$ : entity.isDirty();\n              }\n              return false;\n          };\n          EntityDirtyCheckPlugin.prototype.someDirty = function () {\n              return this.checkSomeDirty();\n          };\n          EntityDirtyCheckPlugin.prototype.isPathDirty = function (id, path) {\n              if (this.entities.has(id)) {\n                  var head = this.getEntity(id).getHead();\n                  var current = this.query.getEntity(id);\n                  var currentPathValue = getNestedPath(current, path);\n                  var headPathValue = getNestedPath(head, path);\n                  return this.params.comparator(currentPathValue, headPathValue);\n              }\n              return null;\n          };\n          EntityDirtyCheckPlugin.prototype.destroy = function (ids) {\n              this.forEachId(ids, function (e) { return e.destroy(); });\n              /** complete only when the plugin destroys */\n              if (!ids) {\n                  this._someDirty.complete();\n              }\n          };\n          EntityDirtyCheckPlugin.prototype.instantiatePlugin = function (id) {\n              return new DirtyCheckPlugin(this.query, this.params, id);\n          };\n          EntityDirtyCheckPlugin.prototype.checkSomeDirty = function () {\n              var e_1, _a;\n              var entitiesIds = this.resolvedIds();\n              try {\n                  for (var entitiesIds_1 = __values(entitiesIds), entitiesIds_1_1 = entitiesIds_1.next(); !entitiesIds_1_1.done; entitiesIds_1_1 = entitiesIds_1.next()) {\n                      var id = entitiesIds_1_1.value;\n                      if (this.getEntity(id).isDirty()) {\n                          return true;\n                      }\n                  }\n              }\n              catch (e_1_1) { e_1 = { error: e_1_1 }; }\n              finally {\n                  try {\n                      if (entitiesIds_1_1 && !entitiesIds_1_1.done && (_a = entitiesIds_1.return)) _a.call(entitiesIds_1);\n                  }\n                  finally { if (e_1) throw e_1.error; }\n              }\n              return false;\n          };\n          return EntityDirtyCheckPlugin;\n      })(EntityCollectionPlugin));\n    \n      /**\n       * Generate random guid\n       *\n       * @example\n       *\n       * {\n       *   id: guid()\n       * }\n       *\n       * @remarks this isn't a GUID, but a 10 char random alpha-num\n       */\n      function guid() {\n          return Math.random()\n              .toString(36)\n              .slice(2);\n      }\n    \n      var _a, _b;\n      var StoreAction;\n      (function (StoreAction) {\n          StoreAction[\"Update\"] = \"UPDATE\";\n      })(StoreAction || (StoreAction = {}));\n      (_a = {},\n          _a[StoreAction.Update] = 'update',\n          _a);\n      var EntityStoreAction;\n      (function (EntityStoreAction) {\n          EntityStoreAction[\"Update\"] = \"UPDATE\";\n          EntityStoreAction[\"AddEntities\"] = \"ADD_ENTITIES\";\n          EntityStoreAction[\"SetEntities\"] = \"SET_ENTITIES\";\n          EntityStoreAction[\"UpdateEntities\"] = \"UPDATE_ENTITIES\";\n          EntityStoreAction[\"RemoveEntities\"] = \"REMOVE_ENTITIES\";\n          EntityStoreAction[\"UpsertEntities\"] = \"UPSERT_ENTITIES\";\n          EntityStoreAction[\"UpsertManyEntities\"] = \"UPSERT_MANY_ENTITIES\";\n      })(EntityStoreAction || (EntityStoreAction = {}));\n      (_b = {},\n          _b[EntityStoreAction.Update] = 'update',\n          _b[EntityStoreAction.AddEntities] = 'add',\n          _b[EntityStoreAction.SetEntities] = 'set',\n          _b[EntityStoreAction.UpdateEntities] = 'update',\n          _b[EntityStoreAction.RemoveEntities] = 'remove',\n          _b[EntityStoreAction.UpsertEntities] = 'upsert',\n          _b[EntityStoreAction.UpsertManyEntities] = 'upsertMany',\n          _b);\n    \n      function combineQueries(observables) {\n          return combineLatest(observables).pipe(auditTime(0));\n      }\n    \n      var immer_cjs_development = {};\n    \n      Object.defineProperty(immer_cjs_development, '__esModule', { value: true });\n    \n      var _ref;\n    \n      // Should be no imports here!\n      // Some things that should be evaluated before all else...\n      // We only want to know if non-polyfilled symbols are available\n      var hasSymbol = typeof Symbol !== \"undefined\" && typeof\n      /*#__PURE__*/\n      Symbol(\"x\") === \"symbol\";\n      var hasMap = typeof Map !== \"undefined\";\n      var hasSet = typeof Set !== \"undefined\";\n      var hasProxies = typeof Proxy !== \"undefined\" && typeof Proxy.revocable !== \"undefined\" && typeof Reflect !== \"undefined\";\n      /**\n       * The sentinel value returned by producers to replace the draft with undefined.\n       */\n    \n      var NOTHING = hasSymbol ?\n      /*#__PURE__*/\n      Symbol.for(\"immer-nothing\") : (_ref = {}, _ref[\"immer-nothing\"] = true, _ref);\n      /**\n       * To let Immer treat your class instances as plain immutable objects\n       * (albeit with a custom prototype), you must define either an instance property\n       * or a static property on each of your custom classes.\n       *\n       * Otherwise, your class instance will never be drafted, which means it won't be\n       * safe to mutate in a produce callback.\n       */\n    \n      var DRAFTABLE = hasSymbol ?\n      /*#__PURE__*/\n      Symbol.for(\"immer-draftable\") : \"__$immer_draftable\";\n      var DRAFT_STATE = hasSymbol ?\n      /*#__PURE__*/\n      Symbol.for(\"immer-state\") : \"__$immer_state\"; // Even a polyfilled Symbol might provide Symbol.iterator\n    \n      var iteratorSymbol = typeof Symbol != \"undefined\" && Symbol.iterator || \"@@iterator\";\n    \n      var errors = {\n        0: \"Illegal state\",\n        1: \"Immer drafts cannot have computed properties\",\n        2: \"This object has been frozen and should not be mutated\",\n        3: function _(data) {\n          return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + data;\n        },\n        4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n        5: \"Immer forbids circular references\",\n        6: \"The first or second argument to `produce` must be a function\",\n        7: \"The third argument to `produce` must be a function or undefined\",\n        8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n        9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n        10: \"The given draft is already finalized\",\n        11: \"Object.defineProperty() cannot be used on an Immer draft\",\n        12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n        13: \"Immer only supports deleting array indices\",\n        14: \"Immer only supports setting array indices and the 'length' property\",\n        15: function _(path) {\n          return \"Cannot apply patch, path doesn't resolve: \" + path;\n        },\n        16: 'Sets cannot have \"replace\" patches.',\n        17: function _(op) {\n          return \"Unsupported patch operation: \" + op;\n        },\n        18: function _(plugin) {\n          return \"The plugin for '\" + plugin + \"' has not been loaded into Immer. To enable the plugin, import and call `enable\" + plugin + \"()` when initializing your application.\";\n        },\n        20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n        21: function _(thing) {\n          return \"produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '\" + thing + \"'\";\n        },\n        22: function _(thing) {\n          return \"'current' expects a draft, got: \" + thing;\n        },\n        23: function _(thing) {\n          return \"'original' expects a draft, got: \" + thing;\n        }\n      };\n      function die(error) {\n        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n          args[_key - 1] = arguments[_key];\n        }\n    \n        {\n          var e = errors[error];\n          var msg = !e ? \"unknown error nr: \" + error : typeof e === \"function\" ? e.apply(null, args) : e;\n          throw new Error(\"[Immer] \" + msg);\n        }\n      }\n    \n      var ArchtypeObject = 0;\n      var ArchtypeArray = 1;\n      var ArchtypeMap = 2;\n      var ArchtypeSet = 3;\n      var ProxyTypeProxyObject = 0;\n      var ProxyTypeProxyArray = 1;\n      var ProxyTypeES5Object = 4;\n      var ProxyTypeES5Array = 5;\n      var ProxyTypeMap = 2;\n      var ProxyTypeSet = 3;\n    \n      /** Returns true if the given value is an Immer draft */\n    \n    \n    \n      function isDraft(value) {\n        return !!value && !!value[DRAFT_STATE];\n      }\n      /** Returns true if the given value can be drafted by Immer */\n    \n    \n    \n      function isDraftable(value) {\n        if (!value) return false;\n        return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE] || isMap(value) || isSet(value);\n      }\n    \n    \n      function isPlainObject(value) {\n        if (!value || typeof value !== \"object\") return false;\n        var proto = Object.getPrototypeOf(value);\n        return !proto || proto === Object.prototype;\n      }\n      function original(value) {\n        if (!isDraft(value)) die(23, value);\n        return value[DRAFT_STATE].base_;\n      }\n    \n    \n      var ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : typeof Object.getOwnPropertySymbols !== \"undefined\" ? function (obj) {\n        return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n      } :\n      /* istanbul ignore next */\n      Object.getOwnPropertyNames;\n      var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n        // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n        var res = {};\n        ownKeys(target).forEach(function (key) {\n          res[key] = Object.getOwnPropertyDescriptor(target, key);\n        });\n        return res;\n      };\n      function each(obj, iter, enumerableOnly) {\n        if (enumerableOnly === void 0) {\n          enumerableOnly = false;\n        }\n    \n        if (getArchtype(obj) === ArchtypeObject) {\n          (enumerableOnly ? Object.keys : ownKeys)(obj).forEach(function (key) {\n            if (!enumerableOnly || typeof key !== \"symbol\") iter(key, obj[key], obj);\n          });\n        } else {\n          obj.forEach(function (entry, index) {\n            return iter(index, entry, obj);\n          });\n        }\n      }\n    \n    \n      function getArchtype(thing) {\n        /* istanbul ignore next */\n        var state = thing[DRAFT_STATE];\n        return state ? state.type_ > 3 ? state.type_ - 4 // cause Object and Array map back from 4 and 5\n        : state.type_ // others are the same\n        : Array.isArray(thing) ? ArchtypeArray : isMap(thing) ? ArchtypeMap : isSet(thing) ? ArchtypeSet : ArchtypeObject;\n      }\n    \n    \n      function has(thing, prop) {\n        return getArchtype(thing) === ArchtypeMap ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);\n      }\n    \n    \n      function get(thing, prop) {\n        // @ts-ignore\n        return getArchtype(thing) === ArchtypeMap ? thing.get(prop) : thing[prop];\n      }\n    \n    \n      function set(thing, propOrOldValue, value) {\n        var t = getArchtype(thing);\n        if (t === ArchtypeMap) thing.set(propOrOldValue, value);else if (t === ArchtypeSet) {\n          thing.delete(propOrOldValue);\n          thing.add(value);\n        } else thing[propOrOldValue] = value;\n      }\n    \n    \n      function is(x, y) {\n        // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n        if (x === y) {\n          return x !== 0 || 1 / x === 1 / y;\n        } else {\n          return x !== x && y !== y;\n        }\n      }\n    \n    \n      function isMap(target) {\n        return hasMap && target instanceof Map;\n      }\n    \n    \n      function isSet(target) {\n        return hasSet && target instanceof Set;\n      }\n    \n    \n      function latest(state) {\n        return state.copy_ || state.base_;\n      }\n    \n    \n      function shallowCopy(base) {\n        if (Array.isArray(base)) return Array.prototype.slice.call(base);\n        var descriptors = getOwnPropertyDescriptors(base);\n        delete descriptors[DRAFT_STATE];\n        var keys = ownKeys(descriptors);\n    \n        for (var i = 0; i < keys.length; i++) {\n          var key = keys[i];\n          var desc = descriptors[key];\n    \n          if (desc.writable === false) {\n            desc.writable = true;\n            desc.configurable = true;\n          } // like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n          // with libraries that trap values, like mobx or vue\n          // unlike object.assign, non-enumerables will be copied as well\n    \n    \n          if (desc.get || desc.set) descriptors[key] = {\n            configurable: true,\n            writable: true,\n            enumerable: desc.enumerable,\n            value: base[key]\n          };\n        }\n    \n        return Object.create(Object.getPrototypeOf(base), descriptors);\n      }\n      function freeze(obj, deep) {\n        if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return;\n    \n        if (getArchtype(obj) > 1\n        /* Map or Set */\n        ) {\n            obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;\n          }\n    \n        Object.freeze(obj);\n        if (deep) each(obj, function (key, value) {\n          return freeze(value, true);\n        }, true);\n      }\n    \n      function dontMutateFrozenCollections() {\n        die(2);\n      }\n    \n      function isFrozen(obj) {\n        if (obj == null || typeof obj !== \"object\") return true; // See #600, IE dies on non-objects in Object.isFrozen\n    \n        return Object.isFrozen(obj);\n      }\n    \n      /** Plugin utilities */\n    \n      var plugins = {};\n      function getPlugin(pluginKey) {\n        var plugin = plugins[pluginKey];\n    \n        if (!plugin) {\n          die(18, pluginKey);\n        } // @ts-ignore\n    \n    \n        return plugin;\n      }\n      function loadPlugin(pluginKey, implementation) {\n        if (!plugins[pluginKey]) plugins[pluginKey] = implementation;\n      }\n    \n      var currentScope;\n      function getCurrentScope() {\n        if ( !currentScope) die(0);\n        return currentScope;\n      }\n    \n      function createScope(parent_, immer_) {\n        return {\n          drafts_: [],\n          parent_: parent_,\n          immer_: immer_,\n          // Whenever the modified draft contains a draft from another scope, we\n          // need to prevent auto-freezing so the unowned draft can be finalized.\n          canAutoFreeze_: true,\n          unfinalizedDrafts_: 0\n        };\n      }\n    \n      function usePatchesInScope(scope, patchListener) {\n        if (patchListener) {\n          getPlugin(\"Patches\"); // assert we have the plugin\n    \n          scope.patches_ = [];\n          scope.inversePatches_ = [];\n          scope.patchListener_ = patchListener;\n        }\n      }\n      function revokeScope(scope) {\n        leaveScope(scope);\n        scope.drafts_.forEach(revokeDraft); // @ts-ignore\n    \n        scope.drafts_ = null;\n      }\n      function leaveScope(scope) {\n        if (scope === currentScope) {\n          currentScope = scope.parent_;\n        }\n      }\n      function enterScope(immer) {\n        return currentScope = createScope(currentScope, immer);\n      }\n    \n      function revokeDraft(draft) {\n        var state = draft[DRAFT_STATE];\n        if (state.type_ === ProxyTypeProxyObject || state.type_ === ProxyTypeProxyArray) state.revoke_();else state.revoked_ = true;\n      }\n    \n      function processResult(result, scope) {\n        scope.unfinalizedDrafts_ = scope.drafts_.length;\n        var baseDraft = scope.drafts_[0];\n        var isReplaced = result !== undefined && result !== baseDraft;\n        if (!scope.immer_.useProxies_) getPlugin(\"ES5\").willFinalizeES5_(scope, result, isReplaced);\n    \n        if (isReplaced) {\n          if (baseDraft[DRAFT_STATE].modified_) {\n            revokeScope(scope);\n            die(4);\n          }\n    \n          if (isDraftable(result)) {\n            // Finalize the result in case it contains (or is) a subset of the draft.\n            result = finalize(scope, result);\n            if (!scope.parent_) maybeFreeze(scope, result);\n          }\n    \n          if (scope.patches_) {\n            getPlugin(\"Patches\").generateReplacementPatches_(baseDraft[DRAFT_STATE], result, scope.patches_, scope.inversePatches_);\n          }\n        } else {\n          // Finalize the base draft.\n          result = finalize(scope, baseDraft, []);\n        }\n    \n        revokeScope(scope);\n    \n        if (scope.patches_) {\n          scope.patchListener_(scope.patches_, scope.inversePatches_);\n        }\n    \n        return result !== NOTHING ? result : undefined;\n      }\n    \n      function finalize(rootScope, value, path) {\n        // Don't recurse in tho recursive data structures\n        if (isFrozen(value)) return value;\n        var state = value[DRAFT_STATE]; // A plain object, might need freezing, might contain drafts\n    \n        if (!state) {\n          each(value, function (key, childValue) {\n            return finalizeProperty(rootScope, state, value, key, childValue, path);\n          }, true // See #590, don't recurse into non-enumarable of non drafted objects\n          );\n          return value;\n        } // Never finalize drafts owned by another scope.\n    \n    \n        if (state.scope_ !== rootScope) return value; // Unmodified draft, return the (frozen) original\n    \n        if (!state.modified_) {\n          maybeFreeze(rootScope, state.base_, true);\n          return state.base_;\n        } // Not finalized yet, let's do that now\n    \n    \n        if (!state.finalized_) {\n          state.finalized_ = true;\n          state.scope_.unfinalizedDrafts_--;\n          var result = // For ES5, create a good copy from the draft first, with added keys and without deleted keys.\n          state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array ? state.copy_ = shallowCopy(state.draft_) : state.copy_; // Finalize all children of the copy\n          // For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n          // Although the original test case doesn't seem valid anyway, so if this in the way we can turn the next line\n          // back to each(result, ....)\n    \n          each(state.type_ === ProxyTypeSet ? new Set(result) : result, function (key, childValue) {\n            return finalizeProperty(rootScope, state, result, key, childValue, path);\n          }); // everything inside is frozen, we can freeze here\n    \n          maybeFreeze(rootScope, result, false); // first time finalizing, let's create those patches\n    \n          if (path && rootScope.patches_) {\n            getPlugin(\"Patches\").generatePatches_(state, path, rootScope.patches_, rootScope.inversePatches_);\n          }\n        }\n    \n        return state.copy_;\n      }\n    \n      function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath) {\n        if ( childValue === targetObject) die(5);\n    \n        if (isDraft(childValue)) {\n          var path = rootPath && parentState && parentState.type_ !== ProxyTypeSet && // Set objects are atomic since they have no keys.\n          !has(parentState.assigned_, prop) // Skip deep patches for assigned keys.\n          ? rootPath.concat(prop) : undefined; // Drafts owned by `scope` are finalized here.\n    \n          var res = finalize(rootScope, childValue, path);\n          set(targetObject, prop, res); // Drafts from another scope must prevented to be frozen\n          // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n    \n          if (isDraft(res)) {\n            rootScope.canAutoFreeze_ = false;\n          } else return;\n        } // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n    \n    \n        if (isDraftable(childValue) && !isFrozen(childValue)) {\n          if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n            // optimization: if an object is not a draft, and we don't have to\n            // deepfreeze everything, and we are sure that no drafts are left in the remaining object\n            // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n            // This benefits especially adding large data tree's without further processing.\n            // See add-data.js perf test\n            return;\n          }\n    \n          finalize(rootScope, childValue); // immer deep freezes plain objects, so if there is no parent state, we freeze as well\n    \n          if (!parentState || !parentState.scope_.parent_) maybeFreeze(rootScope, childValue);\n        }\n      }\n    \n      function maybeFreeze(scope, value, deep) {\n        if (deep === void 0) {\n          deep = false;\n        }\n    \n        if (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n          freeze(value, deep);\n        }\n      }\n    \n      /**\n       * Returns a new draft of the `base` object.\n       *\n       * The second argument is the parent draft-state (used internally).\n       */\n    \n      function createProxyProxy(base, parent) {\n        var isArray = Array.isArray(base);\n        var state = {\n          type_: isArray ? ProxyTypeProxyArray : ProxyTypeProxyObject,\n          // Track which produce call this is associated with.\n          scope_: parent ? parent.scope_ : getCurrentScope(),\n          // True for both shallow and deep changes.\n          modified_: false,\n          // Used during finalization.\n          finalized_: false,\n          // Track which properties have been assigned (true) or deleted (false).\n          assigned_: {},\n          // The parent draft state.\n          parent_: parent,\n          // The base state.\n          base_: base,\n          // The base proxy.\n          draft_: null,\n          // The base copy with any updated values.\n          copy_: null,\n          // Called by the `produce` function.\n          revoke_: null,\n          isManual_: false\n        }; // the traps must target something, a bit like the 'real' base.\n        // but also, we need to be able to determine from the target what the relevant state is\n        // (to avoid creating traps per instance to capture the state in closure,\n        // and to avoid creating weird hidden properties as well)\n        // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n        // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n    \n        var target = state;\n        var traps = objectTraps;\n    \n        if (isArray) {\n          target = [state];\n          traps = arrayTraps;\n        }\n    \n        var _Proxy$revocable = Proxy.revocable(target, traps),\n            revoke = _Proxy$revocable.revoke,\n            proxy = _Proxy$revocable.proxy;\n    \n        state.draft_ = proxy;\n        state.revoke_ = revoke;\n        return proxy;\n      }\n      /**\n       * Object drafts\n       */\n    \n      var objectTraps = {\n        get: function get(state, prop) {\n          if (prop === DRAFT_STATE) return state;\n          var source = latest(state);\n    \n          if (!has(source, prop)) {\n            // non-existing or non-own property...\n            return readPropFromProto(state, source, prop);\n          }\n    \n          var value = source[prop];\n    \n          if (state.finalized_ || !isDraftable(value)) {\n            return value;\n          } // Check for existing draft in modified state.\n          // Assigned values are never drafted. This catches any drafts we created, too.\n    \n    \n          if (value === peek(state.base_, prop)) {\n            prepareCopy(state);\n            return state.copy_[prop] = createProxy(state.scope_.immer_, value, state);\n          }\n    \n          return value;\n        },\n        has: function has(state, prop) {\n          return prop in latest(state);\n        },\n        ownKeys: function ownKeys(state) {\n          return Reflect.ownKeys(latest(state));\n        },\n        set: function set(state, prop\n        /* strictly not, but helps TS */\n        , value) {\n          var desc = getDescriptorFromProto(latest(state), prop);\n    \n          if (desc === null || desc === void 0 ? void 0 : desc.set) {\n            // special case: if this write is captured by a setter, we have\n            // to trigger it with the correct context\n            desc.set.call(state.draft_, value);\n            return true;\n          }\n    \n          if (!state.modified_) {\n            // the last check is because we need to be able to distinguish setting a non-existig to undefined (which is a change)\n            // from setting an existing property with value undefined to undefined (which is not a change)\n            var current = peek(latest(state), prop); // special case, if we assigning the original value to a draft, we can ignore the assignment\n    \n            var currentState = current === null || current === void 0 ? void 0 : current[DRAFT_STATE];\n    \n            if (currentState && currentState.base_ === value) {\n              state.copy_[prop] = value;\n              state.assigned_[prop] = false;\n              return true;\n            }\n    \n            if (is(value, current) && (value !== undefined || has(state.base_, prop))) return true;\n            prepareCopy(state);\n            markChanged(state);\n          } // @ts-ignore\n    \n    \n          state.copy_[prop] = value;\n          state.assigned_[prop] = true;\n          return true;\n        },\n        deleteProperty: function deleteProperty(state, prop) {\n          // The `undefined` check is a fast path for pre-existing keys.\n          if (peek(state.base_, prop) !== undefined || prop in state.base_) {\n            state.assigned_[prop] = false;\n            prepareCopy(state);\n            markChanged(state);\n          } else {\n            // if an originally not assigned property was deleted\n            delete state.assigned_[prop];\n          } // @ts-ignore\n    \n    \n          if (state.copy_) delete state.copy_[prop];\n          return true;\n        },\n        // Note: We never coerce `desc.value` into an Immer draft, because we can't make\n        // the same guarantee in ES5 mode.\n        getOwnPropertyDescriptor: function getOwnPropertyDescriptor(state, prop) {\n          var owner = latest(state);\n          var desc = Reflect.getOwnPropertyDescriptor(owner, prop);\n          if (!desc) return desc;\n          return {\n            writable: true,\n            configurable: state.type_ !== ProxyTypeProxyArray || prop !== \"length\",\n            enumerable: desc.enumerable,\n            value: owner[prop]\n          };\n        },\n        defineProperty: function defineProperty() {\n          die(11);\n        },\n        getPrototypeOf: function getPrototypeOf(state) {\n          return Object.getPrototypeOf(state.base_);\n        },\n        setPrototypeOf: function setPrototypeOf() {\n          die(12);\n        }\n      };\n      /**\n       * Array drafts\n       */\n    \n      var arrayTraps = {};\n      each(objectTraps, function (key, fn) {\n        // @ts-ignore\n        arrayTraps[key] = function () {\n          arguments[0] = arguments[0][0];\n          return fn.apply(this, arguments);\n        };\n      });\n    \n      arrayTraps.deleteProperty = function (state, prop) {\n        if ( isNaN(parseInt(prop))) die(13);\n        return objectTraps.deleteProperty.call(this, state[0], prop);\n      };\n    \n      arrayTraps.set = function (state, prop, value) {\n        if ( prop !== \"length\" && isNaN(parseInt(prop))) die(14);\n        return objectTraps.set.call(this, state[0], prop, value, state[0]);\n      }; // Access a property without creating an Immer draft.\n    \n    \n      function peek(draft, prop) {\n        var state = draft[DRAFT_STATE];\n        var source = state ? latest(state) : draft;\n        return source[prop];\n      }\n    \n      function readPropFromProto(state, source, prop) {\n        var _desc$get;\n    \n        var desc = getDescriptorFromProto(source, prop);\n        return desc ? \"value\" in desc ? desc.value : // This is a very special case, if the prop is a getter defined by the\n        // prototype, we should invoke it with the draft as context!\n        (_desc$get = desc.get) === null || _desc$get === void 0 ? void 0 : _desc$get.call(state.draft_) : undefined;\n      }\n    \n      function getDescriptorFromProto(source, prop) {\n        // 'in' checks proto!\n        if (!(prop in source)) return undefined;\n        var proto = Object.getPrototypeOf(source);\n    \n        while (proto) {\n          var desc = Object.getOwnPropertyDescriptor(proto, prop);\n          if (desc) return desc;\n          proto = Object.getPrototypeOf(proto);\n        }\n    \n        return undefined;\n      }\n    \n      function markChanged(state) {\n        if (!state.modified_) {\n          state.modified_ = true;\n    \n          if (state.parent_) {\n            markChanged(state.parent_);\n          }\n        }\n      }\n      function prepareCopy(state) {\n        if (!state.copy_) {\n          state.copy_ = shallowCopy(state.base_);\n        }\n      }\n    \n      var Immer =\n      /*#__PURE__*/\n      function () {\n        function Immer(config) {\n          this.useProxies_ = hasProxies;\n          this.autoFreeze_ =  true\n          /* istanbul ignore next */\n          ;\n          if (typeof (config === null || config === void 0 ? void 0 : config.useProxies) === \"boolean\") this.setUseProxies(config.useProxies);\n          if (typeof (config === null || config === void 0 ? void 0 : config.autoFreeze) === \"boolean\") this.setAutoFreeze(config.autoFreeze);\n          this.produce = this.produce.bind(this);\n          this.produceWithPatches = this.produceWithPatches.bind(this);\n        }\n        /**\n         * The `produce` function takes a value and a \"recipe function\" (whose\n         * return value often depends on the base state). The recipe function is\n         * free to mutate its first argument however it wants. All mutations are\n         * only ever applied to a __copy__ of the base state.\n         *\n         * Pass only a function to create a \"curried producer\" which relieves you\n         * from passing the recipe function every time.\n         *\n         * Only plain objects and arrays are made mutable. All other objects are\n         * considered uncopyable.\n         *\n         * Note: This function is __bound__ to its `Immer` instance.\n         *\n         * @param {any} base - the initial state\n         * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n         * @param {Function} patchListener - optional function that will be called with all the patches produced here\n         * @returns {any} a new state, or the initial state if nothing was modified\n         */\n    \n    \n        var _proto = Immer.prototype;\n    \n        _proto.produce = function produce(base, recipe, patchListener) {\n          // curried invocation\n          if (typeof base === \"function\" && typeof recipe !== \"function\") {\n            var defaultBase = recipe;\n            recipe = base;\n            var self = this;\n            return function curriedProduce(base) {\n              var _this = this;\n    \n              if (base === void 0) {\n                base = defaultBase;\n              }\n    \n              for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n                args[_key - 1] = arguments[_key];\n              }\n    \n              return self.produce(base, function (draft) {\n                var _recipe;\n    \n                return (_recipe = recipe).call.apply(_recipe, [_this, draft].concat(args));\n              }); // prettier-ignore\n            };\n          }\n    \n          if (typeof recipe !== \"function\") die(6);\n          if (patchListener !== undefined && typeof patchListener !== \"function\") die(7);\n          var result; // Only plain objects, arrays, and \"immerable classes\" are drafted.\n    \n          if (isDraftable(base)) {\n            var scope = enterScope(this);\n            var proxy = createProxy(this, base, undefined);\n            var hasError = true;\n    \n            try {\n              result = recipe(proxy);\n              hasError = false;\n            } finally {\n              // finally instead of catch + rethrow better preserves original stack\n              if (hasError) revokeScope(scope);else leaveScope(scope);\n            }\n    \n            if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n              return result.then(function (result) {\n                usePatchesInScope(scope, patchListener);\n                return processResult(result, scope);\n              }, function (error) {\n                revokeScope(scope);\n                throw error;\n              });\n            }\n    \n            usePatchesInScope(scope, patchListener);\n            return processResult(result, scope);\n          } else if (!base || typeof base !== \"object\") {\n            result = recipe(base);\n            if (result === NOTHING) return undefined;\n            if (result === undefined) result = base;\n            if (this.autoFreeze_) freeze(result, true);\n            return result;\n          } else die(21, base);\n        };\n    \n        _proto.produceWithPatches = function produceWithPatches(arg1, arg2, arg3) {\n          var _this2 = this;\n    \n          if (typeof arg1 === \"function\") {\n            return function (state) {\n              for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n                args[_key2 - 1] = arguments[_key2];\n              }\n    \n              return _this2.produceWithPatches(state, function (draft) {\n                return arg1.apply(void 0, [draft].concat(args));\n              });\n            };\n          }\n    \n          var patches, inversePatches;\n          var nextState = this.produce(arg1, arg2, function (p, ip) {\n            patches = p;\n            inversePatches = ip;\n          });\n          return [nextState, patches, inversePatches];\n        };\n    \n        _proto.createDraft = function createDraft(base) {\n          if (!isDraftable(base)) die(8);\n          if (isDraft(base)) base = current(base);\n          var scope = enterScope(this);\n          var proxy = createProxy(this, base, undefined);\n          proxy[DRAFT_STATE].isManual_ = true;\n          leaveScope(scope);\n          return proxy;\n        };\n    \n        _proto.finishDraft = function finishDraft(draft, patchListener) {\n          var state = draft && draft[DRAFT_STATE];\n    \n          {\n            if (!state || !state.isManual_) die(9);\n            if (state.finalized_) die(10);\n          }\n    \n          var scope = state.scope_;\n          usePatchesInScope(scope, patchListener);\n          return processResult(undefined, scope);\n        }\n        /**\n         * Pass true to automatically freeze all copies created by Immer.\n         *\n         * By default, auto-freezing is disabled in production.\n         */\n        ;\n    \n        _proto.setAutoFreeze = function setAutoFreeze(value) {\n          this.autoFreeze_ = value;\n        }\n        /**\n         * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n         * always faster than using ES5 proxies.\n         *\n         * By default, feature detection is used, so calling this is rarely necessary.\n         */\n        ;\n    \n        _proto.setUseProxies = function setUseProxies(value) {\n          if (value && !hasProxies) {\n            die(20);\n          }\n    \n          this.useProxies_ = value;\n        };\n    \n        _proto.applyPatches = function applyPatches(base, patches) {\n          // If a patch replaces the entire state, take that replacement as base\n          // before applying patches\n          var i;\n    \n          for (i = patches.length - 1; i >= 0; i--) {\n            var patch = patches[i];\n    \n            if (patch.path.length === 0 && patch.op === \"replace\") {\n              base = patch.value;\n              break;\n            }\n          }\n    \n          var applyPatchesImpl = getPlugin(\"Patches\").applyPatches_;\n    \n          if (isDraft(base)) {\n            // N.B: never hits if some patch a replacement, patches are never drafts\n            return applyPatchesImpl(base, patches);\n          } // Otherwise, produce a copy of the base state.\n    \n    \n          return this.produce(base, function (draft) {\n            return applyPatchesImpl(draft, patches.slice(i + 1));\n          });\n        };\n    \n        return Immer;\n      }();\n      function createProxy(immer, value, parent) {\n        // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n        var draft = isMap(value) ? getPlugin(\"MapSet\").proxyMap_(value, parent) : isSet(value) ? getPlugin(\"MapSet\").proxySet_(value, parent) : immer.useProxies_ ? createProxyProxy(value, parent) : getPlugin(\"ES5\").createES5Proxy_(value, parent);\n        var scope = parent ? parent.scope_ : getCurrentScope();\n        scope.drafts_.push(draft);\n        return draft;\n      }\n    \n      function current(value) {\n        if (!isDraft(value)) die(22, value);\n        return currentImpl(value);\n      }\n    \n      function currentImpl(value) {\n        if (!isDraftable(value)) return value;\n        var state = value[DRAFT_STATE];\n        var copy;\n        var archType = getArchtype(value);\n    \n        if (state) {\n          if (!state.modified_ && (state.type_ < 4 || !getPlugin(\"ES5\").hasChanges_(state))) return state.base_; // Optimization: avoid generating new drafts during copying\n    \n          state.finalized_ = true;\n          copy = copyHelper(value, archType);\n          state.finalized_ = false;\n        } else {\n          copy = copyHelper(value, archType);\n        }\n    \n        each(copy, function (key, childValue) {\n          if (state && get(state.base_, key) === childValue) return; // no need to copy or search in something that didn't change\n    \n          set(copy, key, currentImpl(childValue));\n        }); // In the future, we might consider freezing here, based on the current settings\n    \n        return archType === ArchtypeSet ? new Set(copy) : copy;\n      }\n    \n      function copyHelper(value, archType) {\n        // creates a shallow copy, even if it is a map or set\n        switch (archType) {\n          case ArchtypeMap:\n            return new Map(value);\n    \n          case ArchtypeSet:\n            // Set will be cloned as array temporarily, so that we can replace individual items\n            return Array.from(value);\n        }\n    \n        return shallowCopy(value);\n      }\n    \n      function enableES5() {\n        function willFinalizeES5_(scope, result, isReplaced) {\n          if (!isReplaced) {\n            if (scope.patches_) {\n              markChangesRecursively(scope.drafts_[0]);\n            } // This is faster when we don't care about which attributes changed.\n    \n    \n            markChangesSweep(scope.drafts_);\n          } // When a child draft is returned, look for changes.\n          else if (isDraft(result) && result[DRAFT_STATE].scope_ === scope) {\n              markChangesSweep(scope.drafts_);\n            }\n        }\n    \n        function createES5Draft(isArray, base) {\n          if (isArray) {\n            var draft = new Array(base.length);\n    \n            for (var i = 0; i < base.length; i++) {\n              Object.defineProperty(draft, \"\" + i, proxyProperty(i, true));\n            }\n    \n            return draft;\n          } else {\n            var _descriptors = getOwnPropertyDescriptors(base);\n    \n            delete _descriptors[DRAFT_STATE];\n            var keys = ownKeys(_descriptors);\n    \n            for (var _i = 0; _i < keys.length; _i++) {\n              var key = keys[_i];\n              _descriptors[key] = proxyProperty(key, isArray || !!_descriptors[key].enumerable);\n            }\n    \n            return Object.create(Object.getPrototypeOf(base), _descriptors);\n          }\n        }\n    \n        function createES5Proxy_(base, parent) {\n          var isArray = Array.isArray(base);\n          var draft = createES5Draft(isArray, base);\n          var state = {\n            type_: isArray ? ProxyTypeES5Array : ProxyTypeES5Object,\n            scope_: parent ? parent.scope_ : getCurrentScope(),\n            modified_: false,\n            finalized_: false,\n            assigned_: {},\n            parent_: parent,\n            // base is the object we are drafting\n            base_: base,\n            // draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)\n            draft_: draft,\n            copy_: null,\n            revoked_: false,\n            isManual_: false\n          };\n          Object.defineProperty(draft, DRAFT_STATE, {\n            value: state,\n            // enumerable: false <- the default\n            writable: true\n          });\n          return draft;\n        } // property descriptors are recycled to make sure we don't create a get and set closure per property,\n        // but share them all instead\n    \n    \n        var descriptors = {};\n    \n        function proxyProperty(prop, enumerable) {\n          var desc = descriptors[prop];\n    \n          if (desc) {\n            desc.enumerable = enumerable;\n          } else {\n            descriptors[prop] = desc = {\n              configurable: true,\n              enumerable: enumerable,\n              get: function get() {\n                var state = this[DRAFT_STATE];\n                assertUnrevoked(state); // @ts-ignore\n    \n                return objectTraps.get(state, prop);\n              },\n              set: function set(value) {\n                var state = this[DRAFT_STATE];\n                assertUnrevoked(state); // @ts-ignore\n    \n                objectTraps.set(state, prop, value);\n              }\n            };\n          }\n    \n          return desc;\n        } // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.\n    \n    \n        function markChangesSweep(drafts) {\n          // The natural order of drafts in the `scope` array is based on when they\n          // were accessed. By processing drafts in reverse natural order, we have a\n          // better chance of processing leaf nodes first. When a leaf node is known to\n          // have changed, we can avoid any traversal of its ancestor nodes.\n          for (var i = drafts.length - 1; i >= 0; i--) {\n            var state = drafts[i][DRAFT_STATE];\n    \n            if (!state.modified_) {\n              switch (state.type_) {\n                case ProxyTypeES5Array:\n                  if (hasArrayChanges(state)) markChanged(state);\n                  break;\n    \n                case ProxyTypeES5Object:\n                  if (hasObjectChanges(state)) markChanged(state);\n                  break;\n              }\n            }\n          }\n        }\n    \n        function markChangesRecursively(object) {\n          if (!object || typeof object !== \"object\") return;\n          var state = object[DRAFT_STATE];\n          if (!state) return;\n          var base_ = state.base_,\n              draft_ = state.draft_,\n              assigned_ = state.assigned_,\n              type_ = state.type_;\n    \n          if (type_ === ProxyTypeES5Object) {\n            // Look for added keys.\n            // probably there is a faster way to detect changes, as sweep + recurse seems to do some\n            // unnecessary work.\n            // also: probably we can store the information we detect here, to speed up tree finalization!\n            each(draft_, function (key) {\n              if (key === DRAFT_STATE) return; // The `undefined` check is a fast path for pre-existing keys.\n    \n              if (base_[key] === undefined && !has(base_, key)) {\n                assigned_[key] = true;\n                markChanged(state);\n              } else if (!assigned_[key]) {\n                // Only untouched properties trigger recursion.\n                markChangesRecursively(draft_[key]);\n              }\n            }); // Look for removed keys.\n    \n            each(base_, function (key) {\n              // The `undefined` check is a fast path for pre-existing keys.\n              if (draft_[key] === undefined && !has(draft_, key)) {\n                assigned_[key] = false;\n                markChanged(state);\n              }\n            });\n          } else if (type_ === ProxyTypeES5Array) {\n            if (hasArrayChanges(state)) {\n              markChanged(state);\n              assigned_.length = true;\n            }\n    \n            if (draft_.length < base_.length) {\n              for (var i = draft_.length; i < base_.length; i++) {\n                assigned_[i] = false;\n              }\n            } else {\n              for (var _i2 = base_.length; _i2 < draft_.length; _i2++) {\n                assigned_[_i2] = true;\n              }\n            } // Minimum count is enough, the other parts has been processed.\n    \n    \n            var min = Math.min(draft_.length, base_.length);\n    \n            for (var _i3 = 0; _i3 < min; _i3++) {\n              // Only untouched indices trigger recursion.\n              if (assigned_[_i3] === undefined) markChangesRecursively(draft_[_i3]);\n            }\n          }\n        }\n    \n        function hasObjectChanges(state) {\n          var base_ = state.base_,\n              draft_ = state.draft_; // Search for added keys and changed keys. Start at the back, because\n          // non-numeric keys are ordered by time of definition on the object.\n    \n          var keys = ownKeys(draft_);\n    \n          for (var i = keys.length - 1; i >= 0; i--) {\n            var key = keys[i];\n            if (key === DRAFT_STATE) continue;\n            var baseValue = base_[key]; // The `undefined` check is a fast path for pre-existing keys.\n    \n            if (baseValue === undefined && !has(base_, key)) {\n              return true;\n            } // Once a base key is deleted, future changes go undetected, because its\n            // descriptor is erased. This branch detects any missed changes.\n            else {\n                var value = draft_[key];\n    \n                var _state = value && value[DRAFT_STATE];\n    \n                if (_state ? _state.base_ !== baseValue : !is(value, baseValue)) {\n                  return true;\n                }\n              }\n          } // At this point, no keys were added or changed.\n          // Compare key count to determine if keys were deleted.\n    \n    \n          var baseIsDraft = !!base_[DRAFT_STATE];\n          return keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1); // + 1 to correct for DRAFT_STATE\n        }\n    \n        function hasArrayChanges(state) {\n          var draft_ = state.draft_;\n          if (draft_.length !== state.base_.length) return true; // See #116\n          // If we first shorten the length, our array interceptors will be removed.\n          // If after that new items are added, result in the same original length,\n          // those last items will have no intercepting property.\n          // So if there is no own descriptor on the last position, we know that items were removed and added\n          // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check\n          // the last one\n    \n          var descriptor = Object.getOwnPropertyDescriptor(draft_, draft_.length - 1); // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)\n    \n          if (descriptor && !descriptor.get) return true; // For all other cases, we don't have to compare, as they would have been picked up by the index setters\n    \n          return false;\n        }\n    \n        function hasChanges_(state) {\n          return state.type_ === ProxyTypeES5Object ? hasObjectChanges(state) : hasArrayChanges(state);\n        }\n    \n        function assertUnrevoked(state\n        /*ES5State | MapState | SetState*/\n        ) {\n          if (state.revoked_) die(3, JSON.stringify(latest(state)));\n        }\n    \n        loadPlugin(\"ES5\", {\n          createES5Proxy_: createES5Proxy_,\n          willFinalizeES5_: willFinalizeES5_,\n          hasChanges_: hasChanges_\n        });\n      }\n    \n      function enablePatches() {\n        var REPLACE = \"replace\";\n        var ADD = \"add\";\n        var REMOVE = \"remove\";\n    \n        function generatePatches_(state, basePath, patches, inversePatches) {\n          switch (state.type_) {\n            case ProxyTypeProxyObject:\n            case ProxyTypeES5Object:\n            case ProxyTypeMap:\n              return generatePatchesFromAssigned(state, basePath, patches, inversePatches);\n    \n            case ProxyTypeES5Array:\n            case ProxyTypeProxyArray:\n              return generateArrayPatches(state, basePath, patches, inversePatches);\n    \n            case ProxyTypeSet:\n              return generateSetPatches(state, basePath, patches, inversePatches);\n          }\n        }\n    \n        function generateArrayPatches(state, basePath, patches, inversePatches) {\n          var base_ = state.base_,\n              assigned_ = state.assigned_;\n          var copy_ = state.copy_; // Reduce complexity by ensuring `base` is never longer.\n    \n          if (copy_.length < base_.length) {\n            var _ref = [copy_, base_];\n            base_ = _ref[0];\n            copy_ = _ref[1];\n            var _ref2 = [inversePatches, patches];\n            patches = _ref2[0];\n            inversePatches = _ref2[1];\n          } // Process replaced indices.\n    \n    \n          for (var i = 0; i < base_.length; i++) {\n            if (assigned_[i] && copy_[i] !== base_[i]) {\n              var path = basePath.concat([i]);\n              patches.push({\n                op: REPLACE,\n                path: path,\n                // Need to maybe clone it, as it can in fact be the original value\n                // due to the base/copy inversion at the start of this function\n                value: clonePatchValueIfNeeded(copy_[i])\n              });\n              inversePatches.push({\n                op: REPLACE,\n                path: path,\n                value: clonePatchValueIfNeeded(base_[i])\n              });\n            }\n          } // Process added indices.\n    \n    \n          for (var _i = base_.length; _i < copy_.length; _i++) {\n            var _path = basePath.concat([_i]);\n    \n            patches.push({\n              op: ADD,\n              path: _path,\n              // Need to maybe clone it, as it can in fact be the original value\n              // due to the base/copy inversion at the start of this function\n              value: clonePatchValueIfNeeded(copy_[_i])\n            });\n          }\n    \n          if (base_.length < copy_.length) {\n            inversePatches.push({\n              op: REPLACE,\n              path: basePath.concat([\"length\"]),\n              value: base_.length\n            });\n          }\n        } // This is used for both Map objects and normal objects.\n    \n    \n        function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {\n          var base_ = state.base_,\n              copy_ = state.copy_;\n          each(state.assigned_, function (key, assignedValue) {\n            var origValue = get(base_, key);\n            var value = get(copy_, key);\n            var op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;\n            if (origValue === value && op === REPLACE) return;\n            var path = basePath.concat(key);\n            patches.push(op === REMOVE ? {\n              op: op,\n              path: path\n            } : {\n              op: op,\n              path: path,\n              value: value\n            });\n            inversePatches.push(op === ADD ? {\n              op: REMOVE,\n              path: path\n            } : op === REMOVE ? {\n              op: ADD,\n              path: path,\n              value: clonePatchValueIfNeeded(origValue)\n            } : {\n              op: REPLACE,\n              path: path,\n              value: clonePatchValueIfNeeded(origValue)\n            });\n          });\n        }\n    \n        function generateSetPatches(state, basePath, patches, inversePatches) {\n          var base_ = state.base_,\n              copy_ = state.copy_;\n          var i = 0;\n          base_.forEach(function (value) {\n            if (!copy_.has(value)) {\n              var path = basePath.concat([i]);\n              patches.push({\n                op: REMOVE,\n                path: path,\n                value: value\n              });\n              inversePatches.unshift({\n                op: ADD,\n                path: path,\n                value: value\n              });\n            }\n    \n            i++;\n          });\n          i = 0;\n          copy_.forEach(function (value) {\n            if (!base_.has(value)) {\n              var path = basePath.concat([i]);\n              patches.push({\n                op: ADD,\n                path: path,\n                value: value\n              });\n              inversePatches.unshift({\n                op: REMOVE,\n                path: path,\n                value: value\n              });\n            }\n    \n            i++;\n          });\n        }\n    \n        function generateReplacementPatches_(rootState, replacement, patches, inversePatches) {\n          patches.push({\n            op: REPLACE,\n            path: [],\n            value: replacement\n          });\n          inversePatches.push({\n            op: REPLACE,\n            path: [],\n            value: rootState.base_\n          });\n        }\n    \n        function applyPatches_(draft, patches) {\n          patches.forEach(function (patch) {\n            var path = patch.path,\n                op = patch.op;\n            var base = draft;\n    \n            for (var i = 0; i < path.length - 1; i++) {\n              base = get(base, path[i]);\n              if (typeof base !== \"object\") die(15, path.join(\"/\"));\n            }\n    \n            var type = getArchtype(base);\n            var value = deepClonePatchValue(patch.value); // used to clone patch to ensure original patch is not modified, see #411\n    \n            var key = path[path.length - 1];\n    \n            switch (op) {\n              case REPLACE:\n                switch (type) {\n                  case ArchtypeMap:\n                    return base.set(key, value);\n    \n                  /* istanbul ignore next */\n    \n                  case ArchtypeSet:\n                    die(16);\n    \n                  default:\n                    // if value is an object, then it's assigned by reference\n                    // in the following add or remove ops, the value field inside the patch will also be modifyed\n                    // so we use value from the cloned patch\n                    // @ts-ignore\n                    return base[key] = value;\n                }\n    \n              case ADD:\n                switch (type) {\n                  case ArchtypeArray:\n                    return base.splice(key, 0, value);\n    \n                  case ArchtypeMap:\n                    return base.set(key, value);\n    \n                  case ArchtypeSet:\n                    return base.add(value);\n    \n                  default:\n                    return base[key] = value;\n                }\n    \n              case REMOVE:\n                switch (type) {\n                  case ArchtypeArray:\n                    return base.splice(key, 1);\n    \n                  case ArchtypeMap:\n                    return base.delete(key);\n    \n                  case ArchtypeSet:\n                    return base.delete(patch.value);\n    \n                  default:\n                    return delete base[key];\n                }\n    \n              default:\n                die(17, op);\n            }\n          });\n          return draft;\n        }\n    \n        function deepClonePatchValue(obj) {\n          if (!isDraftable(obj)) return obj;\n          if (Array.isArray(obj)) return obj.map(deepClonePatchValue);\n          if (isMap(obj)) return new Map(Array.from(obj.entries()).map(function (_ref3) {\n            var k = _ref3[0],\n                v = _ref3[1];\n            return [k, deepClonePatchValue(v)];\n          }));\n          if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue));\n          var cloned = Object.create(Object.getPrototypeOf(obj));\n    \n          for (var key in obj) {\n            cloned[key] = deepClonePatchValue(obj[key]);\n          }\n    \n          return cloned;\n        }\n    \n        function clonePatchValueIfNeeded(obj) {\n          if (isDraft(obj)) {\n            return deepClonePatchValue(obj);\n          } else return obj;\n        }\n    \n        loadPlugin(\"Patches\", {\n          applyPatches_: applyPatches_,\n          generatePatches_: generatePatches_,\n          generateReplacementPatches_: generateReplacementPatches_\n        });\n      }\n    \n      // types only!\n      function enableMapSet() {\n        /* istanbul ignore next */\n        var _extendStatics = function extendStatics(d, b) {\n          _extendStatics = Object.setPrototypeOf || {\n            __proto__: []\n          } instanceof Array && function (d, b) {\n            d.__proto__ = b;\n          } || function (d, b) {\n            for (var p in b) {\n              if (b.hasOwnProperty(p)) d[p] = b[p];\n            }\n          };\n    \n          return _extendStatics(d, b);\n        }; // Ugly hack to resolve #502 and inherit built in Map / Set\n    \n    \n        function __extends(d, b) {\n          _extendStatics(d, b);\n    \n          function __() {\n            this.constructor = d;\n          }\n    \n          d.prototype = ( // @ts-ignore\n          __.prototype = b.prototype, new __());\n        }\n    \n        var DraftMap = function (_super) {\n          __extends(DraftMap, _super); // Create class manually, cause #502\n    \n    \n          function DraftMap(target, parent) {\n            this[DRAFT_STATE] = {\n              type_: ProxyTypeMap,\n              parent_: parent,\n              scope_: parent ? parent.scope_ : getCurrentScope(),\n              modified_: false,\n              finalized_: false,\n              copy_: undefined,\n              assigned_: undefined,\n              base_: target,\n              draft_: this,\n              isManual_: false,\n              revoked_: false\n            };\n            return this;\n          }\n    \n          var p = DraftMap.prototype;\n          Object.defineProperty(p, \"size\", {\n            get: function get() {\n              return latest(this[DRAFT_STATE]).size;\n            } // enumerable: false,\n            // configurable: true\n    \n          });\n    \n          p.has = function (key) {\n            return latest(this[DRAFT_STATE]).has(key);\n          };\n    \n          p.set = function (key, value) {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n    \n            if (!latest(state).has(key) || latest(state).get(key) !== value) {\n              prepareMapCopy(state);\n              markChanged(state);\n              state.assigned_.set(key, true);\n              state.copy_.set(key, value);\n              state.assigned_.set(key, true);\n            }\n    \n            return this;\n          };\n    \n          p.delete = function (key) {\n            if (!this.has(key)) {\n              return false;\n            }\n    \n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n            prepareMapCopy(state);\n            markChanged(state);\n            state.assigned_.set(key, false);\n            state.copy_.delete(key);\n            return true;\n          };\n    \n          p.clear = function () {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n    \n            if (latest(state).size) {\n              prepareMapCopy(state);\n              markChanged(state);\n              state.assigned_ = new Map();\n              each(state.base_, function (key) {\n                state.assigned_.set(key, false);\n              });\n              state.copy_.clear();\n            }\n          };\n    \n          p.forEach = function (cb, thisArg) {\n            var _this = this;\n    \n            var state = this[DRAFT_STATE];\n            latest(state).forEach(function (_value, key, _map) {\n              cb.call(thisArg, _this.get(key), key, _this);\n            });\n          };\n    \n          p.get = function (key) {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n            var value = latest(state).get(key);\n    \n            if (state.finalized_ || !isDraftable(value)) {\n              return value;\n            }\n    \n            if (value !== state.base_.get(key)) {\n              return value; // either already drafted or reassigned\n            } // despite what it looks, this creates a draft only once, see above condition\n    \n    \n            var draft = createProxy(state.scope_.immer_, value, state);\n            prepareMapCopy(state);\n            state.copy_.set(key, draft);\n            return draft;\n          };\n    \n          p.keys = function () {\n            return latest(this[DRAFT_STATE]).keys();\n          };\n    \n          p.values = function () {\n            var _this2 = this,\n                _ref;\n    \n            var iterator = this.keys();\n            return _ref = {}, _ref[iteratorSymbol] = function () {\n              return _this2.values();\n            }, _ref.next = function next() {\n              var r = iterator.next();\n              /* istanbul ignore next */\n    \n              if (r.done) return r;\n    \n              var value = _this2.get(r.value);\n    \n              return {\n                done: false,\n                value: value\n              };\n            }, _ref;\n          };\n    \n          p.entries = function () {\n            var _this3 = this,\n                _ref2;\n    \n            var iterator = this.keys();\n            return _ref2 = {}, _ref2[iteratorSymbol] = function () {\n              return _this3.entries();\n            }, _ref2.next = function next() {\n              var r = iterator.next();\n              /* istanbul ignore next */\n    \n              if (r.done) return r;\n    \n              var value = _this3.get(r.value);\n    \n              return {\n                done: false,\n                value: [r.value, value]\n              };\n            }, _ref2;\n          };\n    \n          p[iteratorSymbol] = function () {\n            return this.entries();\n          };\n    \n          return DraftMap;\n        }(Map);\n    \n        function proxyMap_(target, parent) {\n          // @ts-ignore\n          return new DraftMap(target, parent);\n        }\n    \n        function prepareMapCopy(state) {\n          if (!state.copy_) {\n            state.assigned_ = new Map();\n            state.copy_ = new Map(state.base_);\n          }\n        }\n    \n        var DraftSet = function (_super) {\n          __extends(DraftSet, _super); // Create class manually, cause #502\n    \n    \n          function DraftSet(target, parent) {\n            this[DRAFT_STATE] = {\n              type_: ProxyTypeSet,\n              parent_: parent,\n              scope_: parent ? parent.scope_ : getCurrentScope(),\n              modified_: false,\n              finalized_: false,\n              copy_: undefined,\n              base_: target,\n              draft_: this,\n              drafts_: new Map(),\n              revoked_: false,\n              isManual_: false\n            };\n            return this;\n          }\n    \n          var p = DraftSet.prototype;\n          Object.defineProperty(p, \"size\", {\n            get: function get() {\n              return latest(this[DRAFT_STATE]).size;\n            } // enumerable: true,\n    \n          });\n    \n          p.has = function (value) {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state); // bit of trickery here, to be able to recognize both the value, and the draft of its value\n    \n            if (!state.copy_) {\n              return state.base_.has(value);\n            }\n    \n            if (state.copy_.has(value)) return true;\n            if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value))) return true;\n            return false;\n          };\n    \n          p.add = function (value) {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n    \n            if (!this.has(value)) {\n              prepareSetCopy(state);\n              markChanged(state);\n              state.copy_.add(value);\n            }\n    \n            return this;\n          };\n    \n          p.delete = function (value) {\n            if (!this.has(value)) {\n              return false;\n            }\n    \n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n            prepareSetCopy(state);\n            markChanged(state);\n            return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) :\n            /* istanbul ignore next */\n            false);\n          };\n    \n          p.clear = function () {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n    \n            if (latest(state).size) {\n              prepareSetCopy(state);\n              markChanged(state);\n              state.copy_.clear();\n            }\n          };\n    \n          p.values = function () {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n            prepareSetCopy(state);\n            return state.copy_.values();\n          };\n    \n          p.entries = function entries() {\n            var state = this[DRAFT_STATE];\n            assertUnrevoked(state);\n            prepareSetCopy(state);\n            return state.copy_.entries();\n          };\n    \n          p.keys = function () {\n            return this.values();\n          };\n    \n          p[iteratorSymbol] = function () {\n            return this.values();\n          };\n    \n          p.forEach = function forEach(cb, thisArg) {\n            var iterator = this.values();\n            var result = iterator.next();\n    \n            while (!result.done) {\n              cb.call(thisArg, result.value, result.value, this);\n              result = iterator.next();\n            }\n          };\n    \n          return DraftSet;\n        }(Set);\n    \n        function proxySet_(target, parent) {\n          // @ts-ignore\n          return new DraftSet(target, parent);\n        }\n    \n        function prepareSetCopy(state) {\n          if (!state.copy_) {\n            // create drafts for all entries to preserve insertion order\n            state.copy_ = new Set();\n            state.base_.forEach(function (value) {\n              if (isDraftable(value)) {\n                var draft = createProxy(state.scope_.immer_, value, state);\n                state.drafts_.set(value, draft);\n                state.copy_.add(draft);\n              } else {\n                state.copy_.add(value);\n              }\n            });\n          }\n        }\n    \n        function assertUnrevoked(state\n        /*ES5State | MapState | SetState*/\n        ) {\n          if (state.revoked_) die(3, JSON.stringify(latest(state)));\n        }\n    \n        loadPlugin(\"MapSet\", {\n          proxyMap_: proxyMap_,\n          proxySet_: proxySet_\n        });\n      }\n    \n      function enableAllPlugins() {\n        enableES5();\n        enableMapSet();\n        enablePatches();\n      }\n    \n      var immer =\n      /*#__PURE__*/\n      new Immer();\n      /**\n       * The `produce` function takes a value and a \"recipe function\" (whose\n       * return value often depends on the base state). The recipe function is\n       * free to mutate its first argument however it wants. All mutations are\n       * only ever applied to a __copy__ of the base state.\n       *\n       * Pass only a function to create a \"curried producer\" which relieves you\n       * from passing the recipe function every time.\n       *\n       * Only plain objects and arrays are made mutable. All other objects are\n       * considered uncopyable.\n       *\n       * Note: This function is __bound__ to its `Immer` instance.\n       *\n       * @param {any} base - the initial state\n       * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n       * @param {Function} patchListener - optional function that will be called with all the patches produced here\n       * @returns {any} a new state, or the initial state if nothing was modified\n       */\n    \n      var produce = immer.produce;\n      /**\n       * Like `produce`, but `produceWithPatches` always returns a tuple\n       * [nextState, patches, inversePatches] (instead of just the next state)\n       */\n    \n      var produceWithPatches =\n      /*#__PURE__*/\n      immer.produceWithPatches.bind(immer);\n      /**\n       * Pass true to automatically freeze all copies created by Immer.\n       *\n       * By default, auto-freezing is disabled in production.\n       */\n    \n      var setAutoFreeze =\n      /*#__PURE__*/\n      immer.setAutoFreeze.bind(immer);\n      /**\n       * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n       * always faster than using ES5 proxies.\n       *\n       * By default, feature detection is used, so calling this is rarely necessary.\n       */\n    \n      var setUseProxies =\n      /*#__PURE__*/\n      immer.setUseProxies.bind(immer);\n      /**\n       * Apply an array of Immer patches to the first argument.\n       *\n       * This function is a producer, which means copy-on-write is in effect.\n       */\n    \n      var applyPatches =\n      /*#__PURE__*/\n      immer.applyPatches.bind(immer);\n      /**\n       * Create an Immer draft from the given base state, which may be a draft itself.\n       * The draft can be modified until you finalize it with the `finishDraft` function.\n       */\n    \n      var createDraft =\n      /*#__PURE__*/\n      immer.createDraft.bind(immer);\n      /**\n       * Finalize an Immer draft from a `createDraft` call, returning the base state\n       * (if no changes were made) or a modified copy. The draft must *not* be\n       * mutated afterwards.\n       *\n       * Pass a function as the 2nd argument to generate Immer patches based on the\n       * changes that were made.\n       */\n    \n      var finishDraft =\n      /*#__PURE__*/\n      immer.finishDraft.bind(immer);\n      /**\n       * This function is actually a no-op, but can be used to cast an immutable type\n       * to an draft type and make TypeScript happy\n       *\n       * @param value\n       */\n    \n      function castDraft(value) {\n        return value;\n      }\n      /**\n       * This function is actually a no-op, but can be used to cast a mutable type\n       * to an immutable type and make TypeScript happy\n       * @param value\n       */\n    \n      function castImmutable(value) {\n        return value;\n      }\n    \n      immer_cjs_development.Immer = Immer;\n      immer_cjs_development.applyPatches = applyPatches;\n      immer_cjs_development.castDraft = castDraft;\n      immer_cjs_development.castImmutable = castImmutable;\n      immer_cjs_development.createDraft = createDraft;\n      immer_cjs_development.current = current;\n      immer_cjs_development.default = produce;\n      immer_cjs_development.enableAllPlugins = enableAllPlugins;\n      immer_cjs_development.enableES5 = enableES5;\n      var enableMapSet_1 = immer_cjs_development.enableMapSet = enableMapSet;\n      immer_cjs_development.enablePatches = enablePatches;\n      immer_cjs_development.finishDraft = finishDraft;\n      immer_cjs_development.immerable = DRAFTABLE;\n      immer_cjs_development.isDraft = isDraft;\n      immer_cjs_development.isDraftable = isDraftable;\n      immer_cjs_development.nothing = NOTHING;\n      immer_cjs_development.original = original;\n      var produce_1 = immer_cjs_development.produce = produce;\n      immer_cjs_development.produceWithPatches = produceWithPatches;\n      var setAutoFreeze_1 = immer_cjs_development.setAutoFreeze = setAutoFreeze;\n      immer_cjs_development.setUseProxies = setUseProxies;\n    \n      var rtc = {exports: {}};\n    \n      /**\n       * \n       * Copyright (c) 2018 Apple (http://www.apple.com)\n       * \n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       * \n       *     http://www.apache.org/licenses/LICENSE-2.0\n       * \n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       * \n       * \n       * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n       * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n       * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n       * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n       * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n       * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n       * THE SOFTWARE.\n       * \n       */\n    \n      (function (module, exports) {\n      /*! Modules included in this bundle:\n       * name: process\n       *   license: MIT\n       *   version: 0.11.10\n       *   text: \n       *     (The MIT License)\n       *     \n       *     Copyright (c) 2013 Roman Shtylman <shtylman@gmail.com>\n       *     \n       *     Permission is hereby granted, free of charge, to any person obtaining\n       *     a copy of this software and associated documentation files (the\n       *     'Software'), to deal in the Software without restriction, including\n       *     without limitation the rights to use, copy, modify, merge, publish,\n       *     distribute, sublicense, and/or sell copies of the Software, and to\n       *     permit persons to whom the Software is furnished to do so, subject to\n       *     the following conditions:\n       *     \n       *     The above copyright notice and this permission notice shall be\n       *     included in all copies or substantial portions of the Software.\n       *     \n       *     THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n       *     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n       *     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n       *     IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n       *     CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n       *     TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n       *     SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n       *     \n       * \n       * name: semver\n       *   license: ISC\n       *   version: 5.5.0\n       *   text: \n       *     The ISC License\n       *     \n       *     Copyright (c) Isaac Z. Schlueter and Contributors\n       *     \n       *     Permission to use, copy, modify, and/or distribute this software for any\n       *     purpose with or without fee is hereby granted, provided that the above\n       *     copyright notice and this permission notice appear in all copies.\n       *     \n       *     THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n       *     WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n       *     MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n       *     ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n       *     WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n       *     ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\n       *     IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n       *     \n       * \n       * name: webpack\n       *   license: MIT\n       *   version: 4.41.2\n       *   text: \n       *     Copyright JS Foundation and other contributors\n       *     \n       *     Permission is hereby granted, free of charge, to any person obtaining\n       *     a copy of this software and associated documentation files (the\n       *     'Software'), to deal in the Software without restriction, including\n       *     without limitation the rights to use, copy, modify, merge, publish,\n       *     distribute, sublicense, and/or sell copies of the Software, and to\n       *     permit persons to whom the Software is furnished to do so, subject to\n       *     the following conditions:\n       *     \n       *     The above copyright notice and this permission notice shall be\n       *     included in all copies or substantial portions of the Software.\n       *     \n       *     THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n       *     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n       *     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n       *     IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n       *     CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n       *     TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n       *     SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n       *     \n       * \n       */\n      (function webpackUniversalModuleDefinition(root, factory) {\n          module.exports = factory();\n      })(commonjsGlobal, function() {\n      return /******/ (function(modules) { // webpackBootstrap\n      /******/ \t// The module cache\n      /******/ \tvar installedModules = {};\n      /******/\n      /******/ \t// The require function\n      /******/ \tfunction __webpack_require__(moduleId) {\n      /******/\n      /******/ \t\t// Check if module is in cache\n      /******/ \t\tif(installedModules[moduleId]) {\n      /******/ \t\t\treturn installedModules[moduleId].exports;\n      /******/ \t\t}\n      /******/ \t\t// Create a new module (and put it into the cache)\n      /******/ \t\tvar module = installedModules[moduleId] = {\n      /******/ \t\t\ti: moduleId,\n      /******/ \t\t\tl: false,\n      /******/ \t\t\texports: {}\n      /******/ \t\t};\n      /******/\n      /******/ \t\t// Execute the module function\n      /******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n      /******/\n      /******/ \t\t// Flag the module as loaded\n      /******/ \t\tmodule.l = true;\n      /******/\n      /******/ \t\t// Return the exports of the module\n      /******/ \t\treturn module.exports;\n      /******/ \t}\n      /******/\n      /******/\n      /******/ \t// expose the modules object (__webpack_modules__)\n      /******/ \t__webpack_require__.m = modules;\n      /******/\n      /******/ \t// expose the module cache\n      /******/ \t__webpack_require__.c = installedModules;\n      /******/\n      /******/ \t// define getter function for harmony exports\n      /******/ \t__webpack_require__.d = function(exports, name, getter) {\n      /******/ \t\tif(!__webpack_require__.o(exports, name)) {\n      /******/ \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n      /******/ \t\t}\n      /******/ \t};\n      /******/\n      /******/ \t// define __esModule on exports\n      /******/ \t__webpack_require__.r = function(exports) {\n      /******/ \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n      /******/ \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n      /******/ \t\t}\n      /******/ \t\tObject.defineProperty(exports, '__esModule', { value: true });\n      /******/ \t};\n      /******/\n      /******/ \t// create a fake namespace object\n      /******/ \t// mode & 1: value is a module id, require it\n      /******/ \t// mode & 2: merge all properties of value into the ns\n      /******/ \t// mode & 4: return value when already ns object\n      /******/ \t// mode & 8|1: behave like require\n      /******/ \t__webpack_require__.t = function(value, mode) {\n      /******/ \t\tif(mode & 1) value = __webpack_require__(value);\n      /******/ \t\tif(mode & 8) return value;\n      /******/ \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n      /******/ \t\tvar ns = Object.create(null);\n      /******/ \t\t__webpack_require__.r(ns);\n      /******/ \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n      /******/ \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n      /******/ \t\treturn ns;\n      /******/ \t};\n      /******/\n      /******/ \t// getDefaultExport function for compatibility with non-harmony modules\n      /******/ \t__webpack_require__.n = function(module) {\n      /******/ \t\tvar getter = module && module.__esModule ?\n      /******/ \t\t\tfunction getDefault() { return module['default']; } :\n      /******/ \t\t\tfunction getModuleExports() { return module; };\n      /******/ \t\t__webpack_require__.d(getter, 'a', getter);\n      /******/ \t\treturn getter;\n      /******/ \t};\n      /******/\n      /******/ \t// Object.prototype.hasOwnProperty.call\n      /******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n      /******/\n      /******/ \t// __webpack_public_path__\n      /******/ \t__webpack_require__.p = \"\";\n      /******/\n      /******/\n      /******/ \t// Load entry module and return exports\n      /******/ \treturn __webpack_require__(__webpack_require__.s = \"./src/rtc_reporting/reporting_agent.ts\");\n      /******/ })\n      /************************************************************************/\n      /******/ ({\n    \n      /***/ \"./node_modules/process/browser.js\":\n      /*!*****************************************!*\\\n        !*** ./node_modules/process/browser.js ***!\n        \\*****************************************/\n      /*! no static exports found */\n      /***/ (function(module, exports) {\n    \n      // shim for using process in browser\n      var process = module.exports = {};\n    \n      // cached from whatever global is present so that test runners that stub it\n      // don't break things.  But we need to wrap it in a try catch in case it is\n      // wrapped in strict mode code which doesn't define any globals.  It's inside a\n      // function because try/catches deoptimize in certain engines.\n    \n      var cachedSetTimeout;\n      var cachedClearTimeout;\n    \n      function defaultSetTimout() {\n          throw new Error('setTimeout has not been defined');\n      }\n      function defaultClearTimeout () {\n          throw new Error('clearTimeout has not been defined');\n      }\n      (function () {\n          try {\n              if (typeof setTimeout === 'function') {\n                  cachedSetTimeout = setTimeout;\n              } else {\n                  cachedSetTimeout = defaultSetTimout;\n              }\n          } catch (e) {\n              cachedSetTimeout = defaultSetTimout;\n          }\n          try {\n              if (typeof clearTimeout === 'function') {\n                  cachedClearTimeout = clearTimeout;\n              } else {\n                  cachedClearTimeout = defaultClearTimeout;\n              }\n          } catch (e) {\n              cachedClearTimeout = defaultClearTimeout;\n          }\n      } ());\n      function runTimeout(fun) {\n          if (cachedSetTimeout === setTimeout) {\n              //normal enviroments in sane situations\n              return setTimeout(fun, 0);\n          }\n          // if setTimeout wasn't available but was latter defined\n          if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n              cachedSetTimeout = setTimeout;\n              return setTimeout(fun, 0);\n          }\n          try {\n              // when when somebody has screwed with setTimeout but no I.E. maddness\n              return cachedSetTimeout(fun, 0);\n          } catch(e){\n              try {\n                  // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n                  return cachedSetTimeout.call(null, fun, 0);\n              } catch(e){\n                  // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n                  return cachedSetTimeout.call(this, fun, 0);\n              }\n          }\n    \n    \n      }\n      function runClearTimeout(marker) {\n          if (cachedClearTimeout === clearTimeout) {\n              //normal enviroments in sane situations\n              return clearTimeout(marker);\n          }\n          // if clearTimeout wasn't available but was latter defined\n          if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n              cachedClearTimeout = clearTimeout;\n              return clearTimeout(marker);\n          }\n          try {\n              // when when somebody has screwed with setTimeout but no I.E. maddness\n              return cachedClearTimeout(marker);\n          } catch (e){\n              try {\n                  // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally\n                  return cachedClearTimeout.call(null, marker);\n              } catch (e){\n                  // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n                  // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n                  return cachedClearTimeout.call(this, marker);\n              }\n          }\n    \n    \n    \n      }\n      var queue = [];\n      var draining = false;\n      var currentQueue;\n      var queueIndex = -1;\n    \n      function cleanUpNextTick() {\n          if (!draining || !currentQueue) {\n              return;\n          }\n          draining = false;\n          if (currentQueue.length) {\n              queue = currentQueue.concat(queue);\n          } else {\n              queueIndex = -1;\n          }\n          if (queue.length) {\n              drainQueue();\n          }\n      }\n    \n      function drainQueue() {\n          if (draining) {\n              return;\n          }\n          var timeout = runTimeout(cleanUpNextTick);\n          draining = true;\n    \n          var len = queue.length;\n          while(len) {\n              currentQueue = queue;\n              queue = [];\n              while (++queueIndex < len) {\n                  if (currentQueue) {\n                      currentQueue[queueIndex].run();\n                  }\n              }\n              queueIndex = -1;\n              len = queue.length;\n          }\n          currentQueue = null;\n          draining = false;\n          runClearTimeout(timeout);\n      }\n    \n      process.nextTick = function (fun) {\n          var args = new Array(arguments.length - 1);\n          if (arguments.length > 1) {\n              for (var i = 1; i < arguments.length; i++) {\n                  args[i - 1] = arguments[i];\n              }\n          }\n          queue.push(new Item(fun, args));\n          if (queue.length === 1 && !draining) {\n              runTimeout(drainQueue);\n          }\n      };\n    \n      // v8 likes predictible objects\n      function Item(fun, array) {\n          this.fun = fun;\n          this.array = array;\n      }\n      Item.prototype.run = function () {\n          this.fun.apply(null, this.array);\n      };\n      process.title = 'browser';\n      process.browser = true;\n      process.env = {};\n      process.argv = [];\n      process.version = ''; // empty string to avoid regexp issues\n      process.versions = {};\n    \n      function noop() {}\n    \n      process.on = noop;\n      process.addListener = noop;\n      process.once = noop;\n      process.off = noop;\n      process.removeListener = noop;\n      process.removeAllListeners = noop;\n      process.emit = noop;\n      process.prependListener = noop;\n      process.prependOnceListener = noop;\n    \n      process.listeners = function (name) { return [] };\n    \n      process.binding = function (name) {\n          throw new Error('process.binding is not supported');\n      };\n    \n      process.cwd = function () { return '/' };\n      process.chdir = function (dir) {\n          throw new Error('process.chdir is not supported');\n      };\n      process.umask = function() { return 0; };\n    \n    \n      /***/ }),\n    \n      /***/ \"./node_modules/semver/semver.js\":\n      /*!***************************************!*\\\n        !*** ./node_modules/semver/semver.js ***!\n        \\***************************************/\n      /*! no static exports found */\n      /***/ (function(module, exports, __webpack_require__) {\n    \n      /* WEBPACK VAR INJECTION */(function(process) {exports = module.exports = SemVer;\n    \n      // The debug function is excluded entirely from the minified version.\n      /* nomin */ var debug;\n      /* nomin */ if (typeof process === 'object' &&\n          /* nomin */ process.env &&\n          /* nomin */ process.env.NODE_DEBUG &&\n          /* nomin */ /\\bsemver\\b/i.test(process.env.NODE_DEBUG))\n        /* nomin */ debug = function() {\n          /* nomin */ var args = Array.prototype.slice.call(arguments, 0);\n          /* nomin */ args.unshift('SEMVER');\n          /* nomin */ console.log.apply(console, args);\n          /* nomin */ };\n      /* nomin */ else\n        /* nomin */ debug = function() {};\n    \n      // Note: this is the semver.org version of the spec that it implements\n      // Not necessarily the package version of this code.\n      exports.SEMVER_SPEC_VERSION = '2.0.0';\n    \n      var MAX_LENGTH = 256;\n      var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n    \n      // Max safe segment length for coercion.\n      var MAX_SAFE_COMPONENT_LENGTH = 16;\n    \n      // The actual regexps go on exports.re\n      var re = exports.re = [];\n      var src = exports.src = [];\n      var R = 0;\n    \n      // The following Regular Expressions can be used for tokenizing,\n      // validating, and parsing SemVer version strings.\n    \n      // ## Numeric Identifier\n      // A single `0`, or a non-zero digit followed by zero or more digits.\n    \n      var NUMERICIDENTIFIER = R++;\n      src[NUMERICIDENTIFIER] = '0|[1-9]\\\\d*';\n      var NUMERICIDENTIFIERLOOSE = R++;\n      src[NUMERICIDENTIFIERLOOSE] = '[0-9]+';\n    \n    \n      // ## Non-numeric Identifier\n      // Zero or more digits, followed by a letter or hyphen, and then zero or\n      // more letters, digits, or hyphens.\n    \n      var NONNUMERICIDENTIFIER = R++;\n      src[NONNUMERICIDENTIFIER] = '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*';\n    \n    \n      // ## Main Version\n      // Three dot-separated numeric identifiers.\n    \n      var MAINVERSION = R++;\n      src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n                         '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n                         '(' + src[NUMERICIDENTIFIER] + ')';\n    \n      var MAINVERSIONLOOSE = R++;\n      src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n                              '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n                              '(' + src[NUMERICIDENTIFIERLOOSE] + ')';\n    \n      // ## Pre-release Version Identifier\n      // A numeric identifier, or a non-numeric identifier.\n    \n      var PRERELEASEIDENTIFIER = R++;\n      src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +\n                                  '|' + src[NONNUMERICIDENTIFIER] + ')';\n    \n      var PRERELEASEIDENTIFIERLOOSE = R++;\n      src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +\n                                       '|' + src[NONNUMERICIDENTIFIER] + ')';\n    \n    \n      // ## Pre-release Version\n      // Hyphen, followed by one or more dot-separated pre-release version\n      // identifiers.\n    \n      var PRERELEASE = R++;\n      src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +\n                        '(?:\\\\.' + src[PRERELEASEIDENTIFIER] + ')*))';\n    \n      var PRERELEASELOOSE = R++;\n      src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +\n                             '(?:\\\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))';\n    \n      // ## Build Metadata Identifier\n      // Any combination of digits, letters, or hyphens.\n    \n      var BUILDIDENTIFIER = R++;\n      src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+';\n    \n      // ## Build Metadata\n      // Plus sign, followed by one or more period-separated build metadata\n      // identifiers.\n    \n      var BUILD = R++;\n      src[BUILD] = '(?:\\\\+(' + src[BUILDIDENTIFIER] +\n                   '(?:\\\\.' + src[BUILDIDENTIFIER] + ')*))';\n    \n    \n      // ## Full Version String\n      // A main version, followed optionally by a pre-release version and\n      // build metadata.\n    \n      // Note that the only major, minor, patch, and pre-release sections of\n      // the version string are capturing groups.  The build metadata is not a\n      // capturing group, because it should not ever be used in version\n      // comparison.\n    \n      var FULL = R++;\n      var FULLPLAIN = 'v?' + src[MAINVERSION] +\n                      src[PRERELEASE] + '?' +\n                      src[BUILD] + '?';\n    \n      src[FULL] = '^' + FULLPLAIN + '$';\n    \n      // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n      // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n      // common in the npm registry.\n      var LOOSEPLAIN = '[v=\\\\s]*' + src[MAINVERSIONLOOSE] +\n                       src[PRERELEASELOOSE] + '?' +\n                       src[BUILD] + '?';\n    \n      var LOOSE = R++;\n      src[LOOSE] = '^' + LOOSEPLAIN + '$';\n    \n      var GTLT = R++;\n      src[GTLT] = '((?:<|>)?=?)';\n    \n      // Something like \"2.*\" or \"1.2.x\".\n      // Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n      // Only the first item is strictly required.\n      var XRANGEIDENTIFIERLOOSE = R++;\n      src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\\\*';\n      var XRANGEIDENTIFIER = R++;\n      src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\\\*';\n    \n      var XRANGEPLAIN = R++;\n      src[XRANGEPLAIN] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIER] + ')' +\n                         '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n                         '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n                         '(?:' + src[PRERELEASE] + ')?' +\n                         src[BUILD] + '?' +\n                         ')?)?';\n    \n      var XRANGEPLAINLOOSE = R++;\n      src[XRANGEPLAINLOOSE] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n                              '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n                              '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n                              '(?:' + src[PRERELEASELOOSE] + ')?' +\n                              src[BUILD] + '?' +\n                              ')?)?';\n    \n      var XRANGE = R++;\n      src[XRANGE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAIN] + '$';\n      var XRANGELOOSE = R++;\n      src[XRANGELOOSE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAINLOOSE] + '$';\n    \n      // Coercion.\n      // Extract anything that could conceivably be a part of a valid semver\n      var COERCE = R++;\n      src[COERCE] = '(?:^|[^\\\\d])' +\n                    '(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +\n                    '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n                    '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n                    '(?:$|[^\\\\d])';\n    \n      // Tilde ranges.\n      // Meaning is \"reasonably at or greater than\"\n      var LONETILDE = R++;\n      src[LONETILDE] = '(?:~>?)';\n    \n      var TILDETRIM = R++;\n      src[TILDETRIM] = '(\\\\s*)' + src[LONETILDE] + '\\\\s+';\n      re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');\n      var tildeTrimReplace = '$1~';\n    \n      var TILDE = R++;\n      src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';\n      var TILDELOOSE = R++;\n      src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$';\n    \n      // Caret ranges.\n      // Meaning is \"at least and backwards compatible with\"\n      var LONECARET = R++;\n      src[LONECARET] = '(?:\\\\^)';\n    \n      var CARETTRIM = R++;\n      src[CARETTRIM] = '(\\\\s*)' + src[LONECARET] + '\\\\s+';\n      re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');\n      var caretTrimReplace = '$1^';\n    \n      var CARET = R++;\n      src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';\n      var CARETLOOSE = R++;\n      src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$';\n    \n      // A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\n      var COMPARATORLOOSE = R++;\n      src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\\\s*(' + LOOSEPLAIN + ')$|^$';\n      var COMPARATOR = R++;\n      src[COMPARATOR] = '^' + src[GTLT] + '\\\\s*(' + FULLPLAIN + ')$|^$';\n    \n    \n      // An expression to strip any whitespace between the gtlt and the thing\n      // it modifies, so that `> 1.2.3` ==> `>1.2.3`\n      var COMPARATORTRIM = R++;\n      src[COMPARATORTRIM] = '(\\\\s*)' + src[GTLT] +\n                            '\\\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')';\n    \n      // this one has to use the /g flag\n      re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');\n      var comparatorTrimReplace = '$1$2$3';\n    \n    \n      // Something like `1.2.3 - 1.2.4`\n      // Note that these all use the loose form, because they'll be\n      // checked against either the strict or loose comparator form\n      // later.\n      var HYPHENRANGE = R++;\n      src[HYPHENRANGE] = '^\\\\s*(' + src[XRANGEPLAIN] + ')' +\n                         '\\\\s+-\\\\s+' +\n                         '(' + src[XRANGEPLAIN] + ')' +\n                         '\\\\s*$';\n    \n      var HYPHENRANGELOOSE = R++;\n      src[HYPHENRANGELOOSE] = '^\\\\s*(' + src[XRANGEPLAINLOOSE] + ')' +\n                              '\\\\s+-\\\\s+' +\n                              '(' + src[XRANGEPLAINLOOSE] + ')' +\n                              '\\\\s*$';\n    \n      // Star ranges basically just allow anything at all.\n      var STAR = R++;\n      src[STAR] = '(<|>)?=?\\\\s*\\\\*';\n    \n      // Compile to actual regexp objects.\n      // All are flag-free, unless they were created above with a flag.\n      for (var i = 0; i < R; i++) {\n        debug(i, src[i]);\n        if (!re[i])\n          re[i] = new RegExp(src[i]);\n      }\n    \n      exports.parse = parse;\n      function parse(version, loose) {\n        if (version instanceof SemVer)\n          return version;\n    \n        if (typeof version !== 'string')\n          return null;\n    \n        if (version.length > MAX_LENGTH)\n          return null;\n    \n        var r = loose ? re[LOOSE] : re[FULL];\n        if (!r.test(version))\n          return null;\n    \n        try {\n          return new SemVer(version, loose);\n        } catch (er) {\n          return null;\n        }\n      }\n    \n      exports.valid = valid;\n      function valid(version, loose) {\n        var v = parse(version, loose);\n        return v ? v.version : null;\n      }\n    \n    \n      exports.clean = clean;\n      function clean(version, loose) {\n        var s = parse(version.trim().replace(/^[=v]+/, ''), loose);\n        return s ? s.version : null;\n      }\n    \n      exports.SemVer = SemVer;\n    \n      function SemVer(version, loose) {\n        if (version instanceof SemVer) {\n          if (version.loose === loose)\n            return version;\n          else\n            version = version.version;\n        } else if (typeof version !== 'string') {\n          throw new TypeError('Invalid Version: ' + version);\n        }\n    \n        if (version.length > MAX_LENGTH)\n          throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')\n    \n        if (!(this instanceof SemVer))\n          return new SemVer(version, loose);\n    \n        debug('SemVer', version, loose);\n        this.loose = loose;\n        var m = version.trim().match(loose ? re[LOOSE] : re[FULL]);\n    \n        if (!m)\n          throw new TypeError('Invalid Version: ' + version);\n    \n        this.raw = version;\n    \n        // these are actually numbers\n        this.major = +m[1];\n        this.minor = +m[2];\n        this.patch = +m[3];\n    \n        if (this.major > MAX_SAFE_INTEGER || this.major < 0)\n          throw new TypeError('Invalid major version')\n    \n        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0)\n          throw new TypeError('Invalid minor version')\n    \n        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0)\n          throw new TypeError('Invalid patch version')\n    \n        // numberify any prerelease numeric ids\n        if (!m[4])\n          this.prerelease = [];\n        else\n          this.prerelease = m[4].split('.').map(function(id) {\n            if (/^[0-9]+$/.test(id)) {\n              var num = +id;\n              if (num >= 0 && num < MAX_SAFE_INTEGER)\n                return num;\n            }\n            return id;\n          });\n    \n        this.build = m[5] ? m[5].split('.') : [];\n        this.format();\n      }\n    \n      SemVer.prototype.format = function() {\n        this.version = this.major + '.' + this.minor + '.' + this.patch;\n        if (this.prerelease.length)\n          this.version += '-' + this.prerelease.join('.');\n        return this.version;\n      };\n    \n      SemVer.prototype.toString = function() {\n        return this.version;\n      };\n    \n      SemVer.prototype.compare = function(other) {\n        debug('SemVer.compare', this.version, this.loose, other);\n        if (!(other instanceof SemVer))\n          other = new SemVer(other, this.loose);\n    \n        return this.compareMain(other) || this.comparePre(other);\n      };\n    \n      SemVer.prototype.compareMain = function(other) {\n        if (!(other instanceof SemVer))\n          other = new SemVer(other, this.loose);\n    \n        return compareIdentifiers(this.major, other.major) ||\n               compareIdentifiers(this.minor, other.minor) ||\n               compareIdentifiers(this.patch, other.patch);\n      };\n    \n      SemVer.prototype.comparePre = function(other) {\n        if (!(other instanceof SemVer))\n          other = new SemVer(other, this.loose);\n    \n        // NOT having a prerelease is > having one\n        if (this.prerelease.length && !other.prerelease.length)\n          return -1;\n        else if (!this.prerelease.length && other.prerelease.length)\n          return 1;\n        else if (!this.prerelease.length && !other.prerelease.length)\n          return 0;\n    \n        var i = 0;\n        do {\n          var a = this.prerelease[i];\n          var b = other.prerelease[i];\n          debug('prerelease compare', i, a, b);\n          if (a === undefined && b === undefined)\n            return 0;\n          else if (b === undefined)\n            return 1;\n          else if (a === undefined)\n            return -1;\n          else if (a === b)\n            continue;\n          else\n            return compareIdentifiers(a, b);\n        } while (++i);\n      };\n    \n      // preminor will bump the version up to the next minor release, and immediately\n      // down to pre-release. premajor and prepatch work the same way.\n      SemVer.prototype.inc = function(release, identifier) {\n        switch (release) {\n          case 'premajor':\n            this.prerelease.length = 0;\n            this.patch = 0;\n            this.minor = 0;\n            this.major++;\n            this.inc('pre', identifier);\n            break;\n          case 'preminor':\n            this.prerelease.length = 0;\n            this.patch = 0;\n            this.minor++;\n            this.inc('pre', identifier);\n            break;\n          case 'prepatch':\n            // If this is already a prerelease, it will bump to the next version\n            // drop any prereleases that might already exist, since they are not\n            // relevant at this point.\n            this.prerelease.length = 0;\n            this.inc('patch', identifier);\n            this.inc('pre', identifier);\n            break;\n          // If the input is a non-prerelease version, this acts the same as\n          // prepatch.\n          case 'prerelease':\n            if (this.prerelease.length === 0)\n              this.inc('patch', identifier);\n            this.inc('pre', identifier);\n            break;\n    \n          case 'major':\n            // If this is a pre-major version, bump up to the same major version.\n            // Otherwise increment major.\n            // 1.0.0-5 bumps to 1.0.0\n            // 1.1.0 bumps to 2.0.0\n            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0)\n              this.major++;\n            this.minor = 0;\n            this.patch = 0;\n            this.prerelease = [];\n            break;\n          case 'minor':\n            // If this is a pre-minor version, bump up to the same minor version.\n            // Otherwise increment minor.\n            // 1.2.0-5 bumps to 1.2.0\n            // 1.2.1 bumps to 1.3.0\n            if (this.patch !== 0 || this.prerelease.length === 0)\n              this.minor++;\n            this.patch = 0;\n            this.prerelease = [];\n            break;\n          case 'patch':\n            // If this is not a pre-release version, it will increment the patch.\n            // If it is a pre-release it will bump up to the same patch version.\n            // 1.2.0-5 patches to 1.2.0\n            // 1.2.0 patches to 1.2.1\n            if (this.prerelease.length === 0)\n              this.patch++;\n            this.prerelease = [];\n            break;\n          // This probably shouldn't be used publicly.\n          // 1.0.0 \"pre\" would become 1.0.0-0 which is the wrong direction.\n          case 'pre':\n            if (this.prerelease.length === 0)\n              this.prerelease = [0];\n            else {\n              var i = this.prerelease.length;\n              while (--i >= 0) {\n                if (typeof this.prerelease[i] === 'number') {\n                  this.prerelease[i]++;\n                  i = -2;\n                }\n              }\n              if (i === -1) // didn't increment anything\n                this.prerelease.push(0);\n            }\n            if (identifier) {\n              // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n              // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n              if (this.prerelease[0] === identifier) {\n                if (isNaN(this.prerelease[1]))\n                  this.prerelease = [identifier, 0];\n              } else\n                this.prerelease = [identifier, 0];\n            }\n            break;\n    \n          default:\n            throw new Error('invalid increment argument: ' + release);\n        }\n        this.format();\n        this.raw = this.version;\n        return this;\n      };\n    \n      exports.inc = inc;\n      function inc(version, release, loose, identifier) {\n        if (typeof(loose) === 'string') {\n          identifier = loose;\n          loose = undefined;\n        }\n    \n        try {\n          return new SemVer(version, loose).inc(release, identifier).version;\n        } catch (er) {\n          return null;\n        }\n      }\n    \n      exports.diff = diff;\n      function diff(version1, version2) {\n        if (eq(version1, version2)) {\n          return null;\n        } else {\n          var v1 = parse(version1);\n          var v2 = parse(version2);\n          if (v1.prerelease.length || v2.prerelease.length) {\n            for (var key in v1) {\n              if (key === 'major' || key === 'minor' || key === 'patch') {\n                if (v1[key] !== v2[key]) {\n                  return 'pre'+key;\n                }\n              }\n            }\n            return 'prerelease';\n          }\n          for (var key in v1) {\n            if (key === 'major' || key === 'minor' || key === 'patch') {\n              if (v1[key] !== v2[key]) {\n                return key;\n              }\n            }\n          }\n        }\n      }\n    \n      exports.compareIdentifiers = compareIdentifiers;\n    \n      var numeric = /^[0-9]+$/;\n      function compareIdentifiers(a, b) {\n        var anum = numeric.test(a);\n        var bnum = numeric.test(b);\n    \n        if (anum && bnum) {\n          a = +a;\n          b = +b;\n        }\n    \n        return (anum && !bnum) ? -1 :\n               (bnum && !anum) ? 1 :\n               a < b ? -1 :\n               a > b ? 1 :\n               0;\n      }\n    \n      exports.rcompareIdentifiers = rcompareIdentifiers;\n      function rcompareIdentifiers(a, b) {\n        return compareIdentifiers(b, a);\n      }\n    \n      exports.major = major;\n      function major(a, loose) {\n        return new SemVer(a, loose).major;\n      }\n    \n      exports.minor = minor;\n      function minor(a, loose) {\n        return new SemVer(a, loose).minor;\n      }\n    \n      exports.patch = patch;\n      function patch(a, loose) {\n        return new SemVer(a, loose).patch;\n      }\n    \n      exports.compare = compare;\n      function compare(a, b, loose) {\n        return new SemVer(a, loose).compare(new SemVer(b, loose));\n      }\n    \n      exports.compareLoose = compareLoose;\n      function compareLoose(a, b) {\n        return compare(a, b, true);\n      }\n    \n      exports.rcompare = rcompare;\n      function rcompare(a, b, loose) {\n        return compare(b, a, loose);\n      }\n    \n      exports.sort = sort;\n      function sort(list, loose) {\n        return list.sort(function(a, b) {\n          return exports.compare(a, b, loose);\n        });\n      }\n    \n      exports.rsort = rsort;\n      function rsort(list, loose) {\n        return list.sort(function(a, b) {\n          return exports.rcompare(a, b, loose);\n        });\n      }\n    \n      exports.gt = gt;\n      function gt(a, b, loose) {\n        return compare(a, b, loose) > 0;\n      }\n    \n      exports.lt = lt;\n      function lt(a, b, loose) {\n        return compare(a, b, loose) < 0;\n      }\n    \n      exports.eq = eq;\n      function eq(a, b, loose) {\n        return compare(a, b, loose) === 0;\n      }\n    \n      exports.neq = neq;\n      function neq(a, b, loose) {\n        return compare(a, b, loose) !== 0;\n      }\n    \n      exports.gte = gte;\n      function gte(a, b, loose) {\n        return compare(a, b, loose) >= 0;\n      }\n    \n      exports.lte = lte;\n      function lte(a, b, loose) {\n        return compare(a, b, loose) <= 0;\n      }\n    \n      exports.cmp = cmp;\n      function cmp(a, op, b, loose) {\n        var ret;\n        switch (op) {\n          case '===':\n            if (typeof a === 'object') a = a.version;\n            if (typeof b === 'object') b = b.version;\n            ret = a === b;\n            break;\n          case '!==':\n            if (typeof a === 'object') a = a.version;\n            if (typeof b === 'object') b = b.version;\n            ret = a !== b;\n            break;\n          case '': case '=': case '==': ret = eq(a, b, loose); break;\n          case '!=': ret = neq(a, b, loose); break;\n          case '>': ret = gt(a, b, loose); break;\n          case '>=': ret = gte(a, b, loose); break;\n          case '<': ret = lt(a, b, loose); break;\n          case '<=': ret = lte(a, b, loose); break;\n          default: throw new TypeError('Invalid operator: ' + op);\n        }\n        return ret;\n      }\n    \n      exports.Comparator = Comparator;\n      function Comparator(comp, loose) {\n        if (comp instanceof Comparator) {\n          if (comp.loose === loose)\n            return comp;\n          else\n            comp = comp.value;\n        }\n    \n        if (!(this instanceof Comparator))\n          return new Comparator(comp, loose);\n    \n        debug('comparator', comp, loose);\n        this.loose = loose;\n        this.parse(comp);\n    \n        if (this.semver === ANY)\n          this.value = '';\n        else\n          this.value = this.operator + this.semver.version;\n    \n        debug('comp', this);\n      }\n    \n      var ANY = {};\n      Comparator.prototype.parse = function(comp) {\n        var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];\n        var m = comp.match(r);\n    \n        if (!m)\n          throw new TypeError('Invalid comparator: ' + comp);\n    \n        this.operator = m[1];\n        if (this.operator === '=')\n          this.operator = '';\n    \n        // if it literally is just '>' or '' then allow anything.\n        if (!m[2])\n          this.semver = ANY;\n        else\n          this.semver = new SemVer(m[2], this.loose);\n      };\n    \n      Comparator.prototype.toString = function() {\n        return this.value;\n      };\n    \n      Comparator.prototype.test = function(version) {\n        debug('Comparator.test', version, this.loose);\n    \n        if (this.semver === ANY)\n          return true;\n    \n        if (typeof version === 'string')\n          version = new SemVer(version, this.loose);\n    \n        return cmp(version, this.operator, this.semver, this.loose);\n      };\n    \n      Comparator.prototype.intersects = function(comp, loose) {\n        if (!(comp instanceof Comparator)) {\n          throw new TypeError('a Comparator is required');\n        }\n    \n        var rangeTmp;\n    \n        if (this.operator === '') {\n          rangeTmp = new Range(comp.value, loose);\n          return satisfies(this.value, rangeTmp, loose);\n        } else if (comp.operator === '') {\n          rangeTmp = new Range(this.value, loose);\n          return satisfies(comp.semver, rangeTmp, loose);\n        }\n    \n        var sameDirectionIncreasing =\n          (this.operator === '>=' || this.operator === '>') &&\n          (comp.operator === '>=' || comp.operator === '>');\n        var sameDirectionDecreasing =\n          (this.operator === '<=' || this.operator === '<') &&\n          (comp.operator === '<=' || comp.operator === '<');\n        var sameSemVer = this.semver.version === comp.semver.version;\n        var differentDirectionsInclusive =\n          (this.operator === '>=' || this.operator === '<=') &&\n          (comp.operator === '>=' || comp.operator === '<=');\n        var oppositeDirectionsLessThan =\n          cmp(this.semver, '<', comp.semver, loose) &&\n          ((this.operator === '>=' || this.operator === '>') &&\n          (comp.operator === '<=' || comp.operator === '<'));\n        var oppositeDirectionsGreaterThan =\n          cmp(this.semver, '>', comp.semver, loose) &&\n          ((this.operator === '<=' || this.operator === '<') &&\n          (comp.operator === '>=' || comp.operator === '>'));\n    \n        return sameDirectionIncreasing || sameDirectionDecreasing ||\n          (sameSemVer && differentDirectionsInclusive) ||\n          oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;\n      };\n    \n    \n      exports.Range = Range;\n      function Range(range, loose) {\n        if (range instanceof Range) {\n          if (range.loose === loose) {\n            return range;\n          } else {\n            return new Range(range.raw, loose);\n          }\n        }\n    \n        if (range instanceof Comparator) {\n          return new Range(range.value, loose);\n        }\n    \n        if (!(this instanceof Range))\n          return new Range(range, loose);\n    \n        this.loose = loose;\n    \n        // First, split based on boolean or ||\n        this.raw = range;\n        this.set = range.split(/\\s*\\|\\|\\s*/).map(function(range) {\n          return this.parseRange(range.trim());\n        }, this).filter(function(c) {\n          // throw out any that are not relevant for whatever reason\n          return c.length;\n        });\n    \n        if (!this.set.length) {\n          throw new TypeError('Invalid SemVer Range: ' + range);\n        }\n    \n        this.format();\n      }\n    \n      Range.prototype.format = function() {\n        this.range = this.set.map(function(comps) {\n          return comps.join(' ').trim();\n        }).join('||').trim();\n        return this.range;\n      };\n    \n      Range.prototype.toString = function() {\n        return this.range;\n      };\n    \n      Range.prototype.parseRange = function(range) {\n        var loose = this.loose;\n        range = range.trim();\n        debug('range', range, loose);\n        // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n        var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];\n        range = range.replace(hr, hyphenReplace);\n        debug('hyphen replace', range);\n        // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n        range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);\n        debug('comparator trim', range, re[COMPARATORTRIM]);\n    \n        // `~ 1.2.3` => `~1.2.3`\n        range = range.replace(re[TILDETRIM], tildeTrimReplace);\n    \n        // `^ 1.2.3` => `^1.2.3`\n        range = range.replace(re[CARETTRIM], caretTrimReplace);\n    \n        // normalize spaces\n        range = range.split(/\\s+/).join(' ');\n    \n        // At this point, the range is completely trimmed and\n        // ready to be split into comparators.\n    \n        var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];\n        var set = range.split(' ').map(function(comp) {\n          return parseComparator(comp, loose);\n        }).join(' ').split(/\\s+/);\n        if (this.loose) {\n          // in loose mode, throw out any that are not valid comparators\n          set = set.filter(function(comp) {\n            return !!comp.match(compRe);\n          });\n        }\n        set = set.map(function(comp) {\n          return new Comparator(comp, loose);\n        });\n    \n        return set;\n      };\n    \n      Range.prototype.intersects = function(range, loose) {\n        if (!(range instanceof Range)) {\n          throw new TypeError('a Range is required');\n        }\n    \n        return this.set.some(function(thisComparators) {\n          return thisComparators.every(function(thisComparator) {\n            return range.set.some(function(rangeComparators) {\n              return rangeComparators.every(function(rangeComparator) {\n                return thisComparator.intersects(rangeComparator, loose);\n              });\n            });\n          });\n        });\n      };\n    \n      // Mostly just for testing and legacy API reasons\n      exports.toComparators = toComparators;\n      function toComparators(range, loose) {\n        return new Range(range, loose).set.map(function(comp) {\n          return comp.map(function(c) {\n            return c.value;\n          }).join(' ').trim().split(' ');\n        });\n      }\n    \n      // comprised of xranges, tildes, stars, and gtlt's at this point.\n      // already replaced the hyphen ranges\n      // turn into a set of JUST comparators.\n      function parseComparator(comp, loose) {\n        debug('comp', comp);\n        comp = replaceCarets(comp, loose);\n        debug('caret', comp);\n        comp = replaceTildes(comp, loose);\n        debug('tildes', comp);\n        comp = replaceXRanges(comp, loose);\n        debug('xrange', comp);\n        comp = replaceStars(comp, loose);\n        debug('stars', comp);\n        return comp;\n      }\n    \n      function isX(id) {\n        return !id || id.toLowerCase() === 'x' || id === '*';\n      }\n    \n      // ~, ~> --> * (any, kinda silly)\n      // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0\n      // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0\n      // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0\n      // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0\n      // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0\n      function replaceTildes(comp, loose) {\n        return comp.trim().split(/\\s+/).map(function(comp) {\n          return replaceTilde(comp, loose);\n        }).join(' ');\n      }\n    \n      function replaceTilde(comp, loose) {\n        var r = loose ? re[TILDELOOSE] : re[TILDE];\n        return comp.replace(r, function(_, M, m, p, pr) {\n          debug('tilde', comp, _, M, m, p, pr);\n          var ret;\n    \n          if (isX(M))\n            ret = '';\n          else if (isX(m))\n            ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';\n          else if (isX(p))\n            // ~1.2 == >=1.2.0 <1.3.0\n            ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';\n          else if (pr) {\n            debug('replaceTilde pr', pr);\n            if (pr.charAt(0) !== '-')\n              pr = '-' + pr;\n            ret = '>=' + M + '.' + m + '.' + p + pr +\n                  ' <' + M + '.' + (+m + 1) + '.0';\n          } else\n            // ~1.2.3 == >=1.2.3 <1.3.0\n            ret = '>=' + M + '.' + m + '.' + p +\n                  ' <' + M + '.' + (+m + 1) + '.0';\n    \n          debug('tilde return', ret);\n          return ret;\n        });\n      }\n    \n      // ^ --> * (any, kinda silly)\n      // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0\n      // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0\n      // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0\n      // ^1.2.3 --> >=1.2.3 <2.0.0\n      // ^1.2.0 --> >=1.2.0 <2.0.0\n      function replaceCarets(comp, loose) {\n        return comp.trim().split(/\\s+/).map(function(comp) {\n          return replaceCaret(comp, loose);\n        }).join(' ');\n      }\n    \n      function replaceCaret(comp, loose) {\n        debug('caret', comp, loose);\n        var r = loose ? re[CARETLOOSE] : re[CARET];\n        return comp.replace(r, function(_, M, m, p, pr) {\n          debug('caret', comp, _, M, m, p, pr);\n          var ret;\n    \n          if (isX(M))\n            ret = '';\n          else if (isX(m))\n            ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';\n          else if (isX(p)) {\n            if (M === '0')\n              ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';\n            else\n              ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';\n          } else if (pr) {\n            debug('replaceCaret pr', pr);\n            if (pr.charAt(0) !== '-')\n              pr = '-' + pr;\n            if (M === '0') {\n              if (m === '0')\n                ret = '>=' + M + '.' + m + '.' + p + pr +\n                      ' <' + M + '.' + m + '.' + (+p + 1);\n              else\n                ret = '>=' + M + '.' + m + '.' + p + pr +\n                      ' <' + M + '.' + (+m + 1) + '.0';\n            } else\n              ret = '>=' + M + '.' + m + '.' + p + pr +\n                    ' <' + (+M + 1) + '.0.0';\n          } else {\n            debug('no pr');\n            if (M === '0') {\n              if (m === '0')\n                ret = '>=' + M + '.' + m + '.' + p +\n                      ' <' + M + '.' + m + '.' + (+p + 1);\n              else\n                ret = '>=' + M + '.' + m + '.' + p +\n                      ' <' + M + '.' + (+m + 1) + '.0';\n            } else\n              ret = '>=' + M + '.' + m + '.' + p +\n                    ' <' + (+M + 1) + '.0.0';\n          }\n    \n          debug('caret return', ret);\n          return ret;\n        });\n      }\n    \n      function replaceXRanges(comp, loose) {\n        debug('replaceXRanges', comp, loose);\n        return comp.split(/\\s+/).map(function(comp) {\n          return replaceXRange(comp, loose);\n        }).join(' ');\n      }\n    \n      function replaceXRange(comp, loose) {\n        comp = comp.trim();\n        var r = loose ? re[XRANGELOOSE] : re[XRANGE];\n        return comp.replace(r, function(ret, gtlt, M, m, p, pr) {\n          debug('xRange', comp, ret, gtlt, M, m, p, pr);\n          var xM = isX(M);\n          var xm = xM || isX(m);\n          var xp = xm || isX(p);\n          var anyX = xp;\n    \n          if (gtlt === '=' && anyX)\n            gtlt = '';\n    \n          if (xM) {\n            if (gtlt === '>' || gtlt === '<') {\n              // nothing is allowed\n              ret = '<0.0.0';\n            } else {\n              // nothing is forbidden\n              ret = '*';\n            }\n          } else if (gtlt && anyX) {\n            // replace X with 0\n            if (xm)\n              m = 0;\n            if (xp)\n              p = 0;\n    \n            if (gtlt === '>') {\n              // >1 => >=2.0.0\n              // >1.2 => >=1.3.0\n              // >1.2.3 => >= 1.2.4\n              gtlt = '>=';\n              if (xm) {\n                M = +M + 1;\n                m = 0;\n                p = 0;\n              } else if (xp) {\n                m = +m + 1;\n                p = 0;\n              }\n            } else if (gtlt === '<=') {\n              // <=0.7.x is actually <0.8.0, since any 0.7.x should\n              // pass.  Similarly, <=7.x is actually <8.0.0, etc.\n              gtlt = '<';\n              if (xm)\n                M = +M + 1;\n              else\n                m = +m + 1;\n            }\n    \n            ret = gtlt + M + '.' + m + '.' + p;\n          } else if (xm) {\n            ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';\n          } else if (xp) {\n            ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';\n          }\n    \n          debug('xRange return', ret);\n    \n          return ret;\n        });\n      }\n    \n      // Because * is AND-ed with everything else in the comparator,\n      // and '' means \"any version\", just remove the *s entirely.\n      function replaceStars(comp, loose) {\n        debug('replaceStars', comp, loose);\n        // Looseness is ignored here.  star is always as loose as it gets!\n        return comp.trim().replace(re[STAR], '');\n      }\n    \n      // This function is passed to string.replace(re[HYPHENRANGE])\n      // M, m, patch, prerelease, build\n      // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n      // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do\n      // 1.2 - 3.4 => >=1.2.0 <3.5.0\n      function hyphenReplace($0,\n                             from, fM, fm, fp, fpr, fb,\n                             to, tM, tm, tp, tpr, tb) {\n    \n        if (isX(fM))\n          from = '';\n        else if (isX(fm))\n          from = '>=' + fM + '.0.0';\n        else if (isX(fp))\n          from = '>=' + fM + '.' + fm + '.0';\n        else\n          from = '>=' + from;\n    \n        if (isX(tM))\n          to = '';\n        else if (isX(tm))\n          to = '<' + (+tM + 1) + '.0.0';\n        else if (isX(tp))\n          to = '<' + tM + '.' + (+tm + 1) + '.0';\n        else if (tpr)\n          to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;\n        else\n          to = '<=' + to;\n    \n        return (from + ' ' + to).trim();\n      }\n    \n    \n      // if ANY of the sets match ALL of its comparators, then pass\n      Range.prototype.test = function(version) {\n        if (!version)\n          return false;\n    \n        if (typeof version === 'string')\n          version = new SemVer(version, this.loose);\n    \n        for (var i = 0; i < this.set.length; i++) {\n          if (testSet(this.set[i], version))\n            return true;\n        }\n        return false;\n      };\n    \n      function testSet(set, version) {\n        for (var i = 0; i < set.length; i++) {\n          if (!set[i].test(version))\n            return false;\n        }\n    \n        if (version.prerelease.length) {\n          // Find the set of versions that are allowed to have prereleases\n          // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n          // That should allow `1.2.3-pr.2` to pass.\n          // However, `1.2.4-alpha.notready` should NOT be allowed,\n          // even though it's within the range set by the comparators.\n          for (var i = 0; i < set.length; i++) {\n            debug(set[i].semver);\n            if (set[i].semver === ANY)\n              continue;\n    \n            if (set[i].semver.prerelease.length > 0) {\n              var allowed = set[i].semver;\n              if (allowed.major === version.major &&\n                  allowed.minor === version.minor &&\n                  allowed.patch === version.patch)\n                return true;\n            }\n          }\n    \n          // Version has a -pre, but it's not one of the ones we like.\n          return false;\n        }\n    \n        return true;\n      }\n    \n      exports.satisfies = satisfies;\n      function satisfies(version, range, loose) {\n        try {\n          range = new Range(range, loose);\n        } catch (er) {\n          return false;\n        }\n        return range.test(version);\n      }\n    \n      exports.maxSatisfying = maxSatisfying;\n      function maxSatisfying(versions, range, loose) {\n        var max = null;\n        var maxSV = null;\n        try {\n          var rangeObj = new Range(range, loose);\n        } catch (er) {\n          return null;\n        }\n        versions.forEach(function (v) {\n          if (rangeObj.test(v)) { // satisfies(v, range, loose)\n            if (!max || maxSV.compare(v) === -1) { // compare(max, v, true)\n              max = v;\n              maxSV = new SemVer(max, loose);\n            }\n          }\n        });\n        return max;\n      }\n    \n      exports.minSatisfying = minSatisfying;\n      function minSatisfying(versions, range, loose) {\n        var min = null;\n        var minSV = null;\n        try {\n          var rangeObj = new Range(range, loose);\n        } catch (er) {\n          return null;\n        }\n        versions.forEach(function (v) {\n          if (rangeObj.test(v)) { // satisfies(v, range, loose)\n            if (!min || minSV.compare(v) === 1) { // compare(min, v, true)\n              min = v;\n              minSV = new SemVer(min, loose);\n            }\n          }\n        });\n        return min;\n      }\n    \n      exports.validRange = validRange;\n      function validRange(range, loose) {\n        try {\n          // Return '*' instead of '' so that truthiness works.\n          // This will throw if it's invalid anyway\n          return new Range(range, loose).range || '*';\n        } catch (er) {\n          return null;\n        }\n      }\n    \n      // Determine if version is less than all the versions possible in the range\n      exports.ltr = ltr;\n      function ltr(version, range, loose) {\n        return outside(version, range, '<', loose);\n      }\n    \n      // Determine if version is greater than all the versions possible in the range.\n      exports.gtr = gtr;\n      function gtr(version, range, loose) {\n        return outside(version, range, '>', loose);\n      }\n    \n      exports.outside = outside;\n      function outside(version, range, hilo, loose) {\n        version = new SemVer(version, loose);\n        range = new Range(range, loose);\n    \n        var gtfn, ltefn, ltfn, comp, ecomp;\n        switch (hilo) {\n          case '>':\n            gtfn = gt;\n            ltefn = lte;\n            ltfn = lt;\n            comp = '>';\n            ecomp = '>=';\n            break;\n          case '<':\n            gtfn = lt;\n            ltefn = gte;\n            ltfn = gt;\n            comp = '<';\n            ecomp = '<=';\n            break;\n          default:\n            throw new TypeError('Must provide a hilo val of \"<\" or \">\"');\n        }\n    \n        // If it satisifes the range it is not outside\n        if (satisfies(version, range, loose)) {\n          return false;\n        }\n    \n        // From now on, variable terms are as if we're in \"gtr\" mode.\n        // but note that everything is flipped for the \"ltr\" function.\n    \n        for (var i = 0; i < range.set.length; ++i) {\n          var comparators = range.set[i];\n    \n          var high = null;\n          var low = null;\n    \n          comparators.forEach(function(comparator) {\n            if (comparator.semver === ANY) {\n              comparator = new Comparator('>=0.0.0');\n            }\n            high = high || comparator;\n            low = low || comparator;\n            if (gtfn(comparator.semver, high.semver, loose)) {\n              high = comparator;\n            } else if (ltfn(comparator.semver, low.semver, loose)) {\n              low = comparator;\n            }\n          });\n    \n          // If the edge version comparator has a operator then our version\n          // isn't outside it\n          if (high.operator === comp || high.operator === ecomp) {\n            return false;\n          }\n    \n          // If the lowest version comparator has an operator and our version\n          // is less than it then it isn't higher than the range\n          if ((!low.operator || low.operator === comp) &&\n              ltefn(version, low.semver)) {\n            return false;\n          } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n            return false;\n          }\n        }\n        return true;\n      }\n    \n      exports.prerelease = prerelease;\n      function prerelease(version, loose) {\n        var parsed = parse(version, loose);\n        return (parsed && parsed.prerelease.length) ? parsed.prerelease : null;\n      }\n    \n      exports.intersects = intersects;\n      function intersects(r1, r2, loose) {\n        r1 = new Range(r1, loose);\n        r2 = new Range(r2, loose);\n        return r1.intersects(r2)\n      }\n    \n      exports.coerce = coerce;\n      function coerce(version) {\n        if (version instanceof SemVer)\n          return version;\n    \n        if (typeof version !== 'string')\n          return null;\n    \n        var match = version.match(re[COERCE]);\n    \n        if (match == null)\n          return null;\n    \n        return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); \n      }\n    \n      /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ \"./node_modules/process/browser.js\")));\n    \n      /***/ }),\n    \n      /***/ \"./node_modules/webpack/buildin/harmony-module.js\":\n      /*!*******************************************!*\\\n        !*** (webpack)/buildin/harmony-module.js ***!\n        \\*******************************************/\n      /*! no static exports found */\n      /***/ (function(module, exports) {\n    \n      module.exports = function(originalModule) {\n          if (!originalModule.webpackPolyfill) {\n              var module = Object.create(originalModule);\n              // module.parent = undefined by default\n              if (!module.children) module.children = [];\n              Object.defineProperty(module, \"loaded\", {\n                  enumerable: true,\n                  get: function() {\n                      return module.l;\n                  }\n              });\n              Object.defineProperty(module, \"id\", {\n                  enumerable: true,\n                  get: function() {\n                      return module.i;\n                  }\n              });\n              Object.defineProperty(module, \"exports\", {\n                  enumerable: true\n              });\n              module.webpackPolyfill = 1;\n          }\n          return module;\n      };\n    \n    \n      /***/ }),\n    \n      /***/ \"./src/rtc_reporting/reporting_agent.ts\":\n      /*!**********************************************!*\\\n        !*** ./src/rtc_reporting/reporting_agent.ts ***!\n        \\**********************************************/\n      /*! exports provided: default */\n      /***/ (function(module, __webpack_exports__, __webpack_require__) {\n      __webpack_require__.r(__webpack_exports__);\n      /* harmony import */ var _reporting_reporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reporting_reporter */ \"./src/rtc_reporting/reporting_reporter.ts\");\n      /* harmony import */ var _reporting_event__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reporting_event */ \"./src/rtc_reporting/reporting_event.ts\");\n      /* harmony import */ var _reporting_storebag__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./reporting_storebag */ \"./src/rtc_reporting/reporting_storebag.ts\");\n      /* harmony import */ var _reporting_config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./reporting_config */ \"./src/rtc_reporting/reporting_config.ts\");\n    \n    \n    \n      const { RTCReportingStoreBag } = _reporting_storebag__WEBPACK_IMPORTED_MODULE_2__;\n      const ReportingVersion = '1';\n    \n      class RTCObjectRef {\n          constructor(objectNotToDestroy = null) {\n              this._objectNotToDestroy = objectNotToDestroy;\n              this._objectToDestroy = null;\n          }\n          addInstantiatedObject(objectToDestroy) {\n              this._objectNotToDestroy = this._objectToDestroy = objectToDestroy;\n          }\n          get instance() {\n              return this._objectNotToDestroy;\n          }\n          destroy() {\n              if (this._objectToDestroy) {\n                  this._objectToDestroy.destroy();\n              }\n              this._objectNotToDestroy = this._objectNotToDestroy = null;\n          }\n      }\n      class RTCReportingAgent {\n          constructor(reportingConfig = {}) {\n              this._sessionInfo = {};\n              this._reportingDisabled = false;\n              this.storebag = new RTCObjectRef();\n              this.reporter = null;\n              this.reportingVersion = ReportingVersion;\n              this.fuzzFactor = 0;\n              this.sessionStartTime = 0;\n              this._initializeReportingAgent(reportingConfig);\n          }\n          destroy() {\n              this.endSession();\n          }\n          get ReportingAllowed() {\n              return !(this._reportingDisabled);\n          }\n          static get version() {\n              return \"0.1.36\";\n          }\n          issueReportingEvent(eventID, eventPayload, eventType = _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentEventTypes\"].BatchEvent) {\n              let error = null;\n              if (this.ReportingAllowed && this.reporter) {\n                  let event = new _reporting_event__WEBPACK_IMPORTED_MODULE_1__[\"RTCReportingEvent\"](eventID, _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingSessionEventStatus\"].EventStatusSessionBegin, eventPayload, this._FuzzFactor, eventType);\n                  error = this.reporter.issueReportingEvent(event, this._sessionInfo);\n              }\n              else {\n                  error = new _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingError\"]('Reporting not allowed.');\n              }\n              return error;\n          }\n          endSession() {\n              if (this.ReportingAllowed && this.reporter) {\n                  this._issueSessionEndEvent();\n                  this.reporter.flushAllEvents();\n              }\n              this._sessionInfo = null;\n              this.reporter = null;\n              this.storebag.destroy();\n              this.storebag = null;\n          }\n          set SessionInfo(session_info) {\n              this._sessionInfo = session_info;\n          }\n          get SessionInfo() {\n              return this._sessionInfo;\n          }\n          get SessionID() {\n              if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SessionID in this._sessionInfo) {\n                  return this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SessionID];\n              }\n              return '';\n          }\n          get ClientName() {\n              if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ClientName in this._sessionInfo) {\n                  return this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ClientName];\n              }\n              return '';\n          }\n          get ServiceName() {\n              if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceName in this._sessionInfo) {\n                  return this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceName];\n              }\n              return '';\n          }\n          get _FuzzFactor() {\n              return this.fuzzFactor;\n          }\n          _initializeReportingAgent(reportingConfig) {\n              let clientName = null;\n              let serviceName = null;\n              let applicationName = '';\n              let sender = null;\n              let deviceName = null;\n              let osVersion = null;\n              let storebagURL = null;\n              let reportingDisabled = false;\n              let startTime = (new Date()).getTime();\n              let hlsEventEmitter = null;\n              let sessionID = null;\n              let userInfoDict = null;\n              let senderOSVersion = null;\n              let storeBag = null;\n              let senderServiceID = null;\n              let senderAltConfig = null;\n              let useHTTPHeaders = null;\n              if (!this._sessionInfo) {\n                  this._sessionInfo = {};\n              }\n              if (reportingConfig) {\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ClientName in reportingConfig) {\n                      clientName = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ClientName];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceName in reportingConfig) {\n                      serviceName = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceName];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ApplicationName in reportingConfig) {\n                      applicationName = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ApplicationName];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].Sender in reportingConfig) {\n                      sender = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].Sender];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].OSVersion in reportingConfig) {\n                      osVersion = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].OSVersion];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].StorebagURL in reportingConfig) {\n                      storebagURL = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].StorebagURL];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].DeviceName in reportingConfig) {\n                      deviceName = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].DeviceName];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ReportingDisabled in reportingConfig) {\n                      reportingDisabled = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ReportingDisabled];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].HLSEventEmitter in reportingConfig) {\n                      hlsEventEmitter = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].HLSEventEmitter];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SessionID in reportingConfig) {\n                      sessionID = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SessionID];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].UserInfoDict in reportingConfig) {\n                      userInfoDict = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].UserInfoDict];\n                      if (userInfoDict && _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].SenderAltConfig in userInfoDict) {\n                          senderAltConfig = userInfoDict[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].SenderAltConfig];\n                          delete userInfoDict[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].SenderAltConfig];\n                          if (senderAltConfig) {\n                              if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceIdentifier in senderAltConfig) {\n                                  senderServiceID = senderAltConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceIdentifier];\n                              }\n                              if (Object.keys(senderAltConfig)) {\n                                  Object.assign(userInfoDict, senderAltConfig);\n                              }\n                          }\n                      }\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SenderOSVersion in reportingConfig) {\n                      senderOSVersion = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SenderOSVersion];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ReportingStoreBag in reportingConfig) {\n                      storeBag = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ReportingStoreBag];\n                  }\n                  if (_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].UseHTTPHeaders in reportingConfig) {\n                      useHTTPHeaders = reportingConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].UseHTTPHeaders];\n                  }\n              }\n              if (!sessionID) {\n                  sessionID = RTCReportingAgent._createSessionID();\n              }\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ClientName] = clientName;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceName] = serviceName;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ApplicationName] = applicationName;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].DeviceName] = deviceName;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].OSVersion] = osVersion;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].Sender] = sender;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].RTCSchemeVersion] = this.reportingVersion;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].RTCReportingVersion] = RTCReportingAgent.version;\n              this._reportingDisabled = reportingDisabled;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SessionID] = sessionID;\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"].SenderOSVersion] = senderOSVersion;\n              if (applicationName && serviceName) {\n                  serviceName = serviceName + '.' + applicationName;\n              }\n              if (senderServiceID && serviceName) {\n                  serviceName = serviceName + '.' + senderServiceID;\n              }\n              this._sessionInfo[_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"].ServiceName] = serviceName;\n              this.fuzzFactor = startTime - Math.floor(startTime / 60000) * 60000;\n              this.sessionStartTime = startTime - this.fuzzFactor;\n              Object.keys(this._sessionInfo).forEach((key) => (this._sessionInfo[key] == null) && delete this._sessionInfo[key]);\n              if (userInfoDict && Object.keys(userInfoDict)) {\n                  Object.assign(this._sessionInfo, userInfoDict);\n              }\n              if (this._reportingDisabled) {\n                  return;\n              }\n              if (storeBag) {\n                  this.storebag = new RTCObjectRef(storeBag);\n              }\n              else {\n                  this.storebag.addInstantiatedObject(new RTCReportingStoreBag(storebagURL, clientName, serviceName, applicationName, deviceName, osVersion));\n              }\n              this.reporter = new _reporting_reporter__WEBPACK_IMPORTED_MODULE_0__[\"RTCReporter\"](clientName, serviceName, sender, this.storebag.instance, this.reportingVersion, hlsEventEmitter, applicationName, senderServiceID, useHTTPHeaders, sessionID);\n              console.log(_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentDefaultConfig\"].LogMsgPrefix + 'Created reporting agent using rtc.js version ' + RTCReportingAgent.version);\n              this._issueSessionBeginEvent();\n          }\n          _issueSessionBeginEvent() {\n              let event = new _reporting_event__WEBPACK_IMPORTED_MODULE_1__[\"RTCReportingEvent\"](_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentMethods\"].ReportingSessionMethod, _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingSessionEventStatus\"].EventStatusSessionBegin, null, this._FuzzFactor, _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentEventTypes\"].BatchEvent);\n              if (this.reporter && event) {\n                  this.reporter.issueReportingEvent(event, this.SessionInfo);\n              }\n          }\n          _issueSessionEndEvent() {\n              let event = new _reporting_event__WEBPACK_IMPORTED_MODULE_1__[\"RTCReportingEvent\"](_reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentMethods\"].ReportingSessionMethod, _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingSessionEventStatus\"].EventStatusSessionEnd, null, this._FuzzFactor, _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentEventTypes\"].RealTimeEvent);\n              if (this.reporter) {\n                  this.reporter.issueReportingEvent(event, this.SessionInfo);\n              }\n          }\n          static _createSessionID() {\n              let word0 = Math.random() * 0xffffffff | 0;\n              let word1 = Math.random() * 0xffffffff | 0;\n              let word2 = Math.random() * 0xffffffff | 0;\n              let word3 = Math.random() * 0xffffffff | 0;\n              const lastNibble = 0x0f;\n              const lastByte = 0xff;\n              const secondByteShift = 8;\n              const thirdByteShift = 16;\n              const fourthByteShift = 24;\n              const uuidVersion = 0x40;\n              const uuidVariant = 0x80;\n              const nByteMask = 0x3f;\n              let guid = [];\n              let radix = 16;\n              let guidLength = 256;\n              for (let i = 0; i < guidLength; ++i) {\n                  guid[i] = (i < radix ? '0' : '') + (i).toString(radix);\n              }\n              return guid[word0 & lastByte] + guid[word0 >> secondByteShift & lastByte] + guid[word0 >> thirdByteShift & lastByte] + guid[word0 >> fourthByteShift & lastByte] + '-' +\n                  guid[word1 & lastByte] + guid[word1 >> secondByteShift & lastByte] + '-' +\n                  guid[word1 >> secondByteShift & lastNibble | uuidVersion] + guid[word1 >> thirdByteShift & lastByte] + '-' +\n                  guid[word2 & nByteMask | uuidVariant] + guid[word2 >> secondByteShift & lastByte] + '-' +\n                  guid[word2 >> secondByteShift & lastByte] + guid[word2 >> thirdByteShift & lastByte] +\n                  guid[word3 & lastByte] + guid[word3 >> secondByteShift & lastByte] + guid[word3 >> thirdByteShift & lastByte] + guid[word3 >> fourthByteShift & lastByte];\n          }\n      }\n      /* harmony default export */ __webpack_exports__[\"default\"] = ({\n          RTCReportingAgent,\n          RTCStorebag: _reporting_storebag__WEBPACK_IMPORTED_MODULE_2__,\n          RTCReportingAgentDefaultConfig: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentDefaultConfig\"],\n          RTCReportingAgentConfigKeys: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentConfigKeys\"],\n          RTCReportingAgentEventTypes: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingAgentEventTypes\"],\n          RTCReportingHTTPHeaderDefault: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingHTTPHeaderDefault\"],\n          RTCReportingHTTPHeaderKeys: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingHTTPHeaderKeys\"],\n          RTCReportingEventMetadataKeys: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingEventMetadataKeys\"],\n          RTC_REPORTING_EVENTS_DISPATCHED: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTC_REPORTING_EVENTS_DISPATCHED\"],\n          RTCObjectRef,\n          RTCReportingStoreBagConfig: _reporting_config__WEBPACK_IMPORTED_MODULE_3__[\"RTCReportingStoreBagConfig\"],\n      });\n    \n    \n      /***/ }),\n    \n      /***/ \"./src/rtc_reporting/reporting_config.ts\":\n      /*!***********************************************!*\\\n        !*** ./src/rtc_reporting/reporting_config.ts ***!\n        \\***********************************************/\n      /*! exports provided: RTCReportingAgentDefaultConfig, RTCReportingAgentConfigKeys, RTCReportingAgentEventTypes, RTCReportingHTTPHeaderKeys, RTCReportingHTTPHeaderDefault, RTCReportingEventMetadataKeys, RTCReportingStoreBagConfig, RTCReportingReporterConfig, RTCReportingAgentMethods, RTCReportingSessionEventStatus, RTCReportingStoreBagKeys, RTCReportingError, RTCReportingBuildTypes, RTC_REPORTING_EVENTS_DISPATCHED */\n      /***/ (function(module, __webpack_exports__, __webpack_require__) {\n      __webpack_require__.r(__webpack_exports__);\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingAgentDefaultConfig\", function() { return RTCReportingAgentDefaultConfig; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingAgentConfigKeys\", function() { return RTCReportingAgentConfigKeys; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingAgentEventTypes\", function() { return RTCReportingAgentEventTypes; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingHTTPHeaderKeys\", function() { return RTCReportingHTTPHeaderKeys; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingHTTPHeaderDefault\", function() { return RTCReportingHTTPHeaderDefault; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingEventMetadataKeys\", function() { return RTCReportingEventMetadataKeys; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingStoreBagConfig\", function() { return RTCReportingStoreBagConfig; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingReporterConfig\", function() { return RTCReportingReporterConfig; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingAgentMethods\", function() { return RTCReportingAgentMethods; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingSessionEventStatus\", function() { return RTCReportingSessionEventStatus; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingStoreBagKeys\", function() { return RTCReportingStoreBagKeys; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingError\", function() { return RTCReportingError; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingBuildTypes\", function() { return RTCReportingBuildTypes; });\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTC_REPORTING_EVENTS_DISPATCHED\", function() { return RTC_REPORTING_EVENTS_DISPATCHED; });\n      const RTCReportingHTTPHeaderKeys = {\n          ContentType: 'ContentType',\n          InternalBuild: 'X-RTC-Internal-Build',\n          ClientName: 'X-RTC-Client-Name',\n          ServiceName: 'X-RTC-Service-Name',\n          ClientVersion: 'X-RTC-Client-Version',\n          Sender: 'X-RTC-Sender',\n          UserAgent: 'User-Agent',\n          SessionID: 'X-RTC-Session-ID',\n      };\n      const RTCReportingHTTPHeaderDefault = {\n          ContentTypekey: 'application/json;charset=UTF-8',\n      };\n      const RTCReportingEventMetadataKeys = {\n          EventID: '_method',\n          EventType: '_eventType',\n          EventNumber: '_eventNumber',\n          EventTime: 'eventTime',\n          Sender: '_sender',\n          Status: '_status',\n          ClientTS: '_clientTS',\n          TimeZoneOffset: '_timezoneOffset',\n          PostTime: 'postTime',\n          Events: 'events',\n          SessionID: '_sessionID',\n          OSVersion: 'osVersion',\n          RTCReportingVersion: '_reportVers',\n          StoreBagVersion: 'StorebagVersion',\n          RTCSchemeVersion: '_reportScheme',\n          BagSchemeVersion: 'StorebagScheme',\n          StoreBagName: 'StorebagName',\n          SessionTag: 'SessionTag',\n          SenderOSVersion: 'SenderOSVersion',\n      };\n      const RTCReportingAgentDefaultConfig = {\n          RunInlineIfNoWebWorker: true,\n          BatchEvent: true,\n          LogMsgPrefix: '[RTC_RA]: ',\n      };\n      const RTCReportingAgentConfigKeys = {\n          ClientName: '_clientName',\n          ServiceName: '_serviceName',\n          StorebagURL: 'storebagURL',\n          ApplicationName: 'applicationName',\n          Sender: 'sender',\n          DeviceName: 'deviceName',\n          OSVersion: 'osVersion',\n          ReportingDisabled: 'reportingDisabled',\n          HLSEventEmitter: 'hlsEventEmitter',\n          BuildType: 'internal',\n          UserInfoDict: 'userInfoDict',\n          ReportingStoreBag: 'reportingStoreBag',\n          SenderAltConfig: 'senderAltConfig',\n          ServiceIdentifier: 'ServiceIdentifier',\n          UseHTTPHeaders: 'UseHTTPHeaders',\n      };\n      const RTCReportingAgentEventTypes = {\n          BatchEvent: 0,\n          RealTimeEvent: 1,\n      };\n      const RTCReportingAgentMethods = {\n          ReportingSessionMethod: 0,\n      };\n      const RTCReportingStoreBagConfig = {\n          StoreBagFetchSyncMode: 0,\n          StoreBagFetchAsyncMode: 1,\n          StoreBagVersionSupported: 1,\n      };\n      const RTCReportingReporterConfig = {\n          BatchThreshold: 50,\n      };\n      const RTCReportingSessionEventStatus = {\n          EventStatusSessionBegin: 0,\n          EventStatusSessionEnd: 1,\n          EventStatusSessionEndWithError: 2,\n      };\n      const RTCReportingStoreBagKeys = {\n          Version: 'Version',\n          Scheme: 'Scheme',\n          BagVersion: 'BagVersion',\n          Configurations: 'Configurations',\n          ConfigurationList: 'ConfigurationList',\n          PostURLs: 'PostURLs',\n          Filters: 'Filters',\n          BagList: 'BagList',\n          MinOSVersionDict: 'MinOSVersionDict',\n          ClientName: 'ClientName',\n          ServiceName: 'ServiceName',\n          ServiceNameList: 'ServiceNameList',\n          SenderServiceIDList: 'SenderServiceIDList',\n          ApplicationNameList: 'ApplicationNameList',\n          DeviceList: 'DeviceList',\n          Remove: 'Remove',\n          EventThreshold: 'EventThreshold',\n          SamplingThreshold: 'SamplingThreshold',\n          DeviceWhiteList: 'DeviceWhiteList',\n          FlushEventsInterval: 'FlushEventsInterval',\n      };\n      const RTCReportingBuildTypes = {\n          BuildTypePublic: 0,\n          BuildTypeInternal: 1,\n          BuildTypeSeed: 2,\n          BuildTypeInternalSeed: 3\n      };\n      class RTCReportingError extends Error {\n          constructor(...args) {\n              super(...args);\n              Error.captureStackTrace(this, RTCReportingError);\n          }\n      }\n      const RTC_REPORTING_EVENTS_DISPATCHED = 'rtcReportingEventsDispatched';\n    \n    \n    \n      /***/ }),\n    \n      /***/ \"./src/rtc_reporting/reporting_event.ts\":\n      /*!**********************************************!*\\\n        !*** ./src/rtc_reporting/reporting_event.ts ***!\n        \\**********************************************/\n      /*! exports provided: RTCReportingEvent */\n      /***/ (function(module, __webpack_exports__, __webpack_require__) {\n      __webpack_require__.r(__webpack_exports__);\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingEvent\", function() { return RTCReportingEvent; });\n      /* harmony import */ var _reporting_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reporting_config */ \"./src/rtc_reporting/reporting_config.ts\");\n    \n      class RTCReportingEvent {\n          constructor(eventID, status = 0, eventPayload = {}, fuzzFactor = 0, eventType = _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentEventTypes\"].BatchEvent) {\n              this.payload = eventPayload ? eventPayload : {};\n              this.payload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].EventID] = eventID;\n              this.payload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].Status] = status;\n              this.payload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].EventType] = eventType;\n              this.fuzzFactor = fuzzFactor;\n              this.isEventRealTime = (eventType === _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentEventTypes\"].RealTimeEvent);\n              this._addEventMetadata();\n          }\n          prepareEventPayload(sessionInfo, sizeTillLastBatch, sizeOfLastBatch) {\n              Object.keys(sessionInfo).forEach(function (sessionInfoKey) {\n                  this.payload[sessionInfoKey] = sessionInfo[sessionInfoKey];\n              }.bind(this));\n              if (this.isEventRealTime && sizeOfLastBatch && sizeTillLastBatch) {\n                  this.payload.sizeOfLastBatch = sizeOfLastBatch;\n                  this.payload.sizeTillLastBatch = sizeTillLastBatch;\n              }\n          }\n          get EventPayload() {\n              return this.payload;\n          }\n          get IsEventRealTime() {\n              return this.isEventRealTime;\n          }\n          _addEventMetadata() {\n              let date = new Date();\n              this.payload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].EventTime] = (date.getTime()) / 1000;\n              this.payload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].TimeZoneOffset] = date.getTimezoneOffset() * 60;\n          }\n      }\n    \n    \n    \n      /***/ }),\n    \n      /***/ \"./src/rtc_reporting/reporting_reporter.ts\":\n      /*!*************************************************!*\\\n        !*** ./src/rtc_reporting/reporting_reporter.ts ***!\n        \\*************************************************/\n      /*! exports provided: RTCReporter */\n      /***/ (function(module, __webpack_exports__, __webpack_require__) {\n      __webpack_require__.r(__webpack_exports__);\n      /* WEBPACK VAR INJECTION */(function(module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReporter\", function() { return RTCReporter; });\n      /* harmony import */ var _reporting_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reporting_config */ \"./src/rtc_reporting/reporting_config.ts\");\n    \n      const ReportingContentType = 'application/json;charset=UTF-8';\n      const ReportingVersion = 'RTCReportingJS/0.314';\n      class EventDispatcher {\n          constructor(eventEmitter, sessionID, useHTTPHeaders = false) {\n              this._eventWriter = null;\n              this._sessionID = sessionID;\n              this._eventDispatcher = eventEmitter;\n              if (typeof navigator !== 'undefined' && navigator && (typeof navigator.sendBeacon !== 'undefined') && navigator.sendBeacon) {\n                  this._eventWriter = this._sendEventDataWithHTTPPost;\n              }\n              else if ( this.module !== module) {\n                  this._eventWriter = this._sendEventDataWithHTTPHeaders;\n              }\n              else {\n                  this._eventWriter = this._sendEventDataWithHTTPPost;\n              }\n              if (useHTTPHeaders) {\n                  this._eventWriter = this._sendEventDataWithHTTPHeaders;\n              }\n          }\n          sendEventData(url, eventDataAsJSON, clientName, serviceName, clientVersion, sender) {\n              if (this._eventWriter) {\n                  this._eventWriter(url, eventDataAsJSON, clientName, serviceName, clientVersion, sender);\n                  if (this._eventDispatcher) {\n                      this._eventDispatcher.emit(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTC_REPORTING_EVENTS_DISPATCHED\"], eventDataAsJSON);\n                  }\n              }\n          }\n          _sendEventDataUsingBeacon(url, eventDataAsJSON, clientName, serviceName, clientVersion, sender) {\n              let headerJSON = this._createEventPayloadAsJSON(clientName, serviceName, clientVersion, sender);\n              let formData = new FormData();\n              formData.append('headers', headerJSON);\n              formData.append('payload', eventDataAsJSON);\n              navigator.sendBeacon(url, formData);\n          }\n          _sendEventDataWithHTTPPost(url, eventDataAsJSON, clientName, serviceName, clientVersion, sender) {\n              let headerJSON = this._createEventPayloadAsJSON(clientName, serviceName, clientVersion, sender);\n              let formData = new FormData();\n              formData.append('headers', headerJSON);\n              formData.append('payload', eventDataAsJSON);\n              let request = new XMLHttpRequest();\n              const method = 'POST';\n              const async = true;\n              request.open(method, url, async);\n              request.send(formData);\n          }\n          _createEventPayloadAsJSON(clientName, serviceName, clientVersion, sender) {\n              let header = {};\n              header[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].InternalBuild] = 0;\n              header[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ClientName] = clientName;\n              header[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ServiceName] = serviceName;\n              header[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ClientVersion] = clientVersion;\n              header[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].Sender] = sender;\n              header[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ContentType] = 'application/json;charset=UTF-8';\n              let headerJSON = JSON.stringify(header);\n              return headerJSON;\n          }\n          _sendEventDataWithHTTPHeaders(url, eventDataAsJSON, clientName, serviceName, clientVersion, sender) {\n              let request = new XMLHttpRequest();\n              const method = 'POST';\n              const async = true;\n              request.onload = function () {\n              };\n              request.open(method, url, async);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ContentType, ReportingContentType);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].InternalBuild, '0');\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ClientName, clientName);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ServiceName, serviceName);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ClientVersion, clientVersion);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].Sender, sender);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].ClientVersion, ReportingVersion);\n              request.setRequestHeader(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingHTTPHeaderKeys\"].SessionID, this._sessionID);\n              request.send(eventDataAsJSON);\n          }\n      }\n      class RTCReporter {\n          constructor(clientName, serviceName, sender, reportingStoreBag, clientVersion, hlsEventEmitter, applicationName = null, senderServiceID = null, useHTTPHeaders = false, sessionID = null) {\n              this.clientName = clientName;\n              this.serviceName = serviceName;\n              this.reportingStoreBag = reportingStoreBag;\n              this.sender = sender;\n              this.clientVersion = clientVersion;\n              this.eventList = [];\n              this._count = 0;\n              this._eventDispatcher = new EventDispatcher(hlsEventEmitter, sessionID, useHTTPHeaders);\n              this.sampleFactor = Math.random();\n              this._storebagStats = {};\n              this._canReport = undefined;\n              this._sizeTillLastBatch = this._sizeOfLastBatch = 0;\n              this.storeBag = null;\n              this.applicationName = applicationName;\n              this.senderServiceID = senderServiceID;\n              this.checkAndConfigureEventFlushTimeoutOnce = false;\n          }\n          issueReportingEvent(event, sessionInfo = {}) {\n              if (!event) {\n                  return new _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingError\"]('not a valid event to report');\n              }\n              this._updateEventMetadata(event);\n              event.prepareEventPayload(sessionInfo, this._sizeTillLastBatch, this._sizeOfLastBatch);\n              this.eventList.push(event);\n              if (!this.checkAndConfigureEventFlushTimeoutOnce) {\n                  if (this.canReportEvents()) {\n                      this._configureEventFlushTimer();\n                  }\n              }\n              if ((this.eventList.length > _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingReporterConfig\"].BatchThreshold) || event.IsEventRealTime) {\n                  return this.flushAllEvents();\n              }\n              return null;\n          }\n          canReportEvents() {\n              let sampleRate;\n              if (this._canReport !== undefined) {\n                  return this._canReport;\n              }\n              if (this.reportingStoreBag && !this.storeBag) {\n                  this.storeBag = this.reportingStoreBag.createParsedStoreBag(this.applicationName, this.senderServiceID);\n                  if (!this.storeBag) {\n                      return false;\n                  }\n              }\n              if (this.storeBag && this.storeBag.IsValid) {\n                  this._canReport = true;\n                  sampleRate = this.storeBag.getStoreBagProperty(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].SamplingThreshold);\n                  if (sampleRate && (parseFloat(sampleRate) < this.sampleFactor)) {\n                      this._canReport = false;\n                  }\n              }\n              else if (this.storeBag) {\n                  console.log(`StoreBag for client ${this.clientName}, service ${this.serviceName}, app ${this.applicationName} senderService ${this.senderServiceID} not valid ${this.storeBag.IsValid} `);\n              }\n              if (this._canReport) {\n                  this._storebagStats[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].SamplingThreshold] = sampleRate;\n                  this._storebagStats[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].BagSchemeVersion] = this.storeBag.StoreBagSchemeVersion;\n                  this._storebagStats[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].StoreBagVersion] = this.storeBag.StoreBagVersion;\n                  this._storebagStats[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].StoreBagName] = this.storeBag.StoreBagName;\n                  let bagMinVersionDict = this.storeBag.BagMinVersionDict;\n                  if (typeof bagMinVersionDict === 'object' && bagMinVersionDict) {\n                      for (let key in bagMinVersionDict) {\n                          if (bagMinVersionDict.hasOwnProperty(key)) {\n                              this._storebagStats[key] = bagMinVersionDict[key];\n                          }\n                      }\n                  }\n              }\n              console.log(`${_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentDefaultConfig\"].LogMsgPrefix} Event reporting is ${this._canReport} for client ${this.clientName} service ${this.serviceName}, app ${this.applicationName}, senderService ${this.senderServiceID}`);\n              return this._canReport;\n          }\n          flushEventTimeout() {\n              this.flushAllEvents();\n          }\n          flushAllEvents() {\n              let error = null;\n              if (this.canReportEvents()) {\n                  this._sendAllEvents();\n              }\n              else {\n                  error = new _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingError\"]('no valid storebag configured or blocked by sampling threshold, ignoring events.');\n              }\n              this.eventList = [];\n              return error;\n          }\n          batchedEventsCount() {\n              return this.eventList.length;\n          }\n          get _EventList() {\n              return this.eventList;\n          }\n          _updateEventMetadata(event) {\n              event.EventPayload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].EventNumber] = this._eventCounter();\n              event.EventPayload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].ClientTS] = ((new Date()).getTime()) / 1000;\n              event.EventPayload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].Sender] = this.sender;\n              event.EventPayload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentConfigKeys\"].ClientName] = this.clientName;\n              event.EventPayload[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentConfigKeys\"].ServiceName] = this.serviceName;\n          }\n          _sendAllEvents() {\n              if (this.eventList.length === 0) {\n                  return;\n              }\n              let backEnds = this.storeBag.listOfSupportedBackEnds(this.clientName, this.serviceName);\n              if (!backEnds || backEnds.length <= 0) {\n                  return;\n              }\n              let blackListKeys = this.storeBag.listOfKeysToBlock();\n              if (blackListKeys) {\n                  this.eventList.forEach(function (event) {\n                      event.prepareEventPayload(this._storebagStats, this._sizeTillLastBatch, this._sizeOfLastBatch);\n                      blackListKeys.forEach(function (key) {\n                          delete event.EventPayload[key];\n                      });\n                  }.bind(this));\n              }\n              let eventData = this._marshallAsJSONString();\n              this._sizeTillLastBatch += eventData.length;\n              this._sizeOfLastBatch = eventData.length;\n              backEnds.forEach(function (backEndURL) {\n                  this._eventDispatcher.sendEventData(backEndURL, eventData, this.clientName, this.serviceName, this.clientVersion, this.sender);\n              }.bind(this));\n              console.log(`${_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentDefaultConfig\"].LogMsgPrefix} events reported.`);\n          }\n          _marshallAsJSONString() {\n              let time = ((new Date()).getTime()) / 1000;\n              let postData = {};\n              let events = [];\n              this.eventList.forEach(function (event) {\n                  events.push(event.EventPayload);\n              });\n              postData[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].PostTime] = time;\n              postData[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingEventMetadataKeys\"].Events] = events;\n              let postBody = JSON.stringify(postData);\n              return postBody;\n          }\n          _eventCounter() {\n              return this._count++;\n          }\n          _configureEventFlushTimer() {\n              let flushTimeout = null;\n              this.checkAndConfigureEventFlushTimeoutOnce = true;\n              if (this.reportingStoreBag && !this.storeBag) {\n                  this.storeBag = this.reportingStoreBag.createParsedStoreBag(this.applicationName, this.senderServiceID);\n              }\n              if (this.storeBag && this.storeBag.IsValid) {\n                  flushTimeout = this.storeBag.getStoreBagProperty(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].FlushEventsInterval);\n              }\n              if (flushTimeout) {\n                  flushTimeout = parseInt(flushTimeout, 10) * 1000;\n                  if (flushTimeout >= 10000) {\n                      setInterval(this.flushEventTimeout.bind(this), flushTimeout);\n                  }\n              }\n          }\n      }\n    \n    \n      /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/harmony-module.js */ \"./node_modules/webpack/buildin/harmony-module.js\")(module)));\n    \n      /***/ }),\n    \n      /***/ \"./src/rtc_reporting/reporting_storebag.ts\":\n      /*!*************************************************!*\\\n        !*** ./src/rtc_reporting/reporting_storebag.ts ***!\n        \\*************************************************/\n      /*! exports provided: RTCReportingStoreBag */\n      /***/ (function(module, __webpack_exports__, __webpack_require__) {\n      __webpack_require__.r(__webpack_exports__);\n      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RTCReportingStoreBag\", function() { return RTCReportingStoreBag; });\n      /* harmony import */ var _reporting_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reporting_config */ \"./src/rtc_reporting/reporting_config.ts\");\n      /* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! semver */ \"./node_modules/semver/semver.js\");\n    \n    \n      class RTCReportingParsedStoreBag {\n          constructor(storeBagConfig, selectedBagName, bagVersion, bagMinVersionDict) {\n              this.storeBagConfig = storeBagConfig;\n              this.selectedBagName = selectedBagName;\n              this.bagVersion = bagVersion;\n              this.bagMinVersionDict = bagMinVersionDict;\n          }\n          listOfSupportedBackEnds() {\n              return this.getStoreBagProperty(_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].PostURLs);\n          }\n          listOfKeysToBlock() {\n              if (!this.storeBagConfig) {\n                  return null;\n              }\n              let filters = this.storeBagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].Filters];\n              if (!filters) {\n                  return null;\n              }\n              return filters[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].Remove];\n          }\n          get IsValid() {\n              return Boolean(this.storeBagConfig);\n          }\n          get StoreBagName() {\n              return this.IsValid ? this.selectedBagName : null;\n          }\n          get StorebagVersion() {\n              return this.IsValid ? this.bagVersion : null;\n          }\n          get StoreBagSchemeVersion() {\n              return _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagConfig\"].StoreBagVersionSupported;\n          }\n          get BagMinVersionDict() {\n              return this.bagMinVersionDict;\n          }\n          getStoreBagProperty(propertyKey) {\n              let propertyValue = null;\n              if (this.IsValid && propertyKey && propertyKey in this.storeBagConfig) {\n                  propertyValue = this.storeBagConfig[propertyKey];\n              }\n              return propertyValue;\n          }\n      }\n      class RTCReportingStoreBag {\n          constructor(storebagURL, clientName = null, serviceName = null, applicationName = null, deviceName = null, bagMinVersionDict = null, mode = _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagConfig\"].StoreBagFetchAsyncMode, storebagAsJSON = null) {\n              this.storebagURL = storebagURL;\n              this.mode = mode;\n              this.storeBagConfig = null;\n              this.clientName = clientName;\n              this.serviceName = serviceName;\n              this.applicationName = applicationName;\n              this.deviceName = deviceName;\n              this.storebagLoader = null;\n              this.selectedBagName = null;\n              this.storebagAsJSON = storebagAsJSON;\n              this.bagVersion = null;\n              this.bagMinVersionDict = null;\n              if (typeof bagMinVersionDict === 'object') {\n                  this.bagMinVersionDict = bagMinVersionDict;\n              }\n              this.fetchAndParseStoreBag();\n          }\n          destroy() {\n              if (this.storebagLoader) {\n                  this.storebagLoader.abort();\n                  this.storebagLoader = null;\n              }\n          }\n          fetchAndParseStoreBag() {\n              this._fetchStoreBag();\n          }\n          createParsedStoreBag(applicationName = this.applicationName, senderServiceID = null) {\n              if (!this.storebagAsJSON) {\n                  console.log('no bag available!');\n                  return null;\n              }\n              return this._parseAndReturnStoreBag(this.storebagAsJSON, applicationName, senderServiceID);\n          }\n          _checkbagMinVersion(bagMinVersionDict, currentVersionDict) {\n              if (bagMinVersionDict && currentVersionDict) {\n                  for (let key in bagMinVersionDict) {\n                      if (bagMinVersionDict.hasOwnProperty(key)) {\n                          let bagMinVersion = bagMinVersionDict[key];\n                          if (currentVersionDict.hasOwnProperty(key)) {\n                              let currentVersion = currentVersionDict[key];\n                              if (Object(semver__WEBPACK_IMPORTED_MODULE_1__[\"gte\"])(currentVersion, bagMinVersion)) {\n                                  return true;\n                              }\n                          }\n                      }\n                  }\n                  return false;\n              }\n              return true;\n          }\n          _parseAndReturnStoreBag(storebag, applicationName, senderServiceID) {\n              let selectedBag = null;\n              let selectedBagConfig = null;\n              let selectedBagConfigKey = null;\n              let selectedBagVersion = null;\n              storebag.forEach(function (bag) {\n                  selectedBag = null;\n                  if (bag[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].Scheme] === _reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagConfig\"].StoreBagVersionSupported) {\n                      let bagList = bag[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].BagList];\n                      Object.keys(bagList).some(function (bagConfigKey) {\n                          let bagConfig = bagList[bagConfigKey];\n                          let bagMinVersionDict = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].MinOSVersionDict];\n                          if (!this._checkbagMinVersion(bagMinVersionDict, this.bagMinVersionDict)) {\n                              console.log(`failed to match the version # `);\n                              return false;\n                          }\n                          if (!this._canUseBagConfig(bagConfig, applicationName, senderServiceID)) {\n                              return false;\n                          }\n                          selectedBag = bagConfig;\n                          selectedBagConfigKey = bagConfigKey;\n                          selectedBagVersion = bag[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].BagVersion];\n                          return false;\n                      }.bind(this));\n                  }\n                  if (selectedBag) {\n                      selectedBagConfig = this._fillSelectedBagConfig(selectedBag, bag);\n                  }\n              }.bind(this));\n              if (!selectedBagConfig) {\n                  console.log(`${_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingAgentDefaultConfig\"].LogMsgPrefix} Failed to select a storebag.`);\n              }\n              return new RTCReportingParsedStoreBag(selectedBagConfig, selectedBagConfigKey, selectedBagVersion, this.bagMinVersionDict);\n          }\n          _fetchStoreBag() {\n              if (this.storebagURL && !this.storebagAsJSON) {\n                  this._requestStoreBagAsync();\n              }\n          }\n          _requestStoreBagAsync() {\n              this.storebagLoader = new XMLHttpRequest();\n              this.storebagLoader.onreadystatechange = function () {\n                  if (this.storebagLoader && this.storebagLoader.readyState === 4 && this.storebagLoader.status === 200 && this.storebagLoader.responseText) {\n                      this.storebagAsJSON = JSON.parse(this.storebagLoader.responseText);\n                  }\n              }.bind(this);\n              this.storebagLoader.open('GET', this.storebagURL, true);\n              this.storebagLoader.send(null);\n          }\n          _canUseBagConfig(bagConfig, applicationName, senderServiceID) {\n              let bagClientName = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].ClientName];\n              if (bagClientName && bagClientName !== this.clientName) {\n                  return false;\n              }\n              let bagServiceNameList = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].ServiceNameList];\n              let bagServiceName = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].ServiceName];\n              if (bagServiceNameList && bagServiceNameList.length > 0 && -1 === bagServiceNameList.indexOf(this.serviceName)) {\n                  return false;\n              }\n              if (!bagServiceNameList && bagServiceName && bagServiceName !== this.serviceName) {\n                  return false;\n              }\n              let bagApplicationNameList = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].ApplicationNameList];\n              if (bagApplicationNameList && bagApplicationNameList.length > 0 && -1 === bagApplicationNameList.indexOf(applicationName)) {\n                  return false;\n              }\n              let bagDeviceList = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].DeviceList];\n              if (bagDeviceList && bagDeviceList.length > 0 && -1 === bagDeviceList.indexOf(this.deviceName)) {\n                  return false;\n              }\n              let bagSenderServiceIDList = bagConfig[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].SenderServiceIDList];\n              if (bagSenderServiceIDList && bagSenderServiceIDList.length > 0 && -1 === bagSenderServiceIDList.indexOf(senderServiceID)) {\n                  return false;\n              }\n              return true;\n          }\n          _fillSelectedBagConfig(selectedBag, bag) {\n              let selectedBagConfig = null;\n              if (!selectedBag || !bag) {\n                  return selectedBagConfig;\n              }\n              let configurationList = bag[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].ConfigurationList];\n              let listOfConfigs = selectedBag[_reporting_config__WEBPACK_IMPORTED_MODULE_0__[\"RTCReportingStoreBagKeys\"].Configurations];\n              if (!listOfConfigs) {\n                  return selectedBagConfig;\n              }\n              listOfConfigs.forEach(function (configName) {\n                  let config = configurationList[configName];\n                  selectedBagConfig = selectedBagConfig ? selectedBagConfig : {};\n                  Object.assign(selectedBagConfig, config);\n              });\n              return selectedBagConfig;\n          }\n      }\n    \n    \n    \n      /***/ })\n    \n      /******/ })[\"default\"];\n      });\n    \n      }(rtc));\n    \n      var socket_io_min = {exports: {}};\n    \n      /*!\n       * Socket.IO v4.0.2\n       * (c) 2014-2021 Guillermo Rauch\n       * Released under the MIT License.\n       */\n    \n      (function (module, exports) {\n      !function(t,e){module.exports=e();}(self,(function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r});},n.r=function(t){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0});},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&\"object\"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\"default\",{enumerable:!0,value:t}),2&e&&\"string\"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,\"a\",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p=\"\",n(n.s=18)}([function(t,e,n){var r=n(24),o=n(25),i=String.fromCharCode(30);t.exports={protocol:4,encodePacket:r,encodePayload:function(t,e){var n=t.length,o=new Array(n),s=0;t.forEach((function(t,c){r(t,!1,(function(t){o[c]=t,++s===n&&e(o.join(i));}));}));},decodePacket:o,decodePayload:function(t,e){for(var n=t.split(i),r=[],s=0;s<n.length;s++){var c=o(n[s],e);if(r.push(c),\"error\"===c.type)break}return r}};},function(t,e,n){function r(t){if(t)return function(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}(t)}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks[\"$\"+t]=this._callbacks[\"$\"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments);}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks[\"$\"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks[\"$\"+t],this;for(var o=0;o<r.length;o++)if((n=r[o])===e||n.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks[\"$\"+t],this},r.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks[\"$\"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,e);}return this},r.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks[\"$\"+t]||[]},r.prototype.hasListeners=function(t){return !!this.listeners(t).length};},function(t,e){t.exports=\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:Function(\"return this\")();},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function i(t,e){return (i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function a(t){return (a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=n(0),f=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e);}(a,t);var e,n,c=s(a);function a(t){var e;return function(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,a),(e=c.call(this)).opts=t,e.query=t.query,e.readyState=\"\",e.socket=t.socket,e}return e=a,(n=[{key:\"onError\",value:function(t,e){var n=new Error(t);return n.type=\"TransportError\",n.description=e,this.emit(\"error\",n),this}},{key:\"open\",value:function(){return \"closed\"!==this.readyState&&\"\"!==this.readyState||(this.readyState=\"opening\",this.doOpen()),this}},{key:\"close\",value:function(){return \"opening\"!==this.readyState&&\"open\"!==this.readyState||(this.doClose(),this.onClose()),this}},{key:\"send\",value:function(t){\"open\"===this.readyState&&this.write(t);}},{key:\"onOpen\",value:function(){this.readyState=\"open\",this.writable=!0,this.emit(\"open\");}},{key:\"onData\",value:function(t){var e=u.decodePacket(t,this.socket.binaryType);this.onPacket(e);}},{key:\"onPacket\",value:function(t){this.emit(\"packet\",t);}},{key:\"onClose\",value:function(){this.readyState=\"closed\",this.emit(\"close\");}}])&&o(e.prototype,n),a}(n(1));t.exports=f;},function(t,e){e.encode=function(t){var e=\"\";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+=\"&\"),e+=encodeURIComponent(n)+\"=\"+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split(\"&\"),r=0,o=n.length;r<o;r++){var i=n[r].split(\"=\");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1]);}return e};},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e,n){return (o=\"undefined\"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=a(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function i(t,e){return (i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function a(t){return (a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function u(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function f(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function p(t,e,n){return e&&f(t.prototype,e),n&&f(t,n),t}Object.defineProperty(e,\"__esModule\",{value:!0}),e.Decoder=e.Encoder=e.PacketType=e.protocol=void 0;var l,h=n(1),y=n(30),d=n(15);e.protocol=5,function(t){t[t.CONNECT=0]=\"CONNECT\",t[t.DISCONNECT=1]=\"DISCONNECT\",t[t.EVENT=2]=\"EVENT\",t[t.ACK=3]=\"ACK\",t[t.CONNECT_ERROR=4]=\"CONNECT_ERROR\",t[t.BINARY_EVENT=5]=\"BINARY_EVENT\",t[t.BINARY_ACK=6]=\"BINARY_ACK\";}(l=e.PacketType||(e.PacketType={}));var v=function(){function t(){u(this,t);}return p(t,[{key:\"encode\",value:function(t){return t.type!==l.EVENT&&t.type!==l.ACK||!d.hasBinary(t)?[this.encodeAsString(t)]:(t.type=t.type===l.EVENT?l.BINARY_EVENT:l.BINARY_ACK,this.encodeAsBinary(t))}},{key:\"encodeAsString\",value:function(t){var e=\"\"+t.type;return t.type!==l.BINARY_EVENT&&t.type!==l.BINARY_ACK||(e+=t.attachments+\"-\"),t.nsp&&\"/\"!==t.nsp&&(e+=t.nsp+\",\"),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data)),e}},{key:\"encodeAsBinary\",value:function(t){var e=y.deconstructPacket(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}]),t}();e.Encoder=v;var b=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e);}(n,t);var e=s(n);function n(){return u(this,n),e.call(this)}return p(n,[{key:\"add\",value:function(t){var e;if(\"string\"==typeof t)(e=this.decodeString(t)).type===l.BINARY_EVENT||e.type===l.BINARY_ACK?(this.reconstructor=new m(e),0===e.attachments&&o(a(n.prototype),\"emit\",this).call(this,\"decoded\",e)):o(a(n.prototype),\"emit\",this).call(this,\"decoded\",e);else {if(!d.isBinary(t)&&!t.base64)throw new Error(\"Unknown type: \"+t);if(!this.reconstructor)throw new Error(\"got binary data when not reconstructing a packet\");(e=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,o(a(n.prototype),\"emit\",this).call(this,\"decoded\",e));}}},{key:\"decodeString\",value:function(t){var e=0,r={type:Number(t.charAt(0))};if(void 0===l[r.type])throw new Error(\"unknown packet type \"+r.type);if(r.type===l.BINARY_EVENT||r.type===l.BINARY_ACK){for(var o=e+1;\"-\"!==t.charAt(++e)&&e!=t.length;);var i=t.substring(o,e);if(i!=Number(i)||\"-\"!==t.charAt(e))throw new Error(\"Illegal attachments\");r.attachments=Number(i);}if(\"/\"===t.charAt(e+1)){for(var s=e+1;++e;){if(\",\"===t.charAt(e))break;if(e===t.length)break}r.nsp=t.substring(s,e);}else r.nsp=\"/\";var c=t.charAt(e+1);if(\"\"!==c&&Number(c)==c){for(var a=e+1;++e;){var u=t.charAt(e);if(null==u||Number(u)!=u){--e;break}if(e===t.length)break}r.id=Number(t.substring(a,e+1));}if(t.charAt(++e)){var f=function(t){try{return JSON.parse(t)}catch(t){return !1}}(t.substr(e));if(!n.isPayloadValid(r.type,f))throw new Error(\"invalid payload\");r.data=f;}return r}},{key:\"destroy\",value:function(){this.reconstructor&&this.reconstructor.finishedReconstruction();}}],[{key:\"isPayloadValid\",value:function(t,e){switch(t){case l.CONNECT:return \"object\"===r(e);case l.DISCONNECT:return void 0===e;case l.CONNECT_ERROR:return \"string\"==typeof e||\"object\"===r(e);case l.EVENT:case l.BINARY_EVENT:return Array.isArray(e)&&e.length>0;case l.ACK:case l.BINARY_ACK:return Array.isArray(e)}}}]),n}(h);e.Decoder=b;var m=function(){function t(e){u(this,t),this.packet=e,this.buffers=[],this.reconPack=e;}return p(t,[{key:\"takeBinaryData\",value:function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=y.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}},{key:\"finishedReconstruction\",value:function(){this.reconPack=null,this.buffers=[];}}]),t}();},function(t,e){var n=/^(?:(?![^:@]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/,r=[\"source\",\"protocol\",\"authority\",\"userInfo\",\"user\",\"password\",\"host\",\"port\",\"relative\",\"path\",\"directory\",\"file\",\"query\",\"anchor\"];t.exports=function(t){var e=t,o=t.indexOf(\"[\"),i=t.indexOf(\"]\");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,\";\")+t.substring(i,t.length));for(var s,c,a=n.exec(t||\"\"),u={},f=14;f--;)u[r[f]]=a[f]||\"\";return -1!=o&&-1!=i&&(u.source=e,u.host=u.host.substring(1,u.host.length-1).replace(/;/g,\":\"),u.authority=u.authority.replace(\"[\",\"\").replace(\"]\",\"\").replace(/;/g,\":\"),u.ipv6uri=!0),u.pathNames=function(t,e){var n=e.replace(/\\/{2,9}/g,\"/\").split(\"/\");\"/\"!=e.substr(0,1)&&0!==e.length||n.splice(0,1);\"/\"==e.substr(e.length-1,1)&&n.splice(n.length-1,1);return n}(0,u.path),u.queryKey=(s=u.query,c={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(c[e]=n);})),c),u};},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function i(t,e){return (i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function a(t){return (a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}Object.defineProperty(e,\"__esModule\",{value:!0}),e.Manager=void 0;var u=n(20),f=n(14),p=n(5),l=n(16),h=n(31),y=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e);}(y,t);var e,n,a=s(y);function y(t,e){var n;!function(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,y),(n=a.call(this)).nsps={},n.subs=[],t&&\"object\"===r(t)&&(e=t,t=void 0),(e=e||{}).path=e.path||\"/socket.io\",n.opts=e,n.reconnection(!1!==e.reconnection),n.reconnectionAttempts(e.reconnectionAttempts||1/0),n.reconnectionDelay(e.reconnectionDelay||1e3),n.reconnectionDelayMax(e.reconnectionDelayMax||5e3),n.randomizationFactor(e.randomizationFactor||.5),n.backoff=new h({min:n.reconnectionDelay(),max:n.reconnectionDelayMax(),jitter:n.randomizationFactor()}),n.timeout(null==e.timeout?2e4:e.timeout),n._readyState=\"closed\",n.uri=t;var o=e.parser||p;return n.encoder=new o.Encoder,n.decoder=new o.Decoder,n._autoConnect=!1!==e.autoConnect,n._autoConnect&&n.open(),n}return e=y,(n=[{key:\"reconnection\",value:function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}},{key:\"reconnectionAttempts\",value:function(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}},{key:\"reconnectionDelay\",value:function(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}},{key:\"randomizationFactor\",value:function(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}},{key:\"reconnectionDelayMax\",value:function(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}},{key:\"timeout\",value:function(t){return arguments.length?(this._timeout=t,this):this._timeout}},{key:\"maybeReconnectOnOpen\",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect();}},{key:\"open\",value:function(t){var e=this;if(~this._readyState.indexOf(\"open\"))return this;this.engine=u(this.uri,this.opts);var n=this.engine,r=this;this._readyState=\"opening\",this.skipReconnect=!1;var o=l.on(n,\"open\",(function(){r.onopen(),t&&t();})),i=l.on(n,\"error\",(function(n){r.cleanup(),r._readyState=\"closed\",e.emitReserved(\"error\",n),t?t(n):r.maybeReconnectOnOpen();}));if(!1!==this._timeout){var s=this._timeout;0===s&&o();var c=setTimeout((function(){o(),n.close(),n.emit(\"error\",new Error(\"timeout\"));}),s);this.opts.autoUnref&&c.unref(),this.subs.push((function(){clearTimeout(c);}));}return this.subs.push(o),this.subs.push(i),this}},{key:\"connect\",value:function(t){return this.open(t)}},{key:\"onopen\",value:function(){this.cleanup(),this._readyState=\"open\",this.emitReserved(\"open\");var t=this.engine;this.subs.push(l.on(t,\"ping\",this.onping.bind(this)),l.on(t,\"data\",this.ondata.bind(this)),l.on(t,\"error\",this.onerror.bind(this)),l.on(t,\"close\",this.onclose.bind(this)),l.on(this.decoder,\"decoded\",this.ondecoded.bind(this)));}},{key:\"onping\",value:function(){this.emitReserved(\"ping\");}},{key:\"ondata\",value:function(t){this.decoder.add(t);}},{key:\"ondecoded\",value:function(t){this.emitReserved(\"packet\",t);}},{key:\"onerror\",value:function(t){this.emitReserved(\"error\",t);}},{key:\"socket\",value:function(t,e){var n=this.nsps[t];return n||(n=new f.Socket(this,t,e),this.nsps[t]=n),n}},{key:\"_destroy\",value:function(t){for(var e=0,n=Object.keys(this.nsps);e<n.length;e++){var r=n[e];if(this.nsps[r].active)return}this._close();}},{key:\"_packet\",value:function(t){for(var e=this.encoder.encode(t),n=0;n<e.length;n++)this.engine.write(e[n],t.options);}},{key:\"cleanup\",value:function(){this.subs.forEach((function(t){return t()})),this.subs.length=0,this.decoder.destroy();}},{key:\"_close\",value:function(){this.skipReconnect=!0,this._reconnecting=!1,\"opening\"===this._readyState&&this.cleanup(),this.backoff.reset(),this._readyState=\"closed\",this.engine&&this.engine.close();}},{key:\"disconnect\",value:function(){return this._close()}},{key:\"onclose\",value:function(t){this.cleanup(),this.backoff.reset(),this._readyState=\"closed\",this.emitReserved(\"close\",t),this._reconnection&&!this.skipReconnect&&this.reconnect();}},{key:\"reconnect\",value:function(){var t=this;if(this._reconnecting||this.skipReconnect)return this;var e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(\"reconnect_failed\"),this._reconnecting=!1;else {var n=this.backoff.duration();this._reconnecting=!0;var r=setTimeout((function(){e.skipReconnect||(t.emitReserved(\"reconnect_attempt\",e.backoff.attempts),e.skipReconnect||e.open((function(n){n?(e._reconnecting=!1,e.reconnect(),t.emitReserved(\"reconnect_error\",n)):e.onreconnect();})));}),n);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r);}));}}},{key:\"onreconnect\",value:function(){var t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(\"reconnect\",t);}}])&&o(e.prototype,n),y}(n(17).StrictEventEmitter);e.Manager=y;},function(t,e,n){var r=n(9),o=n(23),i=n(27),s=n(28);e.polling=function(t){var e=!1,n=!1,s=!1!==t.jsonp;if(\"undefined\"!=typeof location){var c=\"https:\"===location.protocol,a=location.port;a||(a=c?443:80),e=t.hostname!==location.hostname||a!==t.port,n=t.secure!==c;}if(t.xdomain=e,t.xscheme=n,\"open\"in new r(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error(\"JSONP disabled\");return new i(t)},e.websocket=s;},function(t,e,n){var r=n(22),o=n(2);t.exports=function(t){var e=t.xdomain,n=t.xscheme,i=t.enablesXDR;try{if(\"undefined\"!=typeof XMLHttpRequest&&(!e||r))return new XMLHttpRequest}catch(t){}try{if(\"undefined\"!=typeof XDomainRequest&&!n&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[[\"Active\"].concat(\"Object\").join(\"X\")])(\"Microsoft.XMLHTTP\")}catch(t){}};},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function i(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function s(t,e){return (s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=u(t);if(e){var o=u(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return a(this,n)}}function a(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function u(t){return (u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var f=n(3),p=n(4),l=n(0),h=n(12),y=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e);}(u,t);var e,n,a=c(u);function u(){return o(this,u),a.apply(this,arguments)}return e=u,(n=[{key:\"doOpen\",value:function(){this.poll();}},{key:\"pause\",value:function(t){var e=this;function n(){e.readyState=\"paused\",t();}if(this.readyState=\"pausing\",this.polling||!this.writable){var r=0;this.polling&&(r++,this.once(\"pollComplete\",(function(){--r||n();}))),this.writable||(r++,this.once(\"drain\",(function(){--r||n();})));}else n();}},{key:\"poll\",value:function(){this.polling=!0,this.doPoll(),this.emit(\"poll\");}},{key:\"onData\",value:function(t){var e=this;l.decodePayload(t,this.socket.binaryType).forEach((function(t,n,r){if(\"opening\"===e.readyState&&\"open\"===t.type&&e.onOpen(),\"close\"===t.type)return e.onClose(),!1;e.onPacket(t);})),\"closed\"!==this.readyState&&(this.polling=!1,this.emit(\"pollComplete\"),\"open\"===this.readyState&&this.poll());}},{key:\"doClose\",value:function(){var t=this;function e(){t.write([{type:\"close\"}]);}\"open\"===this.readyState?e():this.once(\"open\",e);}},{key:\"write\",value:function(t){var e=this;this.writable=!1,l.encodePayload(t,(function(t){e.doWrite(t,(function(){e.writable=!0,e.emit(\"drain\");}));}));}},{key:\"uri\",value:function(){var t=this.query||{},e=this.opts.secure?\"https\":\"http\",n=\"\";return !1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=h()),this.supportsBinary||t.sid||(t.b64=1),t=p.encode(t),this.opts.port&&(\"https\"===e&&443!==Number(this.opts.port)||\"http\"===e&&80!==Number(this.opts.port))&&(n=\":\"+this.opts.port),t.length&&(t=\"?\"+t),e+\"://\"+(-1!==this.opts.hostname.indexOf(\":\")?\"[\"+this.opts.hostname+\"]\":this.opts.hostname)+n+this.opts.path+t}},{key:\"name\",get:function(){return \"polling\"}}])&&i(e.prototype,n),u}(f);t.exports=y;},function(t,e){var n=Object.create(null);n.open=\"0\",n.close=\"1\",n.ping=\"2\",n.pong=\"3\",n.message=\"4\",n.upgrade=\"5\",n.noop=\"6\";var r=Object.create(null);Object.keys(n).forEach((function(t){r[n[t]]=t;}));t.exports={PACKET_TYPES:n,PACKET_TYPES_REVERSE:r,ERROR_PACKET:{type:\"error\",data:\"parser error\"}};},function(t,e,n){var r,o=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_\".split(\"\"),i={},s=0,c=0;function a(t){var e=\"\";do{e=o[t%64]+e,t=Math.floor(t/64);}while(t>0);return e}function u(){var t=a(+new Date);return t!==r?(s=0,r=t):t+\".\"+a(s++)}for(;c<64;c++)i[o[c]]=c;u.encode=a,u.decode=function(t){var e=0;for(c=0;c<t.length;c++)e=64*e+i[t.charAt(c)];return e},t.exports=u;},function(t,e){t.exports.pick=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return n.reduce((function(e,n){return t.hasOwnProperty(n)&&(e[n]=t[n]),e}),{})};},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){var n;if(\"undefined\"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if(\"string\"==typeof t)return i(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);\"Object\"===n&&t.constructor&&(n=t.constructor.name);if(\"Map\"===n||\"Set\"===n)return Array.from(t);if(\"Arguments\"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(t,e)}(t))||e&&t&&\"number\"==typeof t.length){n&&(t=n);var r=0,o=function(){};return {s:o,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:o}}throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")}var s,c=!0,a=!1;return {s:function(){n=t[Symbol.iterator]();},n:function(){var t=n.next();return c=t.done,t},e:function(t){a=!0,s=t;},f:function(){try{c||null==n.return||n.return();}finally{if(a)throw s}}}}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function c(t,e,n){return (c=\"undefined\"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=p(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function a(t,e){return (a=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function u(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=p(t);if(e){var o=p(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return f(this,n)}}function f(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function p(t){return (p=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}Object.defineProperty(e,\"__esModule\",{value:!0}),e.Socket=void 0;var l=n(5),h=n(16),y=n(17),d=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),v=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&a(t,e);}(f,t);var e,n,i=u(f);function f(t,e,n){var r;return function(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,f),(r=i.call(this)).receiveBuffer=[],r.sendBuffer=[],r.ids=0,r.acks={},r.flags={},r.io=t,r.nsp=e,r.ids=0,r.acks={},r.receiveBuffer=[],r.sendBuffer=[],r.connected=!1,r.disconnected=!0,r.flags={},n&&n.auth&&(r.auth=n.auth),r.io._autoConnect&&r.open(),r}return e=f,(n=[{key:\"subEvents\",value:function(){if(!this.subs){var t=this.io;this.subs=[h.on(t,\"open\",this.onopen.bind(this)),h.on(t,\"packet\",this.onpacket.bind(this)),h.on(t,\"error\",this.onerror.bind(this)),h.on(t,\"close\",this.onclose.bind(this))];}}},{key:\"connect\",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),\"open\"===this.io._readyState&&this.onopen()),this}},{key:\"open\",value:function(){return this.connect()}},{key:\"send\",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return e.unshift(\"message\"),this.emit.apply(this,e),this}},{key:\"emit\",value:function(t){if(d.hasOwnProperty(t))throw new Error('\"'+t+'\" is a reserved event name');for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];n.unshift(t);var o={type:l.PacketType.EVENT,data:n,options:{}};o.options.compress=!1!==this.flags.compress,\"function\"==typeof n[n.length-1]&&(this.acks[this.ids]=n.pop(),o.id=this.ids++);var i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable,s=this.flags.volatile&&(!i||!this.connected);return s||(this.connected?this.packet(o):this.sendBuffer.push(o)),this.flags={},this}},{key:\"packet\",value:function(t){t.nsp=this.nsp,this.io._packet(t);}},{key:\"onopen\",value:function(){var t=this;\"function\"==typeof this.auth?this.auth((function(e){t.packet({type:l.PacketType.CONNECT,data:e});})):this.packet({type:l.PacketType.CONNECT,data:this.auth});}},{key:\"onerror\",value:function(t){this.connected||this.emitReserved(\"connect_error\",t);}},{key:\"onclose\",value:function(t){this.connected=!1,this.disconnected=!0,delete this.id,this.emitReserved(\"disconnect\",t);}},{key:\"onpacket\",value:function(t){if(t.nsp===this.nsp)switch(t.type){case l.PacketType.CONNECT:if(t.data&&t.data.sid){var e=t.data.sid;this.onconnect(e);}else this.emitReserved(\"connect_error\",new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));break;case l.PacketType.EVENT:case l.PacketType.BINARY_EVENT:this.onevent(t);break;case l.PacketType.ACK:case l.PacketType.BINARY_ACK:this.onack(t);break;case l.PacketType.DISCONNECT:this.ondisconnect();break;case l.PacketType.CONNECT_ERROR:var n=new Error(t.data.message);n.data=t.data.data,this.emitReserved(\"connect_error\",n);}}},{key:\"onevent\",value:function(t){var e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e));}},{key:\"emitEvent\",value:function(t){if(this._anyListeners&&this._anyListeners.length){var e,n=o(this._anyListeners.slice());try{for(n.s();!(e=n.n()).done;)e.value.apply(this,t);}catch(t){n.e(t);}finally{n.f();}}c(p(f.prototype),\"emit\",this).apply(this,t);}},{key:\"ack\",value:function(t){var e=this,n=!1;return function(){if(!n){n=!0;for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];e.packet({type:l.PacketType.ACK,id:t,data:o});}}}},{key:\"onack\",value:function(t){var e=this.acks[t.id];\"function\"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id]);}},{key:\"onconnect\",value:function(t){this.id=t,this.connected=!0,this.disconnected=!1,this.emitBuffered(),this.emitReserved(\"connect\");}},{key:\"emitBuffered\",value:function(){var t=this;this.receiveBuffer.forEach((function(e){return t.emitEvent(e)})),this.receiveBuffer=[],this.sendBuffer.forEach((function(e){return t.packet(e)})),this.sendBuffer=[];}},{key:\"ondisconnect\",value:function(){this.destroy(),this.onclose(\"io server disconnect\");}},{key:\"destroy\",value:function(){this.subs&&(this.subs.forEach((function(t){return t()})),this.subs=void 0),this.io._destroy(this);}},{key:\"disconnect\",value:function(){return this.connected&&this.packet({type:l.PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose(\"io client disconnect\"),this}},{key:\"close\",value:function(){return this.disconnect()}},{key:\"compress\",value:function(t){return this.flags.compress=t,this}},{key:\"onAny\",value:function(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}},{key:\"prependAny\",value:function(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}},{key:\"offAny\",value:function(t){if(!this._anyListeners)return this;if(t){for(var e=this._anyListeners,n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}},{key:\"listenersAny\",value:function(){return this._anyListeners||[]}},{key:\"active\",get:function(){return !!this.subs}},{key:\"volatile\",get:function(){return this.flags.volatile=!0,this}}])&&s(e.prototype,n),f}(y.StrictEventEmitter);e.Socket=v;},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}Object.defineProperty(e,\"__esModule\",{value:!0}),e.hasBinary=e.isBinary=void 0;var o=\"function\"==typeof ArrayBuffer,i=Object.prototype.toString,s=\"function\"==typeof Blob||\"undefined\"!=typeof Blob&&\"[object BlobConstructor]\"===i.call(Blob),c=\"function\"==typeof File||\"undefined\"!=typeof File&&\"[object FileConstructor]\"===i.call(File);function a(t){return o&&(t instanceof ArrayBuffer||function(t){return \"function\"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}(t))||s&&t instanceof Blob||c&&t instanceof File}e.isBinary=a,e.hasBinary=function t(e,n){if(!e||\"object\"!==r(e))return !1;if(Array.isArray(e)){for(var o=0,i=e.length;o<i;o++)if(t(e[o]))return !0;return !1}if(a(e))return !0;if(e.toJSON&&\"function\"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return !0;return !1};},function(t,e,n){Object.defineProperty(e,\"__esModule\",{value:!0}),e.on=void 0,e.on=function(t,e,n){return t.on(e,n),function(){t.off(e,n);}};},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function i(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function s(t,e,n){return (s=\"undefined\"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=f(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function c(t,e){return (c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function a(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=f(t);if(e){var o=f(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return u(this,n)}}function u(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function f(t){return (f=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}Object.defineProperty(e,\"__esModule\",{value:!0}),e.StrictEventEmitter=void 0;var p=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e);}(p,t);var e,n,u=a(p);function p(){return o(this,p),u.apply(this,arguments)}return e=p,(n=[{key:\"on\",value:function(t,e){return s(f(p.prototype),\"on\",this).call(this,t,e),this}},{key:\"once\",value:function(t,e){return s(f(p.prototype),\"once\",this).call(this,t,e),this}},{key:\"emit\",value:function(t){for(var e,n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return (e=s(f(p.prototype),\"emit\",this)).call.apply(e,[this,t].concat(r)),this}},{key:\"emitReserved\",value:function(t){for(var e,n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return (e=s(f(p.prototype),\"emit\",this)).call.apply(e,[this,t].concat(r)),this}},{key:\"listeners\",value:function(t){return s(f(p.prototype),\"listeners\",this).call(this,t)}}])&&i(e.prototype,n),p}(n(1));e.StrictEventEmitter=p;},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}Object.defineProperty(e,\"__esModule\",{value:!0}),e.io=e.Socket=e.Manager=e.protocol=void 0;var o=n(19),i=n(7);t.exports=e=c;var s=e.managers={};function c(t,e){\"object\"===r(t)&&(e=t,t=void 0),e=e||{};var n,c=o.url(t,e.path||\"/socket.io\"),a=c.source,u=c.id,f=c.path,p=s[u]&&f in s[u].nsps;return e.forceNew||e[\"force new connection\"]||!1===e.multiplex||p?n=new i.Manager(a,e):(s[u]||(s[u]=new i.Manager(a,e)),n=s[u]),c.query&&!e.query&&(e.query=c.queryKey),n.socket(c.path,e)}e.io=c;var a=n(5);Object.defineProperty(e,\"protocol\",{enumerable:!0,get:function(){return a.protocol}}),e.connect=c;var u=n(7);Object.defineProperty(e,\"Manager\",{enumerable:!0,get:function(){return u.Manager}});var f=n(14);Object.defineProperty(e,\"Socket\",{enumerable:!0,get:function(){return f.Socket}}),e.default=c;},function(t,e,n){Object.defineProperty(e,\"__esModule\",{value:!0}),e.url=void 0;var r=n(6);e.url=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"\",n=arguments.length>2?arguments[2]:void 0,o=t;n=n||\"undefined\"!=typeof location&&location,null==t&&(t=n.protocol+\"//\"+n.host),\"string\"==typeof t&&(\"/\"===t.charAt(0)&&(t=\"/\"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\\/\\//.test(t)||(t=void 0!==n?n.protocol+\"//\"+t:\"https://\"+t),o=r(t)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port=\"80\":/^(http|ws)s$/.test(o.protocol)&&(o.port=\"443\")),o.path=o.path||\"/\";var i=-1!==o.host.indexOf(\":\"),s=i?\"[\"+o.host+\"]\":o.host;return o.id=o.protocol+\"://\"+s+\":\"+o.port+e,o.href=o.protocol+\"://\"+s+(n&&n.port===o.port?\"\":\":\"+o.port),o};},function(t,e,n){var r=n(21);t.exports=function(t,e){return new r(t,e)},t.exports.Socket=r,t.exports.protocol=r.protocol,t.exports.Transport=n(3),t.exports.transports=n(8),t.exports.parser=n(0);},function(t,e,n){function r(){return (r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r]);}return t}).apply(this,arguments)}function o(t){return (o=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function i(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function c(t,e){return (c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function a(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=f(t);if(e){var o=f(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return u(this,n)}}function u(t,e){return !e||\"object\"!==o(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function f(t){return (f=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var p=n(8),l=n(1),h=n(0),y=n(6),d=n(4),v=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e);}(l,t);var e,n,f=a(l);function l(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return i(this,l),e=f.call(this),t&&\"object\"===o(t)&&(n=t,t=null),t?(t=y(t),n.hostname=t.host,n.secure=\"https\"===t.protocol||\"wss\"===t.protocol,n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=y(n.host).host),e.secure=null!=n.secure?n.secure:\"undefined\"!=typeof location&&\"https:\"===location.protocol,n.hostname&&!n.port&&(n.port=e.secure?\"443\":\"80\"),e.hostname=n.hostname||(\"undefined\"!=typeof location?location.hostname:\"localhost\"),e.port=n.port||(\"undefined\"!=typeof location&&location.port?location.port:e.secure?443:80),e.transports=n.transports||[\"polling\",\"websocket\"],e.readyState=\"\",e.writeBuffer=[],e.prevBufferLen=0,e.opts=r({path:\"/engine.io\",agent:!1,withCredentials:!1,upgrade:!0,jsonp:!0,timestampParam:\"t\",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{}},n),e.opts.path=e.opts.path.replace(/\\/$/,\"\")+\"/\",\"string\"==typeof e.opts.query&&(e.opts.query=d.decode(e.opts.query)),e.id=null,e.upgrades=null,e.pingInterval=null,e.pingTimeout=null,e.pingTimeoutTimer=null,\"function\"==typeof addEventListener&&(addEventListener(\"beforeunload\",(function(){e.transport&&(e.transport.removeAllListeners(),e.transport.close());}),!1),\"localhost\"!==e.hostname&&(e.offlineEventListener=function(){e.onClose(\"transport close\");},addEventListener(\"offline\",e.offlineEventListener,!1))),e.open(),e}return e=l,(n=[{key:\"createTransport\",value:function(t){var e=function(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}(this.opts.query);e.EIO=h.protocol,e.transport=t,this.id&&(e.sid=this.id);var n=r({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new p[t](n)}},{key:\"open\",value:function(){var t;if(this.opts.rememberUpgrade&&l.priorWebsocketSuccess&&-1!==this.transports.indexOf(\"websocket\"))t=\"websocket\";else {if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit(\"error\",\"No transports available\");}),0)}t=this.transports[0];}this.readyState=\"opening\";try{t=this.createTransport(t);}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t);}},{key:\"setTransport\",value:function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on(\"drain\",(function(){e.onDrain();})).on(\"packet\",(function(t){e.onPacket(t);})).on(\"error\",(function(t){e.onError(t);})).on(\"close\",(function(){e.onClose(\"transport close\");}));}},{key:\"probe\",value:function(t){var e=this.createTransport(t,{probe:1}),n=!1,r=this;function o(){if(r.onlyBinaryUpgrades){var t=!this.supportsBinary&&r.transport.supportsBinary;n=n||t;}n||(e.send([{type:\"ping\",data:\"probe\"}]),e.once(\"packet\",(function(t){if(!n)if(\"pong\"===t.type&&\"probe\"===t.data){if(r.upgrading=!0,r.emit(\"upgrading\",e),!e)return;l.priorWebsocketSuccess=\"websocket\"===e.name,r.transport.pause((function(){n||\"closed\"!==r.readyState&&(f(),r.setTransport(e),e.send([{type:\"upgrade\"}]),r.emit(\"upgrade\",e),e=null,r.upgrading=!1,r.flush());}));}else {var o=new Error(\"probe error\");o.transport=e.name,r.emit(\"upgradeError\",o);}})));}function i(){n||(n=!0,f(),e.close(),e=null);}function s(t){var n=new Error(\"probe error: \"+t);n.transport=e.name,i(),r.emit(\"upgradeError\",n);}function c(){s(\"transport closed\");}function a(){s(\"socket closed\");}function u(t){e&&t.name!==e.name&&i();}function f(){e.removeListener(\"open\",o),e.removeListener(\"error\",s),e.removeListener(\"close\",c),r.removeListener(\"close\",a),r.removeListener(\"upgrading\",u);}l.priorWebsocketSuccess=!1,e.once(\"open\",o),e.once(\"error\",s),e.once(\"close\",c),this.once(\"close\",a),this.once(\"upgrading\",u),e.open();}},{key:\"onOpen\",value:function(){if(this.readyState=\"open\",l.priorWebsocketSuccess=\"websocket\"===this.transport.name,this.emit(\"open\"),this.flush(),\"open\"===this.readyState&&this.opts.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t]);}},{key:\"onPacket\",value:function(t){if(\"opening\"===this.readyState||\"open\"===this.readyState||\"closing\"===this.readyState)switch(this.emit(\"packet\",t),this.emit(\"heartbeat\"),t.type){case\"open\":this.onHandshake(JSON.parse(t.data));break;case\"ping\":this.resetPingTimeout(),this.sendPacket(\"pong\"),this.emit(\"pong\");break;case\"error\":var e=new Error(\"server error\");e.code=t.data,this.onError(e);break;case\"message\":this.emit(\"data\",t.data),this.emit(\"message\",t.data);}}},{key:\"onHandshake\",value:function(t){this.emit(\"handshake\",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),\"closed\"!==this.readyState&&this.resetPingTimeout();}},{key:\"resetPingTimeout\",value:function(){var t=this;clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=setTimeout((function(){t.onClose(\"ping timeout\");}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref();}},{key:\"onDrain\",value:function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit(\"drain\"):this.flush();}},{key:\"flush\",value:function(){\"closed\"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit(\"flush\"));}},{key:\"write\",value:function(t,e,n){return this.sendPacket(\"message\",t,e,n),this}},{key:\"send\",value:function(t,e,n){return this.sendPacket(\"message\",t,e,n),this}},{key:\"sendPacket\",value:function(t,e,n,r){if(\"function\"==typeof e&&(r=e,e=void 0),\"function\"==typeof n&&(r=n,n=null),\"closing\"!==this.readyState&&\"closed\"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var o={type:t,data:e,options:n};this.emit(\"packetCreate\",o),this.writeBuffer.push(o),r&&this.once(\"flush\",r),this.flush();}}},{key:\"close\",value:function(){var t=this;function e(){t.onClose(\"forced close\"),t.transport.close();}function n(){t.removeListener(\"upgrade\",n),t.removeListener(\"upgradeError\",n),e();}function r(){t.once(\"upgrade\",n),t.once(\"upgradeError\",n);}return \"opening\"!==this.readyState&&\"open\"!==this.readyState||(this.readyState=\"closing\",this.writeBuffer.length?this.once(\"drain\",(function(){this.upgrading?r():e();})):this.upgrading?r():e()),this}},{key:\"onError\",value:function(t){l.priorWebsocketSuccess=!1,this.emit(\"error\",t),this.onClose(\"transport error\",t);}},{key:\"onClose\",value:function(t,e){\"opening\"!==this.readyState&&\"open\"!==this.readyState&&\"closing\"!==this.readyState||(clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners(\"close\"),this.transport.close(),this.transport.removeAllListeners(),\"function\"==typeof removeEventListener&&removeEventListener(\"offline\",this.offlineEventListener,!1),this.readyState=\"closed\",this.id=null,this.emit(\"close\",t,e),this.writeBuffer=[],this.prevBufferLen=0);}},{key:\"filterUpgrades\",value:function(t){for(var e=[],n=0,r=t.length;n<r;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}])&&s(e.prototype,n),l}(l);v.priorWebsocketSuccess=!1,v.protocol=h.protocol,t.exports=v;},function(t,e){try{t.exports=\"undefined\"!=typeof XMLHttpRequest&&\"withCredentials\"in new XMLHttpRequest;}catch(e){t.exports=!1;}},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(){return (o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r]);}return t}).apply(this,arguments)}function i(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function c(t,e,n){return e&&s(t.prototype,e),n&&s(t,n),t}function a(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&u(t,e);}function u(t,e){return (u=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function f(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=l(t);if(e){var o=l(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return p(this,n)}}function p(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function l(t){return (l=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var h=n(9),y=n(10),d=n(1),v=n(13).pick,b=n(2);function m(){}var g=null!=new h({xdomain:!1}).responseType,k=function(t){a(n,t);var e=f(n);function n(t){var r;if(i(this,n),r=e.call(this,t),\"undefined\"!=typeof location){var o=\"https:\"===location.protocol,s=location.port;s||(s=o?443:80),r.xd=\"undefined\"!=typeof location&&t.hostname!==location.hostname||s!==t.port,r.xs=t.secure!==o;}var c=t&&t.forceBase64;return r.supportsBinary=g&&!c,r}return c(n,[{key:\"request\",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return o(t,{xd:this.xd,xs:this.xs},this.opts),new w(this.uri(),t)}},{key:\"doWrite\",value:function(t,e){var n=this.request({method:\"POST\",data:t}),r=this;n.on(\"success\",e),n.on(\"error\",(function(t){r.onError(\"xhr post error\",t);}));}},{key:\"doPoll\",value:function(){var t=this.request(),e=this;t.on(\"data\",(function(t){e.onData(t);})),t.on(\"error\",(function(t){e.onError(\"xhr poll error\",t);})),this.pollXhr=t;}}]),n}(y),w=function(t){a(n,t);var e=f(n);function n(t,r){var o;return i(this,n),(o=e.call(this)).opts=r,o.method=r.method||\"GET\",o.uri=t,o.async=!1!==r.async,o.data=void 0!==r.data?r.data:null,o.create(),o}return c(n,[{key:\"create\",value:function(){var t=v(this.opts,\"agent\",\"enablesXDR\",\"pfx\",\"key\",\"passphrase\",\"cert\",\"ca\",\"ciphers\",\"rejectUnauthorized\",\"autoUnref\");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;var e=this.xhr=new h(t),r=this;try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders)for(var o in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&e.setRequestHeader(o,this.opts.extraHeaders[o]);}catch(t){}if(\"POST\"===this.method)try{e.setRequestHeader(\"Content-type\",\"text/plain;charset=UTF-8\");}catch(t){}try{e.setRequestHeader(\"Accept\",\"*/*\");}catch(t){}\"withCredentials\"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad();},e.onerror=function(){r.onError(e.responseText);}):e.onreadystatechange=function(){4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout((function(){r.onError(\"number\"==typeof e.status?e.status:0);}),0));},e.send(this.data);}catch(t){return void setTimeout((function(){r.onError(t);}),0)}\"undefined\"!=typeof document&&(this.index=n.requestsCount++,n.requests[this.index]=this);}},{key:\"onSuccess\",value:function(){this.emit(\"success\"),this.cleanup();}},{key:\"onData\",value:function(t){this.emit(\"data\",t),this.onSuccess();}},{key:\"onError\",value:function(t){this.emit(\"error\",t),this.cleanup(!0);}},{key:\"cleanup\",value:function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=m:this.xhr.onreadystatechange=m,t)try{this.xhr.abort();}catch(t){}\"undefined\"!=typeof document&&delete n.requests[this.index],this.xhr=null;}}},{key:\"onLoad\",value:function(){var t=this.xhr.responseText;null!==t&&this.onData(t);}},{key:\"hasXDR\",value:function(){return \"undefined\"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR}},{key:\"abort\",value:function(){this.cleanup();}}]),n}(d);if(w.requestsCount=0,w.requests={},\"undefined\"!=typeof document)if(\"function\"==typeof attachEvent)attachEvent(\"onunload\",_);else if(\"function\"==typeof addEventListener){addEventListener(\"onpagehide\"in b?\"pagehide\":\"unload\",_,!1);}function _(){for(var t in w.requests)w.requests.hasOwnProperty(t)&&w.requests[t].abort();}t.exports=k,t.exports.Request=w;},function(t,e,n){var r=n(11).PACKET_TYPES,o=\"function\"==typeof Blob||\"undefined\"!=typeof Blob&&\"[object BlobConstructor]\"===Object.prototype.toString.call(Blob),i=\"function\"==typeof ArrayBuffer,s=function(t,e){var n=new FileReader;return n.onload=function(){var t=n.result.split(\",\")[1];e(\"b\"+t);},n.readAsDataURL(t)};t.exports=function(t,e,n){var c,a=t.type,u=t.data;return o&&u instanceof Blob?e?n(u):s(u,n):i&&(u instanceof ArrayBuffer||(c=u,\"function\"==typeof ArrayBuffer.isView?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer))?e?n(u instanceof ArrayBuffer?u:u.buffer):s(new Blob([u]),n):n(r[a]+(u||\"\"))};},function(t,e,n){var r,o=n(11),i=o.PACKET_TYPES_REVERSE,s=o.ERROR_PACKET;\"function\"==typeof ArrayBuffer&&(r=n(26));var c=function(t,e){if(r){var n=r.decode(t);return a(n,e)}return {base64:!0,data:t}},a=function(t,e){switch(e){case\"blob\":return t instanceof ArrayBuffer?new Blob([t]):t;case\"arraybuffer\":default:return t}};t.exports=function(t,e){if(\"string\"!=typeof t)return {type:\"message\",data:a(t,e)};var n=t.charAt(0);return \"b\"===n?{type:\"message\",data:c(t.substring(1),e)}:i[n]?t.length>1?{type:i[n],data:t.substring(1)}:{type:i[n]}:s};},function(t,e){!function(t){e.encode=function(e){var n,r=new Uint8Array(e),o=r.length,i=\"\";for(n=0;n<o;n+=3)i+=t[r[n]>>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3==2?i=i.substring(0,i.length-1)+\"=\":o%3==1&&(i=i.substring(0,i.length-2)+\"==\"),i},e.decode=function(e){var n,r,o,i,s,c=.75*e.length,a=e.length,u=0;\"=\"===e[e.length-1]&&(c--,\"=\"===e[e.length-2]&&c--);var f=new ArrayBuffer(c),p=new Uint8Array(f);for(n=0;n<a;n+=4)r=t.indexOf(e[n]),o=t.indexOf(e[n+1]),i=t.indexOf(e[n+2]),s=t.indexOf(e[n+3]),p[u++]=r<<2|o>>4,p[u++]=(15&o)<<4|i>>2,p[u++]=(3&i)<<6|63&s;return f};}(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\");},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function i(t,e,n){return (i=\"undefined\"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=f(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function s(t,e){return (s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=f(t);if(e){var o=f(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return a(this,n)}}function a(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?u(t):e}function u(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}function f(t){return (f=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var p,l=n(10),h=n(2),y=/\\n/g,d=/\\\\n/g,v=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e);}(l,t);var e,n,a=c(l);function l(t){var e;!function(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,l),(e=a.call(this,t)).query=e.query||{},p||(p=h.___eio=h.___eio||[]),e.index=p.length;var n=u(e);return p.push((function(t){n.onData(t);})),e.query.j=e.index,e}return e=l,(n=[{key:\"doClose\",value:function(){this.script&&(this.script.onerror=function(){},this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),i(f(l.prototype),\"doClose\",this).call(this);}},{key:\"doPoll\",value:function(){var t=this,e=document.createElement(\"script\");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError(\"jsonp poll error\",e);};var n=document.getElementsByTagName(\"script\")[0];n?n.parentNode.insertBefore(e,n):(document.head||document.body).appendChild(e),this.script=e,\"undefined\"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement(\"iframe\");document.body.appendChild(t),document.body.removeChild(t);}),100);}},{key:\"doWrite\",value:function(t,e){var n,r=this;if(!this.form){var o=document.createElement(\"form\"),i=document.createElement(\"textarea\"),s=this.iframeId=\"eio_iframe_\"+this.index;o.className=\"socketio\",o.style.position=\"absolute\",o.style.top=\"-1000px\",o.style.left=\"-1000px\",o.target=s,o.method=\"POST\",o.setAttribute(\"accept-charset\",\"utf-8\"),i.name=\"d\",o.appendChild(i),document.body.appendChild(o),this.form=o,this.area=i;}function c(){a(),e();}function a(){if(r.iframe)try{r.form.removeChild(r.iframe);}catch(t){r.onError(\"jsonp polling iframe removal error\",t);}try{var t='<iframe src=\"javascript:0\" name=\"'+r.iframeId+'\">';n=document.createElement(t);}catch(t){(n=document.createElement(\"iframe\")).name=r.iframeId,n.src=\"javascript:0\";}n.id=r.iframeId,r.form.appendChild(n),r.iframe=n;}this.form.action=this.uri(),a(),t=t.replace(d,\"\\\\\\n\"),this.area.value=t.replace(y,\"\\\\n\");try{this.form.submit();}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){\"complete\"===r.iframe.readyState&&c();}:this.iframe.onload=c;}},{key:\"supportsBinary\",get:function(){return !1}}])&&o(e.prototype,n),l}(l);t.exports=v;},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function i(t,e){return (i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function s(t){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if(\"function\"==typeof Proxy)return !0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return !1}}();return function(){var n,r=a(t);if(e){var o=a(this).constructor;n=Reflect.construct(r,arguments,o);}else n=r.apply(this,arguments);return c(this,n)}}function c(t,e){return !e||\"object\"!==r(e)&&\"function\"!=typeof e?function(t){if(void 0===t)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return t}(t):e}function a(t){return (a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var u=n(3),f=n(0),p=n(4),l=n(12),h=n(13).pick,y=n(29),d=y.WebSocket,v=y.usingBrowserWebSocket,b=y.defaultBinaryType,m=\"undefined\"!=typeof navigator&&\"string\"==typeof navigator.product&&\"reactnative\"===navigator.product.toLowerCase(),g=function(t){!function(t,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e);}(a,t);var e,n,c=s(a);function a(t){var e;return function(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}(this,a),(e=c.call(this,t)).supportsBinary=!t.forceBase64,e}return e=a,(n=[{key:\"doOpen\",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,n=m?{}:h(this.opts,\"agent\",\"perMessageDeflate\",\"pfx\",\"key\",\"passphrase\",\"cert\",\"ca\",\"ciphers\",\"rejectUnauthorized\",\"localAddress\",\"protocolVersion\",\"origin\",\"maxPayload\",\"family\",\"checkServerIdentity\");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=v&&!m?e?new d(t,e):new d(t):new d(t,e,n);}catch(t){return this.emit(\"error\",t)}this.ws.binaryType=this.socket.binaryType||b,this.addEventListeners();}}},{key:\"addEventListeners\",value:function(){var t=this;this.ws.onopen=function(){t.opts.autoUnref&&t.ws._socket.unref(),t.onOpen();},this.ws.onclose=this.onClose.bind(this),this.ws.onmessage=function(e){return t.onData(e.data)},this.ws.onerror=function(e){return t.onError(\"websocket error\",e)};}},{key:\"write\",value:function(t){var e=this;this.writable=!1;for(var n=t.length,r=0,o=n;r<o;r++)!function(t){f.encodePacket(t,e.supportsBinary,(function(r){var o={};v||(t.options&&(o.compress=t.options.compress),e.opts.perMessageDeflate&&(\"string\"==typeof r?Buffer.byteLength(r):r.length)<e.opts.perMessageDeflate.threshold&&(o.compress=!1));try{v?e.ws.send(r):e.ws.send(r,o);}catch(t){}--n||(e.emit(\"flush\"),setTimeout((function(){e.writable=!0,e.emit(\"drain\");}),0));}));}(t[r]);}},{key:\"onClose\",value:function(){u.prototype.onClose.call(this);}},{key:\"doClose\",value:function(){void 0!==this.ws&&(this.ws.close(),this.ws=null);}},{key:\"uri\",value:function(){var t=this.query||{},e=this.opts.secure?\"wss\":\"ws\",n=\"\";return this.opts.port&&(\"wss\"===e&&443!==Number(this.opts.port)||\"ws\"===e&&80!==Number(this.opts.port))&&(n=\":\"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=l()),this.supportsBinary||(t.b64=1),(t=p.encode(t)).length&&(t=\"?\"+t),e+\"://\"+(-1!==this.opts.hostname.indexOf(\":\")?\"[\"+this.opts.hostname+\"]\":this.opts.hostname)+n+this.opts.path+t}},{key:\"check\",value:function(){return !(!d||\"__initialize\"in d&&this.name===a.prototype.name)}},{key:\"name\",get:function(){return \"websocket\"}}])&&o(e.prototype,n),a}(u);t.exports=g;},function(t,e,n){var r=n(2);t.exports={WebSocket:r.WebSocket||r.MozWebSocket,usingBrowserWebSocket:!0,defaultBinaryType:\"arraybuffer\"};},function(t,e,n){function r(t){return (r=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&\"function\"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?\"symbol\":typeof t})(t)}Object.defineProperty(e,\"__esModule\",{value:!0}),e.reconstructPacket=e.deconstructPacket=void 0;var o=n(15);e.deconstructPacket=function(t){var e=[],n=t.data,i=t;return i.data=function t(e,n){if(!e)return e;if(o.isBinary(e)){var i={_placeholder:!0,num:n.length};return n.push(e),i}if(Array.isArray(e)){for(var s=new Array(e.length),c=0;c<e.length;c++)s[c]=t(e[c],n);return s}if(\"object\"===r(e)&&!(e instanceof Date)){var a={};for(var u in e)e.hasOwnProperty(u)&&(a[u]=t(e[u],n));return a}return e}(n,e),i.attachments=e.length,{packet:i,buffers:e}},e.reconstructPacket=function(t,e){return t.data=function t(e,n){if(!e)return e;if(e&&e._placeholder)return n[e.num];if(Array.isArray(e))for(var o=0;o<e.length;o++)e[o]=t(e[o],n);else if(\"object\"===r(e))for(var i in e)e.hasOwnProperty(i)&&(e[i]=t(e[i],n));return e}(t.data,e),t.attachments=void 0,t};},function(t,e){function n(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0;}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n;}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0;},n.prototype.setMin=function(t){this.ms=t;},n.prototype.setMax=function(t){this.max=t;},n.prototype.setJitter=function(t){this.jitter=t;};}])}));\n    \n      }(socket_io_min));\n    \n      var lzString_min = {exports: {}};\n    \n      (function (module) {\n      var LZString=function(){function o(o,r){if(!t[o]){t[o]={};for(var n=0;n<o.length;n++)t[o][o.charAt(n)]=n;}return t[o][r]}var r=String.fromCharCode,n=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",e=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$\",t={},i={compressToBase64:function(o){if(null==o)return \"\";var r=i._compress(o,6,function(o){return n.charAt(o)});switch(r.length%4){default:case 0:return r;case 1:return r+\"===\";case 2:return r+\"==\";case 3:return r+\"=\"}},decompressFromBase64:function(r){return null==r?\"\":\"\"==r?null:i._decompress(r.length,32,function(e){return o(n,r.charAt(e))})},compressToUTF16:function(o){return null==o?\"\":i._compress(o,15,function(o){return r(o+32)})+\" \"},decompressFromUTF16:function(o){return null==o?\"\":\"\"==o?null:i._decompress(o.length,16384,function(r){return o.charCodeAt(r)-32})},compressToUint8Array:function(o){for(var r=i.compress(o),n=new Uint8Array(2*r.length),e=0,t=r.length;t>e;e++){var s=r.charCodeAt(e);n[2*e]=s>>>8,n[2*e+1]=s%256;}return n},decompressFromUint8Array:function(o){if(null===o||void 0===o)return i.decompress(o);for(var n=new Array(o.length/2),e=0,t=n.length;t>e;e++)n[e]=256*o[2*e]+o[2*e+1];var s=[];return n.forEach(function(o){s.push(r(o));}),i.decompress(s.join(\"\"))},compressToEncodedURIComponent:function(o){return null==o?\"\":i._compress(o,6,function(o){return e.charAt(o)})},decompressFromEncodedURIComponent:function(r){return null==r?\"\":\"\"==r?null:(r=r.replace(/ /g,\"+\"),i._decompress(r.length,32,function(n){return o(e,r.charAt(n))}))},compress:function(o){return i._compress(o,16,function(o){return r(o)})},_compress:function(o,r,n){if(null==o)return \"\";var e,t,i,s={},p={},u=\"\",c=\"\",a=\"\",l=2,f=3,h=2,d=[],m=0,v=0;for(i=0;i<o.length;i+=1)if(u=o.charAt(i),Object.prototype.hasOwnProperty.call(s,u)||(s[u]=f++,p[u]=!0),c=a+u,Object.prototype.hasOwnProperty.call(s,c))a=c;else {if(Object.prototype.hasOwnProperty.call(p,a)){if(a.charCodeAt(0)<256){for(e=0;h>e;e++)m<<=1,v==r-1?(v=0,d.push(n(m)),m=0):v++;for(t=a.charCodeAt(0),e=0;8>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;}else {for(t=1,e=0;h>e;e++)m=m<<1|t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=a.charCodeAt(0),e=0;16>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;}l--,0==l&&(l=Math.pow(2,h),h++),delete p[a];}else for(t=s[a],e=0;h>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;l--,0==l&&(l=Math.pow(2,h),h++),s[c]=f++,a=String(u);}if(\"\"!==a){if(Object.prototype.hasOwnProperty.call(p,a)){if(a.charCodeAt(0)<256){for(e=0;h>e;e++)m<<=1,v==r-1?(v=0,d.push(n(m)),m=0):v++;for(t=a.charCodeAt(0),e=0;8>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;}else {for(t=1,e=0;h>e;e++)m=m<<1|t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=a.charCodeAt(0),e=0;16>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;}l--,0==l&&(l=Math.pow(2,h),h++),delete p[a];}else for(t=s[a],e=0;h>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;l--,0==l&&(l=Math.pow(2,h),h++);}for(t=2,e=0;h>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;for(;;){if(m<<=1,v==r-1){d.push(n(m));break}v++;}return d.join(\"\")},decompress:function(o){return null==o?\"\":\"\"==o?null:i._decompress(o.length,32768,function(r){return o.charCodeAt(r)})},_decompress:function(o,n,e){var i,s,p,u,c,a,l,f=[],h=4,d=4,m=3,v=\"\",w=[],A={val:e(0),position:n,index:1};for(i=0;3>i;i+=1)f[i]=i;for(p=0,c=Math.pow(2,2),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;switch(p){case 0:for(p=0,c=Math.pow(2,8),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;l=r(p);break;case 1:for(p=0,c=Math.pow(2,16),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;l=r(p);break;case 2:return \"\"}for(f[3]=l,s=l,w.push(l);;){if(A.index>o)return \"\";for(p=0,c=Math.pow(2,m),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;switch(l=p){case 0:for(p=0,c=Math.pow(2,8),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;f[d++]=r(p),l=d-1,h--;break;case 1:for(p=0,c=Math.pow(2,16),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;f[d++]=r(p),l=d-1,h--;break;case 2:return w.join(\"\")}if(0==h&&(h=Math.pow(2,m),m++),f[l])v=f[l];else {if(l!==d)return null;v=s+s.charAt(0);}w.push(v),f[d++]=s+v.charAt(0),h--,s=v,0==h&&(h=Math.pow(2,m),m++);}}};return i}();null!=module&&(module.exports=LZString);\n      }(lzString_min));\n    \n      var lzstring = lzString_min.exports;\n    \n      /**\n       * This file contains methods related to retrieving, storing and reading the logs\n       * from a remote server, it is used for QA only and all of them should not get\n       * included in the bundle when using production mode\n       */\n      /**\n       * Logger utility methods used for debugging\n       *\n       * @param {store} store - A storage solution, either sessionStorage, localStorage, indexeddb, etc\n       * @constructor\n       */\n      const LoggerExternals = (store = sessionStorage) => {\n          {\n              return {\n                  /**\n                   * Compress a string to take less space during transmission\n                   *\n                   * @param {string} string - The string to compress\n                   * @returns {string} - The compressed string\n                   */\n                  compress: (string) => {\n                      return lzstring.compressToUTF16(string);\n                  },\n                  /**\n                   * Deletes the logs stored in the store\n                   *\n                   * @return {void}\n                   */\n                  logClear: () => {\n                      return store.clear();\n                  },\n                  /**\n                   * Read the logs that were stored in the long term storage (compressed)\n                   *\n                   * @param {number} chunk - The chunk to read from the log file\n                   * @param {number} chunkSize - The size of the chunk\n                   * @return {string}\n                   */\n                  logRead: (chunk = 0, chunkSize = LoggerExternals(store).logReadLength()) => {\n                      const startPosition = chunk * chunkSize;\n                      const endPosition = startPosition + chunkSize;\n                      const log = [];\n                      // Read each stored line until we read all the lines in a chunk\n                      for (let i = startPosition; i <= endPosition; i += 1) {\n                          const item = lzstring.decompress(store.getItem(String(i)));\n                          if (item)\n                              log.push(JSON.parse(item));\n                      }\n                      return JSON.stringify(log);\n                  },\n                  /**\n                   * Read the size of the logs stored in the sessionStorage, used by the server to calculate\n                   * chunk transmission size\n                   *\n                   * @return {number}\n                   */\n                  logReadLength: () => {\n                      return parseInt(store.getItem('logLength'), 10) || 0;\n                  },\n                  /**\n                   * Store logs in the storage mechanism for later retrieval\n                   *\n                   * @param {string} level - The console level (ex: info, warn, etc)\n                   * @param {*} logEvent - The data\n                   */\n                  logStore: (level, logEvent) => {\n                      store.setItem('logLength', String(LoggerExternals(store).logReadLength() + 1));\n                      store.setItem(String(store.length), lzstring.compress(JSON.stringify(logEvent)));\n                  },\n              };\n          }\n      };\n      var LoggerExternals$1 = LoggerExternals;\n    \n      /**\n       * see https://tools.ietf.org/html/rfc1808\n       *\n       * \n       * This file was modified by Apple Inc.\n       * Modifications Copyright (c) 2018-\n       *\n       * The initial developer is https://github.com/tjenkinson/url-toolkit. Copyright (c) 2016 Tom Jenkinson.\n       *\n       * Licensed under the Apache License, Version 2.0 (the â€œLicenseâ€); you may not\n       * use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       * http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software distributed\n       * under the License is distributed on an â€œAS ISâ€ BASIS, WITHOUT WARRANTIES OR\n       * CONDITIONS OF ANY KIND, either express or implied. See the License for the\n       * specific language governing permissions and limitations under the License.\n       *\n       */\n      const URL_REGEX = /^((?:[^\\/;?#]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\n      const FIRST_SEGMENT_REGEX = /^([^\\/;?#]*)(.*)$/;\n      const SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n      const SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/).*?(?=\\/)/g;\n      const URLToolkit = {\n          // jshint ignore:line\n          // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n          // E.g\n          // With opts.alwaysNormalize = false (default, spec compliant)\n          // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n          // With opts.alwaysNormalize = true (default, not spec compliant)\n          // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n          buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n              opts = opts || {};\n              // remove any remaining space and CRLF\n              baseURL = baseURL.trim();\n              relativeURL = relativeURL.trim();\n              if (!relativeURL) {\n                  // 2a) If the embedded URL is entirely empty, it inherits the\n                  // entire base URL (i.e., is set equal to the base URL)\n                  // and we are done.\n                  if (!opts.alwaysNormalize) {\n                      return baseURL;\n                  }\n                  const basePartsForNormalise = URLToolkit.parseURL(baseURL);\n                  if (!basePartsForNormalise) {\n                      throw new Error('Error trying to parse base URL.');\n                  }\n                  basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);\n                  return URLToolkit.buildURLFromParts(basePartsForNormalise);\n              }\n              const relativeParts = URLToolkit.parseURL(relativeURL);\n              if (!relativeParts) {\n                  throw new Error('Error trying to parse relative URL.');\n              }\n              if (relativeParts.scheme) {\n                  // 2b) If the embedded URL starts with a scheme name, it is\n                  // interpreted as an absolute URL and we are done.\n                  if (!opts.alwaysNormalize) {\n                      return relativeURL;\n                  }\n                  relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n                  return URLToolkit.buildURLFromParts(relativeParts);\n              }\n              const baseParts = URLToolkit.parseURL(baseURL);\n              if (!baseParts) {\n                  throw new Error('Error trying to parse base URL.');\n              }\n              if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n                  // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n                  // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n                  const pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n                  baseParts.netLoc = pathParts[1];\n                  baseParts.path = pathParts[2];\n              }\n              if (baseParts.netLoc && !baseParts.path) {\n                  baseParts.path = '/';\n              }\n              const builtParts = {\n                  // 2c) Otherwise, the embedded URL inherits the scheme of\n                  // the base URL.\n                  scheme: baseParts.scheme,\n                  netLoc: relativeParts.netLoc,\n                  path: null,\n                  params: relativeParts.params,\n                  query: relativeParts.query,\n                  fragment: relativeParts.fragment,\n              };\n              if (!relativeParts.netLoc) {\n                  // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n                  // Step 7.  Otherwise, the embedded URL inherits the <net_loc>\n                  // (if any) of the base URL.\n                  builtParts.netLoc = baseParts.netLoc;\n                  // 4) If the embedded URL path is preceded by a slash \"/\", the\n                  // path is not relative and we skip to Step 7.\n                  if (relativeParts.path[0] !== '/') {\n                      if (!relativeParts.path) {\n                          // 5) If the embedded URL path is empty (and not preceded by a\n                          // slash), then the embedded URL inherits the base URL path\n                          builtParts.path = baseParts.path;\n                          // 5a) if the embedded URL's <params> is non-empty, we skip to\n                          // step 7; otherwise, it inherits the <params> of the base\n                          // URL (if any) and\n                          if (!relativeParts.params) {\n                              builtParts.params = baseParts.params;\n                              // 5b) if the embedded URL's <query> is non-empty, we skip to\n                              // step 7; otherwise, it inherits the <query> of the base\n                              // URL (if any) and we skip to step 7.\n                              if (!relativeParts.query) {\n                                  builtParts.query = baseParts.query;\n                              }\n                          }\n                      }\n                      else {\n                          // Non-standard, allow non-empty paths to inherit the query\n                          if (opts.inheritQuery) {\n                              if (!relativeParts.query) {\n                                  builtParts.query = baseParts.query;\n                              }\n                          }\n                          // 6) The last segment of the base URL's path (anything\n                          // following the rightmost slash \"/\", or the entire path if no\n                          // slash is present) is removed and the embedded URL's path is\n                          // appended in its place.\n                          const baseURLPath = baseParts.path;\n                          const newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;\n                          builtParts.path = URLToolkit.normalizePath(newPath);\n                      }\n                  }\n              }\n              if (builtParts.path === null) {\n                  builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;\n              }\n              return URLToolkit.buildURLFromParts(builtParts);\n          },\n          parseURL: function (url) {\n              const parts = URL_REGEX.exec(url);\n              if (!parts) {\n                  return null;\n              }\n              return {\n                  scheme: parts[1] || '',\n                  netLoc: parts[2] || '',\n                  path: parts[3] || '',\n                  params: parts[4] || '',\n                  query: parts[5] || '',\n                  fragment: parts[6] || '',\n              };\n          },\n          normalizePath: function (path) {\n              // The following operations are\n              // then applied, in order, to the new path:\n              // 6a) All occurrences of \"./\", where \".\" is a complete path\n              // segment, are removed.\n              // 6b) If the path ends with \".\" as a complete path segment,\n              // that \".\" is removed.\n              path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n              // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n              // complete path segment not equal to \"..\", are removed.\n              // Removal of these path segments is performed iteratively,\n              // removing the leftmost matching pattern on each iteration,\n              // until no matching pattern remains.\n              // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n              // complete path segment not equal to \"..\", that\n              // \"<segment>/..\" is removed.\n              while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) { } // eslint-disable-line\n              return path.split('').reverse().join('');\n          },\n          buildURLFromParts: function (parts) {\n              return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;\n          },\n          getHostName: function (url) {\n              let hostname;\n              if (!url) {\n                  return hostname;\n              }\n              if (url.indexOf('://') > -1) {\n                  hostname = url.split('/')[2];\n              }\n              else {\n                  hostname = url.split('/')[0];\n              }\n              // remove port and query if present\n              hostname = hostname.split(':')[0];\n              hostname = hostname.split('?')[0];\n              return hostname;\n          },\n      };\n      var URLToolkit$1 = URLToolkit;\n    \n      /**\n       * URL utils for hostname and other stuff\n       */\n      function isCustomUrl(url) {\n          return url != null && !url.startsWith('http://') && !url.startsWith('https://');\n      }\n      function getHostName(url) {\n          if (url == null) {\n              return null;\n          }\n          if (isCustomUrl(url)) {\n              return null;\n          }\n          return URLToolkit.getHostName(url);\n      }\n      const hostsRequiringQueries = ['.*.itunes.apple.com'];\n      const URLQueries = {\n          deviceName: '&xapdn=',\n          deviceModel: '&xapdm=',\n          language: '&xapdl=',\n          dsid: '&xapdsid=',\n          subs: '&xapsub=',\n      };\n      function urlNeedsUpdate(url, enableQueryParamsForITunes) {\n          if (enableQueryParamsForITunes) {\n              const hostName = getHostName(url);\n              return (undefined !==\n                  hostsRequiringQueries.find((regStr) => {\n                      const regex = new RegExp(regStr);\n                      return regex.exec(hostName);\n                  }));\n          }\n          return false;\n      }\n      function shouldUpdateUrlWithDeviceNameAndModel(platformInfo) {\n          const deviceModel = platformInfo.model, deviceName = platformInfo.manufacturer;\n          if (!deviceModel || !deviceName) {\n              getLogger().warn(`Missing model/manufacturer in platformInfo model ${deviceModel} manufacturer ${deviceName}`);\n          }\n          return !!deviceModel && !!deviceName;\n      }\n      function updateUrlWithDeviceNameAndModel(url, platformInfo) {\n          const deviceModel = platformInfo.model, deviceName = platformInfo.manufacturer, urlHasQueryParams = url.indexOf('?') !== -1, deviceModelEnc = encodeURIComponent(deviceModel), deviceNameEnc = encodeURIComponent(deviceName);\n          url = urlHasQueryParams ? url : url + '?';\n          return url + URLQueries.deviceName + deviceNameEnc + URLQueries.deviceModel + deviceModelEnc;\n      }\n      function updateUrlWithOptionsQuery(url, queryParameters) {\n          const urlHasQueryParams = url.indexOf('?') !== -1;\n          url = urlHasQueryParams ? url : url + '?';\n          let query;\n          const logger = getLogger();\n          for (query in queryParameters) {\n              if (!queryParameters[query]) {\n                  logger.warn(`Missing ${query} info`);\n              }\n              else {\n                  url += URLQueries[query] + (query === 'subs' ? encodeURIComponent(queryParameters[query]) : queryParameters[query]);\n              }\n          }\n          return url;\n      }\n      function updateUrlWithQueryStrings(url, platformInfo, queryParameters) {\n          if (shouldUpdateUrlWithDeviceNameAndModel(platformInfo)) {\n              url = updateUrlWithDeviceNameAndModel(url, platformInfo);\n          }\n          url = updateUrlWithOptionsQuery(url, queryParameters);\n          return url;\n      }\n      function hasMatchingHost(hostName, url) {\n          return !hostName || hostName === getHostName(url);\n      }\n      function isRedirectStatusCode(status) {\n          return status === 300 || status === 302 || status === 303 || status === 305;\n      }\n      /**\n       * Return all the GET parameters passed to a page\n       * This function is different from parseParamsFromURL(),\n       * where it just extracts all the parameters\n       * without trying to determine the correct type\n       *\n       * @param {string} href - The url to extract\n       * @param {array} exclude - A list of parameters to exclude from the list\n       * @return {object} - Key value pair with parameter name as key and value\n       */\n      const getURLParams = (href, exclude = []) => {\n          const params = {};\n          try {\n              const urlObject = new URL(href);\n              const urlSearch = urlObject.search;\n              const searchParams = new URLSearchParams(urlSearch);\n              for (const param of searchParams.entries()) {\n                  if (!exclude.includes(param[0]))\n                      params[param[0]] = param[1];\n              }\n          }\n          catch (e) {\n              getLogger().error(e);\n          }\n          return params;\n      };\n      function getTimeOffsetParameter(url) {\n          const paramString = URLToolkit.parseURL(url).fragment.substr(1);\n          if (paramString.length === 0) {\n              return null;\n          }\n          const searchParams = new URLSearchParams(paramString);\n          if (!searchParams.has('t')) {\n              return null;\n          }\n          const timeOffsetValue = Number(searchParams.get('t'));\n          if (isFiniteNumber(timeOffsetValue)) {\n              return timeOffsetValue;\n          }\n          return null;\n      }\n      /**\n       * Get specified parameters from the search query while\n       * trying to extract the correct type from each one.\n       *\n       * @param {array} extract - The list of parameters to extract\n       * @return {*}\n       */\n      const parseParamsFromURL = (input, extract) => {\n          const url = new URL(input);\n          const params = url.searchParams;\n          const result = {};\n          const getTypedParam = (name, defaultValue = undefined, json = false, transform) => {\n              const param = params.get(name);\n              let value;\n              switch (param) {\n                  case 'undefined':\n                      value = undefined;\n                      break;\n                  case 'null':\n                      value = null;\n                      break;\n                  case 'False':\n                  case 'false':\n                      value = false;\n                      break;\n                  case 'True':\n                  case 'true':\n                      value = true;\n                      break;\n                  default:\n                      if (param) {\n                          const num = Number(param);\n                          if (isFiniteNumber(num)) {\n                              value = num;\n                          }\n                          else {\n                              value = param;\n                          }\n                      }\n                      break;\n              }\n              if (typeof value === 'string' && json) {\n                  value = safeParseJSON(value);\n              }\n              if (typeof value === 'string' && transform) {\n                  value = transform(value);\n              }\n              return value !== null && value !== void 0 ? value : defaultValue;\n          };\n          extract.forEach((param) => {\n              result[param.name] = getTypedParam(param.name, param.default, param.json, param.transform);\n          });\n          return result;\n      };\n      /**\n       * Safely parse a json, prevent throwing an error on non-parseable input\n       *\n       * @param {string} data - Hopefully a JSON string\n       * @return {*}\n       */\n      const safeParseJSON = (data) => {\n          let value;\n          if (typeof data !== 'string')\n              return data;\n          try {\n              value = JSON.parse(data);\n          }\n          catch (err) {\n              // eslint-disable-next-line no-console\n              console.error(`failed to parse param: ${data}`);\n          }\n          return value;\n      };\n      /*\n       * Get a list of the dynamic range formats the user has selected\n       *\n       * Type 0: SDR\n       * Type 2: HDR10\n       * Type 3: DV\n       * Type 4: HLG\n       *\n       * @returns {array}\n       */\n      function getVideoDynamicRangeFormats(dynamicRangeFormatSDR, dynamicRangeFormatHDR10, dynamicRangeFormatDV, dynamicRangeFormatHLG, averageBitrateCap, peakBitrateCap, clearBitrateCap) {\n          const videoDynamicRangeFormats = [\n              { type: 0, highestPlayableAverageBitRate: undefined, highestPlayablePeakBitRate: undefined },\n              { type: 2, highestPlayableAverageBitRate: undefined, highestPlayablePeakBitRate: undefined },\n              { type: 3, highestPlayableAverageBitRate: undefined, highestPlayablePeakBitRate: undefined },\n              { type: 4, highestPlayableAverageBitRate: undefined, highestPlayablePeakBitRate: undefined },\n          ];\n          const videoDynamicRangeFormatsMap = {\n              0: dynamicRangeFormatSDR,\n              2: dynamicRangeFormatHDR10,\n              3: dynamicRangeFormatDV,\n              4: dynamicRangeFormatHLG,\n          };\n          for (let formatIndex = 0; formatIndex < videoDynamicRangeFormats.length; ++formatIndex) {\n              videoDynamicRangeFormats[formatIndex].highestPlayableAverageBitRate = averageBitrateCap;\n              videoDynamicRangeFormats[formatIndex].highestPlayablePeakBitRate = peakBitrateCap;\n              videoDynamicRangeFormats[formatIndex].highestPlayablePeakBitRateForClearContent = clearBitrateCap;\n          }\n          return videoDynamicRangeFormats.filter(function (format) {\n              return !!videoDynamicRangeFormatsMap[format.type];\n          });\n      }\n      /*\n       * Get a list of the video codecs the user has selected\n       *\n       * Type 16: H264\n       * Type 64: HEVC\n       *\n       * @returns {array}\n       */\n      function getVideoCodecs(videoCodecH264, videoCodecHEVC, averageBitrateCap, peakBitrateCap) {\n          const videoCodecs = [\n              { type: 16, highestPlayableAverageBitRate: undefined, highestPlayablePeakBitRate: undefined },\n              { type: 64, highestPlayableAverageBitRate: undefined, highestPlayablePeakBitRate: undefined },\n          ];\n          const videoCodecsMap = { 16: videoCodecH264, 64: videoCodecHEVC };\n          for (let formatIndex = 0; formatIndex < videoCodecs.length; ++formatIndex) {\n              videoCodecs[formatIndex].highestPlayableAverageBitRate = averageBitrateCap;\n              videoCodecs[formatIndex].highestPlayablePeakBitRate = peakBitrateCap;\n          }\n          return videoCodecs.filter(function (format) {\n              return !!videoCodecsMap[format.type];\n          });\n      }\n    \n      class AutomationRemote {\n          constructor() {\n              this.onStop$ = new Subject();\n              this._logger = console;\n              this._playbackData = {\n                  audio: [],\n                  subtitles: [],\n                  variants: [],\n              };\n              this._timers$ = {\n                  cpu: undefined,\n                  memory: undefined,\n                  system: undefined,\n              };\n              /**\n               * Register the current parameters or player configuration\n               * This is used to check if the sockets from the automation server\n               * are requesting the page to be reloaded\n               * or the server is trying to load another player url\n               *\n               * @param {object} config - The list of GET parameters passed to the URL or other configuration values\n               * @return {void}\n               */\n              this.setConfig = (config = {}) => {\n                  this._config = JSON.stringify(config);\n              };\n              /**\n               * Trigger a socket command back to the server to perform backend tasks\n               *\n               * @return {void}\n               */\n              this.triggerSocketCommand = (command) => {\n                  if (!command)\n                      throw new Error('No command value was passed');\n                  this.socket.emit('action', {\n                      type: 'SOCKETS/TRIGGER_CONTROL_SSH',\n                      command,\n                  });\n              };\n          }\n          /**\n           * Do setup/teardown if needed on hls change\n           *\n           * @param {object} hls\n           * @setter\n           * @return {void}\n           */\n          setHls(hls) {\n              if (!hls) {\n                  this.onStop$.next();\n                  this._hls = null;\n                  this._playbackData = {\n                      audio: [],\n                      subtitles: [],\n                      variants: [],\n                  };\n                  return;\n              }\n              this._hls = hls;\n              this._hls.altAudioOptions$\n                  .pipe(tap((altAudioOptions) => (this._playbackData.audio = altAudioOptions)), takeUntil(this.onStop$))\n                  .subscribe();\n              this._hls.subtitleOptions$\n                  .pipe(tap((subtitleOptions) => (this._playbackData.subtitles = subtitleOptions)), takeUntil(this.onStop$))\n                  .subscribe();\n              this._hls.variantOptions$\n                  .pipe(tap((variantOptions) => (this._playbackData.variants = variantOptions)), takeUntil(this.onStop$))\n                  .subscribe();\n          }\n          /**\n           * Set the logger instance\n           *\n           * @param {object} logger\n           * @setter\n           * @return {void}\n           */\n          setLogger(logger) {\n              this._logger = logger;\n          }\n          /**\n           * Execute a function that matches the command name\n           *\n           * @param {string} command - The function name (ex: seek)\n           * @param {string} value - The value to pass to the function (ex: 1000)\n           * @return {*}\n           */\n          applyCommand(command, value) {\n              if (typeof this[command] === 'function') {\n                  try {\n                      return this[command](value) || true; // Always return a value for the socket server to know we responded\n                  }\n                  catch (e) {\n                      this._logger.error(e);\n                  }\n              }\n          }\n          respondToSocketAction(data, callback) {\n              const loggerExternals = LoggerExternals$1();\n              this._logger.qe({ critical: true, name: 'interact', data });\n              if (!this._hls) {\n                  return this._logger.warn(`hls object not initialized while trying to execute ${data.command}`);\n              }\n              switch (data.command) {\n                  case 'cpu':\n                      this._logger.qe({ critical: true, name: 'cpu', data: replaceAll('\\n', ' | ', data.value) });\n                      break;\n                  case 'free-memory':\n                      this._logger.qe({ critical: true, name: 'freeMemory', data: replaceAll('\\n', ' | ', data.value) });\n                      break;\n                  case 'log-clear':\n                      callback(loggerExternals.logClear());\n                      break;\n                  case 'log-end':\n                      //callback(utils.logEnd());\n                      break;\n                  case 'log-read':\n                      callback({ chunk: data.chunk, log: loggerExternals.compress(loggerExternals.logRead(data.chunk, data.chunkSize)) });\n                      break;\n                  case 'log-read-length':\n                      callback({ size: loggerExternals.logReadLength(), format: 'array' });\n                      break;\n                  case 'log-start':\n                      //callback(Utils.logStart());\n                      break;\n                  case 'memory':\n                      this._logger.qe({ critical: true, name: 'memory', data: getJSMemory() });\n                      break;\n                  case 'access-log':\n                      this._logger.qe({ critical: true, name: 'accessLog', data: { accessLogItems: this._hls.accessLog } });\n                      break;\n                  case 'error-log':\n                      this._logger.qe({ critical: true, name: 'errorLog', data: { errorLogItems: this._hls.errorLog } });\n                      break;\n                  default:\n                      callback(this.applyCommand(data.command, data.value));\n              }\n          }\n          /**\n           * Connect to a remote socket.io server\n           *\n           * @return {object}\n           */\n          initializeSocketService(socketurl, socketid) {\n              if (!socketurl)\n                  throw new Error('Attempted to call logConnect() without a socket URL');\n              if (!socketid)\n                  throw new Error('Attempted to call logConnect() without a socket ID');\n              this.socket = socket_io_min.exports.io(socketurl, { query: { ip: socketid } });\n              this._logger.info(`Connecting socket service with server: ${socketurl} and id: ${socketid}`);\n              this.socket.on('connect', () => this._logger.info(`Connected to: ${socketurl}`));\n              this.socket.on('disconnect', () => this._logger.info(`Disonnected from: ${socketurl}`));\n              this.socket.on('error', (e) => this._logger.error(e));\n              this.socket.on('action', this.respondToSocketAction.bind(this));\n          }\n          /**\n           * Load a playlist\n           *\n           * @param {object} data - Server object containing data needed for playback\n           * @param {object} options\n           * @param {number} initialSeekTime\n           * @return {void}\n           */\n          loadURL(data, options = {}, initialSeekTime = 0) {\n              var _a;\n              const pageUrl = data.fullURL || location.href;\n              const params = parseParamsFromURL(pageUrl, [\n                  { name: 'averageBitrateCap' },\n                  { name: 'dynamicRangeFormatSDR', default: true },\n                  { name: 'dynamicRangeFormatHDR10', default: true },\n                  { name: 'dynamicRangeFormatDV', default: true },\n                  { name: 'dynamicRangeFormatHLG', default: true },\n                  { name: 'maxHdcpLevel', default: 'TYPE-2', transform: decodeURIComponent },\n                  { name: 'maxSecurityLevel', transform: decodeURIComponent },\n                  { name: 'peakBitrateCap' },\n                  { name: 'requiresCDMAttachOnStart', default: false, json: true },\n                  { name: 'src' },\n                  { name: 'rand' },\n                  { name: 'videoCodecH264', default: false },\n                  { name: 'videoCodecHEVC', default: false },\n              ]);\n              // Reload if the server requests a different player\n              if (this._config !== JSON.stringify(getURLParams(pageUrl, ['src', 'rand'])) && !((_a = getURLParams(location === null || location === void 0 ? void 0 : location.href)) === null || _a === void 0 ? void 0 : _a.dev)) {\n                  location.href = pageUrl;\n                  return;\n              }\n              const platformInfo = {\n                  videoDynamicRangeFormats: getVideoDynamicRangeFormats(params.dynamicRangeFormatSDR, params.dynamicRangeFormatHDR10, params.dynamicRangeFormatDV, params.dynamicRangeFormatHLG, params.averageBitrateCap, params.peakBitrateCap, params.clearBitrateCap),\n                  videoCodecs: getVideoCodecs(params.videoCodecH264, params.videoCodecHEVC, params.averageBitrateCap, params.peakBitrateCap),\n                  requiresCDMAttachOnStart: params.requiresCDMAttachOnStart,\n                  maxHdcpLevel: params.maxHdcpLevel,\n                  maxSecurityLevel: params.maxSecurityLevel,\n              };\n              const storebag_url = 'https://mediaservices.cdn-apple.com/store_bags/hlsjs_qa/v1/rtc_storebag.json';\n              const reportingStorebag = new rtc.exports.RTCStorebag.RTCReportingStoreBag(storebag_url, 'HLSJSDemoPlayer', 'com.apple.hlsjs.demo', 'DemoPage', '', 1, 0);\n              const reportingAgent = new rtc.exports.RTCReportingAgent({\n                  sender: 'HLSJS',\n                  _clientName: 'HLSJSDemoPlayer',\n                  _serviceName: 'com.apple.hlsjs.demo',\n                  reportingStoreBag: reportingStorebag,\n                  applicationName: 'DemoPage',\n              });\n              const copyOptions = Object.assign({ appData: { clientName: 'HLSJSDemoPlayer', serviceName: 'com.apple.hlsjs.demo', appName: 'DemoPage', reportingAgent: reportingAgent }, userInfo: { internalBuild: true }, platformInfo }, options);\n              this._hls.loadSource(data.url, copyOptions, initialSeekTime);\n          }\n          /**\n           * Start playback if video is not detached\n           */\n          play() {\n              this._hls.desiredRate = 1;\n          }\n          /**\n           * Set the scrubbing speed\n           *\n           * @param {number|string} rate\n           */\n          playbackRate(rate) {\n              this._hls.setRate(rate);\n          }\n          /**\n           * Pause playback\n           */\n          pause() {\n              this._hls.desiredRate = 0;\n          }\n          /**\n           * Reload page\n           */\n          reload() {\n              window.location.reload();\n          }\n          /**\n           * Seek to a time value\n           *\n           * @param {number} time - Seek position\n           */\n          seekTo(time) {\n              this._hls.seekTo = time;\n          }\n          /**\n           * Seek to a date\n           *\n           * @param {Date} date - Seek position\n           */\n          seekToDate(date) {\n              this._hls.seekToDate(date);\n          }\n          /**\n           * Set the current audio\n           *\n           * @param {string} lang (ex: French)\n           */\n          setAudio(lang) {\n              const mediaOption = this._playbackData.audio.find((option) => {\n                  return option.MediaSelectionOptionsExtendedLanguageTag === lang || option.MediaSelectionOptionsName === lang;\n              }) || {};\n              this._hls.audioSelectedPersistentID = mediaOption.MediaSelectionOptionsPersistentID;\n          }\n          /**\n           * Set the current caption given a language\n           *\n           * @param {string} lang (ex: fr)\n           */\n          setCaption(lang) {\n              const mediaOption = this._playbackData.subtitles.find((option) => {\n                  return option.MediaSelectionOptionsExtendedLanguageTag === lang || option.MediaSelectionOptionsName === lang;\n              }) || {};\n              this._hls.subtitleSelectedPersistentID = mediaOption.MediaSelectionOptionsPersistentID;\n          }\n          /**\n           * Start a timer tied to the lifecycle of this class\n           * that will request a cpu value from the server\n           *\n           * @param schedule The periodicity of the timer\n           * @public\n           */\n          setTimerCpu(schedule = 2000) {\n              if (this._timers$.cpu)\n                  return;\n              this._timers$.cpu = timer(200, schedule)\n                  .pipe(tap(() => {\n                  this.triggerSocketCommand('cpu');\n              }), takeUntil(this.onStop$))\n                  .subscribe();\n              return this._timers$.cpu;\n          }\n          /**\n           * Start a timer tied to the lifecycle of this class\n           * that will request the JS memory\n           *\n           * @param schedule The periodicity of the timer\n           * @public\n           */\n          setTimerJSMemory(schedule = 2000) {\n              if (this._timers$.memory)\n                  return;\n              this._timers$.memory = timer(200, schedule)\n                  .pipe(tap(() => {\n                  const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = getJSMemory();\n                  this._logger.qe({ critical: true, name: 'memory', data: { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } });\n              }), takeUntil(this.onStop$))\n                  .subscribe();\n              return this._timers$.memory;\n          }\n          /**\n           * Start a timer tied to the lifecycle of this class\n           * that will request the system memory (RAM) value from the server\n           *\n           * @param schedule The periodicity of the timer\n           * @public\n           */\n          setTimerSystemMemory(schedule = 2000) {\n              if (this._timers$.system)\n                  return;\n              this._timers$.system = timer(200, schedule)\n                  .pipe(tap(() => {\n                  this.triggerSocketCommand('free-memory');\n              }), takeUntil(this.onStop$))\n                  .subscribe();\n              return this._timers$.system;\n          }\n          /**\n           * Trigger onStop observable\n           *\n           * @return {void}\n           */\n          stop() {\n              if (!this._hls)\n                  return;\n              this.onStop$.next();\n          }\n      }\n      let remote;\n      /**\n       * Get the JS memory if supported by the browser, otherwise return defaults\n       *\n       * @return {object}\n       */\n      const getJSMemory = () => {\n          const defaultMemory = {\n              usedJSHeapSize: 0,\n              jsHeapSizeLimit: 0,\n          };\n          const performance = window.performance || {};\n          return performance.memory || defaultMemory;\n      };\n      /**\n       * Create an automation instance singleton.\n       *\n       * @param socketurl The socket server URL\n       * @param socketid The socket identifier\n       */\n      function initialize(socketurl, socketid) {\n          if (socketurl && socketid) {\n              if (!remote) {\n                  remote = new AutomationRemote();\n                  remote.initializeSocketService(socketurl, socketid);\n              }\n              return remote;\n          }\n      }\n      /**\n       * Set the hls instance on the automation remote\n       */\n      function setHls(hls) {\n          remote === null || remote === void 0 ? void 0 : remote.setHls(hls);\n      }\n      /**\n       * Set the logger instance\n       */\n      function setLogger(logger) {\n          remote === null || remote === void 0 ? void 0 : remote.setLogger(logger);\n      }\n    \n      var VideoCodecRank;\n      (function (VideoCodecRank) {\n          VideoCodecRank[VideoCodecRank[\"DOVI\"] = 4] = \"DOVI\";\n          VideoCodecRank[VideoCodecRank[\"HEVC\"] = 3] = \"HEVC\";\n          VideoCodecRank[VideoCodecRank[\"VP09\"] = 2] = \"VP09\";\n          VideoCodecRank[VideoCodecRank[\"AVC\"] = 1] = \"AVC\";\n          VideoCodecRank[VideoCodecRank[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n      })(VideoCodecRank || (VideoCodecRank = {}));\n      var VideoRangeRank;\n      (function (VideoRangeRank) {\n          VideoRangeRank[VideoRangeRank[\"PQ\"] = 3] = \"PQ\";\n          VideoRangeRank[VideoRangeRank[\"HLG\"] = 2] = \"HLG\";\n          VideoRangeRank[VideoRangeRank[\"SDR\"] = 1] = \"SDR\";\n          VideoRangeRank[VideoRangeRank[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n      })(VideoRangeRank || (VideoRangeRank = {}));\n      var AudioCodecRank;\n      (function (AudioCodecRank) {\n          AudioCodecRank[AudioCodecRank[\"ALAC\"] = 7] = \"ALAC\";\n          AudioCodecRank[AudioCodecRank[\"FLAC\"] = 6] = \"FLAC\";\n          AudioCodecRank[AudioCodecRank[\"EC3\"] = 5] = \"EC3\";\n          AudioCodecRank[AudioCodecRank[\"AC3\"] = 4] = \"AC3\";\n          AudioCodecRank[AudioCodecRank[\"XHEAAC\"] = 3] = \"XHEAAC\";\n          AudioCodecRank[AudioCodecRank[\"AAC\"] = 2] = \"AAC\";\n          AudioCodecRank[AudioCodecRank[\"MP3\"] = 1] = \"MP3\";\n          AudioCodecRank[AudioCodecRank[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n      })(AudioCodecRank || (AudioCodecRank = {}));\n      var MatchRanking;\n      (function (MatchRanking) {\n          MatchRanking[MatchRanking[\"VALID\"] = 1] = \"VALID\";\n          MatchRanking[MatchRanking[\"INVALID\"] = 0] = \"INVALID\";\n      })(MatchRanking || (MatchRanking = {}));\n    \n      \n      // List of privacy allowed config headers for ServerInfo\n      // Headers need to be approved by Privacy. Here is a sample radar on how to request approval\n      // rdar://78172175\n      const privacyAllowedLoadConfigHeaders = ['via', 'x-apple-request-uuid'];\n      const defaultManifestLoadPolicy = () => ({\n          default: {\n              // Overall request configs\n              maxTimeToFirstByteMs: 10000,\n              maxLoadTimeMs: 20000,\n              autoRetry: false,\n              // Retries:\n              timeoutRetry: {\n                  maxNumRetry: 2,\n                  retryDelayMs: 0,\n                  maxRetryDelayMs: 0, // Maximum delay between retries\n              },\n              errorRetry: {\n                  maxNumRetry: 1,\n                  retryDelayMs: 1000,\n                  maxRetryDelayMs: 8000, // Maximum delay between retries\n              },\n          },\n          customURL: {\n              // Overall request configs\n              maxTimeToFirstByteMs: 10000,\n              maxLoadTimeMs: 10000,\n              autoRetry: false,\n              // Retries:\n              timeoutRetry: {\n                  maxNumRetry: 2,\n                  retryDelayMs: 0,\n                  maxRetryDelayMs: 0, // Maximum delay between retries\n              },\n              errorRetry: {\n                  maxNumRetry: 1,\n                  retryDelayMs: 1000,\n                  maxRetryDelayMs: 8000, // Maximum delay between retries\n              },\n          },\n      });\n      const fragTimeoutRetryDefaultConfig = {\n          // Timeout Retries default value\n          maxNumRetry: 4,\n          retryDelayMs: 0,\n          maxRetryDelayMs: 0, // Maximum delay between retries\n      };\n      const fragErrorRetryDefaultConfig = {\n          // Error Retries default value\n          maxNumRetry: 6,\n          retryDelayMs: 1000,\n          maxRetryDelayMs: 8000, // Maximum delay between retries\n      };\n      const defaultSessionDataAutoLoad = {\n          'com.apple.hls.chapters': true,\n      };\n      const defaultCertRetry = {\n          maxNumRetry: 0,\n          retryDelayMs: 0,\n          maxRetryDelayMs: 0, // Maximum delay between retries\n      };\n      const defaultCertLoadPolicy = {\n          default: {\n              maxTimeToFirstByteMs: 5000,\n              maxLoadTimeMs: 20000,\n              autoRetry: false,\n              timeoutRetry: defaultCertRetry,\n              errorRetry: defaultCertRetry,\n          },\n          customURL: {\n              maxTimeToFirstByteMs: 10000,\n              maxLoadTimeMs: 20000,\n              autoRetry: false,\n              timeoutRetry: defaultCertRetry,\n              errorRetry: defaultCertRetry,\n          },\n      };\n      // max overall load time should be ~30s ish\n      const defaultKeyRetry = {\n          maxNumRetry: 8,\n          retryDelayMs: 1000,\n          maxRetryDelayMs: 20000,\n          backoff: 'linear',\n      };\n      const timeoutKeyRetry = Object.assign(Object.assign({}, defaultKeyRetry), { maxNumRetry: 1 });\n      const defaultKeyLoadPolicy = {\n          default: {\n              maxTimeToFirstByteMs: 5000,\n              maxLoadTimeMs: 20000,\n              autoRetry: false,\n              timeoutRetry: timeoutKeyRetry,\n              errorRetry: defaultKeyRetry,\n          },\n          customURL: {\n              maxTimeToFirstByteMs: 10000,\n              maxLoadTimeMs: 20000,\n              autoRetry: false,\n              timeoutRetry: timeoutKeyRetry,\n              errorRetry: defaultKeyRetry,\n          },\n      };\n      const defaultTrickPlaybackConfig = {\n          enabled: true,\n          minIframeDuration: 8,\n      };\n      const hlsDefaultConfig = {\n          autoStartLoad: true,\n          startPosition: NaN,\n          defaultAudioCodec: void 0,\n          defaultVideoCodec: void 0,\n          debug: false,\n          debugLevel: 'info',\n          buildType: void 0,\n          minFramesBeforeSwitchingLevel: 11,\n          minTargetDurations: 3,\n          maxBufferLength: 60,\n          maxBufferHole: 0.5,\n          maxSeekHole: 2,\n          nudgeFromEventSeek: true,\n          jaggedSeekTolerance: 0,\n          discontinuitySeekTolerance: 2,\n          bufferedSegmentEjectionToleranceMs: 0.5,\n          almostDryBufferSec: 0.5,\n          maxTotalDurationTolerance: 0.1,\n          lowBufferThreshold: 0.5,\n          lowBufferWatchdogPeriod: 0.5,\n          highBufferWatchdogPeriod: 3,\n          seekWatchdogPeriod: 5,\n          nudgeOffset: 0.1,\n          nudgeMaxRetry: 3,\n          maxFragLookUpTolerance: 0.2,\n          initialLiveManifestSize: 1,\n          liveSyncDurationCount: 3,\n          liveMaxLatencyDurationCount: Infinity,\n          liveSyncDuration: void 0,\n          liveMaxLatencyDuration: void 0,\n          liveFlushExpiredFrags: true,\n          liveMaxUnchangedPlaylistRefresh: 3,\n          liveEdgeForZeroStartPositon: false,\n          livePlaylistUpdateStaleness: 2,\n          livePlaylistDurationNudge: 0.001,\n          allowFastSwitchUp: false,\n          minMatchGroupDuration: 5,\n          desiredIframeFPS: 8,\n          initialIframeFPS: 6,\n          minRemainingTimeInMediaPipeline: 3,\n          leftMediaTimeToAutoPause: 10,\n          startTargetDurationFactor: 0.9,\n          minRequiredStartDuration: 4,\n          maxRequiredStartDuration: 15,\n          enableWorker: true,\n          enableWebCrypto: true,\n          keySystemPreference: void 0,\n          useMultipleKeySessions: false,\n          enablePlayReadyKeySystem: false,\n          useMediaKeySystemAccessFilter: false,\n          playReadyMessageFormat: 'utf16',\n          startLevel: void 0,\n          livePlaylistRefreshDelay: 2500,\n          liveMinPlayingBufferLen: 5,\n          enableIFramePreloading: true,\n          useMediaCapabilities: false,\n          enableID3Cues: true,\n          certLoadPolicy: defaultCertLoadPolicy,\n          keyLoadPolicy: defaultKeyLoadPolicy,\n          manifestLoadPolicy: defaultManifestLoadPolicy(),\n          trickPlaybackConfig: defaultTrickPlaybackConfig,\n          playlistLoadPolicy: {\n              default: {\n                  // Overall request configs\n                  maxTimeToFirstByteMs: 10000,\n                  maxLoadTimeMs: 20000,\n                  autoRetry: false,\n                  // Retries:\n                  timeoutRetry: {\n                      maxNumRetry: 2,\n                      retryDelayMs: 0,\n                      maxRetryDelayMs: 0, // Maximum delay between retries\n                  },\n                  errorRetry: {\n                      maxNumRetry: 2,\n                      retryDelayMs: 1000,\n                      maxRetryDelayMs: 8000, // Maximum delay between retries\n                  },\n              },\n              customURL: {\n                  // Overall request configs\n                  maxTimeToFirstByteMs: 10000,\n                  maxLoadTimeMs: 10000,\n                  autoRetry: false,\n                  // Retries:\n                  timeoutRetry: {\n                      maxNumRetry: 2,\n                      retryDelayMs: 0,\n                      maxRetryDelayMs: 0, // Maximum delay between retries\n                  },\n                  errorRetry: {\n                      maxNumRetry: 2,\n                      retryDelayMs: 1000,\n                      maxRetryDelayMs: 8000, // Maximum delay between retries\n                  },\n              },\n          },\n          fragLoadPolicy: {\n              default: {\n                  // Overall request configs\n                  maxTimeToFirstByteMs: 5000,\n                  maxLoadTimeMs: 20000,\n                  autoRetry: false,\n                  // Retries:\n                  timeoutRetry: fragTimeoutRetryDefaultConfig,\n                  errorRetry: fragErrorRetryDefaultConfig,\n                  forceContentLenCheckIfNoHeader: false,\n                  reportCDNServer: true,\n              },\n              customURL: {\n                  // Overall request configs\n                  maxTimeToFirstByteMs: 10000,\n                  maxLoadTimeMs: 20000,\n                  autoRetry: false,\n                  // Retries:\n                  timeoutRetry: fragTimeoutRetryDefaultConfig,\n                  errorRetry: fragErrorRetryDefaultConfig,\n                  reportCDNServer: true,\n              },\n          },\n          steeringManifestLoadPolicy: defaultManifestLoadPolicy(),\n          maxNumAddLevelToPenaltyBox: 4,\n          firstAudioMustOverlapVideoStart: false,\n          keyMinHoldTimeBeforeCleanup: 15000,\n          startFragPrefetch: false,\n          appendErrorMaxRetry: 3,\n          alwaysResetOnNewCC: false,\n          // loader: XhrLoader, // <jgainfort> deprecated in favor of rxjs fetch\n          // loader: FetchLoader, // <jgainfort> deprecated in favor of rxjs fetch\n          fLoader: void 0,\n          pLoader: void 0,\n          xhrSetup: void 0,\n          // fetchSetup: undefined,\n          // abrController: AbrController, // <jgainfort> deprecated in favor or redux/rxjs\n          // bufferController: BufferController, // <jgainfort> deprecated in favor or redux/rxjs\n          // #if altaudio\n          // audioStreamController: AudioStreamController, // <jgainfort> deprecated in favor or redux/rxjs\n          // audioTrackController: AudioTrackController, // <jgainfort> deprecated in favor or redux/rxjs\n          iframeMaxExitSeekDuration: 2000,\n          iframeStallMaxRetry: 5,\n          audioPrimingDelay: 0,\n          // #endif\n          // #if subtitle\n          // subtitleStreamController: SubtitleStreamController, // <jgainfort> deprecated in favor or redux/rxjs\n          // subtitleTrackController: SubtitleTrackController, // <jgainfort> deprecated in favor or redux/rxjs\n          // timelineController: TimelineController, // <jgainfort> deprecated in favor or redux/rxjs\n          enableCEA708Captions: true,\n          customTextTrackCueRenderer: false,\n          enableWebVTT: true,\n          captionsTextTrack1Label: 'English',\n          captionsTextTrack1LanguageCode: 'en',\n          captionsTextTrack2Label: 'Spanish',\n          captionsTextTrack2LanguageCode: 'es',\n          enableDualTrackSelection: false,\n          condenseSubtitleTrack: false,\n          nativeTextTrackChangeHandling: true,\n          earlyFragTolerance: 7,\n          vttConcurrentLoadCount: 1,\n          trottleCheckInterval: 2000,\n          subtitleLeadTime: 30,\n          lateTolerance: 2,\n          // #endif\n          stretchShortVideoTrack: false,\n          forceKeyFrameOnDiscontinuity: true,\n          useFirstLevelAtIncompatDiscontinuity: true,\n          abrBandwidthEstimator: 'bandwidth-history-controller',\n          abrEwmaDefaultEstimate: 500000,\n          abrDefaultEstimate: 500000,\n          abrBandWidthFactor: 0.95,\n          abrBandWidthUpFactor: 0.9,\n          abrMaxWithRealBitrate: false,\n          maxStarvationDelay: 4,\n          maxLoadingDelay: 4,\n          minAutoBitrate: 0,\n          enableRtcReporting: false,\n          rtcIntervalTimeout: 300000,\n          rtcSender: 'HLSJS',\n          rtcSessionTag: 'none',\n          useHTTPPlaybackSessionId: false,\n          warmupCdms: false,\n          enablePerformanceLogging: false,\n          overridePlaybackRate: false,\n          nativeControlsEnabled: false,\n          useCustomMediaFunctions: true,\n          seekEventThrottleMs: 150,\n          enableAdaptiveStartup: true,\n          bandwidthHistoryWindowSize: 120000,\n          bandwidthHistoryTTL: 600000,\n          bandwidthHistoryAggregationMethod: 'quadratic-time-weighted',\n          bandwidthHistoryGetEstimateThrottleMs: 1000,\n          defaultTargetDuration: 10,\n          targetStartupMs: 4000,\n          adaptiveStartupMetricsOverride: {\n              maxValidHeight: 1080,\n              maxValidBitrate: Infinity,\n              maxPreferredBitrate: Infinity, // the purpose of `maxPreferredBitrate` is to limit startup time. In adaptive startup we use `targetStartupMs` instead.\n          },\n          bandwidthHistoryStorageKey: 'AppleHLS-bandwidth-estimation',\n          storageKeyPrefix: 'AppleHLS-',\n          storage: {\n              get: typeof localStorage === 'undefined' ? undefined : localStorage.getItem.bind(localStorage),\n              set: typeof localStorage === 'undefined' ? undefined : localStorage.setItem.bind(localStorage),\n          },\n          minFragmentCount: 10,\n          minPlaylistCount: 5,\n          enableCDNFallback: true,\n          enableQueryParamsForITunes: false,\n          gapless: false,\n          useViewportSizeForLevelCap: false,\n          statDefaults: {\n              playlistLoadTimeMs: 500,\n              playlistParseTimeMs: 50,\n              fragParseTimeMs: 50,\n              fragBufferCreationDelayMs: 200,\n              dataFragAppendMs: 50,\n              initFragAppendMs: 50,\n          },\n          disableVideoCodecList: new Set([\n          // codecs that will be ignored during playback\n          ]),\n          disableAudioCodecList: new Set([AudioCodecRank.ALAC, AudioCodecRank.FLAC, AudioCodecRank.XHEAAC]),\n          useHighestVideoCodecPrivate: true,\n          sessionDataAutoLoad: defaultSessionDataAutoLoad, // Attributes listed here will be auto-fetched if its URI is given.\n      };\n    \n      const NoMediaOptionKey = { itemId: 'Nah', mediaOptionId: 'Nah' };\n      const NoMediaOption = Object.assign(Object.assign({}, NoMediaOptionKey), { mediaOptionType: undefined });\n      const isEnabledMediaOption = (mediaOptionInfo) => {\n          const { itemId, mediaOptionId } = mediaOptionInfo;\n          return itemId !== 'Nah' && mediaOptionId !== 'Nah';\n      };\n      const mediaOptionKeyEquals = (firstMediaOption, secondMediaOption) => {\n          return firstMediaOption.itemId === secondMediaOption.itemId && firstMediaOption.mediaOptionId === secondMediaOption.mediaOptionId;\n      };\n      var MediaOptionType;\n      (function (MediaOptionType) {\n          MediaOptionType[MediaOptionType[\"Variant\"] = 0] = \"Variant\";\n          MediaOptionType[MediaOptionType[\"AltAudio\"] = 1] = \"AltAudio\";\n          MediaOptionType[MediaOptionType[\"Subtitle\"] = 2] = \"Subtitle\";\n      })(MediaOptionType || (MediaOptionType = {}));\n      const MediaOptionNames = ['variant', 'altAudio', 'subtitle'];\n      const MediaOptionTypes = [MediaOptionType.Variant, MediaOptionType.AltAudio, MediaOptionType.Subtitle];\n      const AVMediaOptionTypes = [MediaOptionType.Variant, MediaOptionType.AltAudio];\n    \n      var SourceBufferType;\n      (function (SourceBufferType) {\n          SourceBufferType[SourceBufferType[\"Variant\"] = 0] = \"Variant\";\n          SourceBufferType[SourceBufferType[\"AltAudio\"] = 1] = \"AltAudio\";\n      })(SourceBufferType || (SourceBufferType = {}));\n      const SourceBufferNames = ['variant', 'altAudio'];\n      function mediaOptionTypeToSourceBufferType(optionType) {\n          switch (optionType) {\n              case MediaOptionType.Variant:\n                  return SourceBufferType.Variant;\n              case MediaOptionType.AltAudio:\n                  return SourceBufferType.AltAudio;\n              default:\n                  return null;\n          }\n      }\n      function sourceBufferTypeToMediaOptionType(sbType) {\n          return sbType === SourceBufferType.Variant ? MediaOptionType.Variant : MediaOptionType.AltAudio;\n      }\n      function initSegmentEquals(a, b) {\n          const equals = a && b && a.itemId === b.itemId && a.mediaOptionId === b.mediaOptionId && a.discoSeqNum === b.discoSeqNum && a.keyId === b.keyId;\n          return equals;\n      }\n    \n      var Allowed;\n      (function (Allowed) {\n          Allowed[Allowed[\"NO\"] = 0] = \"NO\";\n          Allowed[Allowed[\"YES\"] = 1] = \"YES\";\n      })(Allowed || (Allowed = {}));\n    \n      var MediaTypeFourCC;\n      (function (MediaTypeFourCC) {\n          MediaTypeFourCC[\"UNKNOWN\"] = \"unkn\";\n          MediaTypeFourCC[\"VIDEO\"] = \"vide\";\n          MediaTypeFourCC[\"AUDIO\"] = \"soun\";\n          MediaTypeFourCC[\"SUBTITLE\"] = \"sbtl\";\n          MediaTypeFourCC[\"CLOSEDCAPTION\"] = \"clcp\";\n      })(MediaTypeFourCC || (MediaTypeFourCC = {}));\n    \n      \n      const BinarySearch = {\n          /**\n           * Searches for an item in an array which matches a certain condition.\n           * This requires the condition to only match one item in the array,\n           * and for the array to be ordered.\n           *\n           * @param {Array} list The array to search.\n           * @param {Function} comparisonFunction\n           *      Called and provided a candidate item as the first argument.\n           *      Should return:\n           *          > -1 if the item should be located at a lower index than the provided item.\n           *          > 1 if the item should be located at a higher index than the provided item.\n           *          > 0 if the item is the item you're looking for.\n           *\n           * @return {*} The object if it is found or undefined otherwise.\n           */\n          search: function (list, comparisonFunction) {\n              let minIndex = 0;\n              let maxIndex = (list === null || list === void 0 ? void 0 : list.length) - 1;\n              let currentIndex;\n              let currentElement;\n              while (minIndex <= maxIndex) {\n                  currentIndex = ((minIndex + maxIndex) / 2) | 0;\n                  currentElement = list[currentIndex];\n                  const comparisonResult = comparisonFunction(currentElement);\n                  if (comparisonResult > 0) {\n                      minIndex = currentIndex + 1;\n                  }\n                  else if (comparisonResult < 0) {\n                      maxIndex = currentIndex - 1;\n                  }\n                  else {\n                      return currentElement;\n                  }\n              }\n              return null;\n          },\n      };\n      var BinarySearch$1 = BinarySearch;\n    \n      /**\n       * Fragment finder utils, providing methods for determining next fragment to fetch\n       *\n       * \n       * \n       *\n       */\n      function fragTag(frag, level) {\n          return `sn/cc/level: ${frag.mediaSeqNum}/${frag.discoSeqNum}/${level}`;\n      }\n      function rangeString(frag) {\n          let result = 'N/A';\n          if (frag.start >= 0 && frag.duration >= 0) {\n              result = `${frag.start.toFixed(2)}-${(frag.start + frag.duration).toFixed(2)}`;\n          }\n          return result;\n      }\n      const FragmentFetchHelper = {\n          /**\n           * Finds a fragment based on the SN of the previous fragment and current buffer.\n           * @param fragPrevious - The last frag successfully appended\n           * @param fragments - The array of fragments in level\n           * @param bufferEnd - The end of the contiguous buffer range within which playhead is\n           * @param end - End time of the level\n           * @param maxFragLookUpTolerance - acceptable tolerance limit\n           */\n          findFragmentBySNAndBuffer: function (fragPrevious, fragments, bufferEnd = 0, end = 0, maxFragLookUpTolerance = 0) {\n              let foundFrag;\n              const fragNext = fragPrevious ? fragments[fragPrevious.mediaSeqNum - fragments[0].mediaSeqNum + 1] : null;\n              if (bufferEnd < end) {\n                  if (bufferEnd > end - maxFragLookUpTolerance) {\n                      maxFragLookUpTolerance = 0;\n                  }\n                  // Prefer the next fragment if it's within tolerance\n                  if (fragNext && !this.fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n                      foundFrag = fragNext;\n                  }\n                  else {\n                      foundFrag = BinarySearch.search(fragments, this.fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n                  }\n              }\n              else {\n                  // reach end of playlist\n                  foundFrag = fragments[fragments.length - 1];\n              }\n              return foundFrag;\n          },\n          fragmentWithinToleranceTest: function (bufferEnd, maxFragLookUpTolerance, candidate) {\n              // offset should be within fragment boundary - config.maxFragLookUpTolerance\n              // this is to cope with situations like\n              // bufferEnd = 9.991\n              // frag[Ã˜] : [0,10]\n              // frag[1] : [10,20]\n              // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n              //              frag start               frag start+duration\n              //                  |-----------------------------|\n              //              <--->                         <--->\n              //  ...--------><-----------------------------><---------....\n              // previous frag         matching fragment         next frag\n              //  return -1             return 0                 return 1\n              // logger.info(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n              // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n              const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n              if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n                  return 1;\n              }\n              else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n                  // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n                  return -1;\n              }\n              return 0;\n          },\n      };\n      var FragmentFetchHelper$1 = FragmentFetchHelper;\n    \n      const loggerName$9 = { name: 'disco' };\n      const DiscoHelper = {\n          startFragmentInCC: function (fragments, cc, candidate) {\n              let rank = cc - candidate.discoSeqNum;\n              if (rank === 0) {\n                  const fragPrevious = fragments[candidate.mediaSeqNum - fragments[0].mediaSeqNum - 1];\n                  rank = fragPrevious && fragPrevious.discoSeqNum === candidate.discoSeqNum ? -1 : 0;\n              }\n              return rank;\n          },\n          endFragmentInCC: function (fragments, cc, candidate) {\n              let rank = cc - candidate.discoSeqNum;\n              if (rank === 0) {\n                  const fragNext = fragments[candidate.mediaSeqNum - fragments[0].mediaSeqNum + 1];\n                  rank = fragNext && fragNext.discoSeqNum === candidate.discoSeqNum ? 1 : 0;\n              }\n              return rank;\n          },\n          findStartEndFragmentsInCC: function (fragments, cc, logger) {\n              let startFrag;\n              let endFrag;\n              if ((fragments === null || fragments === void 0 ? void 0 : fragments.length) > 0 && isFiniteNumber(cc)) {\n                  startFrag = BinarySearch.search(fragments, DiscoHelper.startFragmentInCC.bind(null, fragments, cc));\n                  endFrag = BinarySearch.search(fragments, DiscoHelper.endFragmentInCC.bind(null, fragments, cc));\n              }\n              if (!endFrag) {\n                  logger.info(loggerName$9, `cc ${cc} does not appear in fragments anymore`);\n              }\n              // handle bogus results due to undefined cc\n              if (startFrag && !isFiniteNumber(startFrag.discoSeqNum)) {\n                  logger.info(loggerName$9, `findStartEndFragmentsInCC startFrag ${startFrag.mediaSeqNum} has undefined cc ${cc}`);\n                  startFrag = undefined;\n              }\n              if (endFrag && !isFiniteNumber(endFrag.discoSeqNum)) {\n                  logger.info(loggerName$9, `findStartEndFragmentsInCC endFrag ${endFrag.mediaSeqNum} has undefined cc ${cc}`);\n                  endFrag = undefined;\n              }\n              return { startFrag, endFrag };\n          },\n          getTimeRangeDictForCC: function (fragments, cc, logger) {\n              const ccFragRange = DiscoHelper.findStartEndFragmentsInCC(fragments, cc, logger);\n              const { startFrag, endFrag } = ccFragRange;\n              const start = startFrag.start;\n              const end = endFrag.start + endFrag.duration;\n              return { start, end };\n          },\n          getTimeRangeForCC: function (fragments, cc, logger) {\n              const ccFragRange = DiscoHelper.findStartEndFragmentsInCC(fragments, cc, logger);\n              const { startFrag, endFrag } = ccFragRange;\n              let ccTimeRange = [];\n              if (startFrag && endFrag) {\n                  ccTimeRange = [startFrag.start, endFrag.start + endFrag.duration];\n              }\n              return ccTimeRange;\n          },\n          snapToCCTimeRange: function (targetTime, fragments, cc, logger) {\n              const ccRange = DiscoHelper.getTimeRangeForCC(fragments, cc, logger);\n              if (!(ccRange === null || ccRange === void 0 ? void 0 : ccRange.length)) {\n                  return targetTime;\n              }\n              return Math.min(ccRange[1], Math.max(ccRange[0], targetTime));\n          },\n          getMinTimeForCC(mainFragments, audioFragments, cc, logger) {\n              if (!(mainFragments === null || mainFragments === void 0 ? void 0 : mainFragments.length)) {\n                  return 0;\n              }\n              // const fragments = this.variantManager.getVariantInfoIfValid(this.currentVariantId)?.details?.fragments;\n              let startCCTime = 0;\n              if (isFiniteNumber(cc) && mainFragments) {\n                  const ccRange = DiscoHelper.getTimeRangeForCC(mainFragments, cc, logger);\n                  if (ccRange) {\n                      const audioCCRange = DiscoHelper.getTimeRangeForCC(audioFragments, cc, logger); // this.audioStreamController?.getAudioTimeRangeForCC(cc);\n                      if (audioCCRange === null || audioCCRange === void 0 ? void 0 : audioCCRange.length) {\n                          startCCTime = Math.max(audioCCRange[0], ccRange[0]);\n                      }\n                      else {\n                          startCCTime = ccRange[0];\n                      }\n                  }\n              }\n              return startCCTime;\n          },\n          discoSeqNumForTime(fragments, pos, tolerance = 0) {\n              const foundFrag = BinarySearch.search(fragments, FragmentFetchHelper$1.fragmentWithinToleranceTest.bind(null, pos, tolerance));\n              return foundFrag === null || foundFrag === void 0 ? void 0 : foundFrag.discoSeqNum;\n          },\n      };\n      var DiscoHelper$1 = DiscoHelper;\n    \n      const VOID = of(void 0);\n      /**\n       * Wait for some condition to be true on an observable\n       * @param source    Source observable\n       * @param condition Condition to apply\n       * @param times     How many times to allow observable to fire before completing. By default, 1\n       */\n      function waitFor(source, condition, times = 1) {\n          return source.pipe(filter(condition), take(times));\n      }\n    \n      /*\n       * Simple clock abstraction to help transform between clocks and their timelines\n       *\n       * 2020 Apple Inc. All rights reserved.\n       */\n      /**\n       * Convert a SyncTimelineValue into a different timeline\n       *\n       * @param sourceValue The value to map to a different timeline\n       * @param destTimeline The timeline to map into\n       *\n       * @returns A new SyncTimelineValue in destTimeline\n       */\n      function mapValueToTimeline(sourceValue, destTimeline) {\n          const sourceTimeline = sourceValue.timeline;\n          const newValue = ((sourceValue.seconds - sourceTimeline.rootTimeSeconds) / sourceTimeline.rate) * destTimeline.rate + destTimeline.rootTimeSeconds;\n          return { seconds: newValue, timeline: destTimeline };\n      }\n    \n      class IframeClock {\n          constructor() {\n              this._timeline = null;\n          }\n          get forward() {\n              var _a;\n              return ((_a = this.timeline) === null || _a === void 0 ? void 0 : _a.rate) > 0;\n          }\n          get isStarted() {\n              return Boolean(this.hostClock);\n          }\n          start(timeline) {\n              this.stopTime = null;\n              this._timeline = Object.assign({}, timeline);\n              const performanceTimeline = { rootTimeSeconds: performance.now() / 1000, rate: 1 };\n              this.hostClock = {\n                  timeline: performanceTimeline,\n                  getCurrentTime: () => {\n                      return { seconds: performance.now() / 1000, timeline: performanceTimeline };\n                  },\n              };\n          }\n          pause() {\n              if (this.isStarted) {\n                  this.stopTime = this.getCurrentTime();\n              }\n          }\n          stop() {\n              this.pause();\n              this.hostClock = null;\n              this._timeline = null;\n          }\n          // ClockSyncAdapter interface\n          get timeline() {\n              return this._timeline;\n          }\n          getCurrentTime() {\n              if (this.stopTime) {\n                  return this.stopTime;\n              }\n              // map the performance clock into the iframe timeline\n              const hostValue = this.hostClock.getCurrentTime();\n              const myValue = mapValueToTimeline(hostValue, this.timeline);\n              return myValue;\n          }\n      }\n    \n      /**\n       * This is a view into our media element we're appending into.  We don't care about any time other\n       * than the buffer end, so that's our time source\n       */\n      class MediaAppendClock {\n          constructor(_timeline) {\n              this._timeline = _timeline;\n              // our start time is our current buffer end\n              this.mediaRootTime = this.lastTimeSeconds = _timeline.rootTimeSeconds;\n          }\n          // ClockSyncAdapter interface\n          get timeline() {\n              return Object.assign({}, this._timeline);\n          }\n          getCurrentTime() {\n              // the latest time we know about\n              return { seconds: this.lastTimeSeconds, timeline: Object.assign({}, this._timeline) };\n          }\n      }\n    \n      /*\n       * Trickplay implementation\n       *\n       * 2020 Apple Inc. All rights reserved.\n       */\n      const loggerName$8 = { name: 'ifm' };\n      /**\n       *\n       *  A sort of 'controller' for iframes\n       *\n       * Managages two clocks:\n       *  The iframe clock has a real time host and is untied to the media progression\n       *  The media append clock represents the media element, where we are actually appending the iframes\n       *\n       * The responsibility of this class is to supply the iframes fragments via nextFragment so that\n       * the media append clock keeps pace with the iframe clock (no drift)\n       *\n       */\n      class IframeMachine {\n          constructor(config, logger) {\n              this.config = config;\n              this.logger = logger;\n              // Fragments we've modified and need to cleanup\n              this.scaledFragments = [];\n              // this is the 'iframe clock', running at the iframe rate\n              // with a timebase anchored at the time trickplay startart\n              this.iframeClock = new IframeClock();\n              this.hasMore$ = new BehaviorSubject(true);\n              this.logger = logger.child(loggerName$8);\n          }\n          destroy() {\n              this.stop();\n          }\n          resetScaledSegments() {\n              this.scaledFragments = [];\n          }\n          get anchorFrag() {\n              return this.scaledFragments.length ? this.scaledFragments[0] : null;\n          }\n          get lastFrag() {\n              return this.scaledFragments.length ? this.scaledFragments.slice(-1)[0] : null;\n          }\n          get isStarted() {\n              return Boolean(this.iframeClock.isStarted);\n          }\n          get iframeRate() {\n              var _a, _b;\n              return (_b = (_a = this.iframeClock.timeline) === null || _a === void 0 ? void 0 : _a.rate) !== null && _b !== void 0 ? _b : 0;\n          }\n          get iframeClockTimeSeconds() {\n              return Math.max(0, this.iframeClock.getCurrentTime().seconds);\n          }\n          get mediaAppendClockTimeSeconds() {\n              var _a, _b;\n              return (_b = (_a = this.mediaAppendClock) === null || _a === void 0 ? void 0 : _a.getCurrentTime().seconds) !== null && _b !== void 0 ? _b : 0;\n          }\n          get mediaRootTime() {\n              var _a;\n              return (_a = this.mediaAppendClock) === null || _a === void 0 ? void 0 : _a.mediaRootTime;\n          }\n          pause() {\n              this.iframeClock.pause();\n          }\n          stop() {\n              this.logger.debug('stop');\n              this.hasMore$.next(true);\n              this.iframeClock.stop();\n              this.mediaAppendClock = null;\n              this.resetScaledSegments();\n          }\n          checkHasMore() {\n              this.hasMore$.next(true);\n          }\n          /**\n           * Re-anchor the iframe clock\n           * @param iframeFragments\n           * @param audioFragments\n           * @param rate\n           * @param pos\n           */\n          startClocksAndGetFirstFragment(iframeFragments, audioFragments, rate, pos, disco) {\n              this.logger.info(`startClocksAndGetFirstFragment: rate(${rate}), pos(${pos})`);\n              let anchorFrag = BinarySearch.search(iframeFragments, FragmentFetchHelper$1.fragmentWithinToleranceTest.bind(null, pos, 0.0001));\n              if (!anchorFrag && pos >= iframeFragments[iframeFragments.length - 1].start) {\n                  this.logger.info(`startClocksAndGetFirstFragment: pick last frag, start=${iframeFragments[iframeFragments.length - 1].start}`);\n                  anchorFrag = iframeFragments[iframeFragments.length - 1];\n              }\n              if (!anchorFrag) {\n                  this.logger.error(`startClocksAndGetFirstFragment => no anchorFrag for time ${pos}`);\n                  this.hasMore$.next(false);\n                  return null;\n              }\n              const nextDisco = isFiniteNumber(disco) ? disco : anchorFrag.discoSeqNum;\n              const startCCTime = DiscoHelper$1.getMinTimeForCC(iframeFragments, audioFragments, nextDisco, this.logger);\n              const newPosition = isFiniteNumber(disco) && rate > 1 ? startCCTime : pos;\n              let newMediaRootTime;\n              if (rate > 1) {\n                  // fast forward should always have enough to anchor at the current point\n                  newMediaRootTime = Math.ceil(newPosition);\n              }\n              else {\n                  newMediaRootTime = Math.ceil(startCCTime);\n              }\n              this.iframeClock.start({ rootTimeSeconds: newPosition, rate });\n              this.mediaAppendClock = new MediaAppendClock({ rootTimeSeconds: newMediaRootTime, rate: 1 });\n              return { frag: anchorFrag, newMediaRootTime };\n          }\n          getNextFragment(fragments, bufferEnd, rate) {\n              const lastFrag = this.lastFrag;\n              const { iframeClock, mediaAppendClock } = this;\n              const iframeTimeline = iframeClock.timeline;\n              mediaAppendClock.lastTimeSeconds = bufferEnd;\n              this.logger.qe({\n                  critical: true,\n                  name: 'iframes',\n                  data: { maxMediaTime: bufferEnd, rate, ifmat: this.mediaAppendClock.timeline.rootTimeSeconds, ifbt: this.iframeClock.timeline.rootTimeSeconds },\n              });\n              const ixStep = iframeClock.forward ? 1 : -1;\n              let ix = Math.max(0, Math.min(lastFrag.mediaSeqNum - fragments[0].mediaSeqNum + ixStep, fragments.length - 1));\n              let nextFrag;\n              if (lastFrag.mediaSeqNum !== fragments[ix].mediaSeqNum) {\n                  // always allow first step to work for EOS cleanliness\n                  do {\n                      nextFrag = fragments[ix];\n                      const seconds = iframeClock.forward ? nextFrag.start : nextFrag.start + nextFrag.duration;\n                      const startAppendTime = mapValueToTimeline({ seconds, timeline: iframeTimeline }, mediaAppendClock.timeline);\n                      if (startAppendTime.seconds >= bufferEnd && ((iframeClock.forward && seconds >= this.iframeClockTimeSeconds) || (!iframeClock.forward && seconds <= this.iframeClockTimeSeconds))) {\n                          break;\n                      }\n                      ix += ixStep;\n                  } while (ix > 0 && ix < fragments.length);\n              }\n              if (!nextFrag) {\n                  // stream controller should have stopped and waited until we said so, and we should have found something new\n                  this.logger.error(`getNextFragment(bufferEnd: ${bufferEnd}) => no more frags, but we should have found an end fragment, setting hasMore to false`);\n                  this.hasMore$.next(false);\n              }\n              return { frag: nextFrag };\n          }\n          /**\n           * Get the next fragment to fetch\n           * @param iframeFragments\n           * @param audioFragments\n           * @param rate\n           * @param pos\n           * @param bufferLen\n           * @return anchor fragment\n           */\n          nextFragment(iframeFragments, audioFragments, rate, pos) {\n              let foundFrag;\n              let rateSwitchPos;\n              if (this.isStarted && rate !== this.iframeRate) {\n                  rateSwitchPos = this.iframeClockTimeSeconds;\n                  this.stop();\n              }\n              if (!this.isStarted) {\n                  foundFrag = this.startClocksAndGetFirstFragment(iframeFragments, audioFragments, rate, rateSwitchPos !== null && rateSwitchPos !== void 0 ? rateSwitchPos : pos);\n                  if (!foundFrag) {\n                      return;\n                  }\n              }\n              else {\n                  foundFrag = this.getNextFragment(iframeFragments, pos, rate);\n                  if (!foundFrag.frag) {\n                      return;\n                  }\n                  else if (foundFrag.frag.discoSeqNum !== this.anchorFrag.discoSeqNum) {\n                      const iframeTimeSeconds = this.iframeClockTimeSeconds;\n                      this.logger.info(`nextFragment iframeClockTime(${iframeTimeSeconds.toFixed(3)}) => found new disco, ${this.anchorFrag.discoSeqNum} to ${foundFrag.frag.discoSeqNum}`);\n                      this.stop();\n                      const { newMediaRootTime } = this.startClocksAndGetFirstFragment(iframeFragments, audioFragments, rate, iframeTimeSeconds, foundFrag.frag.discoSeqNum);\n                      foundFrag.newMediaRootTime = newMediaRootTime;\n                  }\n              }\n              const { frag, newMediaRootTime } = foundFrag;\n              const updatedFrag = this.handleNextFrag(iframeFragments, frag);\n              const appendStart = updatedFrag.iframeMediaStart, appendEnd = appendStart + updatedFrag.iframeMediaDuration;\n              this.logger.info(`nextFragment iframeClockTime(${this.iframeClockTimeSeconds.toFixed(3)}) => picked frag: ${fragTag(updatedFrag)}, source range: ${rangeString(updatedFrag)}, media append times: ${appendStart.toFixed(3)}-${appendEnd.toFixed(3)}${isFiniteNumber(newMediaRootTime) ? ', newMediaRootTime: ' + newMediaRootTime.toFixed(3) : ''}`);\n              return Object.assign(Object.assign({}, foundFrag), { frag: updatedFrag });\n          }\n          handleNextFrag(fragments, frag) {\n              const cpFrag = Object.assign(Object.assign({}, frag), { iframeMediaStart: NaN, iframeMediaDuration: NaN });\n              const { mediaAppendClock, iframeClock } = this;\n              // update our bounds just in case we're live\n              this.iframeClockBounds = DiscoHelper$1.getTimeRangeDictForCC(fragments, cpFrag.discoSeqNum, this.logger);\n              // the start of our iframe is the latest time of the media append clock\n              const bufferEnd = mediaAppendClock.getCurrentTime().seconds;\n              const iframeRate = iframeClock.timeline.rate;\n              if (!isFiniteNumber(cpFrag.iframeOriginalStart)) {\n                  // iframe mode shouldn't have mangled frag.start\n                  // we need the original frag.start to calculate initPTS.\n                  // stash it in frag.iframeOriginalStart\n                  cpFrag.iframeOriginalStart = cpFrag.start;\n              }\n              cpFrag.start = cpFrag.iframeMediaStart = bufferEnd;\n              cpFrag.iframeMediaDuration = Math.max(cpFrag.duration / Math.abs(iframeRate), 1 / this.config.minIframeDuration);\n              // track which frags we've modifed - TODO find a better way to do this\n              this.scaledFragments.push(cpFrag);\n              // check for EOS\n              if (this.isEndFrag(fragments, cpFrag)) {\n                  this.logger.info(`checkEOS(frag: ${cpFrag.mediaSeqNum}) => found end frag, setting hasMore to false`);\n                  this.hasMore$.next(false);\n              }\n              return cpFrag;\n          }\n          get hasMore() {\n              return this.hasMore$.value;\n          }\n          // anchor isn't necessary valid in this function, so don't reference it\n          /**\n           * Wait for there to be more fragments to be downloaded\n           */\n          handleWaitForMore() {\n              this.logger.trace(`handleWaitForMore(): isStarted: ${this.isStarted}`);\n              if (!this.isStarted) {\n                  return VOID;\n              }\n              const currentIframeTime = this.iframeClock.getCurrentTime();\n              const iframeClockTime = currentIframeTime.seconds;\n              const rate = currentIframeTime.timeline.rate;\n              const edgeTime = rate > 1 ? this.iframeClockBounds.end : this.iframeClockBounds.start;\n              const diff = edgeTime - currentIframeTime.seconds;\n              const wait = diff / rate; // the +/- work out with the rate and the diff\n              this.logger.info(`handleWaitForMore(): iframeClockTime: ${iframeClockTime}, edgeTime: ${edgeTime}, diff ${diff} => wait: ${wait}`);\n              return waitFor(this.hasMore$, (hasMore) => hasMore === true).pipe(tap(() => {\n                  this.logger.info(`handleWaitForMore(): iframeClockTime: ${iframeClockTime} => hasMore became true while waiting`);\n              }));\n          }\n          isEndFrag(fragments, frag) {\n              const startFrag = fragments[0];\n              const endFrag = fragments[fragments.length - 1];\n              const ff = this.iframeClock.forward;\n              const rw = !ff;\n              return (rw && (startFrag === null || startFrag === void 0 ? void 0 : startFrag.mediaSeqNum) === frag.mediaSeqNum) || (ff && (endFrag === null || endFrag === void 0 ? void 0 : endFrag.mediaSeqNum) === frag.mediaSeqNum);\n          }\n      }\n      function createIframeMachine(config, logger) {\n          return new Observable((subscriber) => {\n              const iframeMachine = new IframeMachine(config, logger);\n              subscriber.next(iframeMachine);\n              return () => {\n                  // cleanup\n              };\n          });\n      }\n    \n      function _classCallCheck(instance, Constructor) {\n        if (!(instance instanceof Constructor)) {\n          throw new TypeError(\"Cannot call a class as a function\");\n        }\n      }\n    \n      function _defineProperties(target, props) {\n        for (var i = 0; i < props.length; i++) {\n          var descriptor = props[i];\n          descriptor.enumerable = descriptor.enumerable || false;\n          descriptor.configurable = true;\n          if (\"value\" in descriptor) descriptor.writable = true;\n          Object.defineProperty(target, descriptor.key, descriptor);\n        }\n      }\n    \n      function _createClass(Constructor, protoProps, staticProps) {\n        if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n        if (staticProps) _defineProperties(Constructor, staticProps);\n        return Constructor;\n      }\n    \n      function _defineProperty(obj, key, value) {\n        if (key in obj) {\n          Object.defineProperty(obj, key, {\n            value: value,\n            enumerable: true,\n            configurable: true,\n            writable: true\n          });\n        } else {\n          obj[key] = value;\n        }\n    \n        return obj;\n      }\n    \n      /**\n       *  Use of this source code is governed by an MIT-style license that\n       * can be found in the LICENSE file at https://github.com/cartant/rxjs-spy\n       */\n    \n      /*tslint:disable:no-use-before-declare*/\n      function tag(tag) {\n        return function tagOperation(source) {\n          return source.lift(new TagOperator(tag));\n        };\n      }\n    \n      var TagOperator = /*#__PURE__*/function () {\n        // It would be better if this were a symbol. However ...\n        // error TS1166: A computed property name in a class property declaration must directly refer to a built-in symbol.\n        function TagOperator(tag) {\n          _classCallCheck(this, TagOperator);\n    \n          _defineProperty(this, \"tag\", void 0);\n    \n          this.tag = tag;\n        }\n    \n        _createClass(TagOperator, [{\n          key: \"call\",\n          value: function call(subscriber, source) {\n            return source.subscribe(subscriber);\n          }\n        }]);\n    \n        return TagOperator;\n      }();\n    \n      // Key request state from a macro level (substates in KeyRequestContext)\n      var KeyRequestMacroState;\n      (function (KeyRequestMacroState) {\n          KeyRequestMacroState[\"MustRequestResponse\"] = \"MustRequestResponse\";\n          KeyRequestMacroState[\"WaitingForKeyResponse\"] = \"WaitingForKeyResponse\";\n          KeyRequestMacroState[\"GotKeyResponse\"] = \"GotKeyResponse\";\n      })(KeyRequestMacroState || (KeyRequestMacroState = {}));\n      // TODO convert DecryptData types to ArrayBuffer so we don't need these anymore\n      function keyTagInfoToEntity(keyInfo) {\n          var _a, _b, _c, _d, _e;\n          const { method, isEncrypted, uri, format, formatversions } = keyInfo;\n          return {\n              method,\n              isEncrypted,\n              uri,\n              format,\n              formatversions,\n              ivBuf: (_b = (_a = keyInfo.iv) === null || _a === void 0 ? void 0 : _a.buffer) !== null && _b !== void 0 ? _b : null,\n              keyIdBuf: (_c = keyInfo.keyId) === null || _c === void 0 ? void 0 : _c.buffer,\n              keyBuf: (_d = keyInfo.key) === null || _d === void 0 ? void 0 : _d.buffer,\n              psshBuf: (_e = keyInfo.key) === null || _e === void 0 ? void 0 : _e.buffer,\n          };\n      }\n      function entityToKeyTagInfo(entity) {\n          const { method, isEncrypted, uri, format, formatversions } = entity;\n          const keyTagInfo = {\n              method,\n              isEncrypted,\n              uri,\n              format,\n              formatversions,\n              iv: entity.ivBuf ? new Uint8Array(entity.ivBuf) : null,\n          };\n          if (entity.keyIdBuf) {\n              keyTagInfo.keyId = new Uint8Array(entity.keyIdBuf);\n          }\n          if (entity.keyBuf) {\n              keyTagInfo.key = new Uint8Array(entity.keyBuf);\n          }\n          if (entity.psshBuf) {\n              keyTagInfo.pssh = new Uint8Array(entity.psshBuf);\n          }\n          return keyTagInfo;\n      }\n    \n      // Generic network error\n      class GenericNetworkError extends Error {\n          constructor(message, code) {\n              super(message);\n              this.code = code;\n          }\n      }\n      class HlsNetworkError extends HlsError {\n          constructor(details, fatal, reason, code, response, isTimeout) {\n              super(ErrorTypes.NETWORK_ERROR, details, fatal, reason, response);\n              this.code = code;\n              this.isTimeout = isTimeout;\n              this.response = response;\n          }\n      }\n      class ManifestNetworkError extends HlsNetworkError {\n          constructor(fatal, reason, code, response, isTimeout) {\n              super(isTimeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR, fatal, reason, code, response, isTimeout);\n          }\n      }\n      // Problem when loading playlist or manifest\n      class PlaylistNetworkError extends HlsNetworkError {\n          constructor(fatal, reason, code, response, isTimeout, mediaOptionType, mediaOptionId, url) {\n              super('', fatal, reason, code, response, isTimeout);\n              this.mediaOptionType = mediaOptionType;\n              this.mediaOptionId = mediaOptionId;\n              this.url = url;\n              switch (mediaOptionType) {\n                  case MediaOptionType.Variant:\n                      this.details = isTimeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;\n                      break;\n                  case MediaOptionType.AltAudio:\n                      this.details = isTimeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n                      break;\n                  case MediaOptionType.Subtitle:\n                      this.details = isTimeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_TRACK_LOAD_ERROR;\n                      break;\n              }\n          }\n      }\n      // Problem when loading SessionData\n      class SessionDataNetworkError extends HlsNetworkError {\n          constructor(fatal, reason, code, response) {\n              super(ErrorDetails.SESSION_DATA_LOAD_ERROR, fatal, reason, code, response, false);\n          }\n      }\n      // Problem when loading fragment\n      class FragmentNetworkError extends HlsNetworkError {\n          constructor(fatal, reason, code, response, isTimeout, frag, stats) {\n              super(isTimeout ? ErrorDetails.FRAG_LOAD_TIMEOUT : ErrorDetails.FRAG_LOAD_ERROR, fatal, reason, code, response, isTimeout);\n              this.mediaOptionId = frag.mediaOptionId;\n              this.mediaOptionType = frag.mediaOptionType;\n              this.stats = stats;\n          }\n      }\n      class GenericTimeoutError extends TimeoutError {\n          constructor(message, code, stats) {\n              super();\n              this.message = message;\n              this.code = code;\n              this.stats = stats;\n          }\n      }\n      class FragmentAbortError extends HlsNetworkError {\n          constructor(frag, candidateMediaOptionId, response) {\n              super('fragAbortError', false, 'Fragment abort', 0, response, false);\n              this.candidateMediaOptionId = candidateMediaOptionId;\n              this.mediaOptionId = frag.mediaOptionId;\n              this.mediaOptionType = frag.mediaOptionType;\n          }\n      }\n    \n      // Errors generated by CDM / KeySystem\n      class KeyRequestTimeoutError extends HlsNetworkError {\n          constructor(message, keyuri, response, mediaOptionIds = []) {\n              super(ErrorDetails.KEY_LOAD_TIMEOUT, false, message, response.code, response, true);\n              this.keyuri = keyuri;\n              this.response = response;\n              this.mediaOptionIds = mediaOptionIds;\n          }\n      }\n      var KeyRequestErrorReason;\n      (function (KeyRequestErrorReason) {\n          KeyRequestErrorReason[KeyRequestErrorReason[\"InvalidState\"] = 0] = \"InvalidState\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"Abort\"] = 1] = \"Abort\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"OutputRestricted\"] = 2] = \"OutputRestricted\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"AlreadyFailedKey\"] = 3] = \"AlreadyFailedKey\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"HttpError\"] = 4] = \"HttpError\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"InternalError\"] = 5] = \"InternalError\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"LicenseServerError\"] = 6] = \"LicenseServerError\";\n          KeyRequestErrorReason[KeyRequestErrorReason[\"InsufficientCPC\"] = 7] = \"InsufficientCPC\";\n      })(KeyRequestErrorReason || (KeyRequestErrorReason = {}));\n      // Something that failed in the actual request to the license server\n      class KeyRequestError extends HlsNetworkError {\n          constructor(message, keyuri, code, response, isOkToRetry, keyErrorReason, fatal = false, mediaOptionIds = []) {\n              super(ErrorDetails.KEY_LOAD_ERROR, fatal, message, code, response, false);\n              this.keyuri = keyuri;\n              this.isOkToRetry = isOkToRetry;\n              this.keyErrorReason = keyErrorReason;\n              this.mediaOptionIds = mediaOptionIds;\n          }\n      }\n      // Something that failed due to key exchange or key system initialization\n      class KeySystemError extends HlsError {\n          constructor(message, keyuri, code, response, keysystemstring) {\n              super(ErrorTypes.OTHER_ERROR, ErrorDetails.KEY_SYSTEM_GENERIC_ERROR, true, message, response);\n              this.keyuri = keyuri;\n              this.code = code;\n              this.response = response;\n              this.keysystemstring = keysystemstring;\n          }\n      }\n      function copyKeyError(error, mediaOptionIds) {\n          if (error instanceof KeyRequestError) {\n              return new KeyRequestError(error.message, error.keyuri, error.code, error.response, error.isOkToRetry, error.keyErrorReason, error.fatal, mediaOptionIds);\n          }\n          else if (error instanceof KeyRequestTimeoutError) {\n              return new KeyRequestTimeoutError(error.message, error.keyuri, ErrorResponses.CryptResponseReceivedSlowly, mediaOptionIds);\n          }\n          else if (error) {\n              return new ExceptionError(error.fatal, error.reason, ErrorResponses.InternalError);\n          }\n          return null;\n      }\n    \n      /*\n       * FairPlayStreaming key system constants\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const FairPlaySecurityLevels = {\n          AppleBaseline: 0,\n          AppleMain: 1,\n          Main: 1,\n          Baseline: 0,\n      };\n      const FairPlayStreamingKeySystemProperties = {\n          id: 'fairplaystreaming',\n          systemStringPrefix: 'com.apple.fps',\n          keyFormatString: 'com.apple.streamingkeydelivery',\n          securityLevels: FairPlaySecurityLevels,\n      };\n    \n      class LoaderQuery extends QueryEntity {\n          constructor(store) {\n              super(store);\n              this.store = store;\n          }\n          get unresolvedUriLoading$() {\n              return this.selectEntityAction(EntityActions.Add).pipe(map((entityIds) => entityIds.map((id) => this.getEntity(id))));\n          }\n      }\n    \n      class LoaderStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'loader', producerFn: produce_1, idKey: 'uri' });\n          }\n      }\n    \n      class LoaderService {\n          constructor(store) {\n              this.store = store;\n          }\n          createUnresolvedUriLoading(uri, responseType, userAgent) {\n              logAction('loader.create.unresolvedUriLoading');\n              this.store.add({ uri, responseType, userAgent });\n          }\n          removeUnresolvedUriLoading(uri) {\n              logAction('loader.remove.unresolvedUriLoading');\n              this.store.remove(uri);\n          }\n      }\n      const store$1 = new LoaderStore();\n      let service$2 = null; // To be instantiated in loaderService()\n      /***********************************************\n       * Static helper functions that specifically use the above singletons\n       */\n      function createLoaderQuery() {\n          return new LoaderQuery(store$1);\n      }\n      /**\n       * @returns The global instance of LoaderService that operates on global LoaderStore\n       */\n      function getLoaderService() {\n          if (!service$2) {\n              service$2 = new LoaderService(store$1);\n          }\n          return service$2;\n      }\n    \n      /*\n       * HLS Event Emitter\n       *\n       * \n       */\n      /**\n       * Simple adapter sub-class of Nodejs-like EventEmitter.\n       */\n      class HlsEventEmitter extends EventEmitter {\n          /**\n           * We simply want to pass along the event-name itself\n           * in every call to a handler, which is the purpose of our `trigger` method\n           * extending the standard API.\n           */\n          trigger(event, data) {\n              try {\n                  this.emit(event, event, data);\n                  if (event.toString() !== 'hlsFragLoadProgress') {\n                      // do not log fragLoadProgress, too noisy\n                      // <rdar://35043665> Do NOT log data, which can be very large (for instance the data1: and data2: arguments from demuxer\n                      // console will hold onto the arguments in here until the next event loop and can cause memory to balloon over time\n                      let details = '';\n                      if ((event === 'hlsInternalError' || event === 'hlsError') && data.length) {\n                          details = JSON.stringify(data[0], ['fatal', 'details', 'reason']);\n                      }\n                      const eventData = { event: event.toString() };\n                      if (details.length > 0) {\n                          eventData.details = details;\n                      }\n                      getLogger().qe({ critical: true, name: 'eventTrigger', data: eventData });\n                  }\n              }\n              catch (err) {\n                  getLogger().warn(`error in event listener for ${event}: ${err.message}`);\n              }\n          }\n      }\n    \n      class EventTarget {\n          constructor(target, _this) {\n              this.target = target;\n              this._this = _this;\n          }\n          eventWithOptions(event, options, handler, _this = this._this) {\n              let observable = fromEvent(this.target, event, options);\n              if (this.target instanceof HlsEventEmitter) {\n                  // HLS's raw event handlers accepts two arguments:\n                  //    - event: _Event\n                  //    - data: EventData<_EventDataMap, _Event>\n                  // We need to map it to single data argument\n                  observable = observable.pipe(map(([_, data]) => data));\n              }\n              if (handler) {\n                  if (_this) {\n                      handler = handler.bind(_this);\n                  }\n                  observable = observable.pipe(tap(handler));\n              }\n              return observable;\n          }\n          event(event, handler, _this = this._this) {\n              return this.eventWithOptions(event, undefined, handler, _this);\n          }\n          listen(event, notifier, handler, _this = this._this) {\n              return this.event(event, handler, _this).pipe(takeUntil(notifier)).subscribe();\n          }\n      }\n      function fromEventTarget(target, _this) {\n          return new EventTarget(target, _this);\n      }\n      // Note that vuze doesn't implement some events so may not be safe to use ev directly. Use to fill\n      function convertEvent(currentTarget, type, ev) {\n          var _b, _c;\n          return {\n              currentTarget: (_b = ev === null || ev === void 0 ? void 0 : ev.currentTarget) !== null && _b !== void 0 ? _b : currentTarget,\n              target: (_c = ev === null || ev === void 0 ? void 0 : ev.target) !== null && _c !== void 0 ? _c : currentTarget,\n              type: type,\n          };\n      }\n    \n      \n      function getByteRangeLength(byteRangeHeader) {\n          const BYTERANGE = /([0-9]+)\\-([0-9]+)\\/([0-9]+)/;\n          const result = BYTERANGE.exec(byteRangeHeader);\n          return result ? parseInt(result[2]) - parseInt(result[1]) + 1 : undefined;\n      }\n      function getContentLength(xhr) {\n          let contentLength;\n          const contentEncoding = xhr.getResponseHeader('Content-Encoding');\n          const transferEncoding = xhr.getResponseHeader('Transfer-Encoding');\n          const noContentEncoding = !contentEncoding || (contentEncoding && contentEncoding.toLowerCase() === 'identity');\n          const noTransferEncoding = !transferEncoding || (transferEncoding && transferEncoding.toLowerCase() === 'identity');\n          if (noContentEncoding && noTransferEncoding) {\n              // Length only makes sense without encoding/compression\n              contentLength = getByteRangeLength(xhr.getResponseHeader('Content-Range'));\n              if (!isFiniteNumber(contentLength)) {\n                  contentLength = parseInt(xhr.getResponseHeader('Content-Length'));\n              }\n          }\n          return contentLength;\n      }\n      function fromXMLHttpRequest(context, loadConfig) {\n          return new Observable((subscriber) => {\n              const { maxTimeToFirstByteMs, maxLoadTimeMs } = loadConfig;\n              const xhr = new XMLHttpRequest();\n              const stats = {\n                  trequest: performance.now(),\n                  tfirst: NaN,\n                  tload: NaN,\n                  loaded: 0,\n                  total: NaN,\n                  complete: false,\n              };\n              const xhrTarget = fromEventTarget(xhr);\n              // register for events\n              const onprogress$ = xhrTarget.event('progress').pipe(share(), throttleTime(300, queueScheduler, { leading: true, trailing: true }), map((progressEvent) => {\n                  if (isNaN(stats.tfirst)) {\n                      stats.tfirst = performance.now();\n                  }\n                  stats.loaded = progressEvent.loaded;\n                  if (progressEvent.lengthComputable) {\n                      stats.total = progressEvent.total;\n                  }\n                  return progressEvent.target;\n              }), filter((req) => req.readyState >= 3));\n              const onreadystate$ = xhrTarget.event('readystatechange').pipe(share(), map((event) => event.target), filter((req) => req.readyState >= 2), tap((req) => {\n                  if (isNaN(stats.tfirst) && req.readyState >= 3) {\n                      stats.tfirst = performance.now();\n                  }\n              }));\n              let timeToFirstByteTimeout$ = EMPTY;\n              if (isFinite(maxTimeToFirstByteMs) && maxTimeToFirstByteMs > 0) {\n                  timeToFirstByteTimeout$ = merge(onprogress$, onreadystate$).pipe(take(1), timeout(context.extendMaxTTFB > 0 ? context.extendMaxTTFB : maxTimeToFirstByteMs), switchMap(() => EMPTY));\n              }\n              let totalLoadTimeout$ = EMPTY;\n              if (isFinite(maxLoadTimeMs) && maxLoadTimeMs > 0) {\n                  totalLoadTimeout$ = onreadystate$.pipe(filter((req) => req.readyState >= 4), take(1), timeout(maxLoadTimeMs), switchMap(() => EMPTY));\n              }\n              let onProgressCb$ = EMPTY;\n              if (context.onProgress) {\n                  onProgressCb$ = merge(of(xhr), onprogress$) // Emit on subscribe and then on every 'onprogress' event\n                      .pipe(map((xhrReq) => {\n                      const { getData, cb } = context.onProgress;\n                      return cb(context.url, xhrReq.status, stats, getData ? xhrReq.response : undefined);\n                  }), takeWhile((done) => !done, true))\n                      .pipe(switchMapTo(EMPTY));\n              }\n              const sub = merge(onprogress$.pipe(switchMap(() => EMPTY)), onreadystate$, timeToFirstByteTimeout$, totalLoadTimeout$, onProgressCb$)\n                  .pipe(filter((req) => req.readyState >= 4), take(1), switchMap((req) => {\n                  stats.complete = true;\n                  if (req.status >= 200 && req.status < 300) {\n                      stats.tload = performance.now();\n                      stats.contentType = req.getResponseHeader('Content-Type');\n                      if (loadConfig.reportCDNServer) {\n                          stats.cdnServer = req.getResponseHeader('CDN-Server');\n                      }\n                      stats.contentLength = loadConfig.forceContentLenCheckIfNoHeader ? getContentLength(req) : null; // forceContentLenCheckIfNoHeader is true only for non-browser platforms\n                      _relateServerInstanceInfoToRequest(req, context);\n                      if (context.responseType === 'arraybuffer') {\n                          stats.loaded = req.response.byteLength;\n                      }\n                      else {\n                          stats.loaded = req.responseText.length;\n                      }\n                      stats.total = stats.loaded;\n                      if (context.checkContentLength && // checkContentLength is true only when loading fragment\n                          (stats.total === 0 || (isFiniteNumber(stats.contentLength) && stats.total != stats.contentLength))) {\n                          throw new GenericNetworkError('Network error', req.status);\n                      }\n                      const res = [req, stats];\n                      return scheduled(of(res), queueScheduler);\n                  }\n                  else {\n                      throw new GenericNetworkError('Network error', req.status);\n                  }\n              }), catchError((err) => {\n                  if (err instanceof TimeoutError) {\n                      throw new GenericTimeoutError(err.message, 0, stats);\n                  }\n                  if (!(err instanceof GenericNetworkError)) {\n                      throw new GenericNetworkError(err.message, 0);\n                  }\n                  throw err;\n              }))\n                  .subscribe(subscriber);\n              // Setup XHR request\n              const { url, method, byteRangeOffset, responseType, body } = context;\n              if (context.mimeType) {\n                  xhr.overrideMimeType(context.mimeType);\n              }\n              try {\n                  const xhrSetup = context.xhrSetup;\n                  if (xhrSetup) {\n                      try {\n                          xhrSetup(xhr, url);\n                      }\n                      catch (e) {\n                          // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n                          // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n                          xhr.open(method, context.url, true);\n                          xhrSetup(xhr, context.url);\n                      }\n                  }\n                  if (!xhr.readyState) {\n                      xhr.open(method, context.url, true);\n                  }\n              }\n              catch (e) {\n                  // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n                  throw new GenericNetworkError(e.message, xhr.status);\n              }\n              xhr.responseType = responseType;\n              // Set headers\n              if (byteRangeOffset && isFiniteNumber(byteRangeOffset.start) && isFiniteNumber(byteRangeOffset.end) && byteRangeOffset.start >= 0 && byteRangeOffset.end > byteRangeOffset.start) {\n                  const { start, end } = byteRangeOffset;\n                  xhr.setRequestHeader('Range', `bytes=${start}-${end - 1}`);\n              }\n              if (context.headers) {\n                  for (const [name, value] of Object.entries(context.headers)) {\n                      xhr.setRequestHeader(name, value);\n                  }\n              }\n              // Start request\n              if (method === 'POST' && body) {\n                  xhr.send(body);\n              }\n              else {\n                  xhr.send();\n              }\n              return () => {\n                  xhr.abort();\n                  sub.unsubscribe();\n              };\n          });\n      }\n      function _relateServerInstanceInfoToRequest(xhr, context) {\n          if (context.collectServerInstanceInfo) {\n              context.serverInstanceInfo = {};\n              context.collectServerInstanceInfo.forEach((header) => {\n                  const headerValue = xhr.getResponseHeader(header);\n                  if (headerValue) {\n                      context.serverInstanceInfo[header] = headerValue;\n                  }\n              });\n          }\n      }\n    \n      const loggerName$7 = { name: 'CustomUrlLoader' };\n      class CustomUrlLoader {\n          constructor(loaderService) {\n              this.loaderService = loaderService;\n              this.requestMap = {};\n              this.logger = getLogger();\n          }\n          load(context, loadConfig) {\n              return new Observable((observer) => {\n                  const url = context.url;\n                  const { maxTimeToFirstByteMs } = loadConfig;\n                  const stats = {\n                      trequest: performance.now(),\n                      tfirst: NaN,\n                      tload: NaN,\n                      loaded: 0,\n                      total: NaN,\n                      complete: false,\n                  };\n                  const request = (this.requestMap[url] = new AsyncSubject());\n                  const source = request.pipe(timeout(context.extendMaxTTFB > 0 ? context.extendMaxTTFB : maxTimeToFirstByteMs), switchMap((response) => {\n                      this.logger.info(loggerName$7, `loaded originalUri=${redactUrl(url)} uri=${redactUrl(response.uri)} durationMs=${performance.now() - stats.trequest}`);\n                      stats.tfirst = performance.now();\n                      return this.handleExternalResponse(response, context, loadConfig, stats);\n                  }), catchError((err) => {\n                      if (err instanceof TimeoutError) {\n                          throw new GenericTimeoutError(err.message, 0, stats);\n                      }\n                      throw err;\n                  }), finalize$1(() => {\n                      this.requestMap[url] = undefined;\n                      this.loaderService.removeUnresolvedUriLoading(url);\n                  }));\n                  this.logger.info(loggerName$7, `loading originalUri=${redactUrl(url)}`);\n                  if (context.onProgress) {\n                      context.onProgress.cb(url, 0, stats, undefined);\n                  }\n                  const sub = source.subscribe(observer);\n                  this.loaderService.createUnresolvedUriLoading(url, context.responseType, navigator.userAgent);\n                  return () => {\n                      sub.unsubscribe();\n                      this.requestMap[url] = undefined;\n                  };\n              });\n          }\n          setCustomUrlResponse(url, response) {\n              const source = this.requestMap[url];\n              if (source) {\n                  source.next(response);\n                  source.complete();\n                  this.requestMap[url] = undefined;\n              }\n          }\n          handleExternalResponse(data, context, loadConfig, stats) {\n              stats.tload = performance.now();\n              const status = data.response.status || 200;\n              // http status of 200 to 299 are all successfull\n              if (status >= 200 && status < 300) {\n                  if (context.responseType === 'arraybuffer' && data.response.data instanceof ArrayBuffer) {\n                      stats.loaded = data.response.data.byteLength;\n                  }\n                  else {\n                      stats.loaded = data.response.data.toString().length;\n                  }\n                  stats.total = stats.loaded;\n                  stats.complete = true;\n                  return scheduled(of({ status, data, stats }), queueScheduler);\n              }\n              else if (isRedirectStatusCode(status)) {\n                  this.logger.info(loggerName$7, `redirect status=${status} url=${redactUrl(data.response.uri)}`);\n                  return this.redirectRequest(data.response.uri, context, loadConfig, stats);\n              }\n              else {\n                  this.logger.warn(loggerName$7, `unable to load custom url > uri=${redactUrl(data.response.uri)}, status=${status}`);\n                  return throwError(new GenericNetworkError('Unable to load custom url', status));\n              }\n          }\n          redirectRequest(uri, context, loadConfig, stats) {\n              const { maxLoadTimeMs, maxTimeToFirstByteMs } = loadConfig;\n              const updatedMaxLoadTimeMs = maxLoadTimeMs - (performance.now() - stats.trequest); // Recalculate timeout based on request time\n              const updatedMaxTimeToFirstByteMs = context.extendMaxTTFB > 0 ? context.extendMaxTTFB : maxTimeToFirstByteMs - (performance.now() - stats.trequest); // Recalculate timeout based on request time\n              const newConfig = Object.assign(Object.assign({}, loadConfig), { maxLoadTimeMs: updatedMaxLoadTimeMs, maxTimeToFirstByteMs: updatedMaxTimeToFirstByteMs });\n              const newContext = Object.assign(Object.assign({}, context), { url: uri });\n              if (updatedMaxLoadTimeMs <= 0 || updatedMaxTimeToFirstByteMs <= 0) {\n                  return throwError(new TimeoutError());\n              }\n              return fromXMLHttpRequest(newContext, newConfig).pipe(map(([xhr, sample]) => {\n                  const { responseURL, status } = xhr;\n                  const uri = responseURL || '';\n                  const data = {\n                      uri,\n                      response: {\n                          status: status,\n                          uri,\n                          data: xhr.response,\n                      },\n                  };\n                  stats.loaded = stats.total = sample.loaded;\n                  stats.tload = performance.now();\n                  stats.complete = true;\n                  return { status: xhr.status, data, stats };\n              }));\n          }\n      }\n      let loader;\n      function getCustomUrlLoader(loaderService) {\n          if (!loader) {\n              const service = loaderService || getLoaderService();\n              loader = new CustomUrlLoader(service);\n          }\n          return loader;\n      }\n    \n      function fromUrlArrayBuffer(context, loadConfig) {\n          const ctx = Object.assign(Object.assign({}, context), { method: 'GET', responseType: 'arraybuffer' });\n          const customUrlLoader = getCustomUrlLoader();\n          return isCustomUrl(ctx.url)\n              ? customUrlLoader.load(ctx, loadConfig).pipe(map((res) => [res.data.response.data, res.stats, ctx.serverInstanceInfo]))\n              : fromXMLHttpRequest(ctx, loadConfig).pipe(map(([xhr, bwSample]) => [xhr.response, bwSample, ctx.serverInstanceInfo]));\n      }\n    \n      /**\n       * Generic load utils for retry and such\n       */\n      function getLoadConfig(loadable, policy) {\n          return !loadable.url || isCustomUrl(loadable.url) ? policy.customURL : policy.default;\n      }\n      function getRetryConfig(error, config) {\n          if (error instanceof HlsNetworkError) {\n              return error.isTimeout ? config.timeoutRetry : config.errorRetry;\n          }\n          return null;\n      }\n      /**\n       * Operator for converting TimeoutError & GenericNetworkError into ManifestNetworkError\n       */\n      function convertToManifestNetworkError(fatal) {\n          return (source) => source.pipe(catchError((err) => {\n              if (err instanceof GenericTimeoutError) {\n                  throw new ManifestNetworkError(fatal, 'Timeout', 0, ErrorResponses.ManifestTimeoutError, true);\n              }\n              else if (err instanceof GenericNetworkError) {\n                  throw new ManifestNetworkError(fatal, err.message, err.code, { code: err.code, text: 'Manifest network error' }, false);\n              }\n              throw err;\n          }));\n      }\n      /**\n       * Operator for converting TimeoutError & GenericNetworkError into PlaylistNetworkError\n       */\n      function convertToPlaylistNetworkError(mediaOptionType, mediaOptionId, fatal, url) {\n          return (source) => source.pipe(catchError((err) => {\n              if (err instanceof GenericTimeoutError) {\n                  throw new PlaylistNetworkError(fatal, 'Timeout', 0, ErrorResponses.PlaylistTimeoutError, true, mediaOptionType, mediaOptionId, url);\n              }\n              else if (err instanceof GenericNetworkError) {\n                  throw new PlaylistNetworkError(fatal, err.message, err.code, { code: err.code, text: 'Playlist Network Error' }, false, mediaOptionType, mediaOptionId, url);\n              }\n              throw err;\n          }));\n      }\n      /**\n       * Operator for converting TimeoutError & GenericNetworkError into FragmentError\n       */\n      function convertToFragmentNetworkError(frag, fatal) {\n          return (source) => source.pipe(catchError((err) => {\n              if (err instanceof GenericTimeoutError) {\n                  throw new FragmentNetworkError(fatal, 'Timeout', 0, ErrorResponses.FragmentTimeoutError, true, frag, err.stats);\n              }\n              else if (err instanceof GenericNetworkError) {\n                  throw new FragmentNetworkError(fatal, err.message, err.code, { code: err.code, text: 'Fragment Network Error' }, false, frag);\n              }\n              throw err;\n          }));\n      }\n      /**\n       * Helper function to update playtype of levels\n       */\n      function updatePlaylistAttributes(levelDetails) {\n          const playlistTypeString = levelDetails.type;\n          const isLive = levelDetails.liveOrEvent;\n          let playlistType = 'VOD';\n          if (playlistTypeString === 'EVENT' && isLive) {\n              playlistType = 'EVENT';\n          }\n          else if ((!playlistTypeString || playlistTypeString.length === 0 || playlistTypeString === 'LIVE') && isLive) {\n              playlistType = 'LIVE';\n          }\n          if (levelDetails.type !== playlistType) {\n              getLogger().info(`Playlist type updated from ${levelDetails.type} to ${playlistType}`);\n              levelDetails.type = playlistType;\n          }\n      }\n    \n      /**\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const PlayReadySecurityLevels = {\n          SL2000: 0,\n          SL3000: 1,\n      };\n      const PlayReadyKeySystemProperties = {\n          id: 'playready',\n          systemStringPrefix: 'com.microsoft.playready',\n          keyFormatString: 'com.microsoft.playready',\n          securityLevels: PlayReadySecurityLevels,\n      };\n    \n      /**\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const WidevineSecurityLevels = {\n          WIDEVINE_SOFTWARE: 0,\n          WIDEVINE_HARDWARE: 1,\n      };\n      const WidevineKeySystemProperties = {\n          id: 'widevine',\n          systemStringPrefix: 'com.widevine.alpha',\n          keyFormatString: 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',\n          securityLevels: WidevineSecurityLevels,\n      };\n    \n      /*\n       * Utilities for numeric encodings\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      function base64ToBase64Url(base64encodedStr) {\n          return base64encodedStr.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/\\=+$/, '');\n      }\n      class BrowserNumericEncodingUtils {\n          static strToBase64Encode(str) {\n              return btoa(str);\n          }\n          static base64DecodeToStr(str) {\n              return atob(str);\n          }\n          static base64Encode(input) {\n              return btoa(String.fromCharCode(...input));\n          }\n          static base64UrlEncode(input) {\n              return base64ToBase64Url(BrowserNumericEncodingUtils.base64Encode(input));\n          }\n          static base64Decode(base64encodedStr) {\n              return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));\n          }\n      }\n      class NodeJSNumericEncodingUtils {\n          static strToBase64Encode(str) {\n              return global$1.Buffer.from(str).toString('base64');\n          }\n          static base64DecodeToStr(str) {\n              return global$1.Buffer.from(str, 'base64').toString();\n          }\n          static base64Encode(input) {\n              return global$1.Buffer.from(input).toString('base64');\n          }\n          static base64UrlEncode(input) {\n              return base64ToBase64Url(NodeJSNumericEncodingUtils.base64Encode(input));\n          }\n          static base64Decode(base64encodedStr) {\n              const buffer = global$1.Buffer.from(base64encodedStr, 'base64');\n              return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n          }\n      }\n      const NumericEncodingUtils = typeof global$1.Buffer !== 'undefined' ? NodeJSNumericEncodingUtils : BrowserNumericEncodingUtils;\n      var NumericEncodingUtils$1 = NumericEncodingUtils;\n    \n      /*\n       * Utilities for key systems\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      // Map of prefix to mimeType\n      const kVideoCodecToMimeType = {\n          // AVC\n          avc1: 'video/mp4',\n          avc3: 'video/mp4',\n          dvav: 'video/mp4',\n          dva1: 'video/mp4',\n          // HEVC\n          hev1: 'video/mp4',\n          hvc1: 'video/mp4',\n          dvh1: 'video/mp4',\n          dvhe: 'video/mp4', // Dolby vission\n      };\n      const kAudioCodecToMimeType = {\n          mp4a: 'audio/mp4',\n          'ac-3': 'audio/mp4',\n          'ec-3': 'audio/mp4',\n      };\n      function isMediaKeySystemConfig(config) {\n          return config && typeof config === 'object'; // requestMediaKeySystemAccess accepts {}\n      }\n      // Input: set of codec strings for each type\n      // Output:\n      // {\n      // videoCapabilities: [\n      //   { contentType: 'video/mp4;codecs=avc.###', robustness: '' } ],\n      //  audioCapabilities: []\n      // }\n      function getMediaKeysystemMediaCapability(videoCodecs, audioCodecs) {\n          const result = {\n              videoCapabilities: [],\n              audioCapabilities: [],\n          };\n          if (videoCodecs) {\n              videoCodecs.forEach((videoCodec) => {\n                  const prefix = videoCodec.split('.')[0].trim();\n                  if (prefix in kVideoCodecToMimeType) {\n                      result.videoCapabilities.push({\n                          contentType: kVideoCodecToMimeType[prefix] + ';codecs=' + videoCodec,\n                          robustness: '',\n                      });\n                  }\n              });\n          }\n          if (audioCodecs) {\n              audioCodecs.forEach((audioCodec) => {\n                  const prefix = audioCodec.split('.')[0].trim();\n                  if (prefix in kAudioCodecToMimeType) {\n                      result.audioCapabilities.push({\n                          contentType: kAudioCodecToMimeType[prefix] + ';codecs=' + audioCodec,\n                          robustness: '',\n                      });\n                  }\n              });\n          }\n          return result;\n      }\n      /**\n       * Utility to change the endianness of Key ID\n       * @param keyID uint8array representing the keyId\n       * @returns uint8array the keyId after changing the endianness\n       */\n      function changeEndianness(keyId) {\n          // eslint-disable-next-line func-style\n          const swap = function (array, from, to) {\n              const cur = array[from];\n              array[from] = array[to];\n              array[to] = cur;\n          };\n          swap(keyId, 0, 3);\n          swap(keyId, 1, 2);\n          swap(keyId, 4, 5);\n          swap(keyId, 6, 7);\n      }\n      /**\n       * Generate key id from an arbitrary string\n       * @param str String to convert into a 16 byte key\n       * @returns uint8array representing the keyId\n       */\n      function getKeyIdBytes(str) {\n          const keyIdbytes = BufferUtils.strToUtf8array(str).subarray(0, 16);\n          const paddedkeyIdbytes = new Uint8Array(16);\n          paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);\n          return paddedkeyIdbytes;\n      }\n      /**\n       * @param   URI string\n       * @returns Uint8Array of URI data\n       */\n      function convertDataUriToArrayBytes(uri) {\n          // data:[<media type][;attribute=value][;base64],<data>\n          const colonsplit = uri.split(':');\n          let keydata = null;\n          if (colonsplit[0] === 'data' && colonsplit.length === 2) {\n              const semicolonsplit = colonsplit[1].split(';');\n              const commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');\n              if (commasplit.length === 2) {\n                  const isbase64 = commasplit[0] === 'base64';\n                  const data = commasplit[1];\n                  if (isbase64) {\n                      semicolonsplit.splice(-1, 1); // remove from processing\n                      keydata = NumericEncodingUtils$1.base64Decode(data);\n                  }\n                  else {\n                      keydata = getKeyIdBytes(data);\n                  }\n              }\n          }\n          return keydata;\n      }\n      /**\n       * Generate 'keyids' init data from an array of key ids\n       * @param keyIds  Array of key ids represented as uint8array[16] objects\n       * @returns The initData string to pass to generateRequest as part of EME\n       */\n      function makeKeyIdsInitData(keyIds) {\n          const initDataObj = {\n              kids: keyIds.map(NumericEncodingUtils$1.base64UrlEncode),\n          };\n          // Convert string to utf-8 array\n          return BufferUtils.strToUtf8array(JSON.stringify(initDataObj));\n      }\n      // parse pssh list and convert to dictionary:\n      function parsePSSHList(psshList) {\n          const dv = new DataView(psshList);\n          let whichByte = 0;\n          const pssh = {}; // PSSH: systemID => data\n          while (whichByte < dv.buffer.byteLength) {\n              const thisBox = whichByte;\n              const boxSize = dv.getUint32(whichByte);\n              whichByte += 4;\n              const nextBox = thisBox + boxSize;\n              if (dv.getUint32(whichByte) !== 1886614376) {\n                  whichByte = nextBox;\n                  continue; // next box\n              }\n              whichByte += 4;\n              const version = dv.getUint8(whichByte);\n              switch (version) {\n                  case 0: // NO KEY IDS\n                  case 1:\n                      whichByte += 1;\n                      break;\n                  default:\n                      whichByte = nextBox;\n                      break;\n              }\n              whichByte += 3; // flags\n              // UUID: 4 bytes - 2 bytes - 2 bytes - 2 bytes - 6 bytes\n              let systemID = '';\n              // 16 bytes\n              for (let i = 0; i < 16; ++i, ++whichByte) {\n                  systemID += dv.getUint8(whichByte).toString(16);\n                  switch (i) {\n                      case 4:\n                      case 6:\n                      case 8:\n                      case 10:\n                          systemID += '-';\n                          break;\n                  }\n              }\n              whichByte += 4; // Data size\n              pssh[systemID] = dv.buffer.slice(thisBox, nextBox);\n          }\n          return pssh;\n      }\n      const keysystemutil = {\n          getCapabilities: getMediaKeysystemMediaCapability,\n          changeEndianness,\n          getKeyIdBytes,\n          convertDataUriToArrayBytes,\n          makeKeyIdsInitData,\n          parsePSSHList,\n      };\n    \n      /*\n       * Decrypt data\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      // Note that this will not get copied into Worker\n      let keyUriToKeyIdMap = {};\n      // Created in playlist-loader, modified in demux / remux\n      class DecryptData {\n          /**\n           * @param method          From METHOD attribute, mandatory\n           * @param uri             Absolute url of the key (calculated from URI)\n           * @param iv              128-bit unsigned int representing Initialization Vector, used when KEYFORMAT=\"identity\", optional\n           * @param format          From KEYFORMAT, optional with default value of \"identity\"\n           * @param formatversions  Array From KEYFORMATVERSION, an array of unsigned int, optional\n           */\n          constructor(method, uri, iv, format, formatversions) {\n              this.method = method;\n              this.uri = uri;\n              this.iv = iv;\n              this.format = format;\n              this.formatversions = formatversions;\n              this.isEncrypted = this.method && this.method !== 'NONE';\n              if (!this.formatversions || this.formatversions.length === 0) {\n                  this.formatversions = [1];\n              }\n              // Set later\n              this.key = undefined;\n              this.keyId = undefined;\n              if (!this.isEncrypted) {\n                  return;\n              }\n              // Initialize keyId if possible\n              const keyBytes = keysystemutil.convertDataUriToArrayBytes(this.uri);\n              if (keyBytes) {\n                  switch (format) {\n                      case PlayReadyKeySystemProperties.keyFormatString: {\n                          // Playready\n                          this.pssh = keyBytes;\n                          const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);\n                          const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));\n                          // we got entire PSSH data. Incase of Playready it's WRMHEADER XML object. Parse it.\n                          const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf('<'), keyByteStr.length);\n                          const parser = new DOMParser();\n                          const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');\n                          const keyData = xmlDoc.getElementsByTagName('KID')[0];\n                          if (keyData) {\n                              let keyId = null;\n                              if (keyData.childNodes[0]) {\n                                  keyId = keyData.childNodes[0].nodeValue;\n                              }\n                              else {\n                                  keyId = keyData.getAttribute('VALUE');\n                              }\n                              if (keyId) {\n                                  const keyIdArray = NumericEncodingUtils$1.base64Decode(keyId).subarray(0, 16);\n                                  // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID\n                                  // KID value in â€˜tencâ€™ is a big endian UUID GUID interpretation of UUID\n                                  keysystemutil.changeEndianness(keyIdArray);\n                                  this.keyId = keyIdArray;\n                              }\n                          }\n                          break;\n                      }\n                      case WidevineKeySystemProperties.keyFormatString: {\n                          // Widevine\n                          this.pssh = keyBytes;\n                          // In case of widevine keyID is embedded in PSSH box. Read Key ID.\n                          if (keyBytes.length >= 22) {\n                              this.keyId = keyBytes.subarray(keyBytes.length - 22, keyBytes.length - 6);\n                          }\n                          break;\n                      }\n                      default: {\n                          // default handling\n                          let keydata = keyBytes.subarray(0, 16);\n                          if (keydata.length !== 16) {\n                              const padded = new Uint8Array(16);\n                              padded.set(keydata, 16 - keydata.length);\n                              keydata = padded;\n                          }\n                          this.keyId = keydata;\n                          break;\n                      }\n                  }\n              }\n              // Default behavior\n              if (!this.keyId || this.keyId.byteLength !== 16) {\n                  let keyId = keyUriToKeyIdMap[this.uri];\n                  if (!keyId) {\n                      const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;\n                      // MAX_SAFE_INTEGER is huge (9007199254740991) so this /should/ be safe...\n                      keyId = new Uint8Array(16);\n                      const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes\n                      dv.setUint32(0, val);\n                      keyUriToKeyIdMap[this.uri] = keyId;\n                  }\n                  this.keyId = keyId;\n              }\n          }\n          get keyTagInfo() {\n              const { method, isEncrypted, uri, iv, keyId, key, format, formatversions } = this;\n              const keyTagInfo = { method, isEncrypted, uri, iv, keyId, key, format, formatversions };\n              return keyTagInfo;\n          }\n          static clearKeyUriToKeyIdMap() {\n              keyUriToKeyIdMap = {};\n          }\n      }\n    \n      var KeyRequestState;\n      (function (KeyRequestState) {\n          KeyRequestState[\"NONE\"] = \"NONE\";\n          KeyRequestState[\"GET_REQUEST_INFO\"] = \"GET_REQUEST_INFO\";\n          KeyRequestState[\"GET_CHALLENGE\"] = \"GET_CHALLENGE\";\n          KeyRequestState[\"GET_KEY_RESPONSE\"] = \"GET_KEY_RESPONSE\";\n          KeyRequestState[\"PROCESS_LICENSE\"] = \"PROCESS_LICENSE\";\n      })(KeyRequestState || (KeyRequestState = {}));\n      // Wrap subscription and teardown of MediaKeySession callbacks\n      class MediaKeySessionContext {\n          constructor(session, onkeystatuseschange, onkeymessage, logger) {\n              this.session = session;\n              this.onkeystatuseschange = onkeystatuseschange;\n              this.onkeymessage = onkeymessage;\n              this.logger = logger;\n              this.isClosing$ = new BehaviorSubject(false);\n              this.closed$ = new BehaviorSubject(false);\n              const target = fromEventTarget(this.session);\n              target.listen('keystatuseschange', this.isClosing$.pipe(filter((x) => x === true)), this.onkeystatuseschange);\n              // Message is weird because we still want the message until after close()\n              target.listen('message', this.closed$.pipe(filter((x) => x === true)), this.onkeymessage);\n          }\n          get isClosing() {\n              return this.isClosing$.value;\n          }\n          get isClosed() {\n              return this.closed$.value;\n          }\n          /**\n           * Remove and close all keys in MediaKeySession\n           */\n          destroy() {\n              this.logger.info(`[Keys] : remove licenses & keys for session : ${this.session.sessionId} and close it`);\n              this.isClosing$.next(true);\n              const session = this.session;\n              // Unabortable section. Should execute no matter what.\n              return from(session\n                  .remove()\n                  .catch((error) => {\n                  this.logger.info(`Could not remove session: ${error.message}`);\n              })\n                  .then(() => {\n                  return session.close();\n              })\n                  .catch((error) => {\n                  this.logger.info(`Could not close session: ${error.message}`);\n              })).pipe(tap(() => {\n                  this.isClosing$.next(false);\n                  this.closed$.next(true);\n              }), finalize$1(() => {\n                  this.isClosing$.next(false);\n                  this.closed$.next(true);\n              }));\n          }\n      }\n      /**\n       * @brief KeyContext keeps track of the current key request state and information about a given key.\n       *\n       * A key may exist without a key request being in progress. When a key request is in progress, there are\n       * multiple phases / states. Each state of a key request is asynchronous and can be completed either by\n       * the CDM or by the client. If we get out of sync with the current key request state, we will throw an error\n       * and all subscribers will be notified. We will also throw an error if aborted in the middle of the request.\n       * Note that subscribers will not get the abort error if they unsubscribe from the observable.\n       */\n      class KeyContext {\n          constructor(decryptdata, session = null) {\n              this.decryptdata = decryptdata;\n              this._requestState$ = new BehaviorSubject(KeyRequestState.NONE); // Key request state. Note this is different from keystatus from CDM\n              this.destroy$ = new Subject(); // Destroy key. This should stop any renewal timers\n              // If in progress, the current observable\n              this.currentObservable = null;\n              this.session = null; // Current session. Could be shared by others (config.useMultipleKeySessions !== true)\n              this.oldSessions = [];\n              this.session = session;\n          }\n          get requestState() {\n              return this._requestState$.value;\n          }\n          get onKeyRequestState$() {\n              return this._requestState$;\n          }\n          destroy() {\n              this.destroy$.next();\n              // TODO actual cleanup?\n          }\n          abort() {\n              if (this.requestState !== KeyRequestState.NONE) {\n                  const err = new KeyRequestError('Aborted', this.decryptdata.uri, 0, ErrorResponses.KeySystemAbort, true, KeyRequestErrorReason.Abort);\n                  this.error(err);\n              }\n          }\n          /**\n           * Change state and return observable that gets completed when resolveState is called\n           *\n           * @param state The state to switch to\n           */\n          setKeyRequestState(state) {\n              if (this.currentObservable) {\n                  const err = new KeyRequestError(`Unexpected state transition ${this.requestState}->${state}`, this.decryptdata.uri, 0, ErrorResponses.KeySystemUnexpectedStateTransition, true, KeyRequestErrorReason.InvalidState);\n                  this.error(err);\n              }\n              this._requestState$.next(state);\n              const returnVal = new AsyncSubject();\n              if (state === KeyRequestState.NONE) {\n                  returnVal.complete();\n                  this.currentObservable = null;\n              }\n              else {\n                  //@ts-ignore\n                  this.currentObservable = returnVal;\n              }\n              return returnVal;\n          }\n          /**\n           * Resolve current state observable\n           * @param state State to resolve\n           * @param value The value to resolve current observable with\n           */\n          resolveState(state, value) {\n              if (!this.currentObservable) {\n                  return;\n              }\n              if (state !== this.requestState) {\n                  const err = new KeyRequestError(`Unexpected state ${this.requestState} != ${state}`, this.decryptdata.uri, 0, ErrorResponses.KeySystemUnexpectedState, true, KeyRequestErrorReason.InvalidState);\n                  this.error(err);\n                  return;\n              }\n              if (value instanceof Error) {\n                  this.error(value);\n              }\n              else {\n                  const obs = this.currentObservable;\n                  this.currentObservable = null;\n                  obs.next(value);\n                  obs.complete();\n              }\n          }\n          /**\n           * Signal error for this key. Could be due to key request or some other internal error from CDM\n           * @param err The error\n           */\n          error(err) {\n              if (this.currentObservable) {\n                  const obs = this.currentObservable;\n                  this.currentObservable = null;\n                  obs.error(err);\n              }\n              this.setKeyRequestState(KeyRequestState.NONE);\n              // TODO: any other cleanup ?\n          }\n      }\n    \n      /*\n       * Base class for key systems\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const MAX_CERT_LOAD_TIME_MS = 10000; // Maximum time for loading the certificate\n      function printKeyTag(tag) {\n          return `uri=${redactUrl(tag.uri)} keyId=${Hex$1.hexDump(tag.keyId)}`;\n      }\n      class KeySystem {\n          constructor(mediaKeys, systemString, config, eventEmitter, useSingleKeySession, sessionHandler, logger) {\n              this.mediaKeys = mediaKeys;\n              this.systemString = systemString;\n              this.config = config;\n              this.eventEmitter = eventEmitter;\n              this.useSingleKeySession = useSingleKeySession;\n              this.sessionHandler = sessionHandler;\n              this.logger = logger;\n              this.destroy$ = new Subject();\n              this.setCert = false; // Has set cert on MediaKeySession\n              this.certificate$ = new BehaviorSubject(null);\n              // This event will be signalled when a renewal request is needed or if an error occurs.\n              // The key system will not auto renew. Instead client is expected to call startKeyRequest\n              this._keyStatusChange$ = new Subject();\n              this.shouldDestroyMediaKeys = false;\n              // TJH: will playingItem raise a license challenge ?\n              //this.itemId = hls.loadingItem?.itemId || '';\n              this.itemId = '';\n              this.sessions = [];\n              this.keyIdToKeyInfo = {};\n              this.keyUriToKeyInfo = {};\n              this.sessionIdToKeyUri = {};\n              this.onkeystatuseschange = this.handleKeyStatusesChange.bind(this);\n              this.onkeymessage = this.handleKeyMessage.bind(this);\n          }\n          get keyStatusChange$() {\n              return this._keyStatusChange$;\n          }\n          destroy() {\n              this.isDestroying = true;\n              this.destroy$.next();\n              for (const info of Object.values(this.keyIdToKeyInfo)) {\n                  this._abortKeyRequest(info);\n              }\n              // Remove sessions\n              const destroyPromises = this.sessions.map((ctx) => ctx.destroy());\n              const p = iif(() => destroyPromises.length === 0, VOID, forkJoin(destroyPromises)).pipe(mapTo(undefined), finalize$1(() => {\n                  this.mediaKeys = undefined;\n                  this.keyIdToKeyInfo = {};\n                  this.keyUriToKeyInfo = {};\n                  this.sessionIdToKeyUri = {};\n              }));\n              DecryptData.clearKeyUriToKeyIdMap();\n              return p;\n          }\n          /**\n           * @param   certificate Used for generating challenge\n           * @returns {Promise} Fired when non-null certificate has been set on the object.\n           */\n          setServerCertificate(certificate = null) {\n              this.logger.info(this.systemString + ' setServerCertificate(' + (certificate ? 'nonnull' : 'null') + ')');\n              if (!this.needsCert) {\n                  return of(true);\n              }\n              if (certificate) {\n                  this.certificate$.next(certificate);\n              }\n              const waitForCert$ = waitFor(this.certificate$, (x) => x != null).pipe(timeout(MAX_CERT_LOAD_TIME_MS));\n              return waitForCert$.pipe(switchMap((cert) => {\n                  if (this.setCert) {\n                      return of(true);\n                  }\n                  if (!this.setCertSubject || this.setCertSubject.isStopped) {\n                      this.setCertSubject = new AsyncSubject();\n                      return from(this.mediaKeys.setServerCertificate(cert)).pipe(tap((v) => {\n                          // Sometimes the promise returned by the CDM doesn't carry boolean\n                          // This will cause playback failure.\n                          const certStatus = v !== undefined ? v : true;\n                          this.setCert = certStatus;\n                          this.setCertSubject.next(certStatus);\n                          this.setCertSubject.complete();\n                      }), catchError((err) => {\n                          this.logger.info('Failed setServerCertificate');\n                          this.setCert = false;\n                          this.setCertSubject.error(err);\n                          return VOID;\n                      }), switchMap(() => {\n                          return this.setCertSubject;\n                      }));\n                  }\n                  return this.setCertSubject;\n              }), catchError((err) => {\n                  this.logger.info(`setServerCertificate err=${err.message}`);\n                  throw err;\n              }));\n          }\n          ensureKeyContext(decryptdata) {\n              const keyuri = decryptdata.uri;\n              if (!this.keyUriToKeyInfo[keyuri]) {\n                  this.keyUriToKeyInfo[keyuri] = new KeyContext(decryptdata);\n              }\n              const keyInfo = this.keyUriToKeyInfo[keyuri];\n              if (keyInfo.session) {\n                  return keyInfo;\n              }\n              if (this.useSingleKeySession && this.sessions.length > 0) {\n                  keyInfo.session = this.sessions[0].session;\n                  return keyInfo;\n              }\n              this.logger.info(`${this.systemString} createSession`);\n              const session = this.mediaKeys.createSession();\n              if (session) {\n                  this.sessions.push(new MediaKeySessionContext(session, this.onkeystatuseschange, this.onkeymessage, this.logger));\n              }\n              else {\n                  this.logger.info(`${this.systemString} FAIL: could not create MediaKeysSession`);\n              }\n              keyInfo.session = session;\n              return keyInfo;\n          }\n          /**\n           * Start a key request. called from key-system controller or internally on renewal.\n           *\n           * @param decryptdata DecryptData object from EXT-X-KEY\n           * @returns Promise (decryptdata)\n           */\n          startKeyRequest(decryptdata) {\n              const keyuri = decryptdata.uri;\n              const keyInfo = this.ensureKeyContext(decryptdata);\n              const session = keyInfo === null || keyInfo === void 0 ? void 0 : keyInfo.session;\n              if (!session) {\n                  return throwError(new KeySystemError('Could not create key session', decryptdata.uri, 0, ErrorResponses.KeySystemFailedToCreateSession, this.systemString));\n              }\n              const keyIdStr = BufferUtils.utf8arrayToStr(decryptdata.keyId);\n              this.keyIdToKeyInfo[keyIdStr] = keyInfo;\n              this.logger.info(`${this.systemString} startKeyRequest ${printKeyTag(decryptdata)} state=${keyInfo.requestState}`);\n              this.logger.qe({ critical: true, name: 'startKeyRequest', data: { uri: keyuri, keyId: keyIdStr } });\n              return forkJoin([this.getKeyRequestInfo(keyInfo), this.setServerCertificate()]).pipe(map((values) => values[0]), switchMap((requestInfo) => {\n                  var _a;\n                  (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.licenseChallengeSubmitted({ keyuri: keyuri, keyFormat: this.systemString });\n                  return this.generateLicenseChallenge(keyInfo, requestInfo).pipe(catchError((error) => {\n                      var _a;\n                      this.logger.info(`${this.systemString} generateLicenseChallenge Failed ${error.message} ${printKeyTag(decryptdata)}`);\n                      (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.licenseChallengeError({ keyuri: keyuri });\n                      throw error;\n                  }));\n              }), switchMap((licenseChallenge) => {\n                  var _a;\n                  this.logger.info(`${this.systemString} challenge created ${printKeyTag(decryptdata)}`);\n                  this.logger.qe({ critical: true, name: 'challengeCreated', data: { uri: keyuri, keyId: keyIdStr } });\n                  (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.licenseChallengeCreated({ keyuri: keyuri, cdmVersion: this.cdmVersion });\n                  return this.getKeyRequestResponse(keyInfo, licenseChallenge);\n              }), switchMap((parsedKeyResponse) => {\n                  var _a;\n                  this.logger.info(`${this.systemString} onKeyResponseParsed ${printKeyTag(decryptdata)}`);\n                  this.logger.qe({ critical: true, name: 'onKeyResponseParsed', data: { uri: keyuri, keyId: keyIdStr } });\n                  (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.licenseResponseSubmitted({ keyuri: keyuri });\n                  return this.handleParsedKeyResponse(keyInfo, parsedKeyResponse).pipe(catchError((error) => {\n                      var _a;\n                      this.logger.info(`${this.systemString} ParseKeyResponse Failed ${printKeyTag(decryptdata)} error=${error.message}`);\n                      (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.licenseResponseError({ keyuri: keyuri });\n                      throw error;\n                  }));\n              }), map(() => {\n                  var _a;\n                  this.logger.info(`${this.systemString} New usable key: ${printKeyTag(decryptdata)} CDMVersion=${this.cdmVersion}`);\n                  this.logger.qe({ critical: true, name: 'newUsableKey', data: { uri: keyuri, keyId: keyIdStr } });\n                  (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.licenseResponseProcessed({ keyuri: keyuri });\n                  keyInfo.setKeyRequestState(KeyRequestState.NONE);\n                  this.removeSessions(keyInfo.decryptdata, false).subscribe();\n                  return decryptdata; // Resolve\n              }), catchError((err) => {\n                  this.handleKeyExchangeError(keyInfo, err);\n                  throw err;\n              }), \n              // takeUntil(this.destroy$),\n              finalize$1(() => {\n                  this._abortKeyRequest(keyInfo);\n              }));\n          }\n          /**\n           * Internal cleanup of key request\n           * @param keyInfo The key request to abort\n           */\n          _abortKeyRequest(keyInfo) {\n              var _a;\n              if (keyInfo) {\n                  const keyuri = keyInfo.decryptdata.uri;\n                  const keyIdStr = BufferUtils.utf8arrayToStr(keyInfo.decryptdata.keyId);\n                  if (keyInfo.requestState !== KeyRequestState.NONE) {\n                      this.logger.info(`Aborting key ${redactUrl(keyuri)} state=${keyInfo.requestState}`);\n                      this.logger.qe({ critical: true, name: 'keyAborted', data: { uri: keyuri, keyId: keyIdStr } });\n                      (_a = this.sessionHandler) === null || _a === void 0 ? void 0 : _a.keyAborted({ keyuri });\n                  }\n                  keyInfo.abort();\n              }\n          }\n          // Do cleanup if needed\n          handleKeyExchangeError(keyInfo, err) {\n              keyInfo.error(err); // Mark as error so we don't erroneously report abort\n              const keyuri = keyInfo.decryptdata.uri;\n              const keyIdStr = BufferUtils.utf8arrayToStr(keyInfo.decryptdata.keyId);\n              this.logger.qe({ critical: true, name: 'keyExchangeError', data: { uri: keyuri, keyId: keyIdStr, errMsg: err.message } });\n          }\n          updateItemId(itemId) {\n              // Update the itemId to which the key belongs to. The license release message carries this info.\n              // When you generate challenge this itemId was being used.\n              this.itemId = itemId;\n          }\n          /**\n           * Remove a key from the keysystem\n           * @param decryptdata\n           */\n          removeKey(decryptdata) {\n              return this.removeKeyInternal(decryptdata);\n          }\n          removeKeyInternal(decryptdata) {\n              this.logger.info(`removing key ${redactUrl(decryptdata.uri)}`);\n              const keyInfo = this.keyUriToKeyInfo[decryptdata.uri];\n              if (keyInfo && keyInfo.session) {\n                  const session = keyInfo.session;\n                  keyInfo.abort();\n                  keyInfo.destroy();\n                  const keyIdStr = BufferUtils.utf8arrayToStr(decryptdata.keyId);\n                  this.keyIdToKeyInfo[keyIdStr] = undefined;\n                  this.keyUriToKeyInfo[decryptdata.uri] = undefined;\n                  return this.removeSession(session);\n              }\n          }\n          removeSessions(decryptdata, shouldRemoveCurrentSession) {\n              const keyInfo = this.keyUriToKeyInfo[decryptdata.uri];\n              if (keyInfo) {\n                  // Remove all previous sessions\n                  const oldRemoves = keyInfo.oldSessions.map((session) => {\n                      return this.removeSession(session);\n                  });\n                  keyInfo.oldSessions = [];\n                  return iif(() => oldRemoves.length === 0, VOID, forkJoin(oldRemoves)).pipe(switchMap(() => {\n                      if (shouldRemoveCurrentSession) {\n                          // Finally remove the current session\n                          return this.removeKeyInternal(decryptdata);\n                      }\n                      return VOID;\n                  }));\n              }\n              return VOID;\n          }\n          removeSession(session) {\n              this.logger.info(`remove session ${session.sessionId}`);\n              const index = this.sessions.findIndex((sessionCtx) => {\n                  return sessionCtx.session === session;\n              });\n              const sessionCtx = this.sessions[index];\n              if (index > -1) {\n                  this.sessions.splice(index, 1);\n              }\n              this.sessionIdToKeyUri[session.sessionId] = undefined;\n              if (sessionCtx) {\n                  return sessionCtx.destroy();\n              }\n              return VOID;\n          }\n          getKeyRequestInfo(keyInfo) {\n              const decryptdata = keyInfo.decryptdata;\n              const keyuri = decryptdata.uri;\n              const obs = keyInfo.setKeyRequestState(KeyRequestState.GET_REQUEST_INFO);\n              this.eventEmitter.trigger(HlsEvent$1.KEY_REQUEST_STARTED, { keyuri: keyuri, decryptdata: decryptdata, timestamp: Date.now() });\n              return obs;\n          }\n          setKeyRequestInfo(keyuri, requestInfo) {\n              const keyInfo = this.keyUriToKeyInfo[keyuri];\n              if (!keyInfo) {\n                  this.logger.info(`Unexpected key requested ${redactUrl(keyuri)}`);\n                  return;\n              }\n              keyInfo.resolveState(KeyRequestState.GET_REQUEST_INFO, requestInfo);\n          }\n          sanitizeRequest(requestInfo) {\n              return requestInfo;\n          }\n          /**\n           * Generate a license challenge for the key\n           * @param keyInfo     The key we're requesting\n           * @param requestInfo Additional parameters for making the key request\n           * @param state       MediaKeyStatus for the keyId associated with keyInfo\n           */\n          generateLicenseChallengeInternal(keyInfo, requestInfo, state) {\n              if (state === 'status-pending') {\n                  this.logger.info('Request already in progress');\n              }\n              const decryptdata = keyInfo.decryptdata;\n              const session = keyInfo.session;\n              const keyuri = decryptdata.uri;\n              const keyId = decryptdata.keyId;\n              let generateRequest$;\n              const getKeyResponse$ = keyInfo.setKeyRequestState(KeyRequestState.GET_CHALLENGE);\n              if (!session.generateRequestPromise) {\n                  const initDataResult = this.generateInitData(keyId, decryptdata, requestInfo);\n                  this.logger.info(`challenge create start uri=${redactUrl(keyInfo.decryptdata.uri)} versions=${JSON.stringify(keyInfo.decryptdata.formatversions)}`);\n                  session.generateRequestPromise = session.generateRequest(initDataResult.initDataType, initDataResult.initData);\n                  // May only be called once\n                  generateRequest$ = scheduled(session.generateRequestPromise, queueScheduler).pipe(tap(() => {\n                      this.sessionIdToKeyUri[session.sessionId] = keyuri;\n                  }), catchError((reason) => {\n                      this.logger.info(`${this.systemString} FAIL: generateRequest fail keyuri=${redactUrl(keyInfo.decryptdata.uri)} message=${reason.message}`);\n                      throw new KeySystemError(reason.message, keyInfo.decryptdata.uri, 0, ErrorResponses.KeySystemFailedToGenerateLicenseRequest, this.systemString);\n                  }));\n              }\n              else {\n                  // If generateRequest was already called\n                  generateRequest$ = scheduled(session.generateRequestPromise, queueScheduler).pipe(switchMap(() => this.generateRequestInitialized(keyInfo, state === 'usable')));\n              }\n              return forkJoin([getKeyResponse$, generateRequest$]).pipe(map((result) => new Uint8Array(result[0])));\n          }\n          /**\n           * This is different from startKeyRequest in that it could be triggered\n           * from an externally generated event. (Hls.generateKeyRequest)\n           *\n           * @param keyInfo     Key info object\n           * @param requestInfo Extra information needed to make this request\n           */\n          generateLicenseChallenge(keyInfo, requestInfo) {\n              const decryptdata = keyInfo.decryptdata;\n              const session = keyInfo.session;\n              const keyuri = decryptdata.uri;\n              const keyId = decryptdata.keyId;\n              const keyIdStr = BufferUtils.utf8arrayToStr(decryptdata.keyId);\n              this.logger.info(`${this.systemString} generateLicenseChallenge ${printKeyTag(decryptdata)}`);\n              this.logger.qe({ critical: true, name: 'generateLicenseChallenge', data: { uri: keyuri, keyId: keyIdStr } });\n              if (keyInfo.licenseChallenge) {\n                  // This is handling for key systems like Widevine where the license challenge for renewal is already generated and we just need to use it.\n                  keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, keyInfo.licenseChallenge);\n              }\n              requestInfo = this.sanitizeRequest(requestInfo);\n              keyInfo.requestInfo = requestInfo;\n              // In gapless mode itemId needs to be updated to the newly loading item\n              //this.itemId = this.hls.inGaplessMode ? this.hls.loadingItem.itemId : this.itemId;\n              this.sessionId = this.sessionId || (requestInfo && requestInfo.sessionId) || this.itemId; // Use first id\n              let state;\n              // If it's playready Key system we need to change the endianness of the keyid in the key status\n              if (this.systemString === PlayReadyKeySystemProperties.systemStringPrefix) {\n                  // Use a different copy of KID, otherwise it will change the endianness of KID in DecryptData\n                  // since it's a referrence\n                  const curKid = new Uint8Array(keyId);\n                  keysystemutil.changeEndianness(curKid);\n                  state = session.keyStatuses.get(curKid);\n              }\n              else {\n                  state = session.keyStatuses.get(keyId); // Keysystem state\n              }\n              let createRequestPromise;\n              switch (state) {\n                  case 'status-pending': // Challenge created or key known\n                  case 'usable': // Finished key request already, should renew\n                  case 'expired':\n                  case undefined: {\n                      createRequestPromise = this.generateLicenseChallengeInternal(keyInfo, requestInfo, state);\n                      break;\n                  }\n                  default:\n                      createRequestPromise = throwError(new KeySystemError(`Bad internal state state=${state}`, keyuri, 0, ErrorResponses.KeySystemUnexpectedState, this.systemString));\n                      break;\n              }\n              return createRequestPromise;\n          }\n          /**\n           * Set the parsed license response\n           * @param keyuri          URI of key corresponding to request\n           * @param parsedResponse  The parsed response for the key request. Specific to key system\n           */\n          setParsedResponse(keyuri, parsedResponse) {\n              const keyInfo = this.keyUriToKeyInfo[keyuri];\n              if (keyInfo) {\n                  keyInfo.resolveState(KeyRequestState.GET_KEY_RESPONSE, parsedResponse);\n              }\n              else {\n                  this.logger.info(`${this.systemString} no keyInfo for keyuri: ${redactUrl(keyuri)}`);\n              }\n          }\n          // keystatuseschange handler\n          handleKeyStatusesChange(event) {\n              const ks = event.target;\n              ks.keyStatuses.forEach((status, keyid, parent) => {\n                  const currentKeyId = new Uint8Array(keyid);\n                  // If it's playready Key system we need to change the endianness of the keyid in the key status\n                  if (this.systemString === PlayReadyKeySystemProperties.systemStringPrefix) {\n                      keysystemutil.changeEndianness(currentKeyId);\n                  }\n                  const keyIdStr = BufferUtils.utf8arrayToStr(currentKeyId);\n                  const keyInfo = this.keyIdToKeyInfo[keyIdStr];\n                  if (keyInfo) {\n                      this.handleKeyStatusForKey(status, keyInfo);\n                  }\n              });\n          }\n          handleKeyStatusForKey(status, keyInfo) {\n              if (!keyInfo) {\n                  return;\n              }\n              const decryptdata = keyInfo.decryptdata;\n              const keyuri = decryptdata.uri;\n              switch (status) {\n                  case 'internal-error': {\n                      this.logger.error(`${this.systemString} internal-error for key ${printKeyTag(decryptdata)}`);\n                      this._signalError(keyInfo, new KeyRequestError('Got internal error from key system', keyuri, 0, ErrorResponses.KeySystemInternalError, false, KeyRequestErrorReason.InternalError));\n                      break;\n                  }\n                  case 'usable': {\n                      if (keyInfo.requestState === KeyRequestState.PROCESS_LICENSE) {\n                          keyInfo.resolveState(KeyRequestState.PROCESS_LICENSE, undefined);\n                      }\n                      break;\n                  }\n                  case 'output-restricted': {\n                      this.logger.warn(`${this.systemString} output-restricted for key ${printKeyTag(decryptdata)}`);\n                      if (keyInfo.session) {\n                          // Cleanup the session, so that we don't keep the keys and try to renew it later\n                          this.removeSession(keyInfo.session).pipe(takeUntil(this.destroy$)).subscribe();\n                      }\n                      this._signalError(keyInfo, new KeyRequestError('output-restricted', keyuri, 0, ErrorResponses.KeySystemOutputRestricted, false, KeyRequestErrorReason.OutputRestricted));\n                      break;\n                  }\n                  case 'expired': {\n                      this.logger.warn(`${this.systemString} expired for key ${printKeyTag(decryptdata)}. Attempting renewal`);\n                      this._signalRenewal(keyInfo);\n                      break;\n                  }\n                  default:\n                      this.logger.info(`key status ${printKeyTag(decryptdata)} ${status}`);\n                      break;\n              }\n          }\n          _scheduleRenewal(keyInfo, renewalMs) {\n              this.logger.info(`${this.systemString} Scheduling renewal for ${printKeyTag(keyInfo.decryptdata)} in ${renewalMs} ms`);\n              timer(renewalMs)\n                  .pipe(tap(() => this._signalRenewal(keyInfo)), takeUntil(race(keyInfo.destroy$, this.destroy$, waitFor(keyInfo.onKeyRequestState$, (state) => state === KeyRequestState.GET_REQUEST_INFO))))\n                  .subscribe();\n          }\n          _signalRenewal(keyInfo) {\n              this._keyStatusChange$.next({ decryptdata: keyInfo.decryptdata, status: 'needs-renewal' });\n          }\n          _signalError(keyInfo, error) {\n              this._keyStatusChange$.next({ decryptdata: keyInfo.decryptdata, status: 'error', error });\n              keyInfo.error(error);\n          }\n      }\n    \n      const kClearKeySystemString = 'org.w3.clearkey';\n      const ClearKeySecurityLevels = {\n          NONE: 0,\n      };\n      const ClearKeySystemProperties = {\n          id: 'clearkey',\n          systemStringPrefix: kClearKeySystemString,\n          keyFormatString: kClearKeySystemString,\n          securityLevels: ClearKeySecurityLevels,\n      };\n    \n      /**\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const KeySystemIdValues = ['clearkey', 'fairplaystreaming', 'playready', 'widevine'];\n    \n      /**\n       * Clear key system implementation\n       *\n       * Uses July 2016 spec:\n       * https://www.w3.org/TR/2016/CR-encrypted-media-20160705/\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      // default configuration to pass into requestMediaKeySystemAccess\n      const kClearKeySystemConfig = {\n          initDataTypes: ['keyids', 'cenc'],\n      };\n      class ClearKeySystem extends KeySystem {\n          constructor(mediaKeys, keySystemString, config, eventEmitter, sessionHandler, logger) {\n              super(mediaKeys, keySystemString, config, eventEmitter, false, sessionHandler, logger);\n          }\n          // destroy()\n          static get requestAccessConfig() {\n              return kClearKeySystemConfig;\n          }\n          get needsCert() {\n              return false;\n          }\n          getKeyRequestResponse(keyInfo, licenseChallenge) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const loaderConfig = {\n                  maxLoadTimeMs: 0,\n                  maxTimeToFirstByteMs: 0,\n                  autoRetry: false,\n                  timeoutRetry: null,\n                  errorRetry: null,\n              };\n              return fromUrlArrayBuffer({ url: keyuri, xhrSetup: this.config.xhrSetup }, loaderConfig).pipe(map(([loadArrayBufferResult, _]) => {\n                  const key = new Uint8Array(loadArrayBufferResult);\n                  const response = {\n                      response: this.parseResponse(licenseChallenge, key),\n                  };\n                  return response;\n              }));\n          }\n          parseResponse(licenseChallenge, key) {\n              const keyObj = {\n                  kty: 'oct',\n                  kid: NumericEncodingUtils$1.base64UrlEncode(licenseChallenge),\n                  k: NumericEncodingUtils$1.base64UrlEncode(key),\n              };\n              return BufferUtils.strToUtf8array(JSON.stringify({ keys: [keyObj] }));\n          }\n          handleParsedKeyResponse(keyInfo, keyResponse) {\n              const responseBlob = keyResponse.response;\n              const processLicense = keyInfo.setKeyRequestState(KeyRequestState.PROCESS_LICENSE);\n              const updateSession = from(keyInfo.session.update(responseBlob)).pipe(tap(() => {\n                  const keyId = keyInfo.decryptdata.keyId;\n                  const state = keyInfo.session.keyStatuses.get(keyId);\n                  this.handleKeyStatusForKey(state, keyInfo);\n              }), catchError((reason) => {\n                  const response = { code: reason.code, text: 'Failed to update with key response' };\n                  const err = new KeySystemError(reason.message, keyInfo.decryptdata.uri, reason.code, response, this.systemString);\n                  throw err;\n              }));\n              return forkJoin([processLicense, updateSession]).pipe(mapTo(undefined));\n          }\n          generateInitData(keyId /* decryptdata, requestInfo*/) {\n              return { initData: keysystemutil.makeKeyIdsInitData([keyId]), initDataType: 'keyids' };\n          }\n          generateRequestInitialized() {\n              return VOID;\n          }\n          sanitizeRequest(requestInfo) {\n              return requestInfo;\n          }\n          // message\n          handleKeyMessage(event) {\n              if (this.isDestroying) {\n                  this.logger.info('In the middle of destroying, ignore key message');\n                  return;\n              }\n              if (event.messageType !== 'license-request') {\n                  this.logger.info(`${this.systemString} Unexpected key message type ${event.messageType}`);\n                  return;\n              }\n              const message = new Uint8Array(event.message);\n              const request = JSON.parse(BufferUtils.utf8arrayToStr(message).trim());\n              if (request.kids.length !== 1) {\n                  this.logger.info(`${this.systemString} Unexpected number of keyIds ${request.kids.length}`);\n                  return;\n              }\n              const keyId = NumericEncodingUtils$1.base64Decode(request.kids[0]); // just care about the first for now\n              const keyIdStr = BufferUtils.utf8arrayToStr(keyId);\n              const keyInfo = this.keyIdToKeyInfo[keyIdStr];\n              if (keyInfo) {\n                  keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, keyId);\n              }\n              else {\n                  this.logger.info(`${this.systemString} no keyInfo for keyId ${JSON.stringify(keyId)}`);\n              }\n          }\n      }\n      var ClearKeySystem$1 = ClearKeySystem;\n    \n      /*\n       * FairPlayStreaming key system constants\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const kFairPlayStreamingKeySystemConfig = {\n          initDataTypes: ['cenc'],\n      };\n      const kFairPlayStreamingKeySystemUUID = new Uint8Array([148, 206, 134, 251, 7, 255, 79, 67, 173, 184, 147, 210, 250, 150, 140, 162]);\n      var SchemeFourCC;\n      (function (SchemeFourCC) {\n          SchemeFourCC[SchemeFourCC[\"CENC\"] = 1667591779] = \"CENC\";\n          SchemeFourCC[SchemeFourCC[\"CBCS\"] = 1667392371] = \"CBCS\";\n      })(SchemeFourCC || (SchemeFourCC = {}));\n      /**\n       * Base class for FPS key systems\n       */\n      class FairPlayStreamingKeySystemBase extends KeySystem {\n          constructor(mediaKeys, keySystemString, config, eventEmitter, useSingleKeySession, sessionHandler, logger) {\n              super(mediaKeys, keySystemString, config, eventEmitter, useSingleKeySession, sessionHandler, logger);\n              this._hasSetRenewal = false;\n          }\n          static get systemId() {\n              return kFairPlayStreamingKeySystemUUID;\n          }\n          static get requestAccessConfig() {\n              return kFairPlayStreamingKeySystemConfig;\n          }\n          get needsCert() {\n              return true;\n          }\n          sanitizeRequest(requestInfo) {\n              return {\n                  assetId: requestInfo && requestInfo.assetId ? new Uint8Array(requestInfo.assetId) : undefined,\n                  ssc: requestInfo && requestInfo.ssc ? new Uint8Array(requestInfo.ssc) : undefined,\n                  sessionId: requestInfo && requestInfo.sessionId ? requestInfo.sessionId : undefined,\n              };\n          }\n          _scheduleRenewal(keyInfo, renewalMs) {\n              if (!this.useSingleKeySession) {\n                  // Each key has its own timer\n                  super._scheduleRenewal(keyInfo, renewalMs);\n              }\n              else if (!this._hasSetRenewal) {\n                  this._hasSetRenewal = true;\n                  this.logger.info(`${this.systemString} Scheduling renewal in ${renewalMs} ms`);\n                  timer(renewalMs)\n                      .pipe(tap(() => {\n                      // use first available keyInfo\n                      const keyInfo = Object.values(this.keyUriToKeyInfo)[0];\n                      if (keyInfo) {\n                          this._signalRenewal(keyInfo);\n                      }\n                  }), finalize$1(() => {\n                      this._hasSetRenewal = false;\n                  }), takeUntil(this.destroy$))\n                      .subscribe();\n              }\n          }\n          /**\n           * Handle a parsed key response\n           * @param {Object} keyInfo      Info about the key\n           * @param {Object} keyResponse  The parsed key response object { statusCode, ckc, renewalData }\n           * @returns {Observable<void>} message to pass to update() for processing license\n           */\n          handleParsedKeyResponse(keyInfo, keyResponse) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const statusCode = keyResponse.statusCode;\n              const licenseResponse = keyResponse.ckc && keyResponse.ckc.byteLength !== 0 ? keyResponse.ckc : keyResponse.license && keyResponse.license.byteLength !== 0 ? keyResponse.license : undefined;\n              // Special handling in case of HTTP Errors during key requests.\n              if (statusCode === 0 && !licenseResponse) {\n                  return throwError(new KeyRequestError('License request resulted in HTTP Error', keyuri, statusCode, { code: statusCode, text: 'HTTP Error' }, true, KeyRequestErrorReason.HttpError));\n              }\n              if (statusCode !== 0) {\n                  return throwError(new KeyRequestError('License server responded with error', keyuri, statusCode, { code: statusCode, text: 'Server Error' }, false, KeyRequestErrorReason.LicenseServerError));\n              }\n              if (!licenseResponse) {\n                  const err = new KeyRequestError('License server responded with invalid license', keyuri, statusCode, { code: statusCode, text: 'Invalid license' }, false, KeyRequestErrorReason.LicenseServerError);\n                  return throwError(err);\n              }\n              const renewalDate = keyResponse.renewalDate;\n              const now = new Date();\n              const renewalMs = renewalDate > now ? renewalDate.getTime() - now.getTime() : 0;\n              if (renewalMs > 0) {\n                  this._scheduleRenewal(keyInfo, renewalMs);\n              }\n              const ckcArray = this.makeProcessLicenseRequestMessage(keyInfo, licenseResponse, renewalMs);\n              // Only resolve if we got success, either from 'usable' keystatuschange event\n              // or on promise completion with 'usable' key status. Otherwise reject\n              const session = keyInfo.session;\n              const updateSession = from(session.update(ckcArray)).pipe(tap(() => {\n                  const keyId = keyInfo.decryptdata.keyId;\n                  const status = session.keyStatuses.get(keyId);\n                  // Slightly faster than waiting for keystatuschange\n                  this.handleKeyStatusForKey(status, keyInfo);\n              }), catchError((error) => {\n                  const err = new KeySystemError(error.message, keyInfo.decryptdata.uri, 0, ErrorResponses.KeySystemFailedToUpdateSession, this.systemString);\n                  throw err;\n              }));\n              const getLicense = keyInfo.setKeyRequestState(KeyRequestState.PROCESS_LICENSE);\n              return forkJoin([getLicense, updateSession]).pipe(mapTo(undefined));\n          }\n          makeKeyRequests(requestInfoArray) {\n              const keyRequests = [];\n              for (const r of requestInfoArray) {\n                  const decryptdata = r.decryptdata;\n                  const requestInfo = r.requestInfo;\n                  const keyId = decryptdata.keyId;\n                  keyRequests.push({\n                      keyId: keyId,\n                      assetId: requestInfo ? requestInfo.assetId : undefined,\n                      ssc: requestInfo ? requestInfo.ssc : undefined,\n                      versionList: decryptdata.formatversions,\n                  });\n              }\n              return keyRequests;\n          }\n          getSchemeAndFlags(decryptdata) {\n              const scheme = decryptdata.method === 'ISO-23001-7' ? SchemeFourCC.CENC : SchemeFourCC.CBCS; // TODO pass real scheme through.\n              const flags = 0;\n              // TODO\n              /* if (this.hls.playingItem.secureStop) {\n                flags |= 0x01;\n              } */\n              return { scheme, flags };\n          }\n          generateInitData(keyId, decryptdata, requestInfo) {\n              // Generate a PSSH\n              const { scheme, flags } = this.getSchemeAndFlags(decryptdata);\n              const keyRequests = this.makeKeyRequests([{ decryptdata, requestInfo }]);\n              const pssh = this.makeFpsKeySystemInitData(scheme, flags, keyRequests);\n              // console.log('PSSH=' + Hex.hexDump(pssh));\n              return { initData: pssh, initDataType: 'cenc' };\n          }\n          /**\n           * Generate a key renewal request on an already initialized session\n           * @param keyInfo   Info about the key we're requesting\n           * @param isRenewal Is this a renewal requewst\n           * @returns promise for when update call is done.\n           **/\n          generateRequestInitialized(keyInfo, isRenewal) {\n              tag(`[Keys] challenge create start uri=${redactUrl(keyInfo.decryptdata.uri)} versions=${JSON.stringify(keyInfo.decryptdata.formatversions)}`);\n              const message = this.makeKeyRequestMessage(keyInfo, isRenewal);\n              if (!message) {\n                  const err = new KeyRequestError('Unable to generate request using existing keySession', keyInfo.decryptdata.uri, 0, ErrorResponses.KeySystemFailedToGenerateLicenseRequest, true, KeyRequestErrorReason.InvalidState);\n                  return throwError(err);\n              }\n              return from(keyInfo.session.update(message)).pipe(tap(() => {\n                  keyInfo.requestInfo = undefined; // Don't need requestInfo anymore.\n              }), catchError((reason) => {\n                  tag(`[Keys] ${this.systemString} FAIL: generateRequestInitialized keyuri=${redactUrl(keyInfo.decryptdata.uri)} message=${reason.message}`);\n                  throw new KeySystemError(reason.message, keyInfo.decryptdata.uri, 0, ErrorResponses.KeySystemFailedToGenerateLicenseRenewal, this.systemString);\n              }));\n          }\n          /**\n           * @param {Object}      keyInfo           Info about the key we're requesting\n           * @param {Uint8Array}  licenseChallenge  Challenge bytes\n           * @returns {Observable<Object>} Promise returning the license response\n           */\n          getKeyRequestResponse(keyInfo, licenseChallenge) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const getKeyResponse = keyInfo.setKeyRequestState(KeyRequestState.GET_KEY_RESPONSE);\n              this.eventEmitter.trigger(HlsEvent$1.LICENSE_CHALLENGE_CREATED, {\n                  keyuri: keyuri,\n                  licenseChallenge: licenseChallenge,\n                  keysystem: this.systemString,\n              });\n              return getKeyResponse;\n          }\n          resolveSPCPromise(keyInfo, spc) {\n              keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, spc);\n          }\n      }\n    \n      /*\n       * FairPlayStreaming key system\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      //declare var __SECURESTOP_KEYS__: IFPSSecureStopKeys;\n      //const SecureStopKeys = __SECURESTOP_KEYS__;\n      const SecureStopKeys = {};\n      const MessageFourCC = {\n          NONE: 0,\n          CRKR: 1668442994,\n          RMKY: 1919773561,\n          CKCS: 1667982195,\n          CERT: 1667592820,\n          SPCS: 1936745331,\n          RNEW: 1919837559,\n          RLSE: 1919710053,\n          SSTP: 1936946288,\n          CDMI: 1667525993,\n      };\n      const APIProviderId = {\n          CENC: 'EC396D13-FB13-4993-9D0D-71518ACF3D6F',\n          CBCS: 'F19BF03B-7470-41A4-9655-86D078307D59',\n      };\n      /**\n       * Read a generic data field\n       *\n       * Format: 4B length of data, nB data bytes\n       *\n       * @param {Uint8Array} inBuf  Buffer referenced by dv\n       * @param {DataView} dv  DataView wrapper around inBuf\n       * @param {number} pos  Starting position in buffer to read from\n       * @returns {Object} { pos: next byte to read, data: Uint8Array holding data parsed out of inBuf }\n       */\n      function readDataField(inBuf, dv, pos) {\n          if (pos + 4 > inBuf.byteLength) {\n              return undefined;\n          }\n          const dataLen = dv.getUint32(pos);\n          pos += 4;\n          if (pos + dataLen > inBuf.byteLength) {\n              return undefined;\n          }\n          const data = inBuf.slice(pos, pos + dataLen);\n          pos += dataLen;\n          return { pos: pos, data: data };\n      }\n      // Read message:\n      // cmd (4)\n      // arrayLen (4)\n      // keyId (16)\n      // dataLen (4)\n      // data (dataLen)\n      function parseData(message) {\n          const keyIdToData = {};\n          const dv = new DataView(message.buffer);\n          let pos = 4;\n          const arrayLen = dv.getUint32(pos);\n          pos += 4;\n          for (let i = 0; i < arrayLen && pos < message.byteLength; ++i) {\n              if (pos + 16 > message.byteLength) {\n                  break;\n              }\n              const keyId = message.slice(pos, pos + 16);\n              pos += 16;\n              if (pos + 4 > message.byteLength) {\n                  break;\n              }\n              const tmp = readDataField(message, dv, pos);\n              if (tmp) {\n                  pos = tmp.pos;\n                  keyIdToData[BufferUtils.utf8arrayToStr(keyId)] = tmp.data;\n              }\n              else {\n                  break;\n              }\n          }\n          return keyIdToData;\n      }\n      function addDataField(outBuf, dv, pos, data) {\n          const len = data ? data.byteLength : 0;\n          dv.setUint32(pos, len);\n          if (len) {\n              outBuf.set(data, pos + 4);\n          }\n          pos += 4 + len;\n          return pos;\n      }\n      // Including 4 byte arrayLen\n      function getKeyRequestArraySize(keyRequests) {\n          // arrayLen (4)\n          // --------- For each key:\n          // keyId(16)\n          // assetIdLen (4), assetId\n          // sscLen (4), ssc\n          // versionLen (4), versionList (each one 4B)\n          let bytesForArray = 4;\n          for (const kr of keyRequests) {\n              bytesForArray += 28 + (kr.assetId ? kr.assetId.byteLength : 0) + (kr.ssc ? kr.ssc.byteLength : 0) + (kr.versionList ? kr.versionList.length * 4 : 0);\n          }\n          return bytesForArray;\n      }\n      /**\n       * Fill existing array w/ key request data\n       * @param array uint8array\n       * @param dv    dataview for array\n       * @param pos   position to write to within array\n       * @param keyRequests Array of key requests [ { assetId, ssc, versionList } ]\n       * @returns\n       */\n      function addKeyRequestArray(array, dv, pos, keyRequests) {\n          dv.setUint32(pos, keyRequests.length); // arrayLen\n          pos += 4;\n          for (const kr of keyRequests) {\n              array.set(kr.keyId, pos);\n              pos += 16;\n              pos = addDataField(array, dv, pos, kr.assetId);\n              pos = addDataField(array, dv, pos, kr.ssc);\n              dv.setUint32(pos, kr.versionList ? kr.versionList.length : 0);\n              pos += 4;\n              if (kr.versionList) {\n                  for (const vl of kr.versionList) {\n                      dv.setUint32(pos, vl);\n                      pos += 4;\n                  }\n              }\n          }\n          // console.log(`addKeyRequestArray: ${Hex.hexDump(array)}`);\n          return pos;\n      }\n      function makeFpsKeySystemInitData$1(scheme, protocol, flags, keyRequests) {\n          // Generate a PSSH\n          // Data for FPS:\n          // scheme: CC     4B\n          // protocol:      1B\n          // flags:         3B\n          // keyrequestarray\n          const keyRequestBytes = getKeyRequestArraySize(keyRequests);\n          let pos = 0;\n          const data = new Uint8Array(8 + keyRequestBytes);\n          const dv = new DataView(data.buffer);\n          dv.setUint32(pos, scheme); // schm\n          dv.setUint32(pos + 4, (protocol << 24) | (flags & 16777215)); // version | flags\n          pos += 8;\n          pos = addKeyRequestArray(data, dv, pos, keyRequests);\n          // console.log(`makeFpsKeySystemInitData: ${Hex.hexDump(data)}`);\n          return data;\n      }\n      function makeCreateKeyRequestMessage(keyRequests) {\n          // cmd (4)\n          // keyrequest array\n          // first calculate bytes to allocate\n          const bytesForArray = getKeyRequestArraySize(keyRequests);\n          let pos = 0;\n          const req = new Uint8Array(4 + bytesForArray);\n          const dv = new DataView(req.buffer);\n          dv.setUint32(0, MessageFourCC.CRKR); // cmd\n          pos += 4;\n          pos = addKeyRequestArray(req, dv, pos, keyRequests);\n          // console.log(`makeCreateKeyRequestMessage: ${Hex.hexDump(req)}`);\n          return req;\n      }\n      function makeProcessLicenseRequestMessage(licenses) {\n          // cmd (4)\n          // arrayLen (4)\n          // keyId (16)\n          // expiry (4)\n          // ckcLen (4)\n          // ckcBytes\n          // first calculate bytes to allocate\n          let bytesForArray = 0;\n          for (const l of licenses) {\n              bytesForArray += 24 + l.ckc.byteLength;\n          }\n          let pos = 0;\n          const req = new Uint8Array(8 + bytesForArray);\n          const dv = new DataView(req.buffer);\n          dv.setUint32(0, MessageFourCC.CKCS); // cmd\n          dv.setUint32(4, licenses.length); // arrayLen\n          pos += 8;\n          for (const l of licenses) {\n              req.set(l.keyId, pos);\n              pos += 16;\n              dv.setUint32(pos, l.expirySec);\n              pos += 4;\n              pos = addDataField(req, dv, pos, l.ckc);\n          }\n          // console.log(`makeProcessLicenseRequestMessage: ${Hex.hexDump(req)}`);\n          return req;\n      }\n      class FairPlayStreamingKeySystem extends FairPlayStreamingKeySystemBase {\n          constructor(mediaKeys, keySystemString, config, eventEmitter, sessionHandler, logger) {\n              const singleKeySession = typeof config.useMultipleKeySessions === 'undefined' || !config.useMultipleKeySessions;\n              super(mediaKeys, keySystemString, config, eventEmitter, singleKeySession, sessionHandler, logger);\n          }\n          makeProcessLicenseRequestMessage(keyInfo, licenseResponse, renewalMs) {\n              const ckcBytes = new Uint8Array(licenseResponse);\n              const ckcArray = makeProcessLicenseRequestMessage([\n                  {\n                      keyId: keyInfo.decryptdata.keyId,\n                      expirySec: renewalMs / 1000,\n                      ckc: ckcBytes,\n                  },\n              ]);\n              return ckcArray;\n          }\n          makeFpsKeySystemInitData(scheme, flags, keyRequests) {\n              const protocol = 1;\n              const data = makeFpsKeySystemInitData$1(scheme, protocol, flags, keyRequests);\n              const pssh = MP4$1.pssh(FairPlayStreamingKeySystem.systemId, [], data);\n              return pssh;\n          }\n          makeKeyRequestMessage(keyInfo /* , isRenewal*/) {\n              const crkrArray = makeCreateKeyRequestMessage([\n                  {\n                      keyId: keyInfo.decryptdata.keyId,\n                      assetId: keyInfo.requestInfo ? keyInfo.requestInfo.assetId : undefined,\n                      ssc: keyInfo.requestInfo ? keyInfo.requestInfo.ssc : undefined,\n                      versionList: keyInfo.decryptdata.formatversions,\n                  },\n              ]);\n              return crkrArray;\n          }\n          handleKeyMessage(event) {\n              if (event.message.byteLength < 4) {\n                  this.logger.warn('Unexpected message');\n                  return;\n              }\n              // event.message (ArrayBuffer)\n              const message = new Uint8Array(event.message);\n              const dv = new DataView(event.message);\n              const cmd = dv.getUint32(0);\n              if (this.isDestroying && cmd !== MessageFourCC.RLSE) {\n                  this.logger.warn(`In the middle of destroying, ignore command: ${cmd.toString(16)}`);\n                  return;\n              }\n              this.logger.info(`[Keys] ${this.systemString} message 0x${cmd.toString(16)}`);\n              switch (cmd) {\n                  case MessageFourCC.CERT:\n                      this.logger.warn('Certificate not set!');\n                      break;\n                  case MessageFourCC.RNEW: {\n                      const keyIdToData = parseData(message);\n                      for (const keyIdStr in keyIdToData) {\n                          if (Object.prototype.hasOwnProperty.call(keyIdToData, keyIdStr)) {\n                              const keyInfo = this.keyIdToKeyInfo[keyIdStr];\n                              if (keyInfo) {\n                                  this._signalRenewal(keyInfo);\n                              }\n                          }\n                      }\n                      break;\n                  }\n                  case MessageFourCC.SPCS: {\n                      const keyIdToData = parseData(message);\n                      for (const keyIdStr in keyIdToData) {\n                          if (Object.prototype.hasOwnProperty.call(keyIdToData, keyIdStr)) {\n                              const keyInfo = this.keyIdToKeyInfo[keyIdStr];\n                              const spc = keyIdToData[keyIdStr];\n                              if (keyInfo && spc) {\n                                  this.resolveSPCPromise(keyInfo, spc);\n                              }\n                          }\n                      }\n                      break;\n                  }\n                  case MessageFourCC.RLSE: {\n                      this._handleLicenseRelease(message);\n                      break;\n                  }\n                  case MessageFourCC.CDMI: {\n                      // Message length = 4\n                      // CDM version = remaining data\n                      const pos = 4;\n                      const tmp = readDataField(message, dv, pos);\n                      if (tmp) {\n                          const cdmVersion = (this.cdmVersion = BufferUtils.utf8arrayToStr(tmp.data));\n                          this.logger.info(`[Keys] ${this.systemString} CDM Version :  ${cdmVersion}`);\n                      }\n                      break;\n                  }\n                  default:\n                      this.logger.warn(`Unrecognized command:'0x${cmd.toString(16)}'`);\n                      break;\n              }\n          }\n          _handleLicenseRelease(message) {\n              const releaseRecord = {};\n              const dv = new DataView(message.buffer);\n              const type = dv.getUint32(4); // Release type\n              switch (type) {\n                  case MessageFourCC.SSTP: {\n                      // Secure stop\n                      if (!SecureStopKeys) {\n                          this.logger.warn('No secure stop keys defined');\n                          break;\n                      }\n                      releaseRecord[SecureStopKeys.SessionId] = this.sessionId;\n                      // scheme (uint32)\n                      // movieIdLen (uint32)\n                      // movieIdStr\n                      // secureStopSPCLen (uint32)\n                      // secureStopSPC\n                      // sessionLifespanSPCLen (uint32)\n                      // sessionLifespanSPC\n                      let pos = 8;\n                      if (pos + 4 > message.byteLength) {\n                          break;\n                      }\n                      releaseRecord[SecureStopKeys.APIProvider] = dv.getUint32(pos) === SchemeFourCC.CENC ? APIProviderId.CENC : APIProviderId.CBCS;\n                      pos += 4;\n                      let tmp = readDataField(message, dv, pos);\n                      if (tmp) {\n                          pos = tmp.pos;\n                          releaseRecord[SecureStopKeys.MovieID] = BufferUtils.utf8arrayToStr(tmp.data);\n                      }\n                      else {\n                          break;\n                      }\n                      tmp = readDataField(message, dv, pos);\n                      if (tmp) {\n                          pos = tmp.pos;\n                          releaseRecord[SecureStopKeys.SecureStopSPC] = tmp.data;\n                      }\n                      else {\n                          break;\n                      }\n                      tmp = readDataField(message, dv, pos);\n                      if (tmp) {\n                          pos = tmp.pos;\n                          releaseRecord[SecureStopKeys.SessionLifespanSPC] = tmp.data;\n                      }\n                      else {\n                          break;\n                      }\n                      break;\n                  }\n              }\n              this.eventEmitter.trigger(HlsEvent$1.LICENSE_RELEASED, {\n                  keysystem: this.systemString,\n                  itemId: this.itemId,\n                  releaseRecord: releaseRecord,\n              });\n          }\n      }\n      var FPSKeySystem = FairPlayStreamingKeySystem;\n    \n      const FpsBoxTypes = {\n          fpsd: BufferUtils.strToUtf8array('fpsd'),\n          fpsi: BufferUtils.strToUtf8array('fpsi'),\n          fpsk: BufferUtils.strToUtf8array('fpsk'),\n          fkri: BufferUtils.strToUtf8array('fkri'),\n          fkai: BufferUtils.strToUtf8array('fkai'),\n          fkcx: BufferUtils.strToUtf8array('fkcx'),\n          fkvl: BufferUtils.strToUtf8array('fkvl'), // version list\n      };\n      /**\n       * @param   scheme  cbcs or cenc\n       * @param   flags   keySystem flags\n       * @returns FpsKeySystemInitDataBox\n       */\n      function makeFpsKeySystemInfoBox(scheme, flags) {\n          const schemeArray = new Uint8Array(4);\n          MP4$1.set32(scheme, schemeArray, 0);\n          return MP4$1.box(FpsBoxTypes.fpsi, new Uint8Array([\n              0,\n              (flags >> 16) & 255,\n              (flags >> 8) & 255,\n              flags & 255,\n          ]), schemeArray);\n      }\n      /**\n       * Generate a FpsKeyRequestBox\n       * @param {ArrayBuffer} keyId   The key ID\n       * @param {ArrayBuffer} assetId AssetID\n       * @param {ArrayBuffer} ssc     Remote secure context\n       * @param {Array} versionList   A list of Number from EXT-X-KEY:KEYFORMATVERSIONS\n       * @returns {ArrayBuffer} a FpsKeyRequestBox\n       */\n      function makeFpsKeyRequestBox(keyId, assetId, ssc, versionList) {\n          const args = [FpsBoxTypes.fpsk];\n          // Mandatory\n          const fkri = MP4$1.box(FpsBoxTypes.fkri, new Uint8Array([0, 0, 0, 0]), keyId);\n          args.push(fkri);\n          // Optional boxes\n          if (assetId && assetId.byteLength) {\n              args.push(MP4$1.box(FpsBoxTypes.fkai, assetId));\n          }\n          if (ssc && ssc.byteLength) {\n              args.push(MP4$1.box(FpsBoxTypes.fkcx, ssc));\n          }\n          if (versionList && versionList.length) {\n              // List of integers\n              const versionListBuffer = new Uint8Array(4 * versionList.length);\n              let pos = 0;\n              for (const version of versionList) {\n                  MP4$1.set32(version, versionListBuffer, pos);\n                  pos += 4;\n              }\n              args.push(MP4$1.box(FpsBoxTypes.fkvl, versionListBuffer));\n          }\n          const fpsk = MP4$1.box.apply(null, args);\n          return fpsk;\n      }\n      /**\n       * @param {SchemeFourCC} scheme      cbcs or cenc (fourCC)\n       * @param {number} flags       keySystem flags (number)\n       * @param {Array}  keyRequests array of requests [ { keyId, assetId, ssc, versionList } ]\n       * @returns {Uint8Array} a PSSH box for initializing the key system\n       */\n      function makeFpsKeySystemInitData(scheme, flags, keyRequests) {\n          // Mandatory box for key system initialization\n          const args = [FpsBoxTypes.fpsd, makeFpsKeySystemInfoBox(scheme, flags)];\n          for (const kr of keyRequests) {\n              args.push(makeFpsKeyRequestBox(kr.keyId, kr.assetId, kr.ssc, kr.versionList));\n          }\n          const data = MP4$1.box.apply(null, args);\n          const pssh = MP4$1.pssh(FairPlayStreamingKeySystemBase.systemId, null, data);\n          return pssh;\n      }\n      class FairPlayStreamingKeySystemV3 extends FairPlayStreamingKeySystemBase {\n          constructor(mediaKeys, keySystemString, config, eventEmitter, sessionHandler, logger) {\n              super(mediaKeys, keySystemString, config, eventEmitter, false, sessionHandler, logger);\n              this.sessions = [];\n              this.keyIdToKeyInfo = {};\n              this.keyUriToKeyInfo = {};\n              this.sessionIdToKeyUri = {};\n          }\n          static get needsCert() {\n              return true;\n          }\n          handleKeyExchangeError(keyInfo, err) {\n              // If at any point we had an error during key exchange we need to destroy this session\n              this.removeKey(keyInfo.decryptdata).subscribe();\n              super.handleKeyExchangeError(keyInfo, err);\n          }\n          _abortKeyRequest(keyInfo) {\n              if (!this.isDestroying && keyInfo && keyInfo.requestState !== KeyRequestState.NONE) {\n                  this.removeKey(keyInfo.decryptdata).subscribe();\n              }\n              return super._abortKeyRequest(keyInfo);\n          }\n          makeFpsKeySystemInitData(scheme, flags, keyRequests) {\n              return makeFpsKeySystemInitData(scheme, flags, keyRequests);\n          }\n          makeKeyRequestMessage(keyInfo, isRenewal) {\n              if (isRenewal) {\n                  return BufferUtils.strToUtf8array('renew');\n              }\n              return undefined;\n          }\n          makeProcessLicenseRequestMessage(keyInfo, licenseResponse, renewalMs) {\n              const responseStr = JSON.stringify([\n                  {\n                      keyID: NumericEncodingUtils$1.base64Encode(keyInfo.decryptdata.keyId),\n                      payload: NumericEncodingUtils$1.base64Encode(new Uint8Array(licenseResponse)),\n                  },\n              ]);\n              this.logger.debug(`[Keys] processLicense msg=${responseStr}`);\n              return BufferUtils.strToUtf8array(responseStr);\n          }\n          handleKeyMessage(event) {\n              const session = event.target;\n              const sessionId = session.sessionId;\n              const messageType = event.messageType;\n              this.logger.info(`[Keys] onKeyMessage sessionId=${sessionId} type=${messageType}`);\n              const keyuri = this.sessionIdToKeyUri[sessionId];\n              let keyInfo;\n              if (!keyuri) {\n                  // key message could happen before generateRequest() promise completes\n                  for (const ki of Object.values(this.keyUriToKeyInfo)) {\n                      if (ki && ki.session === session) {\n                          keyInfo = ki;\n                      }\n                  }\n              }\n              else {\n                  keyInfo = this.keyUriToKeyInfo[keyuri];\n              }\n              if (!keyInfo) {\n                  this.logger.warn('[Keys] No key associated with session');\n                  return;\n              }\n              switch (messageType) {\n                  case 'license-request': {\n                      const message = new Uint8Array(event.message);\n                      const messagestr = BufferUtils.utf8arrayToStr(message);\n                      try {\n                          // Expect only one but we'll handle all of them anyway\n                          const spcArray = JSON.parse(messagestr);\n                          spcArray.forEach((payload) => {\n                              const keyIdStr = NumericEncodingUtils$1.base64DecodeToStr(payload.keyID);\n                              const spc = NumericEncodingUtils$1.base64Decode(payload.payload);\n                              const keyInfo = this.keyIdToKeyInfo[keyIdStr];\n                              if (keyInfo) {\n                                  this.resolveSPCPromise(keyInfo, spc);\n                              }\n                          });\n                      }\n                      catch (error) {\n                          this.logger.warn('[Keys] got unexpected license-request format');\n                          this.resolveSPCPromise(keyInfo, message); // Last ditch effort\n                      }\n                      break;\n                  }\n                  case 'license-renewal': {\n                      const spc = new Uint8Array(event.message);\n                      this.resolveSPCPromise(keyInfo, spc);\n                      break;\n                  }\n                  case 'license-release':\n                      this._handleLicenseRelease(session);\n                      break;\n                  default:\n                      this.logger.warn(`[Keys] Unexpected messageType ${messageType}`);\n                      break;\n              }\n          }\n          _handleLicenseRelease(keySession) {\n              keySession.update(BufferUtils.strToUtf8array('acknowledged')).catch((error) => {\n                  this.logger.error(`Promise error: ${error.message}`);\n              });\n          }\n      }\n      var FPSKeySystemV3 = FairPlayStreamingKeySystemV3;\n    \n      /**\n       * PlayReady key system\n       */\n      const kPlayReadyKeySystemConfig = {\n          initDataTypes: ['cenc'],\n      };\n      const kPlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);\n      class PlayReadyKeySystem extends KeySystem {\n          constructor(mediaKeys, systemString, config, eventEmitter, sessionHandler, logger) {\n              super(mediaKeys, systemString, config, eventEmitter, false, sessionHandler, logger);\n              this.shouldDestroyMediaKeys = true;\n          }\n          // destroy()\n          static get systemId() {\n              return kPlayReadyKeySystemUUID;\n          }\n          static get requestAccessConfig() {\n              return kPlayReadyKeySystemConfig;\n          }\n          get needsCert() {\n              return false;\n          }\n          generateInitData(keyId, decryptdata /* , requestInfo */) {\n              const data = decryptdata.pssh;\n              const pssh = MP4$1.pssh(PlayReadyKeySystem.systemId, [], data);\n              // console.log('PSSH=' + Hex.hexDump(pssh));\n              return { initData: pssh, initDataType: 'cenc' };\n          }\n          removeKey(decryptdata) {\n              return super.removeSessions(decryptdata, true);\n          }\n          ensureKeyContext(decryptdata) {\n              const keyuri = decryptdata.uri;\n              const keyInfo = this.keyUriToKeyInfo[keyuri];\n              // Create a new session for current key request and preserve previous sessions for\n              // cleanup later\n              if (keyInfo === null || keyInfo === void 0 ? void 0 : keyInfo.session) {\n                  keyInfo.oldSessions.push(keyInfo.session);\n                  keyInfo.session = null;\n              }\n              return super.ensureKeyContext(decryptdata);\n          }\n          getKeyRequestResponse(keyInfo, licenseChallenge) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const getKeyResponse = keyInfo.setKeyRequestState(KeyRequestState.GET_KEY_RESPONSE);\n              this.eventEmitter.trigger(HlsEvent$1.LICENSE_CHALLENGE_CREATED, {\n                  keyuri: keyuri,\n                  licenseChallenge: licenseChallenge,\n                  keysystem: this.systemString,\n                  keyId: keyInfo.decryptdata.keyId,\n              });\n              return getKeyResponse;\n          }\n          /**\n           * Generate a key renewal request\n           * @param keyInfo Info about the key we're requesting\n           * @returns {Observable<Uint8Array>} Promise returning the license challenge\n           **/\n          generateRequestInitialized(keyInfo) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const challenge = keyInfo.licenseChallenge;\n              this.logger.debug(`[Keys] challenge create start uri=${redactUrl(keyuri)} versions=${JSON.stringify(keyInfo.decryptdata.formatversions)}`);\n              keyInfo.requestInfo = undefined; // Don't need requestInfo anymore.\n              keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, challenge);\n              return VOID;\n          }\n          // Default behavior is to just update using data.response\n          handleParsedKeyResponse(keyInfo, keyResponse) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const statusCode = keyResponse.statusCode;\n              if (statusCode !== 0) {\n                  return throwError(new KeyRequestError('License server responded with error', keyuri, statusCode, { code: statusCode, text: 'Server error' }, false, KeyRequestErrorReason.LicenseServerError));\n              }\n              if (!keyResponse.license || !keyResponse.license.byteLength) {\n                  return throwError(new KeyRequestError('License server responded with invalid license', keyuri, statusCode, { code: statusCode, text: 'Invalid license' }, false, KeyRequestErrorReason.LicenseServerError));\n              }\n              if (keyResponse.renewalDate) {\n                  const renewalDate = keyResponse.renewalDate;\n                  const now = new Date();\n                  const renewalMs = renewalDate > now ? renewalDate.getTime() - now.getTime() : 0;\n                  if (renewalMs > 0) {\n                      this._scheduleRenewal(keyInfo, renewalMs);\n                  }\n              }\n              const processLicense = keyInfo.setKeyRequestState(KeyRequestState.PROCESS_LICENSE);\n              const updateSession = from(keyInfo.session.update(keyResponse.license)).pipe(tap(() => {\n                  // PR CDM on Edge won't change key status till the buffers are pushed. To push buffer the key status should be usable\n                  // So don't rely on key status to change the state like other key systems.\n                  keyInfo.resolveState(KeyRequestState.PROCESS_LICENSE, undefined);\n              }), catchError((reason) => {\n                  this.logger.error(`${this.systemString} FAIL: Failed to update with key response message=${reason.message}`);\n                  const err = new KeySystemError(reason.message, keyInfo.decryptdata.uri, 0, ErrorResponses.KeySystemFailedToUpdateSession, this.systemString);\n                  throw err;\n              }));\n              return forkJoin([processLicense, updateSession]).pipe(mapTo(undefined));\n          }\n          // message\n          handleKeyMessage(event) {\n              if (this.isDestroying) {\n                  this.logger.warn('In the middle of destroying, ignore key message');\n                  return;\n              }\n              const parser = new DOMParser();\n              // Verify the message format encoding, based on that create the typed array\n              // TO DO\n              const messageBuffer = this.config.playReadyMessageFormat === 'utf16' ? new Uint16Array(event.message.buffer || event.message) : new Uint8Array(event.message.buffer || event.message);\n              const message = String.fromCharCode.apply(null, Array.from(messageBuffer));\n              // Expected license challenge format\n              // <PlayReadyKeyMessage type=\"LicenseAcquisition\">\n              //   <LicenseAcquisition Version=\"1\">\n              //      <Challenge encoding=\"base64encoded\">base64Challenge </Challenge>\n              //   </LicenseAcquisition>\n              // </PlayReadyKeyMessage>\n              //\n              const keyMessage = parser.parseFromString(message, 'application/xml').getElementsByTagName('PlayReadyKeyMessage')[0];\n              if (!keyMessage || keyMessage.getAttribute('type') !== 'LicenseAcquisition') {\n                  this.logger.warn(`${this.systemString} unrecognized message ignore it`);\n                  return;\n              }\n              const challengeNode = parser.parseFromString(message, 'application/xml').getElementsByTagName('Challenge')[0];\n              if (!challengeNode || challengeNode.getAttribute('encoding') !== 'base64encoded' || challengeNode.childNodes.length === 0) {\n                  this.logger.warn(`${this.systemString} wrong challenge format or empty challenge`);\n                  return;\n              }\n              const challenge = NumericEncodingUtils$1.base64Decode(challengeNode.childNodes[0].nodeValue);\n              const challengeStr = BufferUtils.utf8arrayToStr(challenge);\n              // The license challenge contains the base64 encoded Key ID, extract it.\n              const keyData = parser.parseFromString(challengeStr, 'application/xml').getElementsByTagName('KID')[0];\n              let keyIdBase64 = null;\n              if (keyData.childNodes[0]) {\n                  keyIdBase64 = keyData.childNodes[0].nodeValue;\n              }\n              else {\n                  keyIdBase64 = keyData.getAttribute('VALUE');\n              }\n              // Using KeyID extract KeyInfo and Key URI\n              // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID\n              // KID value in â€˜tencâ€™ is a big endian UUID GUID interpretation of UUID\n              const keyId = NumericEncodingUtils$1.base64Decode(keyIdBase64).subarray(0, 16);\n              keysystemutil.changeEndianness(keyId);\n              const keyInfo = this.keyIdToKeyInfo[BufferUtils.utf8arrayToStr(keyId)];\n              if (!keyInfo) {\n                  this.logger.info(`${this.systemString} no keyInfo for keyId ${JSON.stringify(keyId)}`);\n                  return;\n              }\n              keyInfo.licenseChallenge = challenge;\n              // Check demo/index.xml for more details on how exactly license is acquired. There is switch-case statement for LICENSE_CHALLENGE_CREATED\n              keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, challenge);\n          }\n      }\n      var PlayReadyKeySystem$1 = PlayReadyKeySystem;\n    \n      /**\n       * Widevine key system\n       */\n      const kWidevineKeySystemConfig = {\n          initDataTypes: ['cenc', 'keyids'],\n      };\n      const kWidevineKeySystemUUID = new Uint8Array([237, 239, 139, 169, 121, 214, 74, 206, 163, 200, 39, 220, 213, 29, 33, 237]);\n      class WidevineKeySystem extends KeySystem {\n          constructor(mediaKeys, systemString, config, eventEmitter, sessionHandler, logger) {\n              super(mediaKeys, systemString, config, eventEmitter, false, sessionHandler, logger);\n              this.shouldDestroyMediaKeys = true;\n          }\n          // destroy()\n          static get systemId() {\n              return kWidevineKeySystemUUID;\n          }\n          static get requestAccessConfig() {\n              return kWidevineKeySystemConfig;\n          }\n          get needsCert() {\n              return true;\n          }\n          removeKey(decryptdata) {\n              return super.removeSessions(decryptdata, true);\n          }\n          ensureKeyContext(decryptdata) {\n              const keyuri = decryptdata.uri;\n              const keyInfo = this.keyUriToKeyInfo[keyuri];\n              // Create a new session for current key request and preserve previous sessions for\n              // cleanup later\n              if (keyInfo === null || keyInfo === void 0 ? void 0 : keyInfo.session) {\n                  keyInfo.oldSessions.push(keyInfo.session);\n                  keyInfo.session = null;\n              }\n              return super.ensureKeyContext(decryptdata);\n          }\n          getKeyRequestResponse(keyInfo, licenseChallenge) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const getKeyResponse = keyInfo.setKeyRequestState(KeyRequestState.GET_KEY_RESPONSE);\n              this.eventEmitter.trigger(HlsEvent$1.LICENSE_CHALLENGE_CREATED, {\n                  keyuri: keyuri,\n                  licenseChallenge: licenseChallenge,\n                  keysystem: this.systemString,\n                  keyId: keyInfo.decryptdata.keyId,\n              });\n              return getKeyResponse;\n          }\n          handleParsedKeyResponse(keyInfo, keyResponse) {\n              // clear the license challenge\n              keyInfo.licenseChallenge = undefined;\n              const keyuri = keyInfo.decryptdata.uri;\n              const statusCode = keyResponse.statusCode;\n              if (statusCode !== 0) {\n                  return throwError(new KeyRequestError('License server responded with error', keyuri, statusCode, { code: statusCode, text: 'Server error' }, false, KeyRequestErrorReason.LicenseServerError));\n              }\n              if (!keyResponse.license || !keyResponse.license.byteLength) {\n                  const err = new KeyRequestError('License server responded with invalid license', keyuri, statusCode, { code: statusCode, text: 'Invalid license' }, false, KeyRequestErrorReason.LicenseServerError);\n                  return throwError(err);\n              }\n              if (keyResponse.renewalDate) {\n                  const renewalDate = keyResponse.renewalDate;\n                  const now = new Date();\n                  const renewalMs = renewalDate > now ? renewalDate.getTime() - now.getTime() : 0;\n                  if (renewalMs > 0) {\n                      this._scheduleRenewal(keyInfo, renewalMs);\n                  }\n              }\n              const processLicense = keyInfo.setKeyRequestState(KeyRequestState.PROCESS_LICENSE);\n              const updateSession = from(keyInfo.session.update(keyResponse.license)).pipe(tap(() => {\n                  const keyId = keyInfo.decryptdata.keyId;\n                  const state = keyInfo.session.keyStatuses.get(keyId);\n                  this.handleKeyStatusForKey(state, keyInfo);\n              }), catchError((reason) => {\n                  this.logger.error(`${this.systemString} FAIL: Failed to update with key response code=${reason.code} message=${reason.message}`);\n                  const err = new KeySystemError(reason.message, keyInfo.decryptdata.uri, reason.code, { code: reason.code, text: 'Failed to update with key response' }, this.systemString);\n                  throw err;\n              }));\n              return forkJoin([processLicense, updateSession]).pipe(mapTo(undefined));\n          }\n          /*\n            The pssh has to be generated from the manifest:\n            1. Extract the keyID from the EXT-X-KEY tag (for example URI =â€œdata:;base64,DZ/7Ld9qTnyTi92l+VPlBg==â€œ)\n            2. Generate the initdata using generateInitData\n        \n            generate Widevine pssh\n            0:3      :    size of the 'pssh' box\n            4:7      :    'pssh'\n            8:11     :    not set (all zeros)\n            12:27    :   Widevine Key System (edef8ba9-79d6-4ace-a3c8-27dcd51d21ed)\n            28:31    :   Widevine pssh data size (size of what follows)\n            32:51    :   Protobuf-encoded Widevine pssh data\n            32 & 33  :   (id = 0, wireType = int, value = 1)    means this is using AES-CTR\n            34 & 35  :   (id = 1, wireType = bytes, length = 16)  size of the keyId\n            36:51    :   KeyId bytes\n          */\n          generateInitData(keyId, decryptdata /* , requestInfo*/) {\n              return { initData: decryptdata.pssh, initDataType: 'cenc' };\n          }\n          /**\n           * Generate a key renewal request\n           * @param keyInfo Info about the key we're requesting\n           * @returns {Observable<Uint8Array>} Promise returning the license challenge\n           **/\n          generateRequestInitialized(keyInfo) {\n              const keyuri = keyInfo.decryptdata.uri;\n              const challenge = keyInfo.licenseChallenge;\n              //this.logger.info(`[Keys] challenge create start uri=${this.hls.redactUrl(keyuri)} versions=${JSON.stringify(keyInfo.decryptdata.formatversions)}`);\n              this.logger.debug(`[Keys] challenge create start uri=${redactUrl(keyuri)} versions=${JSON.stringify(keyInfo.decryptdata.formatversions)}`);\n              keyInfo.requestInfo = undefined; // Don't need requestInfo anymore.\n              keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, challenge);\n              return VOID;\n          }\n          // message\n          handleKeyMessage(event) {\n              if (this.isDestroying) {\n                  this.logger.warn('In the middle of destroying, ignore key message');\n                  return;\n              }\n              this.logger.info(`[Keys] ${this.systemString} message : ${event.messageType}`);\n              // Extract KeyUri and KeyInfo from the sessions info strored.\n              const session = event.target;\n              let keyuri = null;\n              let keyInfo = null;\n              if (session.sessionId in this.sessionIdToKeyUri) {\n                  keyuri = this.sessionIdToKeyUri[session.sessionId];\n                  keyInfo = this.keyUriToKeyInfo[keyuri];\n              }\n              else {\n                  for (const [uri, info] of Object.entries(this.keyUriToKeyInfo)) {\n                      if (info.session === session) {\n                          keyuri = uri;\n                          keyInfo = info;\n                          break;\n                      }\n                  }\n              }\n              if (!keyInfo) {\n                  this.logger.warn(`${this.systemString} empty keyuri and keyInfo`);\n                  return;\n              }\n              const cmd = event.messageType;\n              switch (cmd) {\n                  case 'license-request': {\n                      // For widevine just base64 encode the challenge returned by the browser.\n                      const challenge = new Uint8Array(event.message);\n                      // Check demo/index.xml for more details on how exactly license is acquired. There is switch-case statement for LICENSE_CHALLENGE_CREATED\n                      keyInfo.resolveState(KeyRequestState.GET_CHALLENGE, challenge);\n                      break;\n                  }\n              }\n          }\n      }\n      var WidevineKeySystem$1 = WidevineKeySystem;\n    \n      /*\n       * Factory for making a key system\n       *\n       * \n       */\n      const kKeySystemIdToPropertiesMap$1 = {\n          clearkey: ClearKeySystemProperties,\n          fairplaystreaming: FairPlayStreamingKeySystemProperties,\n          playready: PlayReadyKeySystemProperties,\n          widevine: WidevineKeySystemProperties,\n      };\n      const kKeySystemIdToConstructorsMap = {\n          clearkey: [['org.w3.clearkey', ClearKeySystem$1]],\n          fairplaystreaming: [\n              ['com.apple.fps.3_0', FPSKeySystemV3],\n              ['com.apple.fps', FPSKeySystem],\n          ],\n          playready: [['com.microsoft.playready.recommendation', PlayReadyKeySystem$1]],\n          widevine: [['com.widevine.alpha', WidevineKeySystem$1]],\n      };\n      const DEFAULT_KEY_SYSTEM = ClearKeySystemProperties.id;\n      /**\n       * Generate a KeySystem object given a KeySystemProperties\n       */\n      class KeySystemFactory$1 {\n          createMediaKeys(keysystemId, videoCodecs, audioCodecs, logger, keySystemConfig) {\n              let res = KeySystemFactory$1.idToMediaKeysInfoMap[keysystemId];\n              if (!res) {\n                  logger.info(`[Keys] ${keysystemId} requesting key system access`);\n                  const mediaCapabilities = keysystemutil.getCapabilities(videoCodecs, audioCodecs);\n                  const mediaKeys$ = new AsyncSubject();\n                  KeySystemFactory$1.requestKeySystemAccess(keysystemId, mediaCapabilities, keySystemConfig, logger)\n                      .pipe(switchMap(function (keySystemAccess) {\n                      KeySystemFactory$1.idToMediaKeysInfoMap[keysystemId].keySystemAccess = keySystemAccess;\n                      // TODO: probably should use keySystemAccess.getConfiguration() to get supported types.\n                      logger.info(`[Keys] ${keysystemId} creating CDM`);\n                      return from(keySystemAccess.createMediaKeys());\n                  }), tap((mediaKeys) => {\n                      logger.info(`[Keys] ${keysystemId} created CDM`);\n                      mediaKeys$.next(mediaKeys);\n                      mediaKeys$.complete();\n                  }), catchError((err) => {\n                      logger.info(`[Keys] FAIL: could not initialize ${keysystemId} key system: ${err.message}`);\n                      mediaKeys$.error(new KeySystemError(`could not initialize key system: ${err.message}`, undefined, 0, ErrorResponses.KeySystemFailedToInitialize, keysystemId));\n                      return EMPTY;\n                  }), takeUntil(KeySystemFactory$1.destroy$) // Keep alive until destroyMediaKeys\n                  )\n                      .subscribe();\n                  res = KeySystemFactory$1.idToMediaKeysInfoMap[keysystemId] = { mediaKeys$, keySystemAccess: null };\n              }\n              return res.mediaKeys$;\n          }\n          destroyMediaKeys() {\n              // Remove keysystemstring => requestKeySystemAccess promise\n              KeySystemFactory$1.destroy$.next();\n              KeySystemFactory$1.idToMediaKeysInfoMap = {};\n          }\n          static getKeySystemIdForDecryptData(decryptdata) {\n              let selectedId;\n              if (decryptdata) {\n                  selectedId = DEFAULT_KEY_SYSTEM;\n                  const formatString = decryptdata.format;\n                  for (const id of KeySystemIdValues) {\n                      const p = kKeySystemIdToPropertiesMap$1[id];\n                      if ((p === null || p === void 0 ? void 0 : p.keyFormatString) === formatString) {\n                          selectedId = id;\n                          break;\n                      }\n                  }\n              }\n              if (!selectedId) {\n                  throw Error('No matching key system');\n              }\n              return selectedId;\n          }\n          // Pick the first key system that works for this id\n          static requestKeySystemAccess(keysystemId, mediaCapabilities, keySystemConfig, logger) {\n              if (typeof navigator === 'undefined' || typeof navigator.requestMediaKeySystemAccess === 'undefined') {\n                  return throwError(new KeySystemError('navigator undefined', undefined, 0, ErrorResponses.KeySystemUndefinedNavigator, keysystemId));\n              }\n              const keySystemConstructors = kKeySystemIdToConstructorsMap[keysystemId];\n              let obs = throwError(new KeySystemError('no key systems to try', undefined, 0, ErrorResponses.KeySystemNoKeySystemsToTry, keysystemId));\n              for (const pair of keySystemConstructors) {\n                  const keySystemString = pair[0];\n                  const KeySystemConstructor = pair[1];\n                  const accesConfig = isMediaKeySystemConfig(keySystemConfig) ? keySystemConfig : KeySystemConstructor.requestAccessConfig;\n                  const options = [Object.assign({}, accesConfig, mediaCapabilities)];\n                  obs = obs.pipe(catchError(() => {\n                      return KeySystemFactory$1.requestKeySystemInternal(keySystemString, options, logger);\n                  }));\n              }\n              return obs;\n          }\n          /**\n           * @param keySystemString keySystemString passed to requestMediaKeySystemAccess. e.g. 'com.apple.fps'\n           * @param options MediaKeySystemConfiguration passed to requestMediaKeySystemAccess\n           */\n          static requestKeySystemInternal(keySystemString, options, logger) {\n              logger.info(`[Keys] requestKeySystemAccess ${keySystemString} ${JSON.stringify(options)}`);\n              return defer(() => from(navigator.requestMediaKeySystemAccess(keySystemString, options)));\n          }\n          /**\n           * Create KeySystem object\n           *\n           * @param keysystemId Identifier for key system used by HLS.js. e.g. 'fairplaystreaming' 'widevine'\n           * @param hls Hls object\n           * @param mediaKeys MediaKeys for KeySystem to manage\n           * @param keyLoader The loader object\n           */\n          make(keysystemId, mediaKeys, config, eventEmitter, sessionHandler, logger) {\n              var _a;\n              const keySystemAccess = (_a = KeySystemFactory$1.idToMediaKeysInfoMap[keysystemId]) === null || _a === void 0 ? void 0 : _a.keySystemAccess;\n              if (!keySystemAccess) {\n                  throw new KeySystemError(`No keySystemAccess for ${keysystemId}`, undefined, 0, ErrorResponses.KeySystemNoKeySystemAccess, keysystemId);\n              }\n              let KeySystemConstructor;\n              // NOTE: this system string is used in the LICENSE_CHALLENGE_CREATED event for playready and widevine\n              // as the \"keysystem\" parameter. Change with caution.\n              const systemString = kKeySystemIdToPropertiesMap$1[keysystemId].systemStringPrefix;\n              // Find the matching constructor for the key system string\n              for (const pair of kKeySystemIdToConstructorsMap[keysystemId]) {\n                  if (pair[0] === keySystemAccess.keySystem) {\n                      KeySystemConstructor = pair[1];\n                      break;\n                  }\n              }\n              if (!KeySystemConstructor) {\n                  throw new KeySystemError(`No constructor associated with ${keysystemId}`, undefined, 0, ErrorResponses.KeySystemNoConstructor, systemString);\n              }\n              const keySystem = new KeySystemConstructor(mediaKeys, systemString, config, eventEmitter, sessionHandler, logger);\n              return keySystem;\n          }\n          static get availableKeySystems() {\n              return Object.keys(kKeySystemIdToPropertiesMap$1);\n          }\n          /**\n           * Get the EXT-X-KEY:FORMAT value associated with the key system\n           * @param keySystemId Identifier string to request keyFormatString property for\n           */\n          static getKeySystemFormat(keySystemId) {\n              const properties = kKeySystemIdToPropertiesMap$1[keySystemId];\n              return properties ? properties.keyFormatString : '';\n          }\n          static getKeySystemSecurityLevel(keySystemId) {\n              const properties = kKeySystemIdToPropertiesMap$1[keySystemId];\n              return properties ? properties.securityLevels : undefined;\n          }\n      }\n      KeySystemFactory$1.idToMediaKeysInfoMap = {};\n      KeySystemFactory$1.destroy$ = new Subject();\n    \n      // Lets set the max slots as couple of slots less than the normally allowed max slot of 8\n      const MAX_ALLOWED_KEY_SLOTS = 6;\n      const kMediaKeySystemConfigCodecs = {\n          video: ['avc1.42E01E'],\n          audio: ['mp4a.40.2'],\n      };\n      function convertError(keyUri, error, mediaOptionIds) {\n          // Convert error if needed\n          if (!error) {\n              error = new KeyRequestError('Unknown error from CDM', keyUri, 0, ErrorResponses.KeySystemCDMUnknownError, false, KeyRequestErrorReason.InternalError);\n          }\n          else if (error instanceof TimeoutError) {\n              error = new KeyRequestTimeoutError('Key request timed out', keyUri, ErrorResponses.KeySystemRequestTimedOut);\n          }\n          else if (error instanceof KeySystemError) {\n              const response = (error === null || error === void 0 ? void 0 : error.response) || ErrorResponses.InternalError;\n              error = new KeyRequestError(error.message, keyUri, 0, response, false, KeyRequestErrorReason.InternalError, true);\n          }\n          if (error instanceof KeyRequestError || error instanceof KeyRequestTimeoutError) {\n              error.mediaOptionIds = [...mediaOptionIds];\n          }\n          return error;\n      }\n      class KeySystemAdapter {\n          constructor(ksService, mediaSink, config, platformQuery, eventEmitter, sessionHandler, logger, keySystemFactory = new KeySystemFactory$1() // For testing\n          ) {\n              this.ksService = ksService;\n              this.mediaSink = mediaSink;\n              this.config = config;\n              this.platformQuery = platformQuery;\n              this.eventEmitter = eventEmitter;\n              this.sessionHandler = sessionHandler;\n              this.keySystemFactory = keySystemFactory;\n              this.reset$ = new Subject();\n              this.keyRequest$ = new Subject();\n              this.abort$ = new Subject(); // Abort(keyuri)\n              this.keySystem$ = new BehaviorSubject(null);\n              this._keyStatusChange$ = new Subject();\n              this.protectionData = {};\n              this.keySystemId = null; // Identifier for keySystem\n              this.keyUriToRequest = {}; // keyUri => request observable\n              this.ksQuery = ksService.getQuery();\n              this.logger = logger.child({ name: 'eme' });\n              if (this.config.warmupCdms) {\n                  this.keySystemFactory.createMediaKeys(FairPlayStreamingKeySystemProperties.id, kMediaKeySystemConfigCodecs.video, kMediaKeySystemConfigCodecs.audio, this.logger, undefined).subscribe();\n              }\n              const platformInfoChange$ = platformQuery.platformInfo$.pipe(distinctUntilChanged((a, b) => a && b && a.requiresCDMAttachOnStart === b.requiresCDMAttachOnStart), switchMap((platformInfo) => {\n                  if (platformInfo === null || platformInfo === void 0 ? void 0 : platformInfo.requiresCDMAttachOnStart) {\n                      return this.attachMediaKeys().pipe(catchError((err) => {\n                          this.logger.info(`onMediaAttach err:${err.message}`);\n                          this.handleKeySystemError(err);\n                          return EMPTY;\n                      }));\n                  }\n                  else {\n                      return VOID;\n                  }\n              }), switchMapTo(EMPTY));\n              // This is where the key requests actually get subscribed\n              const keyRequests$ = this.keyRequest$.pipe(mergeMap((request) => {\n                  return request.pipe(catchError(() => {\n                      // In band error gets bubbled up to caller\n                      return EMPTY;\n                  }));\n              }));\n              const keyStatusChange$ = this.keySystem$.pipe(switchMap((ks) => {\n                  if (!ks) {\n                      return EMPTY;\n                  }\n                  return ks.keyStatusChange$.pipe(tap((event) => {\n                      var _a;\n                      const keyUri = event.decryptdata.uri;\n                      this.logger.info(`key status change uri=${redactUrl(keyUri)} status=${event.status}`);\n                      const entity = this.ksQuery.getKeyInfo(keyUri);\n                      if (event.status === 'needs-renewal') {\n                          this.ksService.updateKeyRequestState(keyUri, KeyRequestMacroState.MustRequestResponse, (state) => state === KeyRequestMacroState.GotKeyResponse);\n                      }\n                      else {\n                          const error = convertError(keyUri, event.error, (_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionIds) !== null && _a !== void 0 ? _a : []);\n                          this.ksService.setError(keyUri, error);\n                      }\n                      this._keyStatusChange$.next(event);\n                  }));\n              }));\n              const bufferedKeyHandling$ = this.isKeyCleanupSupported()\n                  ? this.mediaSink.mediaQuery.bufferedSegmentsTuple$.pipe(mergeMap((bufferedSegments) => {\n                      const [videoSegments, audioSegments] = bufferedSegments;\n                      const bufferedKeyUris = new Set();\n                      videoSegments.forEach((bufferedSegment) => {\n                          var _a, _b;\n                          const uri = (_b = (_a = bufferedSegment.frag) === null || _a === void 0 ? void 0 : _a.keyTagInfo) === null || _b === void 0 ? void 0 : _b.uri;\n                          if (uri) {\n                              bufferedKeyUris.add(uri);\n                          }\n                      });\n                      audioSegments.forEach((bufferedSegment) => {\n                          var _a, _b;\n                          const uri = (_b = (_a = bufferedSegment.frag) === null || _a === void 0 ? void 0 : _a.keyTagInfo) === null || _b === void 0 ? void 0 : _b.uri;\n                          if (uri) {\n                              bufferedKeyUris.add(uri);\n                          }\n                      });\n                      return this.handleKeyCleanup(bufferedKeyUris);\n                  }))\n                  : VOID;\n              merge(platformInfoChange$, keyRequests$, keyStatusChange$, bufferedKeyHandling$).pipe(takeUntil(this.reset$)).subscribe();\n          }\n          get keyStatusChange$() {\n              return this._keyStatusChange$;\n          }\n          get keySystem() {\n              return this.keySystem$.value;\n          }\n          destroy() {\n              this.reset$.next(); // Stop all requests & stop listening to events\n              this.ksService.removeAll(); // Clear state\n              this.keySystemId = null;\n              const keySystem = this.keySystem;\n              let ksDestroyed$ = VOID;\n              if (keySystem) {\n                  this.keySystem$.next(null);\n                  if (keySystem.shouldDestroyMediaKeys) {\n                      this.keySystemFactory.destroyMediaKeys();\n                  }\n                  ksDestroyed$ = keySystem.destroy();\n              }\n              return combineLatest([ksDestroyed$, this.mediaSink.clearMediaKeys()]).pipe(mapTo(undefined));\n          }\n          attachMediaKeys() {\n              if (this.keySystem) {\n                  // we already wait inside makeKeySystem. nothing to do. Could happen if\n                  // detach happened after keysystem was created (recoverMediaError?)\n                  return VOID;\n              }\n              else {\n                  // Create and attach key system.\n                  // Use 'NONE' so we don't get assigned a keyId for no reason\n                  const keyFormatString = this.config.keySystemPreference ? KeySystemFactory$1.getKeySystemFormat(this.config.keySystemPreference) : FairPlayStreamingKeySystemProperties.keyFormatString;\n                  return this.makeKeySystem(new DecryptData('NONE', null, null, keyFormatString, [1])).pipe(mapTo(void 0));\n              }\n          }\n          isKeyCleanupSupported() {\n              // At this point of time we have two configurations for fairplay. One with single key session and one with multiple key sessions.\n              // In case of single key session, we cannot remove the session or key. The cleanup is supported only when multiple key sessions are supported\n              // Till the app enables that configuration, we should not call cleanup\n              // By default PlayReady and Widevine use multiple key sessions. But app doesn't pass useMultipleKeySessions in this case. So check for the preference and enable it based on that.\n              return this.config.useMultipleKeySessions === true || this.config.keySystemPreference === 'widevine' || this.config.keySystemPreference === 'playready';\n          }\n          handleKeyCleanup(bufferedKeyUris) {\n              if (this.ksQuery.getCount() < MAX_ALLOWED_KEY_SLOTS) {\n                  return VOID;\n              }\n              const currentTime = performance.now();\n              const keyEntities = this.ksQuery.getAll();\n              const removes$ = keyEntities.map((ksEntity) => {\n                  const keyUri = ksEntity.keyUri;\n                  if (!bufferedKeyUris.has(keyUri)) {\n                      const keyTagInfo = entityToKeyTagInfo(ksEntity.decryptdata);\n                      // We don't need to key cleanup for AES-128 and also check if the key has met the minimum holdtime\n                      if (keyTagInfo.method !== 'AES-128' && currentTime > ksEntity.minHoldTime) {\n                          // Remove the entry from store, so that it's no longer tracked\n                          return this._removeKey(keyUri, keyTagInfo);\n                      }\n                  }\n                  return VOID;\n              });\n              return removes$.length ? forkJoin(removes$).pipe(switchMapTo(VOID)) : VOID;\n          }\n          _removeKey(keyUri, keyTagInfo) {\n              this.abort$.next(keyUri);\n              this.ksService.removeKey(keyUri);\n              return this.keySystem.removeKey(keyTagInfo);\n          }\n          removeKeysForItems(ids) {\n              const removes$ = [];\n              applyTransaction(() => {\n                  for (const itemId of ids) {\n                      this.ksService.removeAllKeysForItem(itemId);\n                      const keyInfos = this.ksQuery.getAll({\n                          filterBy: (entity) => entity.itemIds.length === 0,\n                      });\n                      for (const keyInfo of keyInfos) {\n                          removes$.push(this._removeKey(keyInfo.keyUri, entityToKeyTagInfo(keyInfo.decryptdata)));\n                      }\n                  }\n              });\n              return removes$.length ? forkJoin(removes$).pipe(switchMap(() => VOID)) : VOID;\n          }\n          get availableKeySystems() {\n              return KeySystemFactory$1.availableKeySystems;\n          }\n          initialize(config) {\n              var _a;\n              const oldProtectionData = this.protectionData;\n              this.protectionData = {};\n              const preference = this.config.keySystemPreference;\n              for (const keySystemId of KeySystemFactory$1.availableKeySystems) {\n                  const keysystemConfig = config[keySystemId];\n                  if (!keysystemConfig) {\n                      continue;\n                  }\n                  if (preference !== keySystemId) {\n                      this.logger.warn(`Key system ${keySystemId} does not match preference ${preference}, ignoring`);\n                      continue;\n                  }\n                  this.logger.info(`Setting protectionData for ${keySystemId}`);\n                  const cert = keysystemConfig.certificate;\n                  const serverCertUrl = keysystemConfig.serverCertUrl ? URLToolkit$1.buildAbsoluteURL(window.location.href, keysystemConfig.serverCertUrl) : undefined;\n                  this.protectionData[keySystemId] = {\n                      serverCertUrl: serverCertUrl,\n                      certificate: cert,\n                  };\n                  let loadCert$;\n                  if (cert) {\n                      this.logger.info('Got cert');\n                      loadCert$ = of({ keysystem: keySystemId, certificate: cert });\n                  }\n                  else if (serverCertUrl && ((_a = oldProtectionData === null || oldProtectionData === void 0 ? void 0 : oldProtectionData[keySystemId]) === null || _a === void 0 ? void 0 : _a.serverCertUrl) !== serverCertUrl) {\n                      this.logger.info(`Loading cert ${redactUrl(serverCertUrl)} `);\n                      let loaderConfig;\n                      if (isCustomUrl(serverCertUrl)) {\n                          loaderConfig = this.config.certLoadPolicy.customURL;\n                      }\n                      else {\n                          loaderConfig = this.config.certLoadPolicy.default;\n                      }\n                      loadCert$ = fromUrlArrayBuffer({ url: serverCertUrl, xhrSetup: this.config.xhrSetup }, loaderConfig).pipe(map(([loadArrayBufferResult, _]) => {\n                          return { keysystem: keySystemId, certificate: new Uint8Array(loadArrayBufferResult) };\n                      }));\n                  }\n                  if (loadCert$) {\n                      loadCert$\n                          .pipe(switchMap((data) => this.onServerCertificateLoaded(data)), catchError((err) => {\n                          this.logger.error(`Error loading cert: ${err.message}`);\n                          this.eventEmitter.trigger(HlsEvent$1.INTERNAL_ERROR, {\n                              type: ErrorTypes.NETWORK_ERROR,\n                              details: ErrorDetails.CERT_LOAD_ERROR,\n                              fatal: false,\n                              handled: true,\n                              reason: 'Error handling cert',\n                              response: ErrorResponses.KeySystemCertificateLoadError,\n                              message: err.message,\n                              name: 'certificateLoadError',\n                          });\n                          // TODO: Save the error and reject any key requests relying on this.\n                          throw err;\n                      }), takeUntil(this.reset$))\n                          .subscribe();\n                  }\n              }\n          }\n          /**\n           * Generate challenge using request info\n           */\n          generateRequest(keyuri, requestInfo) {\n              if (this.keySystem) {\n                  this.keySystem.setKeyRequestInfo(keyuri, requestInfo);\n              }\n          }\n          /**\n           * Set the challenge response\n           */\n          setLicenseResponse(keyuri, response) {\n              if (this.keySystem) {\n                  this.keySystem.setParsedResponse(keyuri, response);\n              }\n          }\n          /**\n           * Called from externally to retrieve key.\n           * @param decryptdata   Info about the key to retrieve\n           * @param mediaOptionId Id of level associated with this key request. Used for error handling\n           * @returns Observable of type DecryptData. Will signal on success, or throw an Error\n           **/\n          getKeyFromDecryptData(decryptdata, mediaOptionKey) {\n              if (!decryptdata || !decryptdata.isEncrypted) {\n                  return of(decryptdata); // Return immediately\n              }\n              let obs;\n              applyTransaction(() => {\n                  obs = this._getKeyFromDecryptData(decryptdata, mediaOptionKey);\n              });\n              return obs;\n          }\n          _getKeyFromDecryptData(decryptdata, mediaOptionKey) {\n              let itemId = null;\n              let mediaOptionId = null;\n              if (mediaOptionKey) {\n                  itemId = mediaOptionKey.itemId;\n                  mediaOptionId = mediaOptionKey.mediaOptionId;\n              }\n              const keyUri = decryptdata.uri;\n              const keyEntity = this.ksQuery.getKeyInfo(keyUri);\n              if (keyEntity && mediaOptionKey != null) {\n                  this.ksService.addMediaOption(keyUri, mediaOptionKey);\n              }\n              const permanentError = (keyEntity === null || keyEntity === void 0 ? void 0 : keyEntity.error) instanceof KeyRequestError && keyEntity.error.isOkToRetry === false;\n              if (permanentError) {\n                  return throwError(keyEntity.error);\n              }\n              else if (!keyEntity || keyEntity.requestState === KeyRequestMacroState.MustRequestResponse) {\n                  this.logger.info(`getKeyFromDecryptData mediaOptionId=${mediaOptionId} method=${decryptdata.method} keyuri=${redactUrl(keyUri)} state=${keyEntity === null || keyEntity === void 0 ? void 0 : keyEntity.requestState}`);\n                  // specify minimum duration a key may exist in the system before itâ€™s eligible for eviction\n                  const minHoldTime = performance.now() + this.config.keyMinHoldTimeBeforeCleanup;\n                  // Abort any old requests\n                  this.abort$.next(keyUri);\n                  this.ksService.upsertKey({\n                      keyUri,\n                      decryptdata: keyTagInfoToEntity(decryptdata),\n                      minHoldTime,\n                      mediaOptionIds: [mediaOptionId],\n                      requestState: KeyRequestMacroState.WaitingForKeyResponse,\n                      itemIds: [itemId],\n                  });\n                  // Now start fetching key\n                  let request;\n                  const method = decryptdata.method;\n                  switch (method) {\n                      case 'SAMPLE-AES':\n                      case 'ISO-23001-7':\n                      case 'SAMPLE-AES-CTR': {\n                          const loadPolicy = this.config.keyLoadPolicy.customURL;\n                          request = this.fetchKeyEME(decryptdata).pipe(timeout(loadPolicy.maxLoadTimeMs));\n                          break;\n                      }\n                      case 'AES-128':\n                          request = this.fetchKeyHTTP(decryptdata.uri, decryptdata, this.config.keyLoadPolicy);\n                          break;\n                      default:\n                          const err = new ExceptionError(false, `Unexpected METHOD attribute ${method}`, ErrorResponses.KeySystemUnexpectedMETHOD);\n                          return throwError(err);\n                  }\n                  // TODO: stats\n                  const request$ = (this.keyUriToRequest[keyUri] = request.pipe(map((keyLoadedData) => {\n                      const decryptdata = keyLoadedData.decryptdata;\n                      this.ksService.updateKeyValue(keyUri, decryptdata.key);\n                      this.eventEmitter.trigger(HlsEvent$1.KEY_LOADED, keyLoadedData);\n                      return keyLoadedData.decryptdata;\n                  }), catchError((err) => {\n                      var _a;\n                      const keyEntity = this.ksQuery.getKeyInfo(keyUri);\n                      err = convertError(keyUri, err, (_a = keyEntity === null || keyEntity === void 0 ? void 0 : keyEntity.mediaOptionIds) !== null && _a !== void 0 ? _a : []);\n                      this.ksService.setError(keyUri, err);\n                      return throwError(err);\n                  }), finalize$1(() => {\n                      // Update state for abort() only if we were in progress\n                      this.ksService.updateKeyRequestState(keyUri, KeyRequestMacroState.MustRequestResponse, (state) => state === KeyRequestMacroState.WaitingForKeyResponse);\n                      this.keyUriToRequest[keyUri] = null;\n                      this.logger.debug(`${printKeyTag(decryptdata)} finalize state=${this.ksQuery.getKeyInfo(keyUri).requestState}`);\n                  }), share(), takeUntil(race(this.abort$.pipe(filter((uri) => uri === keyUri)), this.reset$).pipe(tap((uri) => this.logger.warn(uri ? `aborted ${redactUrl(uri)}` : 'got reset'))))));\n                  this.keyRequest$.next(request$); // Subscribes to key request\n                  return request$;\n              }\n              else if (keyEntity.requestState === KeyRequestMacroState.GotKeyResponse) {\n                  return of(entityToKeyTagInfo(keyEntity.decryptdata));\n              }\n              // requestState === KeyRequestMacroState.WaitingForKeyResponse\n              return this.keyUriToRequest[keyUri];\n          }\n          fetchKeyEME(decryptdata) {\n              return this.requestKey(decryptdata).pipe(map((decryptdata) => {\n                  const now = performance.now();\n                  const data = {\n                      timestamp: now,\n                      keyuri: decryptdata.uri,\n                      decryptdata,\n                      /*stats: {\n                        trequest: keyInfo.stats.trequest,\n                        tfirst: keyInfo.stats.tfirst,\n                        tload: now\n                      }*/\n                  };\n                  return data;\n              }));\n          }\n          /**\n           * Make generic HTTP request for key\n           * @param uri         The URL to make request to\n           * @param decryptdata Associated DecryptData object\n           * @param loadTimeoutMs\n           */\n          fetchKeyHTTP(uri, decryptdata, loadPolicy) {\n              return KeySystemAdapter.fetchKeyHTTP(uri, this.config, decryptdata, loadPolicy);\n          }\n          static fetchKeyHTTP(uri, config, decryptdata, loadPolicy) {\n              const loadable = {\n                  url: uri,\n                  xhrSetup: config.xhrSetup,\n              };\n              return fromUrlArrayBuffer(loadable, getLoadConfig(loadable, loadPolicy)).pipe(map(([loadArrayBufferResult, _]) => {\n                  decryptdata.key = new Uint8Array(loadArrayBufferResult);\n                  const loadedData = {\n                      decryptdata,\n                      keyuri: uri,\n                      timestamp: performance.now(),\n                      /*stats: {\n                        trequest: keyInfo.stats.trequest,\n                        tfirst: keyInfo.stats.tfirst,\n                        tload: now\n                      }*/\n                  };\n                  return loadedData;\n              }));\n          }\n          requestKey(decryptdata) {\n              // Assumed called from key loader and that it already checked the method and that it's encrypted, etc.\n              this.logger.debug(`requestKey - uri=${redactUrl(decryptdata.uri)}`);\n              return this.makeKeySystem(decryptdata).pipe(switchMap((keySystem) => {\n                  return keySystem.startKeyRequest(decryptdata);\n              }));\n          }\n          ensureKeySystem(mediaKeys) {\n              return defer(() => {\n                  if (!this.keySystem && this.keySystemId) {\n                      this.keySystem$.next(this.keySystemFactory.make(this.keySystemId, mediaKeys, this.config, this.eventEmitter, this.sessionHandler, this.logger));\n                      const protData = this.protectionData && this.protectionData[this.keySystemId];\n                      if (protData) {\n                          return this.keySystem.setServerCertificate(protData.certificate).pipe(mapTo(this.keySystem));\n                      }\n                  }\n                  return of(this.keySystem);\n              });\n          }\n          /**\n           * Make MediaKeys object for decryptdata and attach to current media element\n           * Also creates a KeySystem object\n           * @param decryptdata The KeyTagInfo object\n           */\n          makeKeySystem(decryptdata) {\n              this.logger.debug(`makeKeySystem - uri=${redactUrl(decryptdata.uri)}`);\n              return this.ensureMediaKeys(decryptdata).pipe(switchMap((mediaKeys) => {\n                  this.logger.debug(`setMediaKeys - uri=${redactUrl(decryptdata.uri)}`);\n                  return this.mediaSink.setMediaKeys(mediaKeys).pipe(switchMap(() => {\n                      this.logger.debug(`ensureKeySystem - uri=${redactUrl(decryptdata.uri)}`);\n                      // Create KeySystem object\n                      return this.ensureKeySystem(mediaKeys);\n                  }));\n              }));\n          }\n          // Create MediaKeys object.\n          ensureMediaKeys(decryptdata) {\n              var _a;\n              const newKeySystemId = KeySystemFactory$1.getKeySystemIdForDecryptData(decryptdata);\n              if (this.keySystemId == null) {\n                  this.keySystemId = newKeySystemId;\n              }\n              else if (this.keySystemId !== newKeySystemId) {\n                  const err = new KeyRequestError(`New key system string does not match existing ${newKeySystemId} !== ${this.keySystemId}`, decryptdata.uri, 0, ErrorResponses.KeySystemUnmatchedString, false, KeyRequestErrorReason.InternalError);\n                  return throwError(err);\n              }\n              // CreateMediaKeys will return the same promise for a given key system ID if it's already being created.\n              return this.keySystemFactory.createMediaKeys(this.keySystemId, kMediaKeySystemConfigCodecs.video, kMediaKeySystemConfigCodecs.audio, this.logger, (_a = this.platformQuery.platformInfo) === null || _a === void 0 ? void 0 : _a.keySystemConfig);\n          }\n          /**\n           *\n           * @param data { keysystem: keysystem identifier, certificate: the buffer containing the cert }\n           */\n          onServerCertificateLoaded(data) {\n              const keySystemId = data.keysystem, certificate = data.certificate;\n              this.logger.info(`KeySystemAdapter: ${keySystemId} cert loaded ${certificate ? 'nonnull' : 'null'}`);\n              const protData = this.protectionData[keySystemId];\n              protData.certificate = certificate;\n              this.logger.debug(`current keySystemId: ${this.keySystemId}`);\n              if (this.keySystem && this.keySystemId === keySystemId) {\n                  return this.keySystem.setServerCertificate(certificate).pipe(mapTo(undefined));\n              }\n              return VOID;\n          }\n          // Trigger error due to key system setup issue\n          handleKeySystemError(error) {\n              const keyError = new KeySystemError(error.message, undefined, undefined, ErrorResponses.KeySystemSetupError, undefined);\n              this.eventEmitter.trigger(HlsEvent$1.INTERNAL_ERROR, keyError);\n          }\n      }\n    \n      class KeySystemQuery extends QueryEntity {\n          constructor(store) {\n              super(store);\n          }\n          /**\n           * @returns the key info for a particular key\n           */\n          getKeyInfo(keyuri) {\n              const entity = this.getEntity(keyuri);\n              if (entity) {\n                  // Populate with proper mediaOptionIds every time\n                  return Object.assign(Object.assign({}, entity), { error: copyKeyError(entity.error, entity.mediaOptionIds) });\n              }\n              return null;\n          }\n          getKeyInfo$(keyuri) {\n              return this.selectEntity(keyuri).pipe(map((entity) => {\n                  if (entity) {\n                      // Populate with proper mediaOptionIds every time\n                      return Object.assign(Object.assign({}, entity), { error: copyKeyError(entity.error, entity.mediaOptionIds) });\n                  }\n                  else {\n                      return null;\n                  }\n              }));\n          }\n          getKeyRequestState$(keyuri) {\n              return this.selectEntity(keyuri, (entity) => entity === null || entity === void 0 ? void 0 : entity.requestState);\n          }\n          /**\n           * @returns an observable that emits whenever the key status changes\n           */\n          getKeyStatus$(keyuri) {\n              return this.selectEntity(keyuri, (entity) => entity === null || entity === void 0 ? void 0 : entity.status);\n          }\n          /**\n           * @returns an observable that emits whenever we got an error on a particular key\n           */\n          getKeyError$(keyuri) {\n              return this.selectEntity(keyuri, (entity) => copyKeyError(entity === null || entity === void 0 ? void 0 : entity.error, entity === null || entity === void 0 ? void 0 : entity.mediaOptionIds)).pipe(filterNil);\n          }\n      }\n    \n      /**\n       * @brief Backing store for the playback state\n       */\n      class KeySystemStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'key-system-store', idKey: 'keyUri', producerFn: produce_1 });\n          }\n      }\n    \n      /**\n       * @brief Service that manages playback state\n       */\n      class KeySystemService {\n          constructor(store) {\n              this.store = store;\n          }\n          getQuery() {\n              return new KeySystemQuery(this.store);\n          }\n          upsertKey(keyEntity) {\n              logAction('keys.upsert', keyEntity.keyUri);\n              const newItemIdSet = new Set(keyEntity.itemIds.filter((x) => x != null));\n              const newMediaOptionIdSet = new Set(keyEntity.mediaOptionIds.filter((x) => x != null));\n              this.store.upsert(keyEntity.keyUri, \n              // Update existing\n              (oldEntity) => {\n                  const mergedEntity = Object.assign(Object.assign({}, oldEntity), keyEntity);\n                  // Merge itemIds & mediaOptionIds\n                  if ('itemIds' in oldEntity) {\n                      for (const itemId of oldEntity.itemIds) {\n                          newItemIdSet.add(itemId);\n                      }\n                  }\n                  mergedEntity.itemIds = Array.from(newItemIdSet);\n                  if ('mediaOptionIds' in oldEntity) {\n                      for (const mediaOptionId of oldEntity.mediaOptionIds) {\n                          newMediaOptionIdSet.add(mediaOptionId);\n                      }\n                  }\n                  mergedEntity.mediaOptionIds = Array.from(newMediaOptionIdSet);\n                  return mergedEntity;\n              }, \n              // Create new entity\n              () => (Object.assign(Object.assign({}, keyEntity), { itemIds: Array.from(newItemIdSet), mediaOptionIds: Array.from(newMediaOptionIdSet) })));\n          }\n          removeKey(keyUri) {\n              logAction('keys.removeKey', keyUri);\n              this.store.remove(keyUri);\n          }\n          removeAllKeysForItem(itemId) {\n              logAction(`keys.removeAllKeysForItem ${itemId}`);\n              this.store.update(null, (entity) => {\n                  // Remove itemid from itemId list\n                  const idx = entity.itemIds.findIndex((id) => id === itemId);\n                  if (idx >= 0) {\n                      entity.itemIds.splice(idx, 1);\n                  }\n              });\n          }\n          removeAll() {\n              logAction('keys.remove');\n              this.store.remove();\n          }\n          updateKeyValue(keyUri, key) {\n              logAction('keys.updateKeyValue', keyUri);\n              this.store.update(keyUri, (entity) => {\n                  if (entity.decryptdata.keyBuf == null && key != null) {\n                      entity.decryptdata.keyBuf = key.buffer;\n                  }\n                  entity.requestState = KeyRequestMacroState.GotKeyResponse;\n              });\n          }\n          updateKeyStatus(keyUri, status) {\n              logAction(`keys.updateKeyStatus ${status}`, keyUri);\n              this.store.update(keyUri, (entity) => {\n                  entity.status = status;\n              });\n          }\n          updateKeyRequestState(keyUri, requestState, predicate) {\n              logAction(`keys.updateKeyRequestState ${requestState}`, keyUri);\n              this.store.update(keyUri, (entity) => {\n                  if (!predicate || predicate(entity.requestState)) {\n                      entity.requestState = requestState;\n                  }\n              });\n          }\n          addMediaOption(keyUri, mediaOptionKey) {\n              const { itemId, mediaOptionId } = mediaOptionKey;\n              logAction(`keys.addMediaOption itemId: ${itemId}, mediaOptionId: ${mediaOptionId}`, keyUri);\n              this.store.update(keyUri, (entity) => {\n                  if (mediaOptionId != null) {\n                      if (entity.mediaOptionIds.every((id) => id !== mediaOptionId)) {\n                          entity.mediaOptionIds.push(mediaOptionId);\n                      }\n                  }\n                  if (itemId != null) {\n                      if (entity.itemIds.every((id) => id !== itemId)) {\n                          entity.itemIds.push(itemId);\n                      }\n                  }\n              });\n          }\n          setError(keyUri, error) {\n              var _a;\n              logAction(`keys.setError ${(_a = error === null || error === void 0 ? void 0 : error.constructor) === null || _a === void 0 ? void 0 : _a.name}`, keyUri);\n              this.store.update(keyUri, (entity) => {\n                  // Make a copy so that entity.error is not modified after storage\n                  entity.error = copyKeyError(error);\n                  entity.requestState = KeyRequestMacroState.MustRequestResponse;\n              });\n          }\n      }\n      // state for the service functions\n      const keySystemStore = new KeySystemStore();\n      let globalKeySystemService = null;\n      function keySystemService() {\n          if (!globalKeySystemService) {\n              globalKeySystemService = new KeySystemService(keySystemStore);\n          }\n          return globalKeySystemService;\n      }\n      const makeKeySystemService = (keySystemService, source$, itemRemove$, config, platformQuery, eventEmitter, sessionHandler, logger) => {\n          return source$.pipe(tag('[Keys] playback.keySystemServiceEpic.in'), switchMap((mediaSink) => {\n              if (!mediaSink) {\n                  return of(null);\n              }\n              return new Observable((subscriber) => {\n                  let keySystemAdapter = new KeySystemAdapter(keySystemService, mediaSink, config, platformQuery, eventEmitter, sessionHandler, logger);\n                  const sub = merge(of(keySystemAdapter), itemRemove$.pipe(mergeMap((ids) => {\n                      return keySystemAdapter.removeKeysForItems(ids);\n                  }), switchMapTo(EMPTY))).subscribe(subscriber);\n                  return function unsubscribe() {\n                      logger.warn('[Keys] playback.keySystemServiceEpic.unsubscribe');\n                      sub.unsubscribe();\n                      keySystemAdapter.destroy().subscribe();\n                      keySystemAdapter = undefined;\n                  };\n              });\n          }), tag('[Keys] playback.keySystemServiceEpic.emit'));\n      };\n    \n      function isAlternateMediaOption(option) {\n          return 'groupId' in option;\n      }\n    \n      function safeAssignProperties(target, source) {\n          return Object.assign(target, source);\n      }\n      /**\n       *  Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n       */\n      const specialCea608CharsCodes = {\n          42: 225,\n          92: 233,\n          94: 237,\n          95: 243,\n          96: 250,\n          123: 231,\n          124: 247,\n          125: 209,\n          126: 241,\n          127: 9608,\n          // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n          // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n          // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n          128: 174,\n          129: 176,\n          130: 189,\n          131: 191,\n          132: 8482,\n          133: 162,\n          134: 163,\n          135: 9834,\n          136: 224,\n          137: 32,\n          138: 232,\n          139: 226,\n          140: 234,\n          141: 238,\n          142: 244,\n          143: 251,\n          // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n          // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n          144: 193,\n          145: 201,\n          146: 211,\n          147: 218,\n          148: 220,\n          149: 252,\n          150: 8216,\n          151: 161,\n          152: 42,\n          153: 8217,\n          154: 9473,\n          155: 169,\n          156: 8480,\n          157: 8226,\n          158: 8220,\n          159: 8221,\n          160: 192,\n          161: 194,\n          162: 199,\n          163: 200,\n          164: 202,\n          165: 203,\n          166: 235,\n          167: 206,\n          168: 207,\n          169: 239,\n          170: 212,\n          171: 217,\n          172: 249,\n          173: 219,\n          174: 171,\n          175: 187,\n          // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n          // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n          176: 195,\n          177: 227,\n          178: 205,\n          179: 204,\n          180: 236,\n          181: 210,\n          182: 242,\n          183: 213,\n          184: 245,\n          185: 123,\n          186: 125,\n          187: 92,\n          188: 94,\n          189: 95,\n          190: 124,\n          191: 8764,\n          192: 196,\n          193: 228,\n          194: 214,\n          195: 246,\n          196: 223,\n          197: 165,\n          198: 164,\n          199: 9475,\n          200: 197,\n          201: 229,\n          202: 216,\n          203: 248,\n          204: 9487,\n          205: 9491,\n          206: 9495,\n          207: 9499, // Box drawings heavy up and left\n      };\n      /**\n       * Utils\n       */\n      const getCharForByte = function (byte) {\n          let charCode = byte;\n          // eslint-disable-next-line no-prototype-builtins\n          if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n              charCode = specialCea608CharsCodes[byte];\n          }\n          return String.fromCharCode(charCode);\n      };\n      const NR_ROWS = 15, NR_COLS = 100;\n      // Tables to look up row from PAC data\n      const rowsLowCh1 = { 17: 1, 18: 3, 21: 5, 22: 7, 23: 9, 16: 11, 19: 12, 20: 14 };\n      const rowsHighCh1 = { 17: 2, 18: 4, 21: 6, 22: 8, 23: 10, 19: 13, 20: 15 };\n      const rowsLowCh2 = { 25: 1, 26: 3, 29: 5, 30: 7, 31: 9, 24: 11, 27: 12, 28: 14 };\n      const rowsHighCh2 = { 25: 2, 26: 4, 29: 6, 30: 8, 31: 10, 27: 13, 28: 15 };\n      const backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n      const logger = {\n          verboseFilter: { DATA: 3, DEBUG: 3, INFO: 2, WARNING: 2, TEXT: 1, ERROR: 0 },\n          time: null,\n          verboseLevel: 0,\n          setTime: function (newTime) {\n              this.time = newTime;\n          },\n          log: function (severity, msg) {\n              const minLevel = this.verboseFilter[severity];\n              if (this.verboseLevel >= minLevel) {\n                  // eslint-disable-next-line no-console\n                  console.log(this.time + ' [' + severity + '] ' + msg);\n              }\n          },\n      };\n      const numArrayToHexArray = function (numArray) {\n          const hexArray = [];\n          for (let j = 0; j < numArray.length; j++) {\n              hexArray.push(numArray[j].toString(16));\n          }\n          return hexArray;\n      };\n      class PenState {\n          constructor(foreground, underline, italics, background, flash) {\n              this.foreground = foreground || 'white';\n              this.underline = underline || false;\n              this.italics = italics || false;\n              this.background = background || 'black';\n              this.flash = flash || false;\n          }\n          reset() {\n              this.foreground = 'white';\n              this.underline = false;\n              this.italics = false;\n              this.background = 'black';\n              this.flash = false;\n          }\n          setStyles(styles) {\n              safeAssignProperties(this, styles);\n          }\n          isDefault() {\n              return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;\n          }\n          equals(other) {\n              return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;\n          }\n          copy(newPenState) {\n              this.foreground = newPenState.foreground;\n              this.underline = newPenState.underline;\n              this.italics = newPenState.italics;\n              this.background = newPenState.background;\n              this.flash = newPenState.flash;\n          }\n          toString() {\n              return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;\n          }\n      }\n      /**\n       * Unicode character with styling and background.\n       * @constructor\n       */\n      class StyledUnicodeChar {\n          constructor(uchar, foreground, underline, italics, background, flash) {\n              this.uchar = uchar || ' '; // unicode character\n              this.penState = new PenState(foreground, underline, italics, background, flash);\n          }\n          reset() {\n              this.uchar = ' ';\n              this.penState.reset();\n          }\n          setChar(uchar, newPenState) {\n              this.uchar = uchar;\n              this.penState.copy(newPenState);\n          }\n          setPenState(newPenState) {\n              this.penState.copy(newPenState);\n          }\n          equals(other) {\n              return this.uchar === other.uchar && this.penState.equals(other.penState);\n          }\n          copy(newChar) {\n              this.uchar = newChar.uchar;\n              this.penState.copy(newChar.penState);\n          }\n          isEmpty() {\n              return this.uchar === ' ' && this.penState.isDefault();\n          }\n      }\n      /**\n       * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n       * @constructor\n       */\n      class Row {\n          constructor() {\n              this.chars = [];\n              for (let i = 0; i < NR_COLS; i++) {\n                  this.chars.push(new StyledUnicodeChar());\n              }\n              this.pos = 0;\n              this.currPenState = new PenState();\n          }\n          equals(other) {\n              let equal = true;\n              for (let i = 0; i < NR_COLS; i++) {\n                  if (!this.chars[i].equals(other.chars[i])) {\n                      equal = false;\n                      break;\n                  }\n              }\n              return equal;\n          }\n          copy(other) {\n              for (let i = 0; i < NR_COLS; i++) {\n                  this.chars[i].copy(other.chars[i]);\n              }\n          }\n          isEmpty() {\n              let empty = true;\n              for (let i = 0; i < NR_COLS; i++) {\n                  if (!this.chars[i].isEmpty()) {\n                      empty = false;\n                      break;\n                  }\n              }\n              return empty;\n          }\n          /**\n           *  Set the cursor to a valid column.\n           */\n          setCursor(absPos) {\n              if (this.pos !== absPos) {\n                  this.pos = absPos;\n              }\n              if (this.pos < 0) {\n                  logger.log('ERROR', 'Negative cursor position ' + this.pos);\n                  this.pos = 0;\n              }\n              else if (this.pos > NR_COLS) {\n                  logger.log('ERROR', 'Too large cursor position ' + this.pos);\n                  this.pos = NR_COLS;\n              }\n          }\n          /**\n           * Move the cursor relative to current position.\n           */\n          moveCursor(relPos) {\n              const newPos = this.pos + relPos;\n              if (relPos > 1) {\n                  for (let i = this.pos + 1; i < newPos + 1; i++) {\n                      this.chars[i].setPenState(this.currPenState);\n                  }\n              }\n              this.setCursor(newPos);\n          }\n          /**\n           * Backspace, move one step back and clear character.\n           */\n          backSpace() {\n              this.moveCursor(-1);\n              this.chars[this.pos].setChar(' ', this.currPenState);\n          }\n          insertChar(byte) {\n              if (byte >= 144) {\n                  // Extended char\n                  this.backSpace();\n              }\n              const char = getCharForByte(byte);\n              if (this.pos >= NR_COLS) {\n                  logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');\n                  return;\n              }\n              this.chars[this.pos].setChar(char, this.currPenState);\n              this.moveCursor(1);\n          }\n          clearFromPos(startPos) {\n              let i;\n              for (i = startPos; i < NR_COLS; i++) {\n                  this.chars[i].reset();\n              }\n          }\n          clear() {\n              this.clearFromPos(0);\n              this.pos = 0;\n              this.currPenState.reset();\n          }\n          clearToEndOfRow() {\n              this.clearFromPos(this.pos);\n          }\n          getTextString() {\n              const chars = [];\n              let empty = true;\n              for (let i = 0; i < NR_COLS; i++) {\n                  const char = this.chars[i].uchar;\n                  if (char !== ' ') {\n                      empty = false;\n                  }\n                  chars.push(char);\n              }\n              if (empty) {\n                  return '';\n              }\n              else {\n                  return chars.join('');\n              }\n          }\n          setPenStyles(styles) {\n              this.currPenState.setStyles(styles);\n              const currChar = this.chars[this.pos];\n              currChar.setPenState(this.currPenState);\n          }\n      }\n      /**\n       * Keep a CEA-608 screen of 32x15 styled characters\n       * @constructor\n       */\n      class CaptionScreen {\n          constructor() {\n              this.rows = [];\n              for (let i = 0; i < NR_ROWS; i++) {\n                  this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)\n              }\n              this.currRow = NR_ROWS - 1;\n              this.nrRollUpRows = null;\n              this.reset();\n          }\n          reset() {\n              for (let i = 0; i < NR_ROWS; i++) {\n                  this.rows[i].clear();\n              }\n              this.currRow = NR_ROWS - 1;\n          }\n          equals(other) {\n              let equal = true;\n              for (let i = 0; i < NR_ROWS; i++) {\n                  if (!this.rows[i].equals(other.rows[i])) {\n                      equal = false;\n                      break;\n                  }\n              }\n              return equal;\n          }\n          copy(other) {\n              for (let i = 0; i < NR_ROWS; i++) {\n                  this.rows[i].copy(other.rows[i]);\n              }\n          }\n          isEmpty() {\n              let empty = true;\n              for (let i = 0; i < NR_ROWS; i++) {\n                  if (!this.rows[i].isEmpty()) {\n                      empty = false;\n                      break;\n                  }\n              }\n              return empty;\n          }\n          backSpace() {\n              const row = this.rows[this.currRow];\n              row.backSpace();\n          }\n          clearToEndOfRow() {\n              const row = this.rows[this.currRow];\n              row.clearToEndOfRow();\n          }\n          /**\n           * Insert a character (without styling) in the current row.\n           */\n          insertChar(char) {\n              const row = this.rows[this.currRow];\n              row.insertChar(char);\n          }\n          setPen(styles) {\n              const row = this.rows[this.currRow];\n              row.setPenStyles(styles);\n          }\n          moveCursor(relPos) {\n              const row = this.rows[this.currRow];\n              row.moveCursor(relPos);\n          }\n          setCursor(absPos) {\n              logger.log('INFO', 'setCursor: ' + absPos);\n              const row = this.rows[this.currRow];\n              row.setCursor(absPos);\n          }\n          setPAC(pacData) {\n              logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n              let newRow = pacData.row - 1;\n              if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n                  newRow = this.nrRollUpRows - 1;\n              }\n              // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n              if (this.nrRollUpRows && this.currRow !== newRow) {\n                  // clear all rows first\n                  for (let i = 0; i < NR_ROWS; i++) {\n                      this.rows[i].clear();\n                  }\n                  // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n                  // topRowIndex - the start of rows to copy (inclusive index)\n                  const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n                  // We only copy if the last position was already shown.\n                  // We use the cueStartTime value to check this.\n                  const lastOutputScreen = this.lastOutputScreen;\n                  if (lastOutputScreen) {\n                      const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n                      if (prevLineTime && prevLineTime < logger.time) {\n                          for (let i = 0; i < this.nrRollUpRows; i++) {\n                              this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);\n                          }\n                      }\n                  }\n              }\n              this.currRow = newRow;\n              const row = this.rows[this.currRow];\n              if (pacData.indent !== null) {\n                  const indent = pacData.indent;\n                  const prevPos = Math.max(indent - 1, 0);\n                  row.setCursor(pacData.indent);\n                  pacData.color = row.chars[prevPos].penState.foreground;\n              }\n              const styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };\n              this.setPen(styles);\n          }\n          /**\n           * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n           */\n          setBkgData(bkgData) {\n              logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));\n              this.backSpace();\n              this.setPen(bkgData);\n              this.insertChar(32); // Space\n          }\n          setRollUpRows(nrRows) {\n              this.nrRollUpRows = nrRows;\n          }\n          rollUp() {\n              if (this.nrRollUpRows === null) {\n                  logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');\n                  return; // Not properly setup\n              }\n              logger.log('INFO', 'TEXT ' + this.getDisplayText());\n              const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n              const topRow = this.rows.splice(topRowIndex, 1)[0];\n              topRow.clear();\n              this.rows.splice(this.currRow, 0, topRow);\n              logger.log('INFO', 'Rolling up');\n          }\n          /**\n           * Get all non-empty rows with as unicode text.\n           */\n          getDisplayText(asOneRow) {\n              asOneRow = asOneRow || false;\n              const displayText = [];\n              let text = '';\n              let rowNr = -1;\n              for (let i = 0; i < NR_ROWS; i++) {\n                  const rowText = this.rows[i].getTextString();\n                  if (rowText) {\n                      rowNr = i + 1;\n                      if (asOneRow) {\n                          displayText.push('Row ' + rowNr + ': \\'' + rowText + '\\'');\n                      }\n                      else {\n                          displayText.push(rowText.trim());\n                      }\n                  }\n              }\n              if (displayText.length > 0) {\n                  if (asOneRow) {\n                      text = '[' + displayText.join(' | ') + ']';\n                  }\n                  else {\n                      text = displayText.join('\\n');\n                  }\n              }\n              return text;\n          }\n          getTextAndFormat() {\n              return this.rows;\n          }\n      }\n      // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n      class Cea608Channel {\n          constructor(channelNumber, outputFilter) {\n              this.chNr = channelNumber;\n              this.outputFilter = outputFilter;\n              this.mode = null;\n              this.verbose = 0;\n              this.displayedMemory = new CaptionScreen();\n              this.nonDisplayedMemory = new CaptionScreen();\n              this.lastOutputScreen = new CaptionScreen();\n              this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n              this.writeScreen = this.displayedMemory;\n              this.mode = null;\n              this.cueStartTime = null; // Keeps track of where a cue started.\n          }\n          reset() {\n              this.mode = null;\n              this.displayedMemory.reset();\n              this.nonDisplayedMemory.reset();\n              this.lastOutputScreen.reset();\n              this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n              this.writeScreen = this.displayedMemory;\n              this.mode = null;\n              this.cueStartTime = null;\n              this.lastCueEndTime = null;\n          }\n          getHandler() {\n              return this.outputFilter;\n          }\n          setHandler(newHandler) {\n              this.outputFilter = newHandler;\n          }\n          setPAC(pacData) {\n              this.writeScreen.setPAC(pacData);\n          }\n          setBkgData(bkgData) {\n              this.writeScreen.setBkgData(bkgData);\n          }\n          setMode(newMode) {\n              if (newMode === this.mode) {\n                  return;\n              }\n              this.mode = newMode;\n              logger.log('INFO', 'MODE=' + newMode);\n              if (this.mode === 'MODE_POP-ON') {\n                  this.writeScreen = this.nonDisplayedMemory;\n              }\n              else {\n                  this.writeScreen = this.displayedMemory;\n                  this.writeScreen.reset();\n              }\n              if (this.mode !== 'MODE_ROLL-UP') {\n                  this.displayedMemory.nrRollUpRows = null;\n                  this.nonDisplayedMemory.nrRollUpRows = null;\n              }\n              this.mode = newMode;\n          }\n          insertChars(chars) {\n              for (let i = 0; i < chars.length; i++) {\n                  this.writeScreen.insertChar(chars[i]);\n              }\n              const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n              logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));\n              if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n                  logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n                  this.outputDataUpdate();\n              }\n          }\n          ccRCL() {\n              // Resume Caption Loading (switch mode to Pop On)\n              logger.log('INFO', 'RCL - Resume Caption Loading');\n              this.setMode('MODE_POP-ON');\n          }\n          ccBS() {\n              // BackSpace\n              logger.log('INFO', 'BS - BackSpace');\n              if (this.mode === 'MODE_TEXT') {\n                  return;\n              }\n              this.writeScreen.backSpace();\n              if (this.writeScreen === this.displayedMemory) {\n                  this.outputDataUpdate();\n              }\n          }\n          ccAOF() {\n              // Reserved (formerly Alarm Off)\n              return;\n          }\n          ccAON() {\n              // Reserved (formerly Alarm On)\n              return;\n          }\n          ccDER() {\n              // Delete to End of Row\n              logger.log('INFO', 'DER- Delete to End of Row');\n              this.writeScreen.clearToEndOfRow();\n              this.outputDataUpdate();\n          }\n          ccRU(nrRows) {\n              // Roll-Up Captions-2,3,or 4 Rows\n              logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');\n              this.writeScreen = this.displayedMemory;\n              this.setMode('MODE_ROLL-UP');\n              this.writeScreen.setRollUpRows(nrRows);\n          }\n          ccFON() {\n              // Flash On\n              logger.log('INFO', 'FON - Flash On');\n              this.writeScreen.setPen({ flash: true });\n          }\n          ccRDC() {\n              // Resume Direct Captioning (switch mode to PaintOn)\n              logger.log('INFO', 'RDC - Resume Direct Captioning');\n              this.setMode('MODE_PAINT-ON');\n          }\n          ccTR() {\n              // Text Restart in text mode (not supported, however)\n              logger.log('INFO', 'TR');\n              this.setMode('MODE_TEXT');\n          }\n          ccRTD() {\n              // Resume Text Display in Text mode (not supported, however)\n              logger.log('INFO', 'RTD');\n              this.setMode('MODE_TEXT');\n          }\n          ccEDM() {\n              // Erase Displayed Memory\n              logger.log('INFO', 'EDM - Erase Displayed Memory');\n              this.displayedMemory.reset();\n              this.outputDataUpdate(true);\n          }\n          ccCR() {\n              // Carriage Return\n              logger.log('INFO', 'CR - Carriage Return');\n              this.writeScreen.rollUp();\n              this.outputDataUpdate(true);\n          }\n          ccENM() {\n              // Erase Non-Displayed Memory\n              logger.log('INFO', 'ENM - Erase Non-displayed Memory');\n              this.nonDisplayedMemory.reset();\n          }\n          ccEOC() {\n              // End of Caption (Flip Memories)\n              logger.log('INFO', 'EOC - End Of Caption');\n              if (this.mode === 'MODE_POP-ON') {\n                  const tmp = this.displayedMemory;\n                  this.displayedMemory = this.nonDisplayedMemory;\n                  this.nonDisplayedMemory = tmp;\n                  this.writeScreen = this.nonDisplayedMemory;\n                  logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());\n              }\n              this.outputDataUpdate(true);\n          }\n          ccTO(nrCols) {\n              // Tab Offset 1,2, or 3 columns\n              logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');\n              this.writeScreen.moveCursor(nrCols);\n          }\n          ccMIDROW(secondByte) {\n              // Parse MIDROW command\n              const styles = { flash: false, underline: false, italics: false };\n              styles.underline = secondByte % 2 === 1;\n              styles.italics = secondByte >= 46;\n              if (!styles.italics) {\n                  const colorIndex = Math.floor(secondByte / 2) - 16;\n                  const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n                  styles.foreground = colors[colorIndex];\n              }\n              else {\n                  styles.foreground = 'white';\n              }\n              logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));\n              this.writeScreen.setPen(styles);\n          }\n          outputDataUpdate(dispatch = false) {\n              const t = logger.time;\n              if (t === null) {\n                  return;\n              }\n              if (this.outputFilter) {\n                  if (this.outputFilter.updateData) {\n                      this.outputFilter.updateData(t, this.displayedMemory);\n                  }\n                  if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n                      // Start of a new cue\n                      this.cueStartTime = t;\n                  }\n                  else {\n                      if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n                          if (this.outputFilter.newCue) {\n                              this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);\n                              if (dispatch === true && this.outputFilter.dispatchCue) {\n                                  this.outputFilter.dispatchCue();\n                              }\n                          }\n                          this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;\n                      }\n                  }\n                  this.lastOutputScreen.copy(this.displayedMemory);\n              }\n          }\n          cueSplitAtTime(t) {\n              if (this.outputFilter) {\n                  if (!this.displayedMemory.isEmpty()) {\n                      if (this.outputFilter.newCue) {\n                          this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);\n                      }\n                      this.cueStartTime = t;\n                  }\n              }\n          }\n      }\n      class Cea608Parser {\n          constructor(field = 1, out1, out2) {\n              this.field = field;\n              this.currChNr = -1; // Will be 1 or 2\n              this.lastCmdA = null; // First byte of last command\n              this.lastCmdB = null; // Second byte of last command\n              this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];\n              this.dataCounters = { padding: 0, char: 0, cmd: 0, other: 0 };\n          }\n          getHandler(index) {\n              return this.channels[index].getHandler();\n          }\n          setHandler(index, newHandler) {\n              this.channels[index].setHandler(newHandler);\n          }\n          /**\n           * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n           */\n          addData(t, byteList) {\n              let cmdFound, a, b;\n              let charsFound = null;\n              logger.setTime(t);\n              for (let i = 0; i < byteList.length; i += 2) {\n                  a = byteList[i] & 127;\n                  b = byteList[i + 1] & 127;\n                  if (a >= 16 && a <= 31 && a === this.lastCmdA && b === this.lastCmdB) {\n                      this.lastCmdA = null;\n                      this.lastCmdB = null;\n                      logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n                      continue; // Repeated commands are dropped (once)\n                  }\n                  if (a === 0 && b === 0) {\n                      this.dataCounters.padding += 2;\n                      continue;\n                  }\n                  else {\n                      logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');\n                  }\n                  cmdFound = this.parseCmd(a, b);\n                  if (!cmdFound) {\n                      cmdFound = this.parseMidrow(a, b);\n                  }\n                  if (!cmdFound) {\n                      cmdFound = this.parsePAC(a, b);\n                  }\n                  if (!cmdFound) {\n                      cmdFound = this.parseBackgroundAttributes(a, b);\n                  }\n                  if (!cmdFound) {\n                      charsFound = this.parseChars(a, b);\n                      if (charsFound) {\n                          if (this.currChNr && this.currChNr >= 0) {\n                              const channel = this.channels[this.currChNr - 1];\n                              channel.insertChars(charsFound);\n                          }\n                          else {\n                              logger.log('WARNING', 'No channel found yet. TEXT-MODE?');\n                          }\n                      }\n                  }\n                  if (cmdFound) {\n                      this.dataCounters.cmd += 2;\n                  }\n                  else if (charsFound) {\n                      this.dataCounters.char += 2;\n                  }\n                  else {\n                      this.dataCounters.other += 2;\n                      logger.log('WARNING', 'Couldn\\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));\n                  }\n              }\n          }\n          /**\n           * Parse Command.\n           * @returns {Boolean} Tells if a command was found\n           */\n          parseCmd(a, b) {\n              let chNr = null;\n              const cond1 = (a === 20 || a === 21 || a === 28 || a === 29) && 32 <= b && b <= 47;\n              const cond2 = (a === 23 || a === 31) && 33 <= b && b <= 35;\n              if (!(cond1 || cond2)) {\n                  return false;\n              }\n              if (a === 20 || a === 23) {\n                  chNr = 1;\n              }\n              else {\n                  chNr = 2; // (a === 0x1C || a=== 0x1f)\n              }\n              const channel = this.channels[chNr - 1];\n              if (a === 20 || a === 21 || a === 28 || a === 29) {\n                  if (b === 32) {\n                      channel.ccRCL();\n                  }\n                  else if (b === 33) {\n                      channel.ccBS();\n                  }\n                  else if (b === 34) {\n                      channel.ccAOF();\n                  }\n                  else if (b === 35) {\n                      channel.ccAON();\n                  }\n                  else if (b === 36) {\n                      channel.ccDER();\n                  }\n                  else if (b === 37) {\n                      channel.ccRU(2);\n                  }\n                  else if (b === 38) {\n                      channel.ccRU(3);\n                  }\n                  else if (b === 39) {\n                      channel.ccRU(4);\n                  }\n                  else if (b === 40) {\n                      channel.ccFON();\n                  }\n                  else if (b === 41) {\n                      channel.ccRDC();\n                  }\n                  else if (b === 42) {\n                      channel.ccTR();\n                  }\n                  else if (b === 43) {\n                      channel.ccRTD();\n                  }\n                  else if (b === 44) {\n                      channel.ccEDM();\n                  }\n                  else if (b === 45) {\n                      channel.ccCR();\n                  }\n                  else if (b === 46) {\n                      channel.ccENM();\n                  }\n                  else if (b === 47) {\n                      channel.ccEOC();\n                  }\n              }\n              else {\n                  // a == 0x17 || a == 0x1F\n                  channel.ccTO(b - 32);\n              }\n              this.lastCmdA = a;\n              this.lastCmdB = b;\n              this.currChNr = chNr;\n              return true;\n          }\n          /**\n           * Parse midrow styling command\n           * @returns {Boolean}\n           */\n          parseMidrow(a, b) {\n              let chNr = null;\n              if ((a === 17 || a === 25) && 32 <= b && b <= 47) {\n                  if (a === 17) {\n                      chNr = 1;\n                  }\n                  else {\n                      chNr = 2;\n                  }\n                  if (chNr !== this.currChNr) {\n                      logger.log('ERROR', 'Mismatch channel in midrow parsing');\n                      return false;\n                  }\n                  const channel = this.channels[chNr - 1];\n                  // cea608 spec says midrow codes should inject a space\n                  channel.insertChars([32]);\n                  channel.ccMIDROW(b);\n                  logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n                  this.lastCmdA = a;\n                  this.lastCmdB = b;\n                  return true;\n              }\n              return false;\n          }\n          /**\n           * Parse Preable Access Codes (Table 53).\n           * @returns {Boolean} Tells if PAC found\n           */\n          parsePAC(a, b) {\n              let chNr = null;\n              let row = null;\n              const case1 = ((17 <= a && a <= 23) || (25 <= a && a <= 31)) && 64 <= b && b <= 127;\n              const case2 = (a === 16 || a === 24) && 64 <= b && b <= 95;\n              if (!(case1 || case2)) {\n                  return false;\n              }\n              chNr = a <= 23 ? 1 : 2;\n              if (64 <= b && b <= 95) {\n                  row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n              }\n              else {\n                  // 0x60 <= b <= 0x7F\n                  row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];\n              }\n              const pacData = this.interpretPAC(row, b);\n              const channel = this.channels[chNr - 1];\n              channel.setPAC(pacData);\n              this.lastCmdA = a;\n              this.lastCmdB = b;\n              this.currChNr = chNr;\n              return true;\n          }\n          /**\n           * Interpret the second byte of the pac, and return the information.\n           * @returns {Object} pacData with style parameters.\n           */\n          interpretPAC(row, byte) {\n              let pacIndex = byte;\n              const pacData = { color: null, italics: false, indent: null, underline: false, row: row };\n              if (byte > 95) {\n                  pacIndex = byte - 96;\n              }\n              else {\n                  pacIndex = byte - 64;\n              }\n              pacData.underline = (pacIndex & 1) === 1;\n              if (pacIndex <= 13) {\n                  pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];\n              }\n              else if (pacIndex <= 15) {\n                  pacData.italics = true;\n                  pacData.color = 'white';\n              }\n              else {\n                  pacData.indent = Math.floor((pacIndex - 16) / 2) * 4;\n              }\n              return pacData; // Note that row has zero offset. The spec uses 1.\n          }\n          /**\n           * Parse characters.\n           * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n           */\n          parseChars(a, b) {\n              let channelNr = null, charCodes = null, charCode1 = null;\n              if (a >= 25) {\n                  channelNr = 2;\n                  charCode1 = a - 8;\n              }\n              else {\n                  channelNr = 1;\n                  charCode1 = a;\n              }\n              if (17 <= charCode1 && charCode1 <= 19) {\n                  // Special character\n                  let oneCode = b;\n                  if (charCode1 === 17) {\n                      oneCode = b + 80;\n                  }\n                  else if (charCode1 === 18) {\n                      oneCode = b + 112;\n                  }\n                  else {\n                      oneCode = b + 144;\n                  }\n                  logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n                  charCodes = [oneCode];\n                  this.lastCmdA = a;\n                  this.lastCmdB = b;\n              }\n              else if (32 <= a && a <= 127) {\n                  charCodes = b === 0 ? [a] : [a, b];\n                  this.lastCmdA = null;\n                  this.lastCmdB = null;\n              }\n              if (charCodes) {\n                  const hexCodes = numArrayToHexArray(charCodes);\n                  logger.log('DEBUG', `Char codes =  ${hexCodes.join(',')}`);\n              }\n              return charCodes;\n          }\n          /**\n           * Parse extended background attributes as well as new foreground color black.\n           * @returns{Boolean} Tells if background attributes are found\n           */\n          parseBackgroundAttributes(a, b) {\n              let bkgData, index, chNr, channel;\n              const case1 = (a === 16 || a === 24) && 32 <= b && b <= 47;\n              const case2 = (a === 23 || a === 31) && 45 <= b && b <= 47;\n              if (!(case1 || case2)) {\n                  return false;\n              }\n              // eslint-disable-next-line prefer-const\n              bkgData = { underline: false };\n              if (a === 16 || a === 24) {\n                  index = Math.floor((b - 32) / 2);\n                  bkgData.background = backgroundColors[index];\n                  if (b % 2 === 1) {\n                      bkgData.background = bkgData.background + '_semi';\n                  }\n              }\n              else if (b === 45) {\n                  bkgData.background = 'transparent';\n              }\n              else {\n                  bkgData.foreground = 'black';\n                  if (b === 47) {\n                      bkgData.underline = true;\n                  }\n              }\n              // eslint-disable-next-line prefer-const\n              chNr = a < 24 ? 1 : 2;\n              // eslint-disable-next-line prefer-const\n              channel = this.channels[chNr - 1];\n              channel.setBkgData(bkgData);\n              this.lastCmdA = null;\n              this.lastCmdB = null;\n              return true;\n          }\n          /**\n           * Reset state of parser and its channels.\n           */\n          reset() {\n              for (let i = 0; i < this.channels.length; i++) {\n                  if (this.channels[i]) {\n                      this.channels[i].reset();\n                  }\n              }\n              this.lastCmdA = null;\n              this.lastCmdB = null;\n          }\n          /**\n           * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n           */\n          cueSplitAtTime(t) {\n              for (let i = 0; i < this.channels.length; i++) {\n                  if (this.channels[i]) {\n                      this.channels[i].cueSplitAtTime(t);\n                  }\n              }\n          }\n      }\n      var Cea608Parser$1 = Cea608Parser;\n    \n      class OutputFilter {\n          constructor(handler, track) {\n              this.handler = handler;\n              this.track = track;\n              this.startTime = null;\n              this.endTime = null;\n              this.screen = null;\n          }\n          dispatchCue() {\n              if (this.startTime === null) {\n                  return;\n              }\n              this.handler.addCues('cc' + this.track, this.startTime, this.endTime, this.screen);\n              this.startTime = null;\n          }\n          newCue(startTime, endTime, screen) {\n              if (this.startTime === null || this.startTime > startTime) {\n                  this.startTime = startTime;\n              }\n              this.endTime = endTime;\n              this.screen = screen;\n              this.handler.createHTMLCaptionsTrack(this.track);\n          }\n      }\n    \n      var lib = {};\n    \n      var vttparser = {};\n    \n      var vttcue = {};\n    \n      var vttvalidator = {};\n    \n      /**\n       * Copyright 2019 vtt.js Contributors\n       *\n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       *   http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       */\n      Object.defineProperty(vttvalidator, \"__esModule\", { value: true });\n      function isValidPercentValue(value) {\n          return typeof value === 'number' && value >= 0 && value <= 100;\n      }\n      vttvalidator.isValidPercentValue = isValidPercentValue;\n      function isValidAlignSetting(value) {\n          return (typeof value === 'string' &&\n              ['start', 'center', 'end', 'left', 'right', 'middle'].includes(value));\n      }\n      vttvalidator.isValidAlignSetting = isValidAlignSetting;\n      function isValidDirectionSetting(value) {\n          return typeof value === 'string' && ['', 'rl', 'lr'].includes(value);\n      }\n      vttvalidator.isValidDirectionSetting = isValidDirectionSetting;\n      function isValidLineAndPositionSetting(value) {\n          return typeof value === 'number' || value === 'auto';\n      }\n      vttvalidator.isValidLineAndPositionSetting = isValidLineAndPositionSetting;\n      function isValidLineAlignSetting(value) {\n          return typeof value === 'string' && ['start', 'center', 'end'].includes(value);\n      }\n      vttvalidator.isValidLineAlignSetting = isValidLineAlignSetting;\n      function isValidPositionAlignSetting(value) {\n          return (typeof value === 'string' &&\n              ['line-left', 'center', 'line-right', 'auto', 'left', 'start', 'middle', 'end', 'right'].includes(value));\n      }\n      vttvalidator.isValidPositionAlignSetting = isValidPositionAlignSetting;\n      function isValidScrollSetting(value) {\n          return ['', 'up'].includes(value);\n      }\n      vttvalidator.isValidScrollSetting = isValidScrollSetting;\n    \n      var vttparserUtility = {};\n    \n      Object.defineProperty(vttparserUtility, \"__esModule\", { value: true });\n      const ESCAPE = {\n          '&amp;': '&',\n          '&lt;': '<',\n          '&gt;': '>',\n          '&lrm;': '\\u200e',\n          '&rlm;': '\\u200f',\n          '&nbsp;': '\\u00a0'\n      };\n      const TAG_NAME = {\n          c: 'span',\n          i: 'i',\n          b: 'b',\n          u: 'u',\n          ruby: 'ruby',\n          rt: 'rt',\n          v: 'span',\n          lang: 'span'\n      };\n      const TAG_ANNOTATION = {\n          v: 'title',\n          lang: 'lang'\n      };\n      const NEEDS_PARENT = {\n          rt: 'ruby'\n      };\n      // \"text-combine-upright\" must be remapped into \"-webkit-text-combine\"\n      // until browsers support this property\n      // In the future: https://developer.mozilla.org/en-US/docs/Web/CSS/text-combine-upright\n      const styleMap = {\n          'text-combine-upright': '-webkit-text-combine:horizontal; text-orientation: mixed;'\n      };\n      class ParserUtility {\n          // Try to parse input as a time stamp.\n          static parseTimeStamp(input) {\n              function computeSeconds(arr) {\n                  const [h, m, s, f] = arr.map(n => (n ? parseInt('' + n) : 0));\n                  return h * 3600 + m * 60 + s + f / 1000;\n              }\n              const m = /^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/.exec(input);\n              if (!m) {\n                  return null;\n              }\n              if (m[3]) {\n                  // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n                  return computeSeconds([m[1], m[2], m[3].substring(1), m[4]]);\n              }\n              else if (parseInt(m[1]) > 59) {\n                  // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n                  // First position is hours as it's over 59.\n                  return computeSeconds([m[1], m[2], null, m[4]]);\n              }\n              else {\n                  // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n                  return computeSeconds([null, m[1], m[2], m[4]]);\n              }\n          }\n          // Parse content into a document fragment.\n          static parseContent(window, cue, globalStyleCollection) {\n              let input = cue.text;\n              function nextToken() {\n                  // Check for end-of-string.\n                  if (!input) {\n                      return null;\n                  }\n                  // Consume 'n' characters from the input.\n                  function consume(result) {\n                      input = input.substr(result.length);\n                      return result;\n                  }\n                  const m = /^([^<]*)(<[^>]+>?)?/.exec(input);\n                  // If there is some text before the next tag, return it, otherwise return\n                  // the tag.\n                  return consume(m[1] ? m[1] : m[2]);\n              }\n              // Unescape a string 's'.\n              function unescape1(e) {\n                  return ESCAPE[e];\n              }\n              function unescape(s) {\n                  return s.replace(/&(amp|lt|gt|lrm|rlm|nbsp);/g, unescape1);\n              }\n              function shouldAdd(current, element) {\n                  return (!NEEDS_PARENT[element.dataset.localName] ||\n                      NEEDS_PARENT[element.dataset.localName] === current.dataset.localName);\n              }\n              // Create an element for this tag.\n              function createElement(type, cssSelector, annotation) {\n                  function createStyleString(styles) {\n                      let styleString = '';\n                      for (const key in styles) {\n                          if (styleMap[key]) {\n                              styleString += styleMap[key];\n                          }\n                          else {\n                              styleString += key + ':' + styles[key] + ';';\n                          }\n                      }\n                      return styleString;\n                  }\n                  const tagName = TAG_NAME[type];\n                  if (!tagName) {\n                      return null;\n                  }\n                  const element = window.document.createElement(tagName);\n                  // localName is a read only property, but we can store this as an HTML data-attribute\n                  element.dataset.localName = tagName;\n                  const name = TAG_ANNOTATION[type];\n                  if (name && annotation) {\n                      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                      element[name] = annotation.trim();\n                  }\n                  if (cssSelector) {\n                      if (globalStyleCollection[cssSelector]) {\n                          const elementStyleCollection = globalStyleCollection[cssSelector];\n                          const styleString = createStyleString(elementStyleCollection);\n                          element.setAttribute('style', styleString);\n                      }\n                      else {\n                          console.info(`WebVTT: parseContent: Style referenced, but no style defined for '${cssSelector}'!`);\n                      }\n                  }\n                  return element;\n              }\n              const rootDiv = window.document.createElement('div'), tagStack = [];\n              let current = rootDiv, t, m;\n              while ((t = nextToken()) !== null) {\n                  if (t[0] === '<') {\n                      if (t[1] === '/') {\n                          // If the closing tag matches, move back up to the parent node.\n                          if (tagStack.length &&\n                              tagStack[tagStack.length - 1] === t.substr(2).replace('>', '')) {\n                              tagStack.pop();\n                              current = current.parentNode;\n                          }\n                          // Otherwise just ignore the end tag.\n                          continue;\n                      }\n                      const ts = ParserUtility.parseTimeStamp(t.substr(1, t.length - 2));\n                      let node;\n                      if (ts) {\n                          // Timestamps are lead nodes as well.\n                          node = window.document.createProcessingInstruction('timestamp', ts.toString()\n                          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                          );\n                          current.appendChild(node);\n                          continue;\n                      }\n                      m = /^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/.exec(t);\n                      // If we can't parse the tag, skip to the next tag.\n                      if (!m) {\n                          continue;\n                      }\n                      // Try to construct an element, and ignore the tag if we couldn't.\n                      node = createElement(m[1], m[2], m[3]);\n                      if (!node) {\n                          continue;\n                      }\n                      // Determine if the tag should be added based on the context of where it\n                      // is placed in the cuetext.\n                      if (!shouldAdd(current, node)) {\n                          continue;\n                      }\n                      // Append the node to the current node, and enter the scope of the new\n                      // node.\n                      tagStack.push(m[1]);\n                      current.appendChild(node);\n                      current = node;\n                      continue;\n                  }\n                  // Text nodes are leaf nodes.\n                  current.appendChild(window.document.createTextNode(unescape(t)));\n              }\n              return rootDiv;\n          }\n      }\n      vttparserUtility.default = ParserUtility;\n    \n      /**\n       * Copyright 2013 vtt.js Contributors\n       *\n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       *   http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       */\n      var __decorate$1 = (commonjsGlobal && commonjsGlobal.__decorate) || function (decorators, target, key, desc) {\n          var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n          if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n          else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n          return c > 3 && r && Object.defineProperty(target, key, r), r;\n      };\n      Object.defineProperty(vttcue, \"__esModule\", { value: true });\n      const vttvalidator_1$1 = vttvalidator;\n      const vttparser_utility_1$2 = vttparserUtility;\n      let VTTCue = class VTTCue {\n          constructor(startTime, endTime, text) {\n              /**\n               * VTTCue and TextTrackCue properties\n               * http://dev.w3.org/html5/webvtt/#vttcue-interface\n               */\n              this._id = '';\n              this._pauseOnExit = false;\n              this._region = null;\n              this._vertical = '';\n              this._snapToLines = true;\n              this._line = 'auto';\n              this._lineAlign = 'start';\n              this._position = 'auto';\n              this._positionAlign = 'auto';\n              this._size = 100;\n              this._align = 'center';\n              /**\n               * Other <track> spec defined properties\n               */\n              /**\n               * Shim implementation specific properties. These properties are not in\n               * the spec.\n               */\n              // Lets us know when the VTTCue's data has changed in such a way that we need\n              // to recompute its display state. This lets us compute its display state\n              // lazily.\n              this.hasBeenReset = false;\n              this._startTime = startTime;\n              this._endTime = endTime;\n              this._text = text;\n          }\n          get id() {\n              return this._id;\n          }\n          set id(value) {\n              this._id = '' + value;\n          }\n          get pauseOnExit() {\n              return this._pauseOnExit;\n          }\n          set pauseOnExit(value) {\n              this._pauseOnExit = !!value;\n          }\n          get startTime() {\n              return this._startTime;\n          }\n          set startTime(value) {\n              if (typeof value !== 'number') {\n                  throw new TypeError(`Start time must be set to a number: ${value}`);\n              }\n              this._startTime = value;\n              this.hasBeenReset = true;\n          }\n          get endTime() {\n              return this._endTime;\n          }\n          set endTime(value) {\n              if (typeof value !== 'number') {\n                  throw new TypeError(`End time must be set to a number: ${value}`);\n              }\n              this._endTime = value;\n              this.hasBeenReset = true;\n          }\n          get text() {\n              return this._text;\n          }\n          set text(value) {\n              this._text = '' + value;\n              this.hasBeenReset = true;\n          }\n          get region() {\n              return this._region;\n          }\n          set region(value) {\n              this._region = value;\n              this.hasBeenReset = true;\n          }\n          get vertical() {\n              return this._vertical;\n          }\n          set vertical(value) {\n              if (!vttvalidator_1$1.isValidDirectionSetting(value)) {\n                  throw new SyntaxError(`An invalid or illegal string was specified for vertical: ${value}`);\n              }\n              this._vertical = value;\n              this.hasBeenReset = true;\n          }\n          get snapToLines() {\n              return this._snapToLines;\n          }\n          set snapToLines(value) {\n              this._snapToLines = !!value;\n              this.hasBeenReset = true;\n          }\n          get line() {\n              return this._line;\n          }\n          set line(value) {\n              if (!vttvalidator_1$1.isValidLineAndPositionSetting(value)) {\n                  throw new SyntaxError(`An invalid number or illegal string was specified for line: ${value}`);\n              }\n              this._line = value;\n              this.hasBeenReset = true;\n          }\n          get lineAlign() {\n              return this._lineAlign;\n          }\n          set lineAlign(value) {\n              if (!vttvalidator_1$1.isValidLineAlignSetting(value)) {\n                  throw new SyntaxError(`An invalid or illegal string was specified for lineAlign: ${value}`);\n              }\n              this._lineAlign = value;\n              this.hasBeenReset = true;\n          }\n          get position() {\n              return this._position;\n          }\n          set position(value) {\n              if (!vttvalidator_1$1.isValidLineAndPositionSetting(value)) {\n                  throw new Error(`Position must be between 0 and 100 or auto: ${value}`);\n              }\n              this._position = value;\n              this.hasBeenReset = true;\n          }\n          get positionAlign() {\n              return this._positionAlign;\n          }\n          set positionAlign(value) {\n              if (!vttvalidator_1$1.isValidPositionAlignSetting(value)) {\n                  throw new SyntaxError(`An invalid or illegal string was specified for positionAlign: ${value}`);\n              }\n              this._positionAlign = value;\n              this.hasBeenReset = true;\n          }\n          get size() {\n              return this._size;\n          }\n          set size(value) {\n              if (value < 0 || value > 100) {\n                  throw new Error(`Size must be between 0 and 100: ${value}`);\n              }\n              this._size = value;\n              this.hasBeenReset = true;\n          }\n          get align() {\n              return this._align;\n          }\n          set align(value) {\n              if (!vttvalidator_1$1.isValidAlignSetting(value)) {\n                  throw new SyntaxError(`An invalid or illegal string was specified for align: ${value}`);\n              }\n              this._align = value;\n              this.hasBeenReset = true;\n          }\n          getCueAsHTML() {\n              return vttparser_utility_1$2.default.parseContent(window, this, {});\n          }\n          static create(options) {\n              if (!options.hasOwnProperty('startTime') ||\n                  !options.hasOwnProperty('endTime') ||\n                  !options.hasOwnProperty('text')) {\n                  throw new Error('You must at least have start time, end time, and text.');\n              }\n              const cue = new this(options.startTime, options.endTime, options.text);\n              Object.keys(options).forEach((key) => {\n                  if (cue.hasOwnProperty(key)) {\n                      cue[key] = options[key];\n                  }\n              });\n              return cue;\n          }\n          static fromJSON(json) {\n              return this.create(JSON.parse(json));\n          }\n          toJSON() {\n              const json = {};\n              Object.keys(this).forEach((key) => {\n                  if (this.hasOwnProperty(key) &&\n                      key !== 'getCueAsHTML' &&\n                      key !== 'hasBeenReset' &&\n                      key !== 'displayState') {\n                      json[key] = this[key];\n                  }\n              });\n              return json;\n          }\n      };\n      VTTCue = __decorate$1([\n          replaceVTTCue\n      ], VTTCue);\n      vttcue.VTTCue = VTTCue;\n      function replaceVTTCue(constructor) {\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n          let cls = constructor;\n          if (typeof window !== 'undefined' && window.VTTCue != null) {\n              cls = window.VTTCue;\n              cls.create = constructor.create;\n              cls.fromJSON = constructor.fromJSON;\n              cls.prototype.toJSON = constructor.prototype.toJSON;\n          }\n          return cls;\n      }\n    \n      var vttregion = {};\n    \n      /**\n       * Copyright 2013 vtt.js Contributors\n       *\n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       *   http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       */\n      var __decorate = (commonjsGlobal && commonjsGlobal.__decorate) || function (decorators, target, key, desc) {\n          var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n          if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n          else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n          return c > 3 && r && Object.defineProperty(target, key, r), r;\n      };\n      Object.defineProperty(vttregion, \"__esModule\", { value: true });\n      const vttvalidator_1 = vttvalidator;\n      // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface\n      let VTTRegion = class VTTRegion {\n          constructor() {\n              this._id = '';\n              this._lines = 3;\n              this._regionAnchorX = 0;\n              this._regionAnchorY = 100;\n              this._scroll = '';\n              this._viewportAnchorX = 0;\n              this._viewportAnchorY = 100;\n              this._width = 100;\n          }\n          get id() {\n              return this._id;\n          }\n          set id(value) {\n              if (typeof value !== 'string') {\n                  throw new Error('ID must be a string.');\n              }\n              this._id = value;\n          }\n          get lines() {\n              return this._lines;\n          }\n          set lines(value) {\n              if (typeof value !== 'number') {\n                  throw new TypeError('Lines must be set to a number.');\n              }\n              this._lines = value;\n          }\n          get regionAnchorX() {\n              return this._regionAnchorX;\n          }\n          set regionAnchorX(value) {\n              if (!vttvalidator_1.isValidPercentValue(value)) {\n                  throw new TypeError('RegionAnchorX must be between 0 and 100.');\n              }\n              this._regionAnchorX = value;\n          }\n          get regionAnchorY() {\n              return this._regionAnchorY;\n          }\n          set regionAnchorY(value) {\n              if (!vttvalidator_1.isValidPercentValue(value)) {\n                  throw new TypeError('RegionAnchorY must be between 0 and 100.');\n              }\n              this._regionAnchorY = value;\n          }\n          get scroll() {\n              return this._scroll;\n          }\n          set scroll(value) {\n              if (typeof value === 'string') {\n                  const setting = value.toLowerCase();\n                  if (vttvalidator_1.isValidScrollSetting(setting)) {\n                      this._scroll = setting;\n                      return;\n                  }\n              }\n              throw new SyntaxError('An invalid or illegal string was specified.');\n          }\n          get viewportAnchorX() {\n              return this._viewportAnchorX;\n          }\n          set viewportAnchorX(value) {\n              if (!vttvalidator_1.isValidPercentValue(value)) {\n                  throw new TypeError('ViewportAnchorX must be between 0 and 100.');\n              }\n              this._viewportAnchorX = value;\n          }\n          get viewportAnchorY() {\n              return this._viewportAnchorY;\n          }\n          set viewportAnchorY(value) {\n              if (!vttvalidator_1.isValidPercentValue(value)) {\n                  throw new TypeError('ViewportAnchorY must be between 0 and 100.');\n              }\n              this._viewportAnchorY = value;\n          }\n          get width() {\n              return this._width;\n          }\n          set width(value) {\n              if (!vttvalidator_1.isValidPercentValue(value)) {\n                  throw new TypeError('Width must be between 0 and 100.');\n              }\n              this._lines = value;\n          }\n          toJSON() {\n              const json = {};\n              Object.keys(this).forEach((key) => {\n                  if (this.hasOwnProperty(key)) {\n                      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n                      json[key] = this[key];\n                  }\n              });\n              return json;\n          }\n          static create(options) {\n              const region = new this();\n              Object.keys(options).forEach((key) => {\n                  if (region.hasOwnProperty(key)) {\n                      region[key] = options[key];\n                  }\n              });\n              return region;\n          }\n          static fromJSON(json) {\n              return this.create(JSON.parse(json));\n          }\n      };\n      VTTRegion = __decorate([\n          replaceVTTRegion\n      ], VTTRegion);\n      vttregion.VTTRegion = VTTRegion;\n      function replaceVTTRegion(constructor) {\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n          let cls = constructor;\n          if (typeof window !== 'undefined' && window.VTTRegion != null) {\n              cls = window.VTTRegion;\n              cls.create = constructor.create;\n              cls.fromJSON = constructor.fromJSON;\n              cls.prototype.toJSON = constructor.prototype.toJSON;\n          }\n          return cls;\n      }\n    \n      /**\n       * Copyright 2013 vtt.js Contributors\n       *\n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       *   http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       */\n      Object.defineProperty(vttparser, \"__esModule\", { value: true });\n      const vttcue_1$1 = vttcue;\n      vttparser.VTTCue = vttcue_1$1.VTTCue;\n      const vttregion_1 = vttregion;\n      vttparser.VTTRegion = vttregion_1.VTTRegion;\n      const vttparser_utility_1$1 = vttparserUtility;\n      // Creates a new ParserError object from an errorData object. The errorData\n      // object should have default code and message properties. The default message\n      // property can be overridden by passing in a message parameter.\n      // See ParsingError.Errors below for acceptable errors.\n      class ParsingError extends Error {\n          constructor(errorData, message) {\n              super();\n              this.name = 'ParsingError';\n              if (typeof errorData === 'number') {\n                  this.code = errorData;\n              }\n              else {\n                  this.code = errorData.code;\n              }\n              if (message) {\n                  this.message = message;\n              }\n              else if (errorData instanceof ParsingError) {\n                  this.message = errorData.message;\n              }\n          }\n      }\n      vttparser.ParsingError = ParsingError;\n      // ParsingError metadata for acceptable ParsingErrors.\n      ParsingError.Errors = {\n          BadSignature: new ParsingError(0, 'Malformed WebVTT signature.'),\n          BadTimeStamp: new ParsingError(1, 'Malformed time stamp.')\n      };\n      // A settings object holds key/value pairs and will ignore anything but the first\n      // assignment to a specific key.\n      class Settings {\n          constructor() {\n              this.values = {};\n          }\n          // Only accept the first assignment to any key.\n          set(k, v) {\n              if (!this.get(k) && v !== '') {\n                  this.values[k] = v;\n              }\n          }\n          get(k, dflt, defaultKey) {\n              if (typeof dflt === 'object' && typeof defaultKey === 'string') {\n                  return this.has(k) ? this.values[k] : dflt[defaultKey];\n              }\n              return this.has(k) ? this.values[k] : dflt;\n          }\n          // Check whether we have a value for a key.\n          has(k) {\n              return k in this.values;\n          }\n          // Accept a setting if its one of the given alternatives.\n          alt(k, v, a) {\n              for (let n = 0; n < a.length; ++n) {\n                  if (v === a[n]) {\n                      this.set(k, v);\n                      break;\n                  }\n              }\n          }\n          // Accept a setting if its a valid (signed) integer.\n          integer(k, v) {\n              if (/^-?\\d+$/.test(v)) {\n                  this.set(k, parseInt(v, 10));\n              }\n          }\n          // Accept a setting if its a valid percentage.\n          percent(k, v) {\n              const m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/);\n              if (m) {\n                  try {\n                      const vf = parseFloat(v);\n                      if (vf >= 0 && vf <= 100) {\n                          this.set(k, vf);\n                          return true;\n                      }\n                  }\n                  catch (err) {\n                      return false;\n                  }\n              }\n              return false;\n          }\n      }\n      class WebVTTParser {\n          constructor(window, decoder, onStylesParsedCallback) {\n              this.window = window;\n              this.state = 'INITIAL';\n              this.styleCollector = '';\n              this.buffer = '';\n              this.decoder = decoder || new TextDecoder('utf8');\n              this.regionList = [];\n              this.onStylesParsedCallback = onStylesParsedCallback;\n              this._styles = {};\n          }\n          // Helper to allow strings to be decoded instead of the default binary utf8 data.\n          static StringDecoder() {\n              return {\n                  decode: (input) => {\n                      if (!input) {\n                          return '';\n                      }\n                      if (typeof input !== 'string') {\n                          throw new Error('Error - expected string data.');\n                      }\n                      return decodeURIComponent(encodeURIComponent(input));\n                  }\n              };\n          }\n          // If the error is a ParsingError then report it to the consumer if\n          // possible. If it's not a ParsingError then throw it like normal.\n          reportOrThrowError(e) {\n              if (e instanceof ParsingError &&\n                  typeof this.onparsingerror === 'function') {\n                  this.onparsingerror(e);\n              }\n              else {\n                  throw e;\n              }\n          }\n          // Helper function to parse input into groups separated by 'groupDelim', and\n          // interprete each group as a key/value pair separated by 'keyValueDelim'.\n          parseOptions(input, callback, keyValueDelim, groupDelim) {\n              const groups = groupDelim ? input.split(groupDelim) : [input];\n              for (const group of groups) {\n                  if (typeof group !== 'string') {\n                      continue;\n                  }\n                  const kv = group.split(keyValueDelim);\n                  if (kv.length !== 2) {\n                      continue;\n                  }\n                  const k = kv[0];\n                  const v = kv[1];\n                  callback(k, v);\n              }\n          }\n          parseCue(input, cue, regionList) {\n              // Remember the original input if we need to throw an error.\n              const oInput = input;\n              // 4.1 WebVTT timestamp\n              const consumeTimeStamp = () => {\n                  const ts = vttparser_utility_1$1.default.parseTimeStamp(input);\n                  if (ts === null) {\n                      throw new ParsingError(ParsingError.Errors.BadTimeStamp, 'Malformed timestamp: ' + oInput);\n                  }\n                  // Remove time stamp from input.\n                  input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n                  return ts;\n              };\n              // 4.4.2 WebVTT cue settings\n              const consumeCueSettings = (input, cue) => {\n                  const settings = new Settings();\n                  this.parseOptions(input, (k, v) => {\n                      let vals, vals0;\n                      switch (k) {\n                          case 'region':\n                              // Find the last region we parsed with the same region id.\n                              for (let i = regionList.length - 1; i >= 0; i--) {\n                                  if (regionList[i].id === v) {\n                                      settings.set(k, regionList[i].region);\n                                      break;\n                                  }\n                              }\n                              break;\n                          case 'vertical':\n                              settings.alt(k, v, ['rl', 'lr']);\n                              break;\n                          case 'line':\n                              vals = v.split(',');\n                              vals0 = vals[0];\n                              settings.integer(k, vals0);\n                              if (settings.percent(k, vals0)) {\n                                  settings.set('snapToLines', false);\n                              }\n                              settings.alt(k, vals0, ['auto']);\n                              if (vals.length === 2) {\n                                  settings.alt('lineAlign', vals[1], [\n                                      'start',\n                                      'center',\n                                      'end'\n                                  ]);\n                              }\n                              break;\n                          case 'position':\n                              vals = v.split(',');\n                              settings.percent(k, vals[0]);\n                              if (vals.length === 2) {\n                                  let positionAlignSettings = ['line-left', 'line-right',\n                                      'center', 'auto', 'left', 'start', 'middle', 'end', 'right'];\n                                  settings.alt('positionAlign', vals[1], positionAlignSettings);\n                              }\n                              break;\n                          case 'size':\n                              settings.percent(k, v);\n                              break;\n                          case 'align':\n                              let alignSettings = ['start', 'center', 'end', 'left', 'right', 'middle'];\n                              settings.alt(k, v, alignSettings);\n                              break;\n                      }\n                  }, /:/, /\\s/);\n                  // Apply default values for any missing fields.\n                  cue.region = settings.get('region', null);\n                  cue.vertical = settings.get('vertical', '');\n                  // Workaround to rdar://57719277\n                  // Waiting Webkit team to provide a proper fix, tracking in rdar://57778093\n                  cue.line = settings.get('line', typeof cue.line === 'undefined' ? 'auto' : cue.line);\n                  cue.lineAlign = settings.get('lineAlign', 'start');\n                  cue.snapToLines = settings.get('snapToLines', true);\n                  cue.size = settings.get('size', 100);\n                  let tempAlign = settings.get('align', 'center');\n                  cue.align = tempAlign === 'middle' ? 'center' : tempAlign;\n                  cue.position = settings.get('position', 'auto');\n                  let tempPositionAlign = settings.get('positionAlign', {\n                      'start': 'start',\n                      'left': 'start',\n                      'center': 'center',\n                      'right': 'end',\n                      'end': 'end',\n                  }, cue.align // We should default to 'auto' here - but might break in other places\n                  );\n                  let positionAlignMap = {\n                      'start': 'start',\n                      'line-left': 'start',\n                      'left': 'start',\n                      'center': 'center',\n                      'middle': 'center',\n                      'line-right': 'end',\n                      'right': 'end',\n                      'end': 'end',\n                  };\n                  cue.positionAlign = positionAlignMap[tempPositionAlign];\n              };\n              const skipWhitespace = () => {\n                  input = input.replace(/^\\s+/, '');\n              };\n              // 4.1 WebVTT cue timings.\n              skipWhitespace();\n              cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n              skipWhitespace();\n              if (input.substr(0, 3) !== '-->') {\n                  // (3) next characters must match \"-->\"\n                  throw new ParsingError(ParsingError.Errors.BadTimeStamp, `Malformed time stamp (time stamps must be separated by '-->'): ${oInput}`);\n              }\n              input = input.substr(3);\n              skipWhitespace();\n              cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n              // 4.1 WebVTT cue settings list.\n              skipWhitespace();\n              consumeCueSettings(input, cue);\n          }\n          // 3.4 WebVTT region and WebVTT region settings syntax\n          parseRegion(input) {\n              const settings = new Settings();\n              this.parseOptions(input, (k, v) => {\n                  switch (k) {\n                      case 'id':\n                          settings.set(k, v);\n                          break;\n                      case 'width':\n                          settings.percent(k, v);\n                          break;\n                      case 'lines':\n                          settings.integer(k, v);\n                          break;\n                      case 'regionanchor':\n                      case 'viewportanchor': {\n                          const xy = v.split(',');\n                          if (xy.length !== 2) {\n                              break;\n                          }\n                          // We have to make sure both x and y parse, so use a temporary\n                          // settings object here.\n                          const anchor = new Settings();\n                          anchor.percent('x', xy[0]);\n                          anchor.percent('y', xy[1]);\n                          if (!anchor.has('x') || !anchor.has('y')) {\n                              break;\n                          }\n                          settings.set(k + 'X', anchor.get('x'));\n                          settings.set(k + 'Y', anchor.get('y'));\n                          break;\n                      }\n                      case 'scroll':\n                          settings.alt(k, v, ['up']);\n                          break;\n                  }\n              }, /=/, /\\s/);\n              // Create the region, using default values for any values that were not\n              // specified.\n              if (settings.has('id')) {\n                  const region = new vttregion_1.VTTRegion();\n                  region.width = settings.get('width', 100);\n                  region.lines = settings.get('lines', 3);\n                  region.regionAnchorX = settings.get('regionanchorX', 0);\n                  region.regionAnchorY = settings.get('regionanchorY', 100);\n                  region.viewportAnchorX = settings.get('viewportanchorX', 0);\n                  region.viewportAnchorY = settings.get('viewportanchorY', 100);\n                  region.scroll = settings.get('scroll', '');\n                  // Register the region.\n                  if (this.onregion) {\n                      this.onregion(region);\n                  }\n                  // Remember the VTTRegion for later in case we parse any VTTCues that\n                  // reference it.\n                  this.regionList.push({\n                      id: settings.get('id'),\n                      region: region\n                  });\n              }\n          }\n          // 1.3 WebVTT style block syntax\n          // Works on single line CSS only\n          parseStyle(input) {\n              const parseStyles = (css) => {\n                  const rules = {};\n                  const properties = css.split(';');\n                  for (let i = 0; i < properties.length; i++) {\n                      if (properties[i].includes(':')) {\n                          const keyValue = properties[i].split(':', 2);\n                          const key = keyValue[0].trim();\n                          const value = keyValue[1].trim();\n                          if (key !== '' && value !== '') {\n                              rules[key] = value;\n                          }\n                      }\n                  }\n                  return rules;\n              };\n              const blocks = input.split('}');\n              blocks.pop();\n              for (const block of blocks) {\n                  let selector = null;\n                  let styles = null;\n                  const pair = block.split('{');\n                  if (pair[0]) {\n                      selector = pair[0].trim();\n                  }\n                  if (pair[1]) {\n                      styles = parseStyles(pair[1]);\n                  }\n                  if (selector && styles) {\n                      this._styles[selector] = styles;\n                  }\n              }\n              if (this.onStylesParsedCallback) {\n                  this.onStylesParsedCallback(this._styles);\n              }\n          }\n          // 3.2 WebVTT metadata header syntax\n          parseHeader(input) {\n              this.parseOptions(input, function (k, v) {\n                  switch (k) {\n                      case 'Region':\n                          // 3.3 WebVTT region metadata header syntax\n                          this.parseRegion(v);\n                          break;\n                  }\n              }, /:/);\n          }\n          parse(data) {\n              // If there is no data then we won't decode it, but will just try to parse\n              // whatever is in buffer already. This may occur in circumstances, for\n              // example when flush() is called.\n              if (data) {\n                  // Try to decode the data that we received.\n                  this.buffer += this.decoder.decode(data, { stream: true });\n              }\n              const collectNextLine = () => {\n                  const buffer = this.buffer;\n                  let pos = 0;\n                  const calculateBreakPosition = (buffer, index) => {\n                      const breakPosition = { start: -1, length: -1 };\n                      if (buffer[index] === '\\r') {\n                          breakPosition.start = index;\n                          breakPosition.length = 1;\n                      }\n                      else if (buffer[index] === '\\n') {\n                          breakPosition.start = index;\n                          breakPosition.length = 1;\n                      }\n                      else if (buffer[index] === '<') {\n                          if (index + 1 < buffer.length && buffer[index + 1] === 'b') {\n                              if (index + 2 < buffer.length && buffer[index + 2] === 'r') {\n                                  let endPosition = index + 2;\n                                  while (endPosition < buffer.length) {\n                                      if (buffer[endPosition++] === '>') {\n                                          break;\n                                      }\n                                  }\n                                  breakPosition.start = index;\n                                  breakPosition.length = endPosition - index;\n                              }\n                          }\n                      }\n                      return breakPosition;\n                  };\n                  let breakPosition = { start: buffer.length, length: 0 };\n                  while (pos < buffer.length) {\n                      const foundBreakPosition = calculateBreakPosition(buffer, pos);\n                      if (foundBreakPosition.length > 0) {\n                          breakPosition = foundBreakPosition;\n                          break;\n                      }\n                      ++pos;\n                  }\n                  const line = buffer.substr(0, breakPosition.start);\n                  this.buffer = buffer.substr(breakPosition.start + breakPosition.length);\n                  return line;\n              };\n              // 5.1 WebVTT file parsing.\n              try {\n                  let line;\n                  if (this.state === 'INITIAL') {\n                      // We can't start parsing until we have the first line.\n                      if (!/\\r\\n|\\n/.test(this.buffer)) {\n                          return this;\n                      }\n                      line = collectNextLine();\n                      // strip of UTF-8 BOM if any\n                      // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n                      const m = /^(Ã¯Â»Â¿)?WEBVTT([ \\t].*)?$/.exec(line);\n                      if (!m || !m[0]) {\n                          throw new ParsingError(ParsingError.Errors.BadSignature);\n                      }\n                      this.state = 'HEADER';\n                  }\n                  let alreadyCollectedLine = false;\n                  while (this.buffer) {\n                      // We can't parse a line until we have the full line.\n                      if (!/\\r\\n|\\n/.test(this.buffer)) {\n                          return this;\n                      }\n                      if (!alreadyCollectedLine) {\n                          line = collectNextLine();\n                      }\n                      else {\n                          alreadyCollectedLine = false;\n                      }\n                      switch (this.state) {\n                          case 'HEADER':\n                              // 13-18 - Allow a header (metadata) under the WEBVTT line.\n                              if (line.includes(':')) {\n                                  this.parseHeader(line);\n                              }\n                              else if (!line) {\n                                  // An empty line terminates the header and starts the body (cues).\n                                  this.state = 'ID';\n                              }\n                              continue;\n                          case 'NOTE':\n                              // Ignore NOTE blocks.\n                              if (!line) {\n                                  this.state = 'ID';\n                              }\n                              continue;\n                          case 'STYLE':\n                              // Parse style blocks.\n                              if (!line) {\n                                  this.parseStyle(this.styleCollector);\n                                  this.state = 'ID';\n                                  this.styleCollector = '';\n                              }\n                              else {\n                                  this.styleCollector += line;\n                              }\n                              continue;\n                          case 'ID':\n                              // Check for the start of NOTE blocks.\n                              if (/^NOTE($|[ \\t])/.test(line)) {\n                                  this.state = 'NOTE';\n                                  break;\n                              }\n                              if (/^STYLE($|[ \\t])/.test(line)) {\n                                  this.state = 'STYLE';\n                                  break;\n                              }\n                              // 19-29 - Allow any number of line terminators, then initialize new cue values.\n                              if (!line) {\n                                  continue;\n                              }\n                              this.cue = new vttcue_1$1.VTTCue(0, 0, '');\n                              this.state = 'CUE';\n                              // 30-39 - Check if self line contains an optional identifier or timing data.\n                              if (!line.includes('-->')) {\n                                  this.cue.id = line;\n                                  continue;\n                              }\n                          // Process line as start of a cue.\n                          /* falls through */\n                          case 'CUE':\n                              // 40 - Collect cue timings and settings.\n                              try {\n                                  this.parseCue(line, this.cue, this.regionList);\n                              }\n                              catch (e) {\n                                  this.reportOrThrowError(e);\n                                  // In case of an error ignore rest of the cue.\n                                  this.cue = null;\n                                  this.state = 'BADCUE';\n                                  continue;\n                              }\n                              this.state = 'CUETEXT';\n                              continue;\n                          case 'CUETEXT': {\n                              const hasSubstring = line.includes('-->');\n                              // 34 - If we have an empty line then report the cue.\n                              // 35 - If we have the special substring '-->' then report the cue,\n                              // but do not collect the line as we need to process the current\n                              // one as a new cue.\n                              if (!line || hasSubstring) {\n                                  // We are done parsing self cue.\n                                  alreadyCollectedLine = true;\n                                  if (this.oncue) {\n                                      this.oncue(this.cue);\n                                  }\n                                  this.cue = null;\n                                  this.state = 'ID';\n                                  continue;\n                              }\n                              if (this.cue.text) {\n                                  this.cue.text += '\\n';\n                              }\n                              this.cue.text += line;\n                              continue;\n                          }\n                          case 'BADCUE': // BADCUE\n                              // 54-62 - Collect and discard the remaining cue.\n                              if (!line) {\n                                  this.state = 'ID';\n                              }\n                              continue;\n                      }\n                  }\n              }\n              catch (e) {\n                  this.reportOrThrowError(e);\n                  // If we are currently parsing a cue, report what we have.\n                  if (this.state === 'CUETEXT' && this.cue && this.oncue) {\n                      this.oncue(this.cue);\n                  }\n                  this.cue = null;\n                  // Enter BADWEBVTT state if header was not parsed correctly otherwise\n                  // another exception occurred so enter BADCUE state.\n                  this.state = this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n              }\n              return this;\n          }\n          flush() {\n              try {\n                  // Finish decoding the stream.\n                  this.buffer += this.decoder.decode();\n                  // Synthesize the end of the current cue or region.\n                  if (this.cue || this.state === 'HEADER') {\n                      this.buffer += '\\n\\n';\n                      this.parse();\n                  }\n                  // If we've flushed, parsed, and we're still on the INITIAL state then\n                  // that means we don't have enough of the stream to parse the first\n                  // line.\n                  if (this.state === 'INITIAL') {\n                      throw new ParsingError(ParsingError.Errors.BadSignature);\n                  }\n              }\n              catch (e) {\n                  this.reportOrThrowError(e);\n              }\n              if (this.onflush) {\n                  this.onflush();\n              }\n              return this;\n          }\n          styles() {\n              return this._styles;\n          }\n      }\n      vttparser.default = WebVTTParser;\n      vttparser.WebVTTParser = WebVTTParser;\n    \n      var vtthtmlrenderer = {};\n    \n      /**\n       * Copyright 2013 vtt.js Contributors\n       *\n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       *   http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       */\n      Object.defineProperty(vtthtmlrenderer, \"__esModule\", { value: true });\n      const vttcue_1 = vttcue;\n      vtthtmlrenderer.VTTCue = vttcue_1.VTTCue;\n      const vttparser_utility_1 = vttparserUtility;\n      const CUE_BACKGROUND_PADDING = '1.5%';\n      const OVERLAP_PADDING = 0; // Pixels\n      const PERCENT_EDGE_OFFSET = 0.05;\n      const MAX_PLACEMENT_ATTEMPTS = 10;\n      const DEFAULT_LINE_HEIGHT = 41; // line height for 36px Helvetica font\n      const foregroundStyleSelector = '::cue';\n      const backgroundStyleSelector = '::-webkit-media-text-track-display';\n      const classSelectorRegex = /^(::cue\\()(\\..*)(\\))/;\n      const idSelectorRegex = /^(::cue\\()(#.*)(\\))/;\n      const typeSelectorRegex = /^(::cue\\()(c|i|b|u|ruby|rt|v|lang)(\\))/;\n      const globalStyleRegex = [\n          classSelectorRegex,\n          idSelectorRegex,\n          typeSelectorRegex\n      ];\n      // This is a list of all the Unicode characters that have a strong\n      // right-to-left category. What this means is that these characters are\n      // written right-to-left for sure. It was generated by pulling all the strong\n      // right-to-left characters out of the Unicode data table. That table can\n      // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt\n      const strongRTLRanges = [\n          [0x5be, 0x5be],\n          [0x5c0, 0x5c0],\n          [0x5c3, 0x5c3],\n          [0x5c6, 0x5c6],\n          [0x5d0, 0x5ea],\n          [0x5f0, 0x5f4],\n          [0x608, 0x608],\n          [0x60b, 0x60b],\n          [0x60d, 0x60d],\n          [0x61b, 0x61b],\n          [0x61e, 0x64a],\n          [0x66d, 0x66f],\n          [0x671, 0x6d5],\n          [0x6e5, 0x6e6],\n          [0x6ee, 0x6ef],\n          [0x6fa, 0x70d],\n          [0x70f, 0x710],\n          [0x712, 0x72f],\n          [0x74d, 0x7a5],\n          [0x7b1, 0x7b1],\n          [0x7c0, 0x7ea],\n          [0x7f4, 0x7f5],\n          [0x7fa, 0x7fa],\n          [0x800, 0x815],\n          [0x81a, 0x81a],\n          [0x824, 0x824],\n          [0x828, 0x828],\n          [0x830, 0x83e],\n          [0x840, 0x858],\n          [0x85e, 0x85e],\n          [0x8a0, 0x8a0],\n          [0x8a2, 0x8ac],\n          [0x200f, 0x200f],\n          [0xfb1d, 0xfb1d],\n          [0xfb1f, 0xfb28],\n          [0xfb2a, 0xfb36],\n          [0xfb38, 0xfb3c],\n          [0xfb3e, 0xfb3e],\n          [0xfb40, 0xfb41],\n          [0xfb43, 0xfb44],\n          [0xfb46, 0xfbc1],\n          [0xfbd3, 0xfd3d],\n          [0xfd50, 0xfd8f],\n          [0xfd92, 0xfdc7],\n          [0xfdf0, 0xfdfc],\n          [0xfe70, 0xfe74],\n          [0xfe76, 0xfefc],\n          [0x10800, 0x10805],\n          [0x10808, 0x10808],\n          [0x1080a, 0x10835],\n          [0x10837, 0x10838],\n          [0x1083c, 0x1083c],\n          [0x1083f, 0x10855],\n          [0x10857, 0x1085f],\n          [0x10900, 0x1091b],\n          [0x10920, 0x10939],\n          [0x1093f, 0x1093f],\n          [0x10980, 0x109b7],\n          [0x109be, 0x109bf],\n          [0x10a00, 0x10a00],\n          [0x10a10, 0x10a13],\n          [0x10a15, 0x10a17],\n          [0x10a19, 0x10a33],\n          [0x10a40, 0x10a47],\n          [0x10a50, 0x10a58],\n          [0x10a60, 0x10a7f],\n          [0x10b00, 0x10b35],\n          [0x10b40, 0x10b55],\n          [0x10b58, 0x10b72],\n          [0x10b78, 0x10b7f],\n          [0x10c00, 0x10c48],\n          [0x1ee00, 0x1ee03],\n          [0x1ee05, 0x1ee1f],\n          [0x1ee21, 0x1ee22],\n          [0x1ee24, 0x1ee24],\n          [0x1ee27, 0x1ee27],\n          [0x1ee29, 0x1ee32],\n          [0x1ee34, 0x1ee37],\n          [0x1ee39, 0x1ee39],\n          [0x1ee3b, 0x1ee3b],\n          [0x1ee42, 0x1ee42],\n          [0x1ee47, 0x1ee47],\n          [0x1ee49, 0x1ee49],\n          [0x1ee4b, 0x1ee4b],\n          [0x1ee4d, 0x1ee4f],\n          [0x1ee51, 0x1ee52],\n          [0x1ee54, 0x1ee54],\n          [0x1ee57, 0x1ee57],\n          [0x1ee59, 0x1ee59],\n          [0x1ee5b, 0x1ee5b],\n          [0x1ee5d, 0x1ee5d],\n          [0x1ee5f, 0x1ee5f],\n          [0x1ee61, 0x1ee62],\n          [0x1ee64, 0x1ee64],\n          [0x1ee67, 0x1ee6a],\n          [0x1ee6c, 0x1ee72],\n          [0x1ee74, 0x1ee77],\n          [0x1ee79, 0x1ee7c],\n          [0x1ee7e, 0x1ee7e],\n          [0x1ee80, 0x1ee89],\n          [0x1ee8b, 0x1ee9b],\n          [0x1eea1, 0x1eea3],\n          [0x1eea5, 0x1eea9],\n          [0x1eeab, 0x1eebb],\n          [0x10fffd, 0x10fffd]\n      ];\n      class StyleBox {\n          // Apply styles to a div. If there is no div passed then it defaults to the\n          // div on 'this'.\n          applyStyles(styles, div) {\n              div = div || this.div;\n              for (const prop in styles) {\n                  if (styles.hasOwnProperty(prop)) {\n                      div.style[prop] = styles[prop];\n                  }\n              }\n          }\n          formatStyle(val, unit) {\n              return val === 0 ? '0' : val + unit;\n          }\n      }\n      vtthtmlrenderer.StyleBox = StyleBox;\n      // Constructs the computed display state of the cue (a div). Places the div\n      // into the overlay which should be a block level element (usually a div).\n      class CueStyleBox extends StyleBox {\n          constructor(window, cue, foregroundStyleOptions, backgroundStyleOptions, globalStyleCollection) {\n              super();\n              this.cue = cue;\n              let textAlignMap = {\n                  'start': 'left',\n                  'line-left': 'left',\n                  'left': 'left',\n                  'center': 'center',\n                  'middle': 'center',\n                  'line-right': 'right',\n                  'right': 'right',\n                  'end': 'right',\n              };\n              let textAlign = textAlignMap[cue.positionAlign] || cue.align;\n              let styles = {\n                  textAlign: textAlign,\n                  whiteSpace: 'pre-line',\n                  position: 'absolute'\n              };\n              styles.direction = this.determineBidi(this.cueDiv);\n              styles.writingMode = this.directionSettingToWritingMode(cue.vertical);\n              styles.unicodeBidi = 'plaintext';\n              // Create an absolutely positioned div that will be used to position the cue\n              // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS\n              // mirrors of them except \"middle\" which is \"center\" in CSS.\n              this.div = window.document.createElement('div');\n              this.applyStyles(styles);\n              styles = {\n                  backgroundColor: backgroundStyleOptions.backgroundColor,\n                  display: 'inline-block'\n              };\n              // If the background opacity is 0 or undefined don't want to increase\n              // the cue size by adding padding to the background div\n              if (this.parseOpacity(styles.backgroundColor)) {\n                  styles.padding = '5px';\n                  styles.borderRadius = '5px';\n              }\n              this.backgroundDiv = window.document.createElement('div');\n              this.applyStyles(styles, this.backgroundDiv);\n              styles = {\n                  color: foregroundStyleOptions.color,\n                  backgroundColor: foregroundStyleOptions.backgroundColor,\n                  textShadow: foregroundStyleOptions.textShadow,\n                  fontSize: foregroundStyleOptions.fontSize,\n                  fontFamily: foregroundStyleOptions.fontFamily,\n                  position: 'relative',\n                  left: '0',\n                  right: '0',\n                  top: '0',\n                  bottom: '0',\n                  display: 'inline-block',\n                  textOrientation: 'upright'\n              };\n              styles.writingMode = this.directionSettingToWritingMode(cue.vertical);\n              styles.unicodeBidi = 'plaintext';\n              // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will\n              // have inline-block positioning and will function as the cue foreground box.\n              this.cueDiv = vttparser_utility_1.default.parseContent(window, cue, globalStyleCollection);\n              this.applyStyles(styles, this.cueDiv);\n              this.backgroundDiv.appendChild(this.cueDiv);\n              this.div.appendChild(this.backgroundDiv);\n              // Calculate the distance from the reference edge of the viewport to the text\n              // position of the cue box. The reference edge will be resolved later when\n              // the box orientation styles are applied.\n              let textPos = 0;\n              if (typeof cue.position === 'number') {\n                  let cueAlignment = cue.positionAlign || cue.align;\n                  if (cueAlignment) {\n                      switch (cueAlignment) {\n                          case 'start':\n                          case 'left':\n                              textPos = cue.position;\n                              break;\n                          case 'center':\n                          case 'middle':\n                              textPos = cue.position - cue.size / 2;\n                              break;\n                          case 'end':\n                          case 'right':\n                              textPos = cue.position - cue.size;\n                              break;\n                      }\n                  }\n              }\n              // Horizontal box orientation; textPos is the distance from the left edge of the\n              // area to the left edge of the box and cue.size is the distance extending to\n              // the right from there.\n              if (cue.vertical === '') {\n                  this.applyStyles({\n                      left: this.formatStyle(textPos, '%'),\n                      width: this.formatStyle(cue.size, '%')\n                  });\n                  // Vertical box orientation; textPos is the distance from the top edge of the\n                  // area to the top edge of the box and cue.size is the height extending\n                  // downwards from there.\n              }\n              else {\n                  this.applyStyles({\n                      top: this.formatStyle(textPos, '%'),\n                      height: this.formatStyle(cue.size, '%')\n                  });\n              }\n          }\n          determineBidi(cueDiv) {\n              let nodeStack = [];\n              let text = '';\n              let charCode;\n              if (!cueDiv || !cueDiv.childNodes) {\n                  return 'ltr';\n              }\n              function pushNodes(nodeStack, node) {\n                  for (let i = node.childNodes.length - 1; i >= 0; i--) {\n                      nodeStack.push(node.childNodes[i]);\n                  }\n              }\n              function nextTextNode(nodeStack) {\n                  if (!nodeStack || !nodeStack.length) {\n                      return null;\n                  }\n                  let node = nodeStack.pop();\n                  let text = node.textContent || node.innerText;\n                  if (text) {\n                      // TODO: This should match all unicode type B characters (paragraph\n                      // separator characters). See issue #115.\n                      const m = /^.*(\\n|\\r)/.exec(text);\n                      if (m) {\n                          nodeStack.length = 0;\n                          return m[0];\n                      }\n                      return text;\n                  }\n                  if (node.tagName === 'ruby') {\n                      return nextTextNode(nodeStack);\n                  }\n                  if (node.childNodes) {\n                      pushNodes(nodeStack, node);\n                      return nextTextNode(nodeStack);\n                  }\n              }\n              function isContainedInCharacterList(charCode, characterList) {\n                  for (const currentRange of characterList) {\n                      if (charCode >= currentRange[0] && charCode <= currentRange[1]) {\n                          return true;\n                      }\n                  }\n                  return false;\n              }\n              pushNodes(nodeStack, cueDiv);\n              while ((text = nextTextNode(nodeStack))) {\n                  for (let i = 0; i < text.length; i++) {\n                      charCode = text.charCodeAt(i);\n                      if (isContainedInCharacterList(charCode, strongRTLRanges)) {\n                          return 'rtl';\n                      }\n                  }\n              }\n              return 'ltr';\n          }\n          parseOpacity(colorString) {\n              if (!colorString || typeof colorString !== 'string') {\n                  return null;\n              }\n              // Trim whitespace, strip out \"rgba(\" and \")\" from the string\n              colorString = colorString.replace(/ /g, '').replace('rgba(', '').replace(')', '');\n              // Split r, g, b, a into an array for easier processing - we just need the opacity\n              const parts = colorString.split(',');\n              if (parts && parts.length >= 4) {\n                  return parts[3];\n              }\n              return null;\n          }\n          directionSettingToWritingMode(directionSetting) {\n              if (directionSetting === '') {\n                  return 'horizontal-tb';\n              }\n              else if (directionSetting === 'lr') {\n                  return 'vertical-lr';\n              }\n              else {\n                  return 'vertical-rl';\n              }\n          }\n          move(box) {\n              this.applyStyles({\n                  top: this.formatStyle(box.top, 'px'),\n                  bottom: this.formatStyle(box.bottom, 'px'),\n                  left: this.formatStyle(box.left, 'px'),\n                  right: this.formatStyle(box.right, 'px'),\n                  height: this.formatStyle(box.height, 'px'),\n                  width: this.formatStyle(box.width, 'px')\n              });\n          }\n      }\n      vtthtmlrenderer.CueStyleBox = CueStyleBox;\n      // Represents the co-ordinates of an Element in a way that we can easily\n      // compute things with such as if it overlaps or intersects with another Element.\n      // Can initialize it with either a StyleBox or another BoxPosition.\n      class BoxPosition {\n          constructor(obj) {\n              function isVertical(cue) {\n                  return cue && cue.vertical !== '';\n              }\n              if (obj instanceof CueStyleBox && obj.cue) {\n                  if (isVertical(obj.cue)) {\n                      this.property = 'width';\n                  }\n                  else {\n                      this.property = 'height';\n                  }\n              }\n              else if (obj instanceof BoxPosition) {\n                  this.property = obj.property || 'height';\n              }\n              // Either a BoxPosition was passed in and we need to copy it, or a StyleBox\n              // was passed in and we need to copy the results of 'getBoundingClientRect'\n              // as the object returned is readonly. All co-ordinate values are in reference\n              // to the viewport origin (top left).\n              let lh, slh, height, width, top, rect;\n              if (obj instanceof CueStyleBox && obj.div) {\n                  height = obj.div.offsetHeight;\n                  width = obj.div.offsetWidth;\n                  top = obj.div.offsetTop;\n                  const outerDiv = obj.div.firstChild;\n                  // When we're initializing a BoxPosition with a CueStyleBox want to use the child element which just has\n                  // the width / length of the text, otherwise the full length will overflow outside of the container\n                  // causing the CueStyleBox.within function to return false, and then the overlap algorithm to fail\n                  if (outerDiv) {\n                      rect = outerDiv.getBoundingClientRect();\n                  }\n                  else {\n                      rect = obj.div.getBoundingClientRect();\n                  }\n                  lh = (rect && rect[this.property]) || null;\n                  if (outerDiv && outerDiv.firstChild) {\n                      const innerDiv = outerDiv.firstChild;\n                      if (innerDiv && typeof innerDiv.textContent === 'string') {\n                          const numOfLines = this.calculateNewLines(innerDiv.textContent);\n                          slh = lh / numOfLines;\n                      }\n                  }\n              }\n              else if (obj instanceof BoxPosition) {\n                  rect = obj;\n              }\n              this.left = rect.left;\n              this.right = rect.right;\n              this.top = rect.top || top;\n              this.height = rect.height || height;\n              this.bottom = rect.bottom || top + (rect.height || height);\n              this.width = rect.width || width;\n              this.lineHeight = lh !== null ? lh : rect.lineHeight;\n              this.singleLineHeight = slh !== null ? slh : rect.singleLineHeight;\n              if (!this.singleLineHeight) {\n                  this.singleLineHeight = DEFAULT_LINE_HEIGHT;\n              }\n          }\n          calculateNewLines(str) {\n              let numOfLines = 1;\n              for (let i = 0; i < str.length; i++) {\n                  if (str[i] === '\\n') {\n                      numOfLines++;\n                  }\n              }\n              return numOfLines;\n          }\n          // Move the box along a particular axis. Optionally pass in an amount to move\n          // the box. If no amount is passed then the default is the line height of the\n          // box.\n          move(axis, toMove) {\n              toMove = toMove !== undefined ? toMove : this.singleLineHeight;\n              switch (axis) {\n                  case '+x':\n                      this.left += toMove;\n                      this.right += toMove;\n                      break;\n                  case '-x':\n                      this.left -= toMove;\n                      this.right -= toMove;\n                      break;\n                  case '+y':\n                      this.top += toMove;\n                      this.bottom += toMove;\n                      break;\n                  case '-y':\n                      this.top -= toMove;\n                      this.bottom -= toMove;\n                      break;\n              }\n          }\n          // Check if this box overlaps another box, b2.\n          overlaps(b2) {\n              return (this.left < b2.right &&\n                  this.right > b2.left &&\n                  this.top < b2.bottom &&\n                  this.bottom > b2.top);\n          }\n          // Check if this box overlaps any other boxes in boxes.\n          overlapsAny(boxes) {\n              for (const box of boxes) {\n                  if (this.overlaps(box)) {\n                      return true;\n                  }\n              }\n              return false;\n          }\n          // Check if this box is within another box.\n          within(container) {\n              return (this.top >= container.top &&\n                  this.bottom <= container.bottom &&\n                  this.left >= container.left &&\n                  this.right <= container.right);\n          }\n          // Check if this box is entirely within the container or it is overlapping\n          // on the edge opposite of the axis direction passed. For example, if \"+x\" is\n          // passed and the box is overlapping on the left edge of the container, then\n          // move the left edge of the box to align with the left edge of the container\n          moveIfOutOfBounds(container, axis) {\n              switch (axis) {\n                  case '+x':\n                      if (this.left < container.left) {\n                          this.left = container.left;\n                          this.right = this.left + this.width;\n                      }\n                      break;\n                  case '-x':\n                      if (this.right > container.right) {\n                          this.right = container.right;\n                          this.left = this.right - this.width;\n                      }\n                      break;\n                  case '+y':\n                      if (this.top < container.top) {\n                          this.top = container.top;\n                          this.bottom = this.top + this.height;\n                      }\n                      break;\n                  case '-y':\n                      if (this.bottom > container.bottom) {\n                          this.bottom = container.bottom;\n                          this.top = this.bottom - this.height;\n                      }\n                      break;\n              }\n          }\n          // Convert the positions from this box to CSS compatible positions using\n          // the reference container's positions. This has to be done because this\n          // box's positions are in reference to the viewport origin, whereas, CSS\n          // values are in reference to their respective edges.\n          toCSSCompatValues(reference) {\n              return {\n                  top: this.top - reference.top,\n                  bottom: reference.bottom - this.bottom,\n                  left: this.left - reference.left,\n                  right: reference.right - this.right,\n                  height: this.height,\n                  width: this.width\n              };\n          }\n          // Get an object that represents the box's position without anything extra.\n          // Can pass a StyleBox or HTMLElement.\n          static getSimpleBoxPosition(obj) {\n              let element = null;\n              if (obj instanceof StyleBox && obj.div) {\n                  element = obj.div;\n              }\n              else if (obj instanceof HTMLElement) {\n                  element = obj;\n              }\n              let height = element.offsetHeight || 0;\n              let width = element.offsetWidth || 0;\n              let top = element.offsetTop || 0;\n              let bottom = top + height;\n              let rect = element.getBoundingClientRect();\n              const { left, right } = rect;\n              if (rect.top) {\n                  top = rect.top;\n              }\n              if (rect.height) {\n                  height = rect.height;\n              }\n              if (rect.width) {\n                  width = rect.width;\n              }\n              if (rect.bottom) {\n                  bottom = rect.bottom;\n              }\n              return { left, right, top, height, bottom, width };\n          }\n          static getBoxPosition(boxPositions, direction) {\n              if (boxPositions && boxPositions.length > 0) {\n                  let savedIndex = 0;\n                  let maxValue = boxPositions[0][direction];\n                  for (let i = 0; i < boxPositions.length; i++) {\n                      if (direction in ['top', 'right']) {\n                          if (boxPositions[i][direction] > maxValue) {\n                              savedIndex = i;\n                              maxValue = boxPositions[i][direction];\n                          }\n                      }\n                      else if (direction in ['bottom', 'left']) {\n                          if (boxPositions[i][direction] < maxValue) {\n                              savedIndex = i;\n                              maxValue = boxPositions[i][direction];\n                          }\n                      }\n                  }\n                  return boxPositions[savedIndex];\n              }\n              else {\n                  return null;\n              }\n          }\n          // Move our box (cue), b, so there's no overlap with any other cues along that axis\n          // For example, if our axis is +y, we'll want to place our box right above the top-most cue\n          static moveToMinimumDistancePlacement(b, axis, boxes) {\n              if (b.property === 'height') {\n                  if (axis === '+y') {\n                      b.top = boxes.topMostBoxPosition.bottom + OVERLAP_PADDING;\n                      b.bottom = b.top + b.height;\n                  }\n                  else if (axis === '-y') {\n                      b.bottom = boxes.bottomMostBoxPosition.top - OVERLAP_PADDING;\n                      b.top = b.bottom - b.height;\n                  }\n                  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n              }\n              else if (b.property === 'width') {\n                  if (axis === '+x') {\n                      b.left = boxes.rightMostBoxPosition.right + OVERLAP_PADDING;\n                      b.right = b.left + b.width;\n                  }\n                  else if (axis === '-x') {\n                      b.right = boxes.leftMostBoxPosition.left - OVERLAP_PADDING;\n                      b.left = b.right - b.width;\n                  }\n              }\n          }\n          // Move a StyleBox to its specified, or next best, position. The containerBox\n          // is the box that contains the StyleBox, such as a div. boxPositions are\n          // a list of other boxes that the styleBox can't overlap with.\n          static moveBoxToLinePosition(styleBox, containerBox, boxPositions) {\n              // Find the best position for a cue box, b, on the video. The axis parameter\n              // is a list of axis, the order of which, it will move the box along. For example:\n              // Passing [\"+x\", \"-x\"] will move the box first along the x axis in the positive\n              // direction. If it doesn't find a good position for it there it will then move\n              // it along the x axis in the negative direction.\n              function findBestPosition(b, axis) {\n                  let minimumDistanceBoxes;\n                  for (let i = 0; i < axis.length; i++) {\n                      // Step 1. check if our current cue is within our render area boundary and re-position our cue if needed\n                      b.moveIfOutOfBounds(containerBox, axis[i]);\n                      // We'll do our best to place the next cue, but want\n                      // another way to exit this while loop in case we get stuck\n                      let currentAttempt = 0;\n                      let attemptedMinimumDistancePlacement = false;\n                      // Step 2. check if our current cue overlaps any other cues and re-position our cue if needed\n                      while (b.overlapsAny(boxPositions)) {\n                          if (currentAttempt > MAX_PLACEMENT_ATTEMPTS - 1) {\n                              break;\n                          }\n                          if (!attemptedMinimumDistancePlacement) {\n                              if (boxPositions && boxPositions.length > 0) {\n                                  // Calculating here so we don't spend time on this calculation unless there was collision\n                                  if (!minimumDistanceBoxes) {\n                                      minimumDistanceBoxes = {\n                                          topMostBoxPosition: BoxPosition.getBoxPosition(boxPositions, 'top'),\n                                          bottomMostBoxPosition: BoxPosition.getBoxPosition(boxPositions, 'bottom'),\n                                          leftMostBoxPosition: BoxPosition.getBoxPosition(boxPositions, 'left'),\n                                          rightMostBoxPosition: BoxPosition.getBoxPosition(boxPositions, 'right')\n                                      };\n                                  }\n                                  BoxPosition.moveToMinimumDistancePlacement(b, axis[i], minimumDistanceBoxes);\n                              }\n                              attemptedMinimumDistancePlacement = true;\n                          }\n                          else {\n                              b.move(axis[i]);\n                          }\n                          currentAttempt++;\n                      }\n                  }\n                  // Our original position if we were already in bounds and\n                  // didn't overlap with other cues, otherwise was moved by above\n                  return b;\n              }\n              function computeLinePos(cue) {\n                  if (typeof cue.line === 'number' &&\n                      (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {\n                      return cue.line;\n                  }\n                  if (!cue.track ||\n                      !cue.track.textTrackList ||\n                      !cue.track.textTrackList.mediaElement) {\n                      return -1;\n                  }\n                  let count = 0;\n                  const track = cue.track, trackList = track.textTrackList;\n                  for (let i = 0; i < trackList.length && trackList[i] !== track; i++) {\n                      if (trackList[i].mode === 'showing') {\n                          count++;\n                      }\n                  }\n                  return ++count * -1;\n              }\n              const cue = styleBox.cue;\n              let boxPosition = new BoxPosition(styleBox), linePos = computeLinePos(cue), axis = [], size;\n              // If we have a line number to align the cue to.\n              if (cue.snapToLines) {\n                  let position = 0;\n                  switch (cue.vertical) {\n                      case '':\n                          axis = ['+y', '-y'];\n                          size = 'height';\n                          break;\n                      case 'rl':\n                          axis = ['+x', '-x'];\n                          size = 'width';\n                          break;\n                      case 'lr':\n                          axis = ['-x', '+x'];\n                          size = 'width';\n                          break;\n                  }\n                  const step = boxPosition.lineHeight, maxPosition = containerBox[size] + step, initialAxis = axis[0];\n                  // If computed line position returns negative then line numbers are\n                  // relative to the bottom of the video instead of the top. Therefore, we\n                  // need to increase our initial position by the length or width of the\n                  // video, depending on the writing direction, and reverse our axis directions.\n                  // Provide a reasonable automatic position that is closest to the \"towards direction\"\n                  if (linePos < 0) {\n                      let initialOffset = 0;\n                      switch (cue.vertical) {\n                          case '':\n                              initialOffset = containerBox.height - step - containerBox.height * PERCENT_EDGE_OFFSET; // default to bottom\n                              break;\n                          // Depending on positioning, chromium will fip layout when writing-mode:vertical-rl is set\n                          // https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/core/layout/README.md\n                          // In this case, chromium writing-mode:vertical-lr property defaults the div to the left, and writing-mode:vertical-rl defaults the div to the right\n                          // For WebVTT default values we want to render the initial values at the opposite end, so will use the equations below to adjust\n                          case 'rl':\n                              initialOffset = -containerBox.width + step + containerBox.width * PERCENT_EDGE_OFFSET; // rl: 100% <----- 0%; default to left\n                              break;\n                          case 'lr':\n                              initialOffset = -containerBox.width + step + containerBox.width * PERCENT_EDGE_OFFSET; // lr: 0% -----> 100%; default to right\n                              break;\n                      }\n                      position = initialOffset;\n                      axis = axis.reverse();\n                  }\n                  else {\n                      // We have been given an actual line position. Calculate appropriate layout.\n                      switch (cue.vertical) {\n                          case '':\n                              position = step * Math.round(linePos); // step down from top\n                              break;\n                          case 'rl':\n                              position = containerBox.width - step * Math.round(linePos); // step down from right side\n                              break;\n                          case 'lr':\n                              position = step * Math.round(linePos); // step down from left side\n                              break;\n                      }\n                      // If the specified initial position is greater then the max position then\n                      // clamp the box to the amount of steps it would take for the box to\n                      // reach the max position.\n                      if (Math.abs(position) > maxPosition) {\n                          position = position < 0 ? -1 : 1;\n                          position *= Math.ceil(maxPosition / step) * step;\n                      }\n                  }\n                  // Move the box to the specified position. This may not be its best position.\n                  boxPosition.move(initialAxis, position);\n              }\n              else {\n                  // If we have a percentage line value for the cue.\n                  const percentageBase = cue.vertical === '' ? containerBox.height : containerBox.width;\n                  const calculatedPercentage = (boxPosition.lineHeight / percentageBase) * 100;\n                  switch (cue.lineAlign) {\n                      case 'center':\n                          linePos -= calculatedPercentage / 2;\n                          break;\n                      case 'end':\n                          linePos -= calculatedPercentage;\n                          break;\n                  }\n                  // Apply initial line position to the cue box.\n                  switch (cue.vertical) {\n                      case '':\n                          styleBox.applyStyles({\n                              top: styleBox.formatStyle(linePos, '%') // step down from top\n                          });\n                          break;\n                      case 'rl':\n                          styleBox.applyStyles({\n                              right: styleBox.formatStyle(linePos, '%') // step down from right\n                          });\n                          break;\n                      case 'lr':\n                          styleBox.applyStyles({\n                              left: styleBox.formatStyle(linePos, '%') // step down from left\n                          });\n                          break;\n                  }\n                  axis = ['+y', '-y', '+x', '-x'];\n                  // Using this as a hint of which direction we want to place the next cues\n                  // Only doing this for horizontally positioned subtitles for now\n                  // TODO: rdar://50386682 (Improve overlap rendering for vertical subtitles [Nice to Have])\n                  if (cue.axis === '+y') {\n                      axis = ['+y', '-y', '+x', '-x'];\n                  }\n                  else if (cue.axis === '-y') {\n                      axis = ['-y', '+y', '+x', '-x'];\n                  }\n                  // Get the box position again after we've applied the specified positioning to it.\n                  boxPosition = new BoxPosition(styleBox);\n              }\n              const bestPosition = findBestPosition(boxPosition, axis);\n              styleBox.move(bestPosition.toCSSCompatValues(containerBox));\n          }\n      }\n      vtthtmlrenderer.BoxPosition = BoxPosition;\n      class WebVTTRenderer {\n          constructor(window, overlay, loggingEnabled = true) {\n              if (!window) {\n                  return null;\n              }\n              this.window = window;\n              this.overlay = overlay;\n              this.loggingEnabled = loggingEnabled;\n              this.foregroundStyleOptions = {\n                  fontFamily: 'Helvetica',\n                  fontSize: '36px',\n                  color: 'rgba(255, 255, 255, 1)',\n                  textShadow: '',\n                  backgroundColor: 'rgba(0, 0, 0, 0)' // Text Highlight\n              };\n              this.backgroundStyleOptions = {\n                  backgroundColor: 'rgba(0, 0, 0, 0.5)'\n              };\n              this.globalStyleCollection = {};\n              const paddedOverlay = window.document.createElement('div');\n              paddedOverlay.style.position = 'absolute';\n              paddedOverlay.style.left = '0';\n              paddedOverlay.style.right = '0';\n              paddedOverlay.style.top = '0';\n              paddedOverlay.style.bottom = '0';\n              paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;\n              this.paddedOverlay = paddedOverlay;\n              overlay.appendChild(this.paddedOverlay);\n              this.initSubtitleCSS();\n          }\n          /**\n           * Sometimes, certain CSS isn't being applied to the first cue rendered\n           * We can init some of the CSS here by rendering a dummy cue\n           */\n          initSubtitleCSS() {\n              const dummyCue = new vttcue_1.VTTCue(0, 0, `String to init CSS - Won't be visible to user`);\n              const dummyCueTextTrack = [dummyCue];\n              // Hide the overlay so we don't get a flash of the text\n              this.paddedOverlay.style.opacity = '0';\n              this.processCues(dummyCueTextTrack);\n              this.processCues([]);\n              this.paddedOverlay.style.opacity = '1';\n          }\n          convertCueToDOMTree(cue) {\n              if (!cue) {\n                  return null;\n              }\n              return vttparser_utility_1.default.parseContent(this.window, cue, this.globalStyleCollection);\n          }\n          setStyles(styles) {\n              function applyStyles(collection, newStyles, confine) {\n                  for (const prop in newStyles) {\n                      if (newStyles.hasOwnProperty(prop)) {\n                          if (confine === true && collection[prop] !== undefined) {\n                              collection[prop] = newStyles[prop];\n                          }\n                          else if (confine === false) {\n                              collection[prop] = newStyles[prop];\n                          }\n                      }\n                  }\n              }\n              for (const selector in styles) {\n                  let confinedStyleOption = false;\n                  let styleOptions = null;\n                  if (selector === foregroundStyleSelector) {\n                      styleOptions = this.foregroundStyleOptions;\n                      confinedStyleOption = true;\n                  }\n                  else if (selector === backgroundStyleSelector) {\n                      styleOptions = this.backgroundStyleOptions;\n                      confinedStyleOption = true;\n                  }\n                  const selectorStyles = styles[selector];\n                  if (confinedStyleOption === true) {\n                      // Limited set of allowed styles to update\n                      applyStyles(styleOptions, selectorStyles, confinedStyleOption);\n                  }\n                  else {\n                      // Styles with a selector. Parse out selector: ::cue(<some selector>)\n                      for (let index = 0; index < globalStyleRegex.length; index++) {\n                          const regex = globalStyleRegex[index];\n                          const match = regex.exec(selector);\n                          if (match && match.length === 4) {\n                              const newSelector = match[2];\n                              const newCollection = {};\n                              applyStyles(newCollection, selectorStyles, confinedStyleOption);\n                              this.globalStyleCollection[newSelector] = newCollection;\n                          }\n                      }\n                  }\n              }\n              this.initSubtitleCSS();\n              if (this.loggingEnabled) {\n                  console.log('WebVTTRenderer setStyles foregroundStyleOptions: ' + JSON.stringify(this.foregroundStyleOptions));\n                  console.log('WebVTTRenderer setStyles backgroundStyleOptions: ' + JSON.stringify(this.backgroundStyleOptions));\n                  console.log('WebVTTRenderer setStyles globalStyleCollection: ' + JSON.stringify(this.globalStyleCollection));\n              }\n          }\n          /**\n           * Runs the WebVTT processing model over the cues passed to it.\n           * See https://www.w3.org/TR/webvtt1/#rendering for implementation details.\n           *\n           * @param {VTTCue|TextTrackCueList} cues list of cues to be rendered\n           */\n          processCues(cues) {\n              if (!cues) {\n                  return;\n              }\n              // Remove all previous children.\n              while (this.paddedOverlay.firstChild) {\n                  this.paddedOverlay.removeChild(this.paddedOverlay.firstChild);\n              }\n              function sortCues(cues) {\n                  const cueList = [];\n                  let avgLine = 0;\n                  for (let i = 0; i < cues.length; i++) {\n                      let cue = cues[i];\n                      // If any of the line positions aren't a number return our original TextTrackCueList\n                      if (typeof cue.line !== 'number') {\n                          return cues;\n                      }\n                      avgLine += cue.line;\n                      cueList.push(cue);\n                  }\n                  avgLine = avgLine / cues.length;\n                  if (avgLine > 50) {\n                      // Render highest line value first\n                      cueList.forEach(function (cue) {\n                          cue.axis = '-y';\n                      });\n                      cueList.sort((a, b) => b.line - a.line);\n                  }\n                  else {\n                      // Render lowest line value first\n                      cueList.forEach(function (cue) {\n                          cue.axis = '+y';\n                      });\n                      cueList.sort((a, b) => a.line - b.line);\n                  }\n                  // Just a normal array where we had a TextTrackCueList before, but should be okay\n                  return cueList;\n              }\n              // Determine if we need to compute the display states of the cues. This could\n              // be the case if a cue's state has been changed since the last computation or\n              // if it has not been computed yet.\n              function shouldCompute(cues) {\n                  for (let i = 0; i < cues.length; i++) {\n                      if (cues[i].hasBeenReset || !cues[i].displayState) {\n                          return true;\n                      }\n                  }\n                  return false;\n              }\n              // We don't need to recompute the cues' display states. Just reuse them.\n              if (!shouldCompute(cues)) {\n                  for (let i = 0; i < cues.length; i++) {\n                      this.paddedOverlay.appendChild(cues[i].displayState);\n                  }\n                  return;\n              }\n              const boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(this.paddedOverlay);\n              // cues is of type TextTrackCueList which has a length property\n              if (cues.length > 1) {\n                  cues = sortCues(cues);\n              }\n              for (let i = 0; i < cues.length; i++) {\n                  let cue = cues[i];\n                  // Compute the initial position and styles of the cue div.\n                  let styleBox = new CueStyleBox(this.window, cue, this.foregroundStyleOptions, this.backgroundStyleOptions, this.globalStyleCollection);\n                  this.paddedOverlay.appendChild(styleBox.div);\n                  // Move the cue div to it's correct line position.\n                  BoxPosition.moveBoxToLinePosition(styleBox, containerBox, boxPositions);\n                  // Remember the computed div so that we don't have to recompute it later\n                  // if we don't have too.\n                  cue.displayState = styleBox.div;\n                  boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));\n              }\n          }\n          /**\n           * Update the dimensions of the overlay container\n           * @param width width in pixels\n           * @param height height in pixels\n           */\n          setSize(width, height) {\n              if (width) {\n                  this.overlay.style.width = width + \"px\";\n              }\n              if (height) {\n                  this.overlay.style.height = height + \"px\";\n              }\n          }\n          /**\n           * Returns the HTMLElement passed in to instantiate this class\n           */\n          getOverlay() {\n              return this.overlay;\n          }\n      }\n      vtthtmlrenderer.default = WebVTTRenderer;\n      vtthtmlrenderer.WebVTTRenderer = WebVTTRenderer;\n    \n      (function (exports) {\n      /**\n       * Copyright 2013 vtt.js Contributors\n       *\n       * Licensed under the Apache License, Version 2.0 (the \"License\");\n       * you may not use this file except in compliance with the License.\n       * You may obtain a copy of the License at\n       *\n       *   http://www.apache.org/licenses/LICENSE-2.0\n       *\n       * Unless required by applicable law or agreed to in writing, software\n       * distributed under the License is distributed on an \"AS IS\" BASIS,\n       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n       * See the License for the specific language governing permissions and\n       * limitations under the License.\n       */\n      function __export(m) {\n          for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n      }\n      Object.defineProperty(exports, \"__esModule\", { value: true });\n      // Default exports for Node. Export the extended versions of VTTCue and\n      // VTTRegion in Node since we likely want the capability to convert back and\n      // forth between JSON. If we don't then it's not that big of a deal since we're\n      // off browser.\n      __export(vttparser);\n      __export(vtthtmlrenderer);\n      }(lib));\n    \n      \n      const tsTimescale = 90000; // MPEG-TS timescale value\n      function isExtendedTextTrackCue(value) {\n          return Boolean(value.webVTTCue);\n      }\n      // String.prototype.startsWith is not supported in IE11\n      function startsWith(input, search, position) {\n          return input.substr(position || 0, search.length) === search;\n      }\n      function cueString2millis(timeString) {\n          let ts = parseInt(timeString.substr(-3));\n          const secs = parseInt(timeString.substr(-6, 2));\n          const mins = parseInt(timeString.substr(-9, 2));\n          const hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;\n          if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {\n              return -1;\n          }\n          ts += 1000 * secs;\n          ts += 60000 * mins;\n          ts += 3600000 * hours;\n          return ts;\n      }\n      // From https://github.com/darkskyapp/string-hash\n      function hash(text) {\n          let hash = 5381;\n          let i = text.length;\n          while (i) {\n              hash = (hash * 33) ^ text.charCodeAt(--i);\n          }\n          return (hash >>> 0).toString();\n      }\n      function snapToHalfSecond(time) {\n          const lower = Math.floor(time);\n          const mid = lower + 0.5;\n          const upper = lower + 1;\n          let snappedTime;\n          if (time >= mid) {\n              snappedTime = time - mid >= upper - time ? upper : mid;\n          }\n          else {\n              snappedTime = time - lower >= mid - time ? mid : lower;\n          }\n          return snappedTime;\n      }\n      // find value x where:\n      // x = value + n * cardinality, for some integer n such that:\n      // |x - reference| <= cardinality / 2\n      function wrapPtsInteger(value, reference = 0, cardinality = 8589934592) {\n          if (!Number.isFinite(reference)) {\n              return value;\n          }\n          const midpoint = cardinality / 2;\n          const diff = Math.abs(value - reference) % cardinality;\n          const offset = diff > midpoint ? cardinality - diff : -diff;\n          const direction = value > reference ? -1 : 1;\n          return reference + direction * offset;\n      }\n      const HLSVTTParser = {\n          parse: function (vttByteArray, initPTS, // initPTS of current cc\n          wrapReference, // reference time for wrapping overflowed timestamp (pick a time close to the actual time. e.g., frag.start)\n          cc, // current cc\n          callBack, errorCallBack, stylesParsedCallback, logger) {\n              // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n              const re = /\\r\\n|\\n\\r|\\n|\\r/g;\n              // Uint8Array.prototype.reduce is not implemented in IE11\n              const vttLines = BufferUtils.utf8arrayToStr(new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n              const initPTS90k = convertTimescale(initPTS, tsTimescale); // Convert initPTS to 90k timescale\n              // X-TIMESTAMP-MAP MPEGTS attribute integer value (in 90k timescale)\n              // assume MPEGTS = 0 if X-TIMESTAMP-MAP is absent\n              let mpegTs = 0; // basetime with timescale 90000\n              // X-TIMESTAMP-MAP LOCAL attribute value parsed as number of seconds\n              let localTime = 0;\n              // Calculate wrapped ((MPEGTS - initPTS) / 90k)\n              // The number of seconds on the player timeline that the anchor point of the X-TIMESTAMP-MAP maps to\n              function calculateTimelineOffset() {\n                  // wrapReference should be close to the final wrapped integer to prevent overflowed number after wrapped\n                  // logger.debug(`mpegTs ${wrapPtsInteger(mpegTs)} - initPTS ${initPTS}, reference ${wrapReference} (${wrapReference * 90000})`);\n                  return convertTimestampToSeconds({\n                      baseTime: wrapPtsInteger(wrapPtsInteger(mpegTs) - initPTS90k.baseTime, wrapReference * tsTimescale),\n                      timescale: tsTimescale,\n                  });\n              }\n              const cues = [];\n              let parsingError = null;\n              let inHeader = true;\n              // let VTTCue = VTTCue || window.TextTrackCue;\n              // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n              const parser = new lib.WebVTTParser(window, lib.WebVTTParser.StringDecoder(), stylesParsedCallback);\n              parser.oncue = function (cue) {\n                  // cue offset = MPEGTS adjusted by InitPTS, assuming localtime is zero\n                  const cueOffset = calculateTimelineOffset();\n                  // logger.log(`cueOffset ${cueOffset}`);\n                  cue.startTime = wrapPtsInteger(cue.startTime + cueOffset - localTime, 0, 95443.7176888889);\n                  cue.endTime = wrapPtsInteger(cue.endTime + cueOffset - localTime, 0, 95443.7176888889);\n                  // Create a unique hash id for a cue based on start/end times and text.\n                  // This helps timeline-controller to avoid showing repeated captions.\n                  cue.id = hash(snapToHalfSecond(cue.startTime).toString()) + hash(snapToHalfSecond(cue.endTime - cue.startTime).toString()) + hash(cue.text);\n                  // Fix encoding of special characters. TODO: Test with all sorts of weird characters.\n                  cue.text = decodeURIComponent(encodeURIComponent(cue.text));\n                  if (cue.endTime > 0) {\n                      cues.push(cue);\n                  }\n              };\n              parser.onparsingerror = function (e) {\n                  parsingError = e;\n              };\n              parser.onflush = function () {\n                  if (parsingError && errorCallBack) {\n                      errorCallBack(parsingError);\n                      return;\n                  }\n                  callBack(cues);\n              };\n              // Go through contents line by line.\n              vttLines.forEach((line) => {\n                  if (inHeader) {\n                      // Look for X-TIMESTAMP-MAP in header.\n                      if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n                          // Once found, no more are allowed anyway, so stop searching.\n                          inHeader = false;\n                          // Extract LOCAL and MPEGTS.\n                          line\n                              .substr(16)\n                              .split(',')\n                              .forEach((timestamp) => {\n                              if (startsWith(timestamp, 'LOCAL:')) {\n                                  let localTimeMs;\n                                  try {\n                                      localTimeMs = cueString2millis(timestamp.substr(6));\n                                  }\n                                  catch (e) {\n                                      localTimeMs = -1;\n                                  }\n                                  if (localTimeMs !== -1) {\n                                      localTime = localTimeMs / 1000;\n                                  }\n                                  else {\n                                      parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n                                  }\n                              }\n                              else if (startsWith(timestamp, 'MPEGTS:')) {\n                                  mpegTs = parseInt(timestamp.substr(7));\n                              }\n                          });\n                          // Return without parsing X-TIMESTAMP-MAP line.\n                          return;\n                      }\n                  }\n                  // Parse line by default.\n                  parser.parse(line + '\\n');\n              });\n              parser.flush();\n          },\n      };\n      var HLSVTTParser$1 = HLSVTTParser;\n    \n      \n      const Cues = {\n          newCue: function (track, startTime, endTime, screen, media) {\n              let cue;\n              let indenting;\n              let indent;\n              let text;\n              let line;\n              const context = {\n                  foreground: false,\n                  background: false,\n                  italics: false,\n                  underline: false,\n                  flash: false,\n                  styleStack: [],\n              };\n              for (const [r, row] of screen.rows.entries()) {\n                  indenting = true;\n                  indent = 0;\n                  text = '';\n                  if (!row.isEmpty()) {\n                      for (let c = 0; c < row.chars.length; c++) {\n                          if (row.chars[c].uchar.match(/\\s/) && indenting) {\n                              indent++;\n                          }\n                          else {\n                              text += this.getFormattedChar(row.chars[c], context);\n                              indenting = false;\n                          }\n                      }\n                      // To be used for cleaning-up orphaned roll-up captions\n                      row.cueStartTime = startTime;\n                      // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n                      if (startTime === endTime) {\n                          endTime += 0.0001;\n                      }\n                      text = text.trim().replace(/<br(?: \\/)?>/gi, '\\n');\n                      text += this.closeStyles(context);\n                      // console.log('VTTCue ' + startTime + ' - ' + endTime + ': ' + text);\n                      cue = new lib.VTTCue(startTime, endTime, text);\n                      if (indent >= 16) {\n                          indent--;\n                      }\n                      else {\n                          indent++;\n                      }\n                      // VTTCue.line get's flakey when using controls, so let's now include line 13&14\n                      // also, drop line 1 since it's to close to the top\n                      if (navigator.userAgent.match(/Firefox\\//)) {\n                          line = r + 1;\n                      }\n                      else {\n                          line = r > 7 ? r : r + 1;\n                      }\n                      cue.snapToLines = false; // Need this to be false for position % to work\n                      cue.line = 10 + line * 5.33; // ( 10% top padding + line number * (80% vertical render length / 15 rows) )\n                      cue.align = 'left';\n                      cue.position = this.getPosition(indent, media);\n                      track.addCue(cue);\n                  }\n              }\n          },\n          getPosition: function (indent, media) {\n              // Assume our aspect ratio is 4:3\n              let aspectRatio = 1.3333333333333333;\n              if (media && media.offsetWidth && media.offsetHeight) {\n                  const mediaRatio = media.offsetWidth / media.offsetHeight;\n                  // There are some 16:10 screens out there, which is closer to 16:9 than a 4:3 aspect ratio\n                  // So, anything with a ratio of 16:10 or wider will treat as a 16:9 screen for our calculations\n                  if (mediaRatio >= 1.6) {\n                      aspectRatio = 1.7777777777777777;\n                  }\n              }\n              // CEA-608 has 32 columns, and defines 10% padding on each side\n              // ( 10% left padding + indent * (80% horizontal render length / 32 columns) )\n              let position = 10 + (indent / 32) * 80;\n              let leftBound = 10;\n              let rightBound = 90;\n              if (aspectRatio === 1.7777777777777777) {\n                  // CEA-608 captions assume a 4:3 screen size, but since we'll be playing on a 16:9 need to adjust some numbers\n                  // 4:3 => 12:9, and a 12:9 screen's width is 3/4 the size of a 16:9 screen\n                  // 3/4 * 16 = 4, and 4/16 = 25%, which means we need to pad by 12.5% on each side\n                  // Also, when calculating the left offset it was originally for a 4:3 screen, so need to divide by 3/4 to adjust to 16:9 percentages\n                  position = 12.5 + position * 0.75;\n                  leftBound = 20;\n                  rightBound = 80;\n              }\n              // Clamp the position based on the aspect ratio - if out of these bounds, Firefox throws an exception and captions break\n              return Math.max(leftBound, Math.min(rightBound, position + (navigator.userAgent.match(/Firefox\\//) ? 50 : 0)));\n          },\n          // return 'c' for all possible class tags (for color and bg_color); or the given style tag untouched (e.g., u, i, blink)\n          getRootStyleTag: function (style) {\n              const styleKey = style[0];\n              return styleKey === 'c' ? styleKey : style;\n          },\n          closeStyles: function (context) {\n              let postfix = '';\n              for (let i = context.styleStack.length - 1; i >= 0; --i) {\n                  const styleTag = this.getRootStyleTag(context.styleStack[i]);\n                  postfix += '</' + styleTag + '>';\n                  context.styleStack.pop();\n              }\n              return postfix;\n          },\n          beginStyleAndBalance: function (context, newStyle) {\n              let balancedStyles = '';\n              if (newStyle[0] === 'c') {\n                  balancedStyles += this.closeStyleAndBalance(context, 'c');\n              }\n              balancedStyles += '<' + newStyle + '>';\n              context.styleStack.push(newStyle);\n              return balancedStyles;\n          },\n          closeStyleAndBalance: function (context, oldStyle) {\n              const totalStyleCount = context.styleStack.length;\n              let childrenStyleCount = 0;\n              let closingChildrenStyles = '';\n              let balancedStyles = '';\n              for (let i = totalStyleCount - 1; i >= 0; --i) {\n                  const styleUsed = context.styleStack[i];\n                  const styleTag = this.getRootStyleTag(styleUsed);\n                  if (oldStyle[0] === styleUsed[0]) {\n                      closingChildrenStyles += '</' + styleTag + '>';\n                      context.styleStack.splice(totalStyleCount - 1 - childrenStyleCount);\n                      break;\n                  }\n                  else {\n                      if (styleTag[0] === 'c') {\n                          context.background = '';\n                          context.foreground = '';\n                          context.flash = false;\n                          closingChildrenStyles += '</c>';\n                      }\n                      else if (styleTag[0] === 'u') {\n                          context.underline = false;\n                          closingChildrenStyles += '</u>';\n                      }\n                      else if (styleTag[0] === 'i') {\n                          context.italics = false;\n                          closingChildrenStyles += '</i>';\n                      }\n                      childrenStyleCount++;\n                  }\n              }\n              balancedStyles = closingChildrenStyles;\n              return balancedStyles;\n          },\n          getFormattedChar: function (c, context) {\n              let prefix = '';\n              let formattedChar = c.uchar;\n              // color styles\n              let newColorStyle = '';\n              const foregroundChanged = c.penState.foreground !== context.foreground;\n              const backgroundChanged = c.penState.background !== context.background;\n              const blinkChanged = c.penState.flash !== context.flash;\n              if (foregroundChanged || backgroundChanged || blinkChanged) {\n                  // always include current colors in tag\n                  newColorStyle = '.' + c.penState.foreground;\n                  newColorStyle += '.bg_' + c.penState.background;\n                  if (c.penState.flash && blinkChanged) {\n                      newColorStyle += '.blink'; // but blink may be optional\n                  }\n                  if (c.penState.foreground || c.penState.background || c.penState.blink) {\n                      prefix += this.beginStyleAndBalance(context, 'c' + newColorStyle);\n                  }\n                  else {\n                      // changed to undefined foreground _and_ background color\n                      prefix += this.closeStyleAndBalance(context, 'c');\n                  }\n                  if (foregroundChanged) {\n                      context.foreground = c.penState.foreground;\n                  }\n                  if (backgroundChanged) {\n                      context.background = c.penState.background;\n                  }\n                  if (blinkChanged) {\n                      context.flash = c.penState.flash;\n                  }\n              }\n              // other styles\n              if (c.penState.underline !== context.underline) {\n                  prefix += c.penState.underline ? this.beginStyleAndBalance(context, 'u') : this.closeStyleAndBalance(context, 'u');\n                  context.underline = c.penState.underline;\n              }\n              if (c.penState.italics !== context.italics) {\n                  prefix += c.penState.italics ? this.beginStyleAndBalance(context, 'i') : this.closeStyleAndBalance(context, 'i');\n                  context.italics = c.penState.italics;\n              }\n              formattedChar = prefix + formattedChar;\n              return formattedChar;\n          },\n      };\n      var Cues$1 = Cues;\n    \n      /*\n       * LegibleSystemAdapter\n       *\n       * \n       */\n      var ParsedFragQuality;\n      (function (ParsedFragQuality) {\n          ParsedFragQuality[\"CloseEnough\"] = \"CloseEnough\";\n          ParsedFragQuality[\"TooFar\"] = \"TooFar\";\n          ParsedFragQuality[\"Unknown\"] = \"Unknown\";\n      })(ParsedFragQuality || (ParsedFragQuality = {}));\n      const isChannelTextTrackKey = (value) => {\n          return value === 'cc1' || value === 'cc2';\n      };\n      function filterSelectableTextTracks(textTrackList) {\n          const tracks = [];\n          for (let ix = 0; ix < textTrackList.length; ix++) {\n              const textTrack = textTrackList[ix];\n              if (textTrack.kind === 'captions' || textTrack.kind === 'subtitles' || (textTrack.kind === 'metadata' && textTrack.customTextTrackCueRenderer)) {\n                  tracks.push(textTrack);\n              }\n          }\n          return tracks;\n      }\n      const cea608Duration = 0.03336666666666667;\n      function clearCurrentCues(track) {\n          if (track && track.cues) {\n              while (track.cues.length > 0) {\n                  track.removeCue(track.cues[0]);\n              }\n          }\n      }\n      function intersection(x1, x2, y1, y2) {\n          return Math.min(x2, y2) - Math.max(x1, y1);\n      }\n      class LegibleSystemAdapter extends Observable {\n          constructor(mediaSink, config, hls, logger) {\n              super((subscriber) => {\n                  const hlsTarget = fromEventTarget(this.hls, this);\n                  subscriber.add(hlsTarget\n                      .event(HlsEvent$1.INLINE_STYLES_PARSED, this.onInlineStylesParsed)\n                      .pipe(finalize$1(() => this.destroy()))\n                      .subscribe());\n                  subscriber.add(timer(0, this.config.trottleCheckInterval)\n                      .pipe(switchMap(() => {\n                      this.checkReadyToLoadNextSubtitleFragment();\n                      return VOID;\n                  }))\n                      .subscribe());\n                  if (this.config.nativeTextTrackChangeHandling) {\n                      const useTextTrackPolling = !(this.mediaSink.textTracks && 'onchange' in this.mediaSink.textTracks);\n                      if (useTextTrackPolling) {\n                          subscriber.add(timer(0, 500)\n                              .pipe(switchMap(() => {\n                              this._onTextTracksChanged();\n                              return VOID;\n                          }))\n                              .subscribe());\n                      }\n                      else {\n                          const textTrackListTarget = fromEventTarget(this.mediaSink.textTracks, this);\n                          subscriber.add(textTrackListTarget.event('change', this._onTextTracksChanged).subscribe());\n                      }\n                  }\n              });\n              this.config = config;\n              this.hls = hls;\n              this.logger = logger.child({ name: 'legible' });\n              this.mediaSink = mediaSink;\n              // Add the id3 text track to the legibleSystemAdapter\n              this.id3Track = mediaSink.id3TextTrack;\n              this.enableCaption = true;\n              this.Cues = Cues$1;\n              this.tracks = [];\n              this.cueRanges = [];\n              this.channelToTrackMap = {};\n              this.htmlTextTrackMap = new Map();\n              this.lastCueEndTime = 0;\n              this.gotTracks = false;\n              this.tryAgain$ = new BehaviorSubject(true);\n              this.needNextSubtitle$ = new BehaviorSubject(true);\n          }\n          destroy() {\n              clearCurrentCues(this.textTrack1);\n              clearCurrentCues(this.textTrack2);\n              this.mediaSink = undefined;\n              this.nativeSubtitleTrackChange$ = undefined;\n          }\n          convertCuesIntoSubtitleFragInfo(cues) {\n              const fragCueRecord = {};\n              if (cues != null && cues.length > 0) {\n                  // When we parse WebVTT cues, we assign the cue's containing\n                  // fragment's sequence number to cue.fragSN.\n                  for (let i = 0; i < cues.length; i++) {\n                      const cue = cues[i];\n                      if (!isFiniteNumber(cue.fragSN)) {\n                          continue;\n                      }\n                      const record = fragCueRecord[cue.fragSN];\n                      if (!record) {\n                          fragCueRecord[cue.fragSN] = { count: 1, startTime: cue.startTime, endTime: cue.endTime };\n                      }\n                      else {\n                          record.count++;\n                          record.startTime = Math.min(cue.startTime, record.startTime);\n                          record.endTime = Math.max(cue.endTime, record.endTime);\n                      }\n                  }\n              }\n              return fragCueRecord;\n          }\n          checkReadyToLoadNextSubtitleFragment() {\n              const currentTime = this.mediaSink.mediaQuery.currentTime;\n              const lastParsedCue = this.lastCueEndTime;\n              let need = false;\n              if (currentTime >= lastParsedCue - this.config.subtitleLeadTime) {\n                  need = true; // less than (default) 30 seconds away from last parsed cue\n              }\n              this.logger.trace(`[subtitle] needtoLoadNextSubtitle: ${need}: ${currentTime} >= ${lastParsedCue} - ${this.config.subtitleLeadTime}`);\n              this.needNextSubtitle$.next(need);\n          }\n          checkReadyToLoadNextSubtitleFragment$(frag, generatedFrags) {\n              var _a;\n              if (frag.mediaSeqNum === ((_a = generatedFrags[0]) === null || _a === void 0 ? void 0 : _a.mediaSeqNum)) {\n                  return of(true); // don't delay the first fragment because we may need to reload if it's too far\n              }\n              this.checkReadyToLoadNextSubtitleFragment();\n              return this.needNextSubtitle$;\n          }\n          getNextFragment(details, mediaFragment) {\n              const nextSN = mediaFragment.mediaSeqNum + 1;\n              const nextFrag = nextSN < details.fragments.length ? details.fragments[nextSN - details.startSN] : null;\n              return nextFrag;\n          }\n          // aggressive loading: always load subtitles until there is none left,\n          // without checking for waterlevel in the current HTML5 texttrack\n          //\n          // In mediaSink.archiveParsedSubtitleFragmentRecord():\n          // After the legibleSystemAdapter parses a subtitle fragment,\n          // it records the startTime (of the first cue in the fragment), endTime (of the last cue),\n          // and number of added cues in the fragment on its corresponding fragInfo object.\n          // In this way, hls.js knows the time boundary of each parsed subtitle fragment and how many cues it has generated.\n          // In legibleSystemAdapter.calculateFragInfoMap():\n          // Iterate through the cues in the current HTML5 texttrack\n          // to tally the cues for each fragment.\n          // * If this \"remaining cue\" count does not match the \"added cue\" count in archiveParsedSubtitleFragmentRecord(),\n          //   we will pretend that the fragment has not been loaded (probably error'ed out during cue creation)\n          //\n          // When starting up, seeking or track switching, hls.js needs to find the first subtitle fragment to load.\n          // It is the first unloaded fragment beyond the playback position.\n          // * Ignore subtitle fragments earlier than the current playback position\n          // * Find any continuous series of loaded subtitle fragments that overlaps the current playback position.\n          //   Determine the media sequence number of the last fragment in this series. hls.js will load the next fragment.\n          // * If no fragment overlaps the playback position, find the 1st fragment with start time >=\n          //   playback position.\n          // * To deal with subtitle playlist timestamp inaccuracies, we use the parsed timestamps calculated in\n          //   mediaSink.archiveParsedSubtitleFragmentRecord() to anchor the timeline. That way, we can use each fragment's\n          //   parsed duration to approximate the right fragment to load.\n          calculateFragInfoMap(position, cues, subtitleParsedRecord, details) {\n              const actualFragInfoMap = this.convertCuesIntoSubtitleFragInfo(cues);\n              let bufferInfo = { len: 0, start: position, end: position };\n              let start = position;\n              let end = position;\n              let prevFragSN = null;\n              let nextFragSN = null;\n              // ES6 will sort numeric property keys in ascending order automatically\n              // https://exploringjs.com/es6/ch_oop-besides-classes.html#_traversal-order-of-properties\n              for (const propertyKey in actualFragInfoMap) {\n                  if (!Object.prototype.hasOwnProperty.call(actualFragInfoMap, propertyKey)) {\n                      continue;\n                  }\n                  const sn = Number(propertyKey);\n                  if (!isFiniteNumber(sn)) {\n                      this.logger.warn(`$fragInfoMap has invalid key ${sn}`);\n                      continue; // should not happen\n                  }\n                  const fragInfo = actualFragInfoMap[sn];\n                  if (!this.isFragmentCompleteOrEmpty(sn, fragInfo.count, subtitleParsedRecord)) {\n                      continue;\n                  }\n                  // current search position is earlier than the very 1st cue in the entire fragment details\n                  // re-adjust search position to 1st cue's start time so that we can anchor the search from this 1st (buffered) frag\n                  if (sn === details.startSN && position < fragInfo.startTime) {\n                      start = end = bufferInfo.start = bufferInfo.end = position = fragInfo.startTime;\n                  }\n                  // found a fragment where start < position and is the leading frag in a frag sequence\n                  if (position >= fragInfo.startTime &&\n                      (start === position || // 1st frag in the loadPos\n                          (isFiniteNumber(prevFragSN) && sn - prevFragSN > 1))) {\n                      // frag disjoint from the last one\n                      start = end = fragInfo.startTime;\n                  }\n                  // look for the overlapping fragment\n                  if (position >= fragInfo.startTime) {\n                      // potentially inside a frag, assume its endTime as our next load position, and keep going ...\n                      end = fragInfo.endTime;\n                      prevFragSN = sn;\n                      continue;\n                  }\n                  if (isFiniteNumber(prevFragSN) && sn - prevFragSN === 1) {\n                      // Consecutive SN between 2 neighboring cues, keep scanning down the frag chain\n                      end = fragInfo.endTime;\n                      prevFragSN = sn;\n                      continue;\n                  }\n                  // found the end of a continuous fragment series which overlaps the current position\n                  nextFragSN = sn;\n                  break;\n              }\n              bufferInfo = { len: end - start, start, end };\n              const subtitleBufferInfo = { fragInfoMap: actualFragInfoMap, bufferInfo, prevFragSN, nextFragSN };\n              return subtitleBufferInfo;\n          }\n          findFrags$(details, activeDiscoSeq) {\n              return this.tryAgain$.pipe(observeOn(asyncScheduler), switchMap(() => {\n                  const findFragResult = this.findFragmentsForPosition(this.mediaSink.mediaQuery.currentTime, activeDiscoSeq, details);\n                  const nextFrags = findFragResult.foundFrags;\n                  if (!nextFrags) {\n                      return EMPTY; // no more frag left to process\n                  }\n                  this.lastCueEndTime = 0; // reset needNextSubtitle$ check\n                  this.needNextSubtitle$.next(true);\n                  return of(findFragResult);\n              }));\n          }\n          // return true to continue loading the entire fragment batch\n          reviewParsedFrag(parsedFragResult, findFragsResult, details) {\n              var _a, _b, _c, _d;\n              const frag = parsedFragResult.frag;\n              const parsedCueRecord = parsedFragResult.cueRange;\n              const subtitleBufferInfo = findFragsResult.subtitleBufferInfo;\n              const subtitleParsedInfo = findFragsResult.subtitleParsedInfo;\n              const currentTime = this.mediaSink.mediaQuery.currentTime;\n              const generatedFrags = findFragsResult.foundFrags;\n              let success = true;\n              if (frag.mediaSeqNum === generatedFrags[0].mediaSeqNum) {\n                  if (!findFragsResult.timelineEstablished) {\n                      this.logger.info(`[subtitle] frag sn ${frag.mediaSeqNum} parsed. retry findFrag`);\n                      return ParsedFragQuality.TooFar;\n                  }\n                  // only check the starting frag\n                  if (!parsedCueRecord) {\n                      // missing parsed data: should not happen. let currentTime move until the findFrag returns another frag\n                      this.logger.warn(`[subtitle] 1st frag sn ${frag.mediaSeqNum} has no cue; details ${details.fragments.length} frags`);\n                      return ParsedFragQuality.Unknown;\n                  }\n                  // Check whether we inferred the first frag close enough.\n                  if (parsedCueRecord.startTime < currentTime) {\n                      const actualDurationToPlayHead = currentTime - parsedCueRecord.startTime;\n                      const fragments = details.fragments;\n                      const startIdx = frag.mediaSeqNum - details.startSN;\n                      let i = startIdx;\n                      let fragTime = parsedCueRecord.startTime;\n                      for (; i < fragments.length; ++i) {\n                          fragTime += fragments[i].duration;\n                          if (fragTime >= currentTime) {\n                              break;\n                          }\n                      }\n                      const fragCount = i - startIdx + 1;\n                      success = fragCount <= this.config.earlyFragTolerance; // find another frag if we are too many fragments away\n                      this.logger.info(`[subtitle] 1st frag sn ${frag.mediaSeqNum} is ${actualDurationToPlayHead}s earlier and ${fragCount} frags away from currentTime ${currentTime}; success ${success}`);\n                  }\n                  else if (parsedCueRecord.startTime > currentTime && frag.mediaSeqNum !== details.startSN) {\n                      const actualDurationToPlayHead = parsedCueRecord.startTime - currentTime;\n                      const latestBufferedFrag = subtitleBufferInfo.prevFragSN;\n                      this.logger.info(`[subtitle] last buffered frag is complete: ${(_a = subtitleBufferInfo.fragInfoMap[latestBufferedFrag]) === null || _a === void 0 ? void 0 : _a.count} vs ${(_b = subtitleParsedInfo[latestBufferedFrag]) === null || _b === void 0 ? void 0 : _b.count}`);\n                      if (frag.mediaSeqNum === latestBufferedFrag + 1 && ((_c = subtitleBufferInfo.fragInfoMap[latestBufferedFrag]) === null || _c === void 0 ? void 0 : _c.count) === ((_d = subtitleParsedInfo[latestBufferedFrag]) === null || _d === void 0 ? void 0 : _d.count)) {\n                          // parsed frag is later than currentTime, but it is just the next consecutive frag from a latest *processed* frag. success.\n                          success = true;\n                          this.logger.info(`[subtitle] parsed frag sn ${frag.mediaSeqNum} is ${actualDurationToPlayHead}s later than currentTime ${currentTime} but continues from previous frag ${subtitleBufferInfo.prevFragSN}; success ${success}`);\n                      }\n                      else {\n                          // parsed frag is later than currentTime. This should not happen because the cues are usually later than the frag start time,\n                          // causing the findFrag function to (always) return an earlier frag than expected.\n                          success = actualDurationToPlayHead <= this.config.lateTolerance;\n                          this.logger.info(`[subtitle] 1st frag sn ${frag.mediaSeqNum} is ${actualDurationToPlayHead}s later than currentTime ${currentTime} and is ${frag.duration}s long; success ${success}`);\n                      }\n                  }\n              }\n              return success ? ParsedFragQuality.CloseEnough : ParsedFragQuality.TooFar;\n          }\n          isFragmentEmpty(subtitleParsedRecord) {\n              return subtitleParsedRecord && !isFiniteNumber(subtitleParsedRecord.startTime) && subtitleParsedRecord.count === 0;\n          }\n          isFragmentCompleteOrEmpty(mediaSeqNum, cueCount, subtitleParsedRecord) {\n              const parsedRecord = subtitleParsedRecord ? subtitleParsedRecord[mediaSeqNum] : null;\n              const result = (parsedRecord === null || parsedRecord === void 0 ? void 0 : parsedRecord.count) === cueCount || this.isFragmentEmpty(parsedRecord);\n              return result;\n          }\n          // use one *unbuffered* fragment early because we used cue startTime as fragment startTime to find media fragment\n          getEarlierFragmentInSameDisco(details, frag, subtitleParsedRecord) {\n              const fragIdx = frag.mediaSeqNum - details.startSN - 1;\n              if (fragIdx < 0 || fragIdx > details.fragments.length - 1) {\n                  this.logger.error(`[subtitle] getEarlierFragmentInSameDisco index ${fragIdx} out of range`);\n                  return frag; // return original frag\n              }\n              const prevFrag = details.fragments[fragIdx];\n              return prevFrag && prevFrag.discoSeqNum === frag.discoSeqNum && !subtitleParsedRecord[frag.mediaSeqNum] ? prevFrag : frag;\n          }\n          // subtitleParsedInfo: Records containing cue count, start and end time of parsed fragments.\n          //                     subtitleParsedInfo is calculated when we parse a frag to add its WebVTT cues\n          //                     (archiveParsedSubtitleFragmentRecord)\n          // subtitleBufferInfo: Records containing cue count, start and end time of buffered fragments.\n          //                     subtitleBufferInfo is calculated when we enumarate added (remaining) cues in text tracks\n          //                     (calculateFragInfoMap)\n          // 2 main differences:\n          // (1) subtitleParsedInfo is stored in akita store for the entire session. Each subtitle persistent id\n          // has one record (That means primary and backup subtitle track may share the same record).\n          // subtitleBufferInfo is calculated on-demand from the cues in the current enabled text track only.\n          // (2) The calculated frag (cue) start and end time in subtitleParsedInfo should be more accurate than\n          // the start and end time in subtitleBufferInfo. This is in case MSE or the app removes used cues from the text tracks.\n          inferSubtitleFragmentForPosition(position, activeDiscoSeqNum, subtitleParsedInfo, subtitleBufferInfo, details) {\n              let foundFrag;\n              let startFragIdx;\n              let startParsedRecord;\n              let endFragIdx;\n              let endParsedRecord;\n              if (isFiniteNumber(subtitleBufferInfo.prevFragSN)) {\n                  startFragIdx = subtitleBufferInfo.prevFragSN - details.startSN;\n                  startParsedRecord = subtitleParsedInfo[subtitleBufferInfo.prevFragSN];\n              }\n              if (isFiniteNumber(subtitleBufferInfo.nextFragSN)) {\n                  endFragIdx = subtitleBufferInfo.nextFragSN - details.startSN;\n                  endParsedRecord = subtitleParsedInfo[subtitleBufferInfo.nextFragSN];\n              }\n              if (isFiniteNumber(startFragIdx) && startFragIdx >= 0 && startFragIdx < details.fragments.length && startParsedRecord) {\n                  let startPos = startParsedRecord.startTime;\n                  const lastIdx = isFiniteNumber(endFragIdx) ? endFragIdx : details.fragments.length;\n                  for (let i = startFragIdx; i < lastIdx; ++i) {\n                      const mediaFragment = details.fragments[i];\n                      if (isFiniteNumber(activeDiscoSeqNum) && mediaFragment.discoSeqNum !== activeDiscoSeqNum) {\n                          continue;\n                      }\n                      if (i === lastIdx - 1) {\n                          // get the fragment before nextFragSN (in case we guessed too late during the last inference)\n                          this.logger.info(`[subtitle] from frag sn ${subtitleBufferInfo.prevFragSN}, infer frag sn ${mediaFragment.mediaSeqNum} using lastIdx ${lastIdx}. startPos ${startPos} duration ${mediaFragment.duration} position ${position}`);\n                          foundFrag = { foundFrag: mediaFragment, timelineEstablished: true };\n                          break;\n                      }\n                      else if (startPos + mediaFragment.duration > position && i > startFragIdx) {\n                          // we have already loaded frag prevFragSN, so we are really only interested in frag (prevFragSN + 1) and beyond\n                          this.logger.info(`[subtitle] from frag sn ${subtitleBufferInfo.prevFragSN}, infer frag sn ${mediaFragment.mediaSeqNum}: startPos ${startPos} + duration ${mediaFragment.duration} > ${position}`);\n                          foundFrag = { foundFrag: mediaFragment, timelineEstablished: true };\n                          break;\n                      }\n                      startPos += mediaFragment.duration;\n                  }\n              }\n              else if (isFiniteNumber(endFragIdx) && endFragIdx >= 0 && endFragIdx < details.fragments.length && endParsedRecord) {\n                  let startPos = endParsedRecord.startTime; // endParsedRecord.startTime is fragments[endFragIdx].start\n                  for (let i = endFragIdx - 1; i >= 0; --i) {\n                      // keep probing the earlier fragment as long as the later/previous fragment's startPos > position\n                      const mediaFragment = details.fragments[i];\n                      if (isFiniteNumber(activeDiscoSeqNum) && mediaFragment.discoSeqNum !== activeDiscoSeqNum) {\n                          continue;\n                      }\n                      if (startPos <= position) {\n                          // we want one fragment earlier than position, which is mediaFragment (because startPos belongs to the later/previous fragment)\n                          this.logger.info(`[subtitle] from frag sn ${subtitleBufferInfo.nextFragSN}, infer frag sn ${mediaFragment.mediaSeqNum}: startPos ${startPos} <= ${position}`);\n                          foundFrag = { foundFrag: mediaFragment, timelineEstablished: true };\n                          break;\n                      }\n                      startPos -= mediaFragment.duration;\n                  }\n              }\n              else {\n                  for (let i = 0; i < details.fragments.length; ++i) {\n                      const mediaFragment = details.fragments[i];\n                      if (isFiniteNumber(activeDiscoSeqNum) && mediaFragment.discoSeqNum === activeDiscoSeqNum) {\n                          this.logger.info(`[subtitle] infer frag sn ${mediaFragment.mediaSeqNum} in cc ${activeDiscoSeqNum}`);\n                          foundFrag = { foundFrag: mediaFragment, timelineEstablished: false };\n                          break;\n                      }\n                  }\n              }\n              return foundFrag;\n          }\n          generateFragmentBatch(batchSize, activeDiscoSeqNum, fragResult, subtitleParsedInfo, subtitleBufferInfo, details) {\n              var _a;\n              const generatedFrags = [];\n              const anchorFrag = fragResult === null || fragResult === void 0 ? void 0 : fragResult.foundFrag;\n              if (!anchorFrag) {\n                  return { foundFrags: undefined, subtitleParsedInfo: undefined, subtitleBufferInfo: undefined, timelineEstablished: fragResult === null || fragResult === void 0 ? void 0 : fragResult.timelineEstablished };\n              }\n              const startIdx = anchorFrag ? anchorFrag.mediaSeqNum - details.startSN : details.fragments.length;\n              for (let i = startIdx; i < details.fragments.length && generatedFrags.length < batchSize; ++i) {\n                  const frag = details.fragments[i];\n                  if (frag.discoSeqNum !== activeDiscoSeqNum) {\n                      continue;\n                  }\n                  const bufferedCueCount = (_a = subtitleBufferInfo.fragInfoMap[frag.mediaSeqNum]) === null || _a === void 0 ? void 0 : _a.count;\n                  if (!this.isFragmentCompleteOrEmpty(frag.mediaSeqNum, bufferedCueCount !== null && bufferedCueCount !== void 0 ? bufferedCueCount : 0, subtitleParsedInfo)) {\n                      generatedFrags.push(frag); // include frag if not fully parsed\n                  }\n              }\n              return { foundFrags: generatedFrags, subtitleParsedInfo, subtitleBufferInfo, timelineEstablished: fragResult === null || fragResult === void 0 ? void 0 : fragResult.timelineEstablished };\n          }\n          findFragmentsForPosition(currentTime, activeDiscoSeqNum, details) {\n              // get past addCue records\n              const subtitleParsedRecord = this.mediaSink.mediaQuery.getParsedSubtitleRecordsForMediaOption(this.selectedTrack.persistentID);\n              // compose addCue records from remaining cues in current texttrack\n              const cues = this.getCuesOfEnabledTrack(this.selectedMediaOption.mediaOptionId, false /* this.enabledTrack.sideTrackId !== undefined */);\n              const subtitleBufferInfo = this.calculateFragInfoMap(currentTime, cues, subtitleParsedRecord, details);\n              const bufferInfo = subtitleBufferInfo.bufferInfo;\n              const loadPos = Math.max(currentTime, bufferInfo.end);\n              const fragResult = this.inferSubtitleFragmentForPosition(loadPos, activeDiscoSeqNum, subtitleParsedRecord, subtitleBufferInfo, details);\n              return this.generateFragmentBatch(Infinity, activeDiscoSeqNum, fragResult, subtitleParsedRecord, subtitleBufferInfo, details);\n          }\n          get selectedMediaOption() {\n              return this.selectedTrack ? this.selectedTrack : this._disabledMediaOption;\n          }\n          set selectedMediaOption(mediaOption) {\n              this.selectedTrack = isAlternateMediaOption(mediaOption) ? mediaOption : undefined;\n          }\n          get selectedTrack() {\n              return this._selectedMediaOption;\n          }\n          set selectedTrack(track) {\n              if (track === this._selectedMediaOption) {\n                  return;\n              }\n              this.logger.info(`[subtitle] pick track #${track === null || track === void 0 ? void 0 : track.id} mediaOptionId ${track === null || track === void 0 ? void 0 : track.mediaOptionId} persistentId ${track === null || track === void 0 ? void 0 : track.persistentID}`);\n              this._selectedMediaOption = track;\n              this.updateTextTrackState();\n          }\n          getTrack(mediaOptionId) {\n              return this._availableMediaOptions.find((mediaOption) => mediaOption.mediaOptionId === mediaOptionId);\n          }\n          updateTextTrackState() {\n              if (!this.mediaSink.textTracks) {\n                  // catch an update later\n                  return;\n              }\n              const selectedHTMLTextTrack = this.selectedTrack ? this.getExistingHTMLTextTrack(this.selectedTrack) : undefined;\n              const textTracks = filterSelectableTextTracks(this.mediaSink.textTracks);\n              for (let id = 0; id < textTracks.length; id++) {\n                  const aTrack = textTracks[id];\n                  if (aTrack === selectedHTMLTextTrack && textTracks[id].mode !== 'showing') {\n                      textTracks[id].mode = 'showing';\n                      this.logger.info(`textTracks[${id}].mode = 'showing'`);\n                  }\n                  else if (aTrack !== selectedHTMLTextTrack && textTracks[id].mode !== 'hidden') {\n                      textTracks[id].mode = 'hidden';\n                      this.logger.info(`textTracks[${id}].mode = 'hidden'`);\n                  }\n              }\n          }\n          mapHTMLTextTrackIndexToMediaOptionId(searchIndex) {\n              const searchTextTrack = this.mediaSink.textTracks[searchIndex];\n              let foundOptionId;\n              this.htmlTextTrackMap.forEach((textTrack, optionId) => {\n                  if (searchTextTrack === textTrack) {\n                      foundOptionId = optionId;\n                  }\n              });\n              return foundOptionId;\n          }\n          get mediaSelectionOptions() {\n              return this._availableMediaOptions;\n          }\n          _makeDisableOption(mediaOption) {\n              return { itemId: mediaOption.itemId, mediaOptionType: mediaOption.mediaOptionType, mediaOptionId: 'Nah' };\n          }\n          _onTextTracksChanged() {\n              // Media is undefined when switching streams via loadSource()\n              if (!this.mediaSink) {\n                  return;\n              }\n              let newTrackEvent = false;\n              let showingPersistentId;\n              const textTracks = filterSelectableTextTracks(this.mediaSink.textTracks);\n              let newTracksSeenAndIgnored = 0;\n              for (let id = 0; id < textTracks.length; id++) {\n                  if (textTracks[id].seen) {\n                      // Existing text tracks\n                      if (textTracks[id].mode === 'showing') {\n                          showingPersistentId = textTracks[id].persistentId;\n                      }\n                  }\n                  else {\n                      // Newly added text track always has 'hidden' mode by default.\n                      // We must not make any selection change based on \"new track\" event.\n                      // A real track change event may be in-flight and will be overriden later if we re-select an active subtitle track or 'undefined' now.\n                      textTracks[id].seen = true;\n                      newTracksSeenAndIgnored += 1;\n                      newTrackEvent = true;\n                  }\n              }\n              this.logger.info(`New tracks marked seen and ignored: ${newTracksSeenAndIgnored} vs total: ${textTracks.length}`);\n              if (!newTrackEvent) {\n                  const currentSelectedMediaOption = this.selectedTrack;\n                  if ((currentSelectedMediaOption === null || currentSelectedMediaOption === void 0 ? void 0 : currentSelectedMediaOption.persistentID) !== showingPersistentId) {\n                      const newOption = this.mediaSelectionOptions.find(function (mediaOption) {\n                          return mediaOption.persistentID === showingPersistentId;\n                      });\n                      this.nativeSubtitleTrackChange$.next(newOption ? newOption : this._disabledMediaOption);\n                  }\n              }\n          }\n          addCues(channel, startTime, endTime, screen) {\n              // skip cues which overlap more than 50% with previously parsed time ranges\n              const ranges = this.cueRanges;\n              let merged = false;\n              for (let i = ranges.length; i--;) {\n                  const cueRange = ranges[i];\n                  const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n                  if (overlap >= 0) {\n                      cueRange[0] = Math.min(cueRange[0], startTime);\n                      cueRange[1] = Math.max(cueRange[1], endTime);\n                      merged = true;\n                      if (overlap / (endTime - startTime) > 0.5) {\n                          return;\n                      }\n                  }\n              }\n              if (!merged) {\n                  ranges.push([startTime, endTime]);\n              }\n              this.Cues.newCue(this.channelToTrackMap[channel], startTime, endTime, screen, this.mediaSink);\n          }\n          getExistingHTMLTextTrackWithChannelNumber(channelNumber) {\n              const mediaSink = this.mediaSink;\n              if (mediaSink) {\n                  for (let i = 0; i < mediaSink.textTracks.length; i++) {\n                      const textTrack = mediaSink.textTracks[i];\n                      const propName = 'cc' + channelNumber;\n                      if (isChannelTextTrackKey(propName) && textTrack[propName] === true) {\n                          return textTrack;\n                      }\n                  }\n              }\n              return null;\n          }\n          sendAddTrackEvent(track, mediaSink) {\n              let e = null;\n              try {\n                  e = new window.Event('addtrack');\n              }\n              catch (err) {\n                  // for IE11\n                  e = document.createEvent('Event');\n                  e.initEvent('addtrack', false, false);\n              }\n              e.track = track;\n              mediaSink.dispatchEvent(e);\n          }\n          createHTMLCaptionsTrackGuts(channelNumber, name, languageCode, forced) {\n              const trackVar = 'cc' + channelNumber;\n              if (!this.channelToTrackMap[trackVar]) {\n                  // Enable reuse of existing closed caption text track.\n                  const existingHTMLTrack = this.getExistingHTMLTextTrackWithChannelNumber(channelNumber);\n                  if (!existingHTMLTrack) {\n                      const textTrack = this.createHTMLTextTrackGuts('captions', name, languageCode, forced);\n                      if (textTrack && isChannelTextTrackKey(trackVar)) {\n                          textTrack[trackVar] = true;\n                          this.channelToTrackMap[trackVar] = textTrack;\n                      }\n                  }\n                  else {\n                      this.channelToTrackMap[trackVar] = existingHTMLTrack;\n                      clearCurrentCues(this.channelToTrackMap[trackVar]);\n                      this.sendAddTrackEvent(this.channelToTrackMap[trackVar], this.mediaSink);\n                  }\n              }\n              return this.channelToTrackMap[trackVar];\n          }\n          createHTMLCaptionsTrack(channel) {\n              return this.createHTMLCaptionsTrackGuts(channel, this.config[channel === 1 ? 'captionsTextTrack1Label' : 'captionsTextTrack2Label'], this.config.captionsTextTrack1LanguageCode, false);\n          }\n          getExistingHTMLTextTrack(track) {\n              // this.logger.info(`getExistingHTMLTextTrack condenseSubtitleTrack ${this.config.condenseSubtitleTrack} track.persistentID ${track.persistentID} track.id ${track.id}`);\n              return this.config.condenseSubtitleTrack ? this.htmlTextTrackMap.get(track.persistentID) : this.htmlTextTrackMap.get(track.id);\n          }\n          getExistingHTMLTextTrackWithSubtitleTrackId(id) {\n              const altOption = this._availableMediaOptions.find((mediaOption) => mediaOption.id === id);\n              const htmlTextTrack = altOption ? this.getExistingHTMLTextTrack(altOption) : undefined;\n              this.logger.debug(`[subtitle] map track id ${id} to ${htmlTextTrack === null || htmlTextTrack === void 0 ? void 0 : htmlTextTrack.label} ${htmlTextTrack === null || htmlTextTrack === void 0 ? void 0 : htmlTextTrack.kind} ${htmlTextTrack === null || htmlTextTrack === void 0 ? void 0 : htmlTextTrack.language}`);\n              return htmlTextTrack;\n          }\n          getExistingHTMLTextTrackIndex(track) {\n              const htmlTextTrack = this.getExistingHTMLTextTrack(track);\n              const tracks = this.mediaSink.textTracks;\n              let found = -1;\n              for (let i = 0; i < tracks.length; ++i) {\n                  if (tracks[i] === htmlTextTrack) {\n                      found = i;\n                      break;\n                  }\n              }\n              return found;\n          }\n          setExistingHTMLTextTrack(track, textTrack) {\n              textTrack.persistentId = track.persistentID;\n              if (this.config.condenseSubtitleTrack) {\n                  // this.logger.info(`setExistingHTMLTextTrack: track.persistentID ${track.persistentID}, textTrack ${textTrack?.id} ${textTrack}`);\n                  return this.htmlTextTrackMap.set(track.persistentID, textTrack);\n              }\n              else {\n                  // this.logger.info(`setExistingHTMLTextTrack: track.id ${track.id}, textTrack ${textTrack?.id} ${textTrack}`);\n                  return this.htmlTextTrackMap.set(track.id, textTrack);\n              }\n          }\n          createHTMLTextTrack(track) {\n              let HTMLTextTrack = this.getExistingHTMLTextTrack(track);\n              if (!HTMLTextTrack) {\n                  if (track.mediaType === 'sbtl') {\n                      // this.logger.info(`create subtitle track ${track.name} from manifest`);\n                      this.subtitleTracksCreated += 1;\n                      HTMLTextTrack = this.createHTMLTextTrackGuts('subtitles', track.name, track.lang, track.forced);\n                  }\n                  else {\n                      let channelNumber = 1;\n                      if (track.inStreamID) {\n                          channelNumber = Number(track.inStreamID.substring(2));\n                      }\n                      // this.logger.info(`create caption track ${track.name} from manifest`);\n                      this.captionTracksCreated += 1;\n                      HTMLTextTrack = this.createHTMLCaptionsTrackGuts(channelNumber, track.name, track.lang, false);\n                  }\n                  if (HTMLTextTrack) {\n                      this.setExistingHTMLTextTrack(track, HTMLTextTrack);\n                      /* const data = {\n                        trackId: track.id,\n                        mediaOptionId: track.mediaOptionId,\n                        persistentId: track.persistentID,\n                        kind: HTMLTextTrack.kind,\n                        label: HTMLTextTrack.label,\n                        language: HTMLTextTrack.language,\n                      };\n                      this.logger.info(`textTrackCreated: ${JSON.stringify(data)}`);\n                      */\n                  }\n                  else {\n                      this.logger.error(`failed to create HTML text track for track ${track.id}: persistent id ${track.persistentID} name ${track.name} lang ${track.lang} inStreamID ${track.inStreamID}`);\n                      this.tracksFailed += 1;\n                  }\n              }\n              else {\n                  // this.logger.info(`reuse HTML text track for track ${track.id}: persistent id ${HTMLTextTrack.persistentId} kind ${HTMLTextTrack.kind} label ${HTMLTextTrack.label} lang ${HTMLTextTrack.language}`);\n                  this.tracksReused += 1;\n              }\n              return HTMLTextTrack;\n          }\n          createHTMLTextTrackGuts(kind, label, lang, forced) {\n              const mediaSink = this.mediaSink;\n              if (mediaSink) {\n                  let customTextTrackCueRenderer = false;\n                  if (kind !== 'metadata' && this.config.customTextTrackCueRenderer) {\n                      customTextTrackCueRenderer = true;\n                      kind = 'metadata';\n                  }\n                  const textTrack = mediaSink.addTextTrack(kind, label, lang);\n                  if (customTextTrackCueRenderer) {\n                      textTrack.customTextTrackCueRenderer = true;\n                  }\n                  return textTrack;\n              }\n              return undefined;\n          }\n          resetLoadSource() {\n              this.resetTracks();\n          }\n          resetTracks() {\n              this.logger.info('clean out all cues and cueRanges');\n              this._cleanTracks();\n              this.cueRanges = [];\n          }\n          _cleanTracks() {\n              // clear outdated subtitles\n              const mediaSink = this.mediaSink;\n              if (mediaSink) {\n                  const textTracks = mediaSink.textTracks;\n                  if (textTracks) {\n                      for (let i = 0; i < textTracks.length; i++) {\n                          clearCurrentCues(textTracks[i]);\n                      }\n                  }\n              }\n          }\n          getCuesOfEnabledTrack(trackId, checkForWebVTTCue = false) {\n              let cues = [];\n              if (!checkForWebVTTCue) {\n                  this.logger.info(`[subtitle] return regular cue list for track ${trackId}`);\n                  cues = this._getCuesOfEnabledTrack(trackId);\n              }\n              else {\n                  const sideTrackCues = this._getCuesOfEnabledTrack(trackId);\n                  for (let i = 0; i < sideTrackCues.length; i++) {\n                      const targetCue = sideTrackCues[i];\n                      if (isExtendedTextTrackCue(targetCue)) {\n                          // this.logger.info(`[subtitle] consider WebVTT cue: ${targetCue.startTime} ${targetCue.endTime} '${targetCue.text}'`);\n                          cues.push(targetCue);\n                      }\n                  }\n              }\n              return cues;\n          }\n          _getCuesOfEnabledTrack(trackId) {\n              const track = this.getTrack(trackId);\n              const htmlTrackKey = this.config.condenseSubtitleTrack ? track === null || track === void 0 ? void 0 : track.persistentID : track === null || track === void 0 ? void 0 : track.id;\n              const enabledHTMLTrack = this.htmlTextTrackMap.get(htmlTrackKey);\n              if (enabledHTMLTrack && enabledHTMLTrack.cues) {\n                  return Array.from(enabledHTMLTrack.cues);\n              }\n              else {\n                  return [];\n              }\n          }\n          attachSubtitleTracks() {\n              // We need both onSubtitleTrackUpdated and onMediaAttaching to resolve before attaching subtitle tracks\n              if (!this.gotTracks) {\n                  return;\n              }\n              this.subtitleTracksCreated = 0;\n              this.captionTracksCreated = 0;\n              this.tracksReused = 0;\n              this.tracksFailed = 0;\n              this.tracks.forEach((track) => {\n                  this.createHTMLTextTrack(track);\n              });\n              const data = {\n                  totalTracks: this.tracks.length,\n                  subtitleTracksCreated: this.subtitleTracksCreated,\n                  captionTracksCreated: this.captionTracksCreated,\n                  tracksReused: this.tracksReused,\n                  tracksFailed: this.tracksFailed,\n              };\n              this.logger.qe({ critical: true, name: 'textTrackCreated', data });\n          }\n          setTracks(mediaOptions, enabledMediaOption, disabledMediaOption) {\n              this._cleanTracks();\n              this.htmlTextTrackMap = new Map();\n              this.cueRanges = [];\n              if (this.config.enableWebVTT) {\n                  this.tracks = mediaOptions || [];\n              }\n              this.gotTracks = true;\n              this._availableMediaOptions = mediaOptions;\n              this._disabledMediaOption = disabledMediaOption;\n              this.attachSubtitleTracks();\n              this.selectedTrack = enabledMediaOption;\n              this.nativeSubtitleTrackChange$ = new Subject();\n              this.mediaSink.textTracksCreated = true;\n          }\n          // Need this to suppress errors when no client is listening for these styles\n          onInlineStylesParsed(data) { }\n          processSubtitleFrag(enabledMediaOption, frag, initPTS, payload) {\n              const data = new Uint8Array(payload);\n              const trackIndex = this.getExistingHTMLTextTrackIndex(enabledMediaOption);\n              // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n              /*\n              let re = /\\r\\n|\\n\\r|\\n|\\r/g;\n              let vtt = BufferUtils.utf8arrayToStr(data).trim().replace(re, '\\n').split('\\n');\n              vtt.forEach((line) => {\n                this.logger.info(`vtt.subtitle: ${line}`);\n              });\n              */\n              if (frag && payload.byteLength) {\n                  const fragCueRange = this._parseVTTs(trackIndex, frag, initPTS, data);\n                  if (fragCueRange && isFiniteNumber(fragCueRange.startTime)) {\n                      // startTime is valid only if there are cues (duplicated or otherwise) in the fragment\n                      this.lastCueEndTime = Math.max(this.lastCueEndTime, fragCueRange.endTime);\n                      this.logger.debug(`[subtitle] update lastCueEndTime ${this.lastCueEndTime}`);\n                  }\n                  return fragCueRange;\n              }\n              return;\n          }\n          _parseVTTs(textTrackIdx, frag, initPTS, payload) {\n              // Parse the WebVTT file contents.\n              let parsedfragCueRecord;\n              HLSVTTParser$1.parse(payload, initPTS, frag.start, frag.discoSeqNum, (cues) => {\n                  // Sometimes there are cue overlaps on segmented vtts so the same\n                  // cue can appear more than once in different vtt files.\n                  // This avoid showing duplicated cues with same timecode and text.\n                  const textTrack = this.mediaSink.textTracks[textTrackIdx];\n                  // Add cues and trigger event with success true.\n                  const fragCueRecord = { count: 0, startTime: Number.POSITIVE_INFINITY, endTime: 0 };\n                  cues.map((cue) => {\n                      if (textTrack && (!textTrack.cues || !textTrack.cues.getCueById(cue.id))) {\n                          this.logger.trace(`new cue for subtitle track[${frag.mediaOptionId}] frag sn ${frag.mediaSeqNum}: #${cue.id} [${cue.startTime}, ${cue.endTime}]: ${cue.text}`);\n                          cue.fragSN = frag.mediaSeqNum;\n                          cue.webVTTCue = true;\n                          textTrack.addCue(cue);\n                          fragCueRecord.count++;\n                          this.logger.debug(`[subtitle] cue added. fragCueRecord ${JSON.stringify(fragCueRecord)}`);\n                      }\n                      fragCueRecord.startTime = Math.min(cue.startTime, fragCueRecord.startTime);\n                      fragCueRecord.endTime = Math.max(cue.endTime, fragCueRecord.endTime);\n                      this.logger.debug(`[subtitle] frag processed. fragCueRecord ${JSON.stringify(fragCueRecord)}`);\n                  });\n                  this.logger.debug(`[subtitle] frag processing done. fragCueRecord ${JSON.stringify(fragCueRecord)}`);\n                  // fragCueRecord:\n                  // * startTime is a finite number only if there is at least 1 cue in the fragment\n                  // * count may be zero if duplicated cue (finite startTime) or no cue (PostiveInfinity startTime)\n                  parsedfragCueRecord = fragCueRecord;\n                  this.mediaSink.archiveParsedSubtitleFragmentRecord(this.selectedTrack.persistentID, frag.mediaSeqNum, fragCueRecord);\n              }, (e) => {\n                  // Something went wrong while parsing. Trigger event with success false.\n                  this.logger.info(`Failed to parse VTT cue: ${e}`);\n              }, (styles) => {\n                  this.hls.trigger(HlsEvent$1.INLINE_STYLES_PARSED, { styles: styles });\n              }, this.logger);\n              return parsedfragCueRecord;\n          }\n          _ensureParser() {\n              if (!this.cea608Parser) {\n                  const channel1 = new OutputFilter(this, 1);\n                  const channel2 = new OutputFilter(this, 2);\n                  this.cea608Parser = new Cea608Parser$1(0, channel1, channel2);\n              }\n          }\n          setupForFrag(frag) {\n              if (!frag || frag.mediaOptionType !== MediaOptionType.Variant || frag.iframe) {\n                  return;\n              }\n              const sn = frag.mediaSeqNum;\n              // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n              if (sn !== this.lastVariantSeqNum + 1) {\n                  this.resetClosedCaptionParser();\n              }\n              this.lastVariantSeqNum = sn;\n          }\n          resetClosedCaptionParser() {\n              var _a;\n              this.logger.info('reset cea608Parser');\n              (_a = this.cea608Parser) === null || _a === void 0 ? void 0 : _a.reset();\n          }\n          /**\n           * Add CLCP / ID3 samples\n           * @param offsetTimestamp offsetTimestamp is offset used for SourceBuffer timestampOffset calculation. All samples should be shifted by this value\n           * @param captionData Parsed caption data from demuxer\n           * @param id3Samples Parsed id3 samples from demuxer\n           * @param endPTS end Presentation Timestamp of the fragment\n           */\n          addLegibleSamples(offsetTimestamp, captionData, id3Samples, endPTS) {\n              if (captionData) {\n                  this.addClosedCaptionSamples(offsetTimestamp, captionData);\n              }\n              if (id3Samples && id3Samples.length > 0) {\n                  this.addId3Samples(offsetTimestamp, id3Samples, convertTimestampToSeconds(endPTS));\n              }\n          }\n          addClosedCaptionSamples(offsetTimestamp, captionData) {\n              if (captionData.mp4) {\n                  this.addMP4CaptionSamples(offsetTimestamp, captionData.mp4);\n              }\n              else if (captionData.ts) {\n                  this.addTSCaptionSamples(offsetTimestamp, captionData.ts);\n              }\n          }\n          addMP4CaptionSamples(offsetTimestamp, samples) {\n              // push all of the CEA-608 messages into the interpreter\n              // immediately. It will create the proper timestamps based on our PTS value\n              if (this.enableCaption && this.config.enableCEA708Captions) {\n                  const offsetTimestampSec = convertTimestampToSeconds(offsetTimestamp);\n                  this._ensureParser();\n                  for (let i = 0; i < samples.length; i++) {\n                      let startSec = samples[i].pts - offsetTimestampSec;\n                      const ccData = samples[i].bytes;\n                      for (let j = 0; j < ccData.length; j += 2) {\n                          const doubleByte = [];\n                          doubleByte.push(ccData[j]);\n                          if (j + 1 < ccData.length) {\n                              doubleByte.push(ccData[j + 1]);\n                          }\n                          else {\n                              this.logger.info(`CEA608 sample ${i} not even length (index ${j + 1} >= length ${ccData.length})`);\n                              doubleByte.push(80); // safest character to push is 80 (noop)\n                          }\n                          this.cea608Parser.addData(startSec, doubleByte);\n                          startSec += cea608Duration;\n                      }\n                  }\n              }\n          }\n          addTSCaptionSamples(offsetTimestamp, samples) {\n              if (this.enableCaption && this.config.enableCEA708Captions) {\n                  const offsetTimestampSec = convertTimestampToSeconds(offsetTimestamp);\n                  this._ensureParser();\n                  for (let i = 0; i < samples.length; i++) {\n                      const startSec = samples[i].pts - offsetTimestampSec;\n                      const ccdatas = LegibleSystemAdapter.extractCea608Data(samples[i].bytes);\n                      this.cea608Parser.addData(startSec, ccdatas);\n                  }\n              }\n          }\n          addId3Samples(offsetTimestamp, samples, endPTSSec) {\n              if (!this.config.enableID3Cues) {\n                  this.logger.info('id3 cues disabled by config');\n                  return;\n              }\n              // Attempt to recreate Safari functionality by creating\n              // WebKitDataCue objects when available and store the decoded\n              // ID3 data in the value property of the cue\n              const Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n              const offsetTimestampSec = convertTimestampToSeconds(offsetTimestamp);\n              for (let i = 0; i < samples.length; i++) {\n                  const startSec = samples[i].pts - offsetTimestampSec;\n                  let endSec = (i < samples.length - 1 ? samples[i + 1].pts : endPTSSec) - offsetTimestampSec;\n                  // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n                  if (startSec === endSec) {\n                      endSec += 0.0001;\n                  }\n                  if (samples[i].frames) {\n                      samples[i].frames.forEach((frame) => {\n                          if (frame && !this.id3shouldIgnore(frame)) {\n                              const cue = new Cue(startSec, endSec, '');\n                              cue.value = frame;\n                              this.logger.trace(`[id3] addCue [${startSec},${endSec}] ${JSON.stringify(cue.value).substr(0, 20)}...`);\n                              this.id3Track.addCue(cue);\n                          }\n                      });\n                  }\n              }\n          }\n          id3shouldIgnore(frame) {\n              return frame.key === 'PRIV' && (frame.info === 'com.apple.streaming.transportStreamTimestamp' || frame.info === 'com.apple.streaming.audioDescription');\n          }\n          static extractCea608Data(byteArray) {\n              const count = byteArray[0] & 31;\n              let position = 2;\n              let tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n              const actualCCBytes = [];\n              for (let j = 0; j < count; j++) {\n                  tmpByte = byteArray[position++];\n                  ccbyte1 = 127 & byteArray[position++];\n                  ccbyte2 = 127 & byteArray[position++];\n                  ccValid = (4 & tmpByte) !== 0;\n                  ccType = 3 & tmpByte;\n                  if (ccbyte1 === 0 && ccbyte2 === 0) {\n                      continue;\n                  }\n                  if (ccValid) {\n                      if (ccType === 0) {\n                          // || ccType === 1\n                          actualCCBytes.push(ccbyte1);\n                          actualCCBytes.push(ccbyte2);\n                      }\n                  }\n              }\n              return actualCCBytes;\n          }\n      }\n    \n      const makeLegibleService = (source$, config, eventEmitter, logger) => {\n          return source$.pipe(tag('playback.legibleServiceEpic.in'), switchMap((mediaSink) => {\n              if (!mediaSink) {\n                  return of(null);\n              }\n              const textTrackAdapter = new LegibleSystemAdapter(mediaSink, config, eventEmitter, logger);\n              return merge(of(textTrackAdapter), textTrackAdapter);\n          }), tag('playback.legibleServiceEpic.emit'));\n      };\n    \n      const SessionDataStatusCode = {\n          // Typucally (positive) HTTP Status code for network errors.\n          // Plus these ...\n          JSON_PARSE_ERROR: -1,\n      };\n    \n      const loggerName$6 = { name: 'plist' };\n      function stringIsXMLPlist(data) {\n          const XML_TAG_REGEX = /[\\s]*<\\?xml/i;\n          const PLIST_TAG_REGEX = /[\\s]*<plist/i;\n          XML_TAG_REGEX.lastIndex = 0;\n          const isXML = XML_TAG_REGEX.exec(data);\n          if (!isXML) {\n              return !!PLIST_TAG_REGEX.exec(data);\n          }\n          return !!isXML;\n      }\n      function stringIsJSONPlist(data) {\n          const JSON_REGEX = /[\\s]*[\\{\\[]/;\n          JSON_REGEX.lastIndex = 0;\n          return !!JSON_REGEX.exec(data);\n      }\n      function convertPlistToJSON(domNode) {\n          var _a, _b;\n          if (!domNode) {\n              return null;\n          }\n          const logger = getLogger();\n          let jsonObj = null;\n          const childNodes = domNode.childNodes;\n          if (childNodes) {\n              if (domNode.tagName) {\n                  const tagName = (_a = domNode.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase();\n                  // plist branch elements all have valid tag MediaOptionNames\n                  if (tagName === 'plist') {\n                      jsonObj = [];\n                      for (let i = 0; i < childNodes.length; ++i) {\n                          const child = childNodes[i];\n                          if (child.tagName) {\n                              jsonObj.push(convertPlistToJSON(child));\n                          }\n                      }\n                      if (jsonObj.length === 1) {\n                          jsonObj = jsonObj[0];\n                      }\n                  }\n                  if (tagName === 'array') {\n                      jsonObj = [];\n                      for (let i = 0; i < childNodes.length; ++i) {\n                          const child = childNodes[i];\n                          if (child.tagName) {\n                              jsonObj.push(convertPlistToJSON(child));\n                          }\n                      }\n                  }\n                  if (tagName === 'dict') {\n                      let key;\n                      let value;\n                      let validIndex = 0;\n                      jsonObj = {};\n                      for (let i = 0; i < childNodes.length; i++) {\n                          const child = childNodes[i];\n                          const cTagName = (_b = child.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase();\n                          if (cTagName) {\n                              if (validIndex % 2 === 0) {\n                                  if (cTagName === 'key') {\n                                      key = convertPlistToJSON(child);\n                                      validIndex++;\n                                  }\n                                  else {\n                                      logger.info(loggerName$6, `Skipping unknown dict element ${i} => ${cTagName}`);\n                                  }\n                              }\n                              else {\n                                  value = convertPlistToJSON(child);\n                                  jsonObj[key] = value;\n                                  key = null;\n                                  value = null;\n                                  validIndex++;\n                              }\n                          }\n                      }\n                      if (key) {\n                          // Last value may be missing. Treat it as NULL.\n                          jsonObj[key] = value;\n                          logger.info(loggerName$6, `Orphaned pair: ${key} = ${JSON.stringify(value)}`);\n                          key = null;\n                          value = null;\n                      }\n                  }\n                  else if (tagName === 'key') {\n                      // Leaf dict elements are wrapped in the sole child of TextNode. Reach down 1 level to get the value.\n                      const firstChild = childNodes[0];\n                      if (firstChild) {\n                          jsonObj = firstChild.nodeValue;\n                      }\n                      else {\n                          // Should not happen\n                          logger.warn(loggerName$6, 'Invalid dict key: Key is null, probably like this: <key/>');\n                          jsonObj = null;\n                      }\n                  }\n                  else if (tagName === 'string') {\n                      const firstChild = childNodes[0];\n                      if (firstChild) {\n                          jsonObj = firstChild.nodeValue;\n                      }\n                      else {\n                          jsonObj = null;\n                      }\n                  }\n                  else if (tagName === 'integer') {\n                      const firstChild = childNodes[0];\n                      if (firstChild) {\n                          jsonObj = parseInt(firstChild.nodeValue);\n                      }\n                      else {\n                          jsonObj = 0;\n                      }\n                  }\n                  else if (tagName === 'float') {\n                      const firstChild = childNodes[0];\n                      if (firstChild) {\n                          jsonObj = parseFloat(firstChild.nodeValue);\n                      }\n                      else {\n                          jsonObj = 0;\n                      }\n                  }\n                  else if (tagName === 'date') {\n                      const firstChild = childNodes[0];\n                      if (firstChild) {\n                          jsonObj = new Date(firstChild.nodeValue);\n                      }\n                      else {\n                          jsonObj = null;\n                      }\n                  }\n                  else if (tagName === 'data') {\n                      const firstChild = childNodes[0];\n                      if (firstChild) {\n                          // base64 encoded\n                          jsonObj = atob(firstChild.nodeValue);\n                      }\n                      else {\n                          jsonObj = null;\n                      }\n                  }\n                  else if (tagName === 'true') {\n                      jsonObj = true;\n                  }\n                  else if (tagName === 'false') {\n                      jsonObj = false;\n                  }\n              }\n              else {\n                  // Node without tagName may exist in the XML DOM tree.\n                  // See if its child/children are valid plist elements.\n                  if (childNodes.length < 1) {\n                      // This should never happen\n                      logger.warn(loggerName$6, `unknown node with unknown value > nodeType=${domNode.nodeType} tagName=${domNode.tagName} nodeName=${domNode.nodeName} value=${domNode.nodeValue}`);\n                  }\n                  else {\n                      jsonObj = [];\n                      for (let i = 0; i < childNodes.length; ++i) {\n                          const child = childNodes[i];\n                          if (child.tagName) {\n                              jsonObj.push(convertPlistToJSON(child));\n                          }\n                      }\n                      if (jsonObj.length === 1) {\n                          // If unknown node has only 1 child, replace it with its child's value.\n                          // Essentially drop the unknown node.\n                          jsonObj = jsonObj[0];\n                      }\n                  }\n              }\n          }\n          return jsonObj;\n      }\n    \n      class SessionDataLoader {\n          constructor(config, xhrLoader, customUrlLoader, logger) {\n              this.config = config;\n              this.xhrLoader = xhrLoader;\n              this.customUrlLoader = customUrlLoader;\n              this.sessionDataCheckForCompleteness = (sessionData) => {\n                  const { sessionDataAutoLoad } = this.config;\n                  const result = Object.assign({}, sessionData);\n                  if (!sessionData.complete) {\n                      if (sessionData.itemList) {\n                          // Playlist wihout SESSION-DATA tag has an empty itemList array\n                          result.complete = sessionData.itemList.every((metadata) => {\n                              if (sessionDataAutoLoad[metadata['DATA-ID']] && !metadata.VALUE && !metadata._STATUS && metadata.URI) {\n                                  this.logger.warn(`Incomplete because ${metadata['DATA-ID']} was autoloaded but no response yet`);\n                                  return false;\n                              }\n                              if (sessionDataAutoLoad[metadata['DATA-ID']] && !metadata.URI) {\n                                  this.logger.warn(`id=${metadata['DATA-ID']} missing uri`);\n                              }\n                              return true;\n                          });\n                      }\n                      else {\n                          this.logger.warn('Uninitialized SessionData');\n                      }\n                  }\n                  return result;\n              };\n              this.logger = logger.child({ name: 'SessionDataLoader' });\n          }\n          loadSessionData(sessionData) {\n              const { sessionDataAutoLoad } = this.config;\n              const itemList = sessionData.itemList || [];\n              let loadItems$ = of(sessionData);\n              itemList.forEach((item) => {\n                  const id = item['DATA-ID'];\n                  const uri = item.URI;\n                  //this.logger.info(`SessionData autoload ${id}: ${JSON.stringify(sessionDataAutoLoad[id])}`);\n                  if (uri && sessionDataAutoLoad[id]) {\n                      const url = URLToolkit$1.buildAbsoluteURL(sessionData.baseUrl, uri, { alwaysNormalize: true });\n                      const responseType = ''; // Use default responseType to allow XML parsing where necessary\n                      loadItems$ = loadItems$.pipe(switchMap((sd) => {\n                          return this.loadSessionDataItemWithUrl(url, id, responseType, this.config, sd, this.xhrLoader, this.customUrlLoader).pipe(catchError((err) => {\n                              this.logger.error(`Error loading SessionData > url=${url}, id=${id}, err=${err}`);\n                              return of(sd);\n                          }));\n                      }));\n                  }\n              });\n              return loadItems$.pipe(map((sd) => {\n                  if (itemList.length < 1) {\n                      return sd;\n                  }\n                  const updated = this.sessionDataCheckForCompleteness(sd);\n                  if (updated.complete) {\n                      return updated;\n                  }\n                  else {\n                      throw new ExceptionError(false, 'Session data not complete after loading all items', ErrorResponses.IncompleteSessionData);\n                  }\n              }), finalize$1(() => {\n                  this.logger.info('finalized');\n              }));\n          }\n          // Loading session data\n          // url : session data attribute URL, id : sessionData attribute data-id, responseType: \"text\", \"arraybuffer\", or other XMLHTTPRequest responseType\n          loadSessionDataItemWithUrl(url, id, responseType, config, sessionData, xhrLoader, customUrlLoader) {\n              const logger = getLogger();\n              const context = {\n                  url,\n                  method: 'GET',\n                  responseType,\n                  xhrSetup: config.xhrSetup,\n                  mimeType: 'application/xml',\n              };\n              const loadConfig = getLoadConfig({ url }, config.fragLoadPolicy);\n              let loader;\n              if (isCustomUrl(url)) {\n                  loader = customUrlLoader(context, loadConfig).pipe(map((res) => {\n                      return this.onLoadSuccess(sessionData, id, res.data.response.data.toString(), res.data.response.data);\n                  }));\n              }\n              else {\n                  loader = xhrLoader(context, loadConfig).pipe(map(([xhr]) => {\n                      return this.onLoadSuccess(sessionData, id, xhr.response, xhr.responseXML);\n                  }));\n              }\n              return loader.pipe(catchError((err) => {\n                  if (err instanceof TimeoutError) {\n                      err = new SessionDataNetworkError(false, err.message, 0, ErrorResponses.SessionDataLoadTimeout);\n                  }\n                  else if (err instanceof GenericNetworkError) {\n                      err = new SessionDataNetworkError(false, err.message, err.code, { code: err.code, text: 'Failed to load SessionData' });\n                  }\n                  logger.error(`Unable to load SessionData > err=${err}`);\n                  return of(this.onLoadError(sessionData, id, err));\n              }));\n          }\n          onLoadSuccess(sessionData, id, response, responseXML) {\n              let plistDOM = null;\n              let result = sessionData;\n              if (stringIsXMLPlist(response) && (plistDOM = responseXML)) {\n                  // Looks like XML. Use built-in XMLHttpRequest XML parser.\n                  const attrValue = convertPlistToJSON(plistDOM);\n                  result = this.setSessionData(sessionData, id, 'VALUE', attrValue);\n              }\n              else if (stringIsJSONPlist(response)) {\n                  // JSON format\n                  try {\n                      const attrValue = JSON.parse(response);\n                      result = this.setSessionData(sessionData, id, 'VALUE', attrValue);\n                  }\n                  catch (err) {\n                      this.logger.error(`JSON parser error: ${err}`);\n                      result = this.setSessionData(sessionData, id, 'VALUE', response);\n                      result = this.setSessionData(result, id, '_STATUS', SessionDataStatusCode.JSON_PARSE_ERROR);\n                  }\n              }\n              else {\n                  this.logger.info(`Unknown ${id} format. Using raw value`);\n                  result = this.setSessionData(sessionData, id, 'VALUE', response);\n              }\n              return result;\n          }\n          setSessionData(sessionData, id, attrName, obj) {\n              let result = sessionData;\n              if (sessionData.itemList) {\n                  let i;\n                  const itemList = [...sessionData.itemList];\n                  for (i = 0; i < sessionData.itemList.length; ++i) {\n                      const metadata = Object.assign({}, itemList[i]);\n                      if (metadata['DATA-ID'] === id) {\n                          metadata[attrName] = obj;\n                          itemList[i] = metadata;\n                          break;\n                      }\n                  }\n                  if (i === sessionData.itemList.length) {\n                      this.logger.error(`Can't set ${attrName} of session data ${id}`);\n                  }\n                  result = Object.assign(Object.assign({}, sessionData), { itemList });\n              }\n              else {\n                  this.logger.error(`Can't set ${attrName} on uninitialized session data`);\n              }\n              return result;\n          }\n          onLoadError(sessionData, id, err) {\n              var _a;\n              return this.setSessionData(sessionData, id, '_STATUS', (_a = err.response) === null || _a === void 0 ? void 0 : _a.code);\n          }\n      }\n    \n      function cacheEntityToInfoEntity(initSegmentEntity) {\n          const { itemId, mediaOptionId, discoSeqNum, keyTagInfo } = initSegmentEntity;\n          const initSegmentInfo = { itemId, mediaOptionId, discoSeqNum, keyId: Hex.hexDump(keyTagInfo === null || keyTagInfo === void 0 ? void 0 : keyTagInfo.keyId) };\n          return initSegmentInfo;\n      }\n      class MediaElementStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'media-element-store', producerFn: produce_1 });\n              this._activeId = '';\n          }\n          get activeId() {\n              return this._activeId;\n          }\n          startMediaSession(meState, maxBufferSeconds, almostDryWaterLevelSeconds, targetDurationSeconds) {\n              logAction('playback.session.start');\n              this._activeId = `media session: ${new Date().toISOString()}`;\n              applyTransaction(() => {\n                  const lowWaterLevelSeconds = targetDurationSeconds;\n                  const highWaterLevelSeconds = Math.max(lowWaterLevelSeconds, maxBufferSeconds - lowWaterLevelSeconds);\n                  const mediaElementEntity = {\n                      id: this.activeId,\n                      desiredRate: !meState.autoplay && meState.paused ? 0 : 1,\n                      paused: meState.paused,\n                      gotPlaying: false,\n                      gotLoadStart: false,\n                      firstPlayTime: undefined,\n                      seeking: meState.seeking,\n                      flushing: false,\n                      readyState: meState.readyState,\n                      ended: meState.ended,\n                      bufferedRanges: [],\n                      haveEnough: false,\n                      mediaSourceEntity: null,\n                      expectedSbCount: NaN,\n                      bufferMonitorInfo: {\n                          waterLevelType: null,\n                          almostDryWaterLevelSeconds,\n                          lowWaterLevelSeconds,\n                          highWaterLevelSeconds,\n                          maxBufferSeconds,\n                      },\n                      mediaOptionParsedSubtitleRecord: [],\n                      textTracksCreated: false,\n                      waitingForDisco: false,\n                  };\n                  this.add(mediaElementEntity);\n                  this.setActive(this.activeId);\n              });\n              this.logger = getLogger().child({ name: 'UpdateBufferedSegments' });\n              return this.activeId;\n          }\n          setMediaSourceEntity(objectUrl, readyState) {\n              logAction('playback.set.msObjectUrl');\n              this.updateActive((mediaElementEntity) => {\n                  if (objectUrl != null && readyState != null) {\n                      mediaElementEntity.mediaSourceEntity = { objectUrl, readyState, duration: NaN, sourceBufferEntities: [null, null] };\n                  }\n                  else {\n                      mediaElementEntity.mediaSourceEntity = null;\n                  }\n                  mediaElementEntity.bufferedRanges = [];\n                  mediaElementEntity.haveEnough = false;\n                  mediaElementEntity.readyState = 0;\n                  mediaElementEntity.bufferMonitorInfo.waterLevelType = null;\n              });\n          }\n          set mediaElementDuration(duration) {\n              logAction('playback.set.mediaElementDuration');\n              this.updateActive((mediaElementEntity) => {\n                  if (mediaElementEntity) {\n                      mediaElementEntity.mediaElementDuration = duration;\n                  }\n              });\n          }\n          set msReadyState(readyState) {\n              logAction('playback.set.msReadyState');\n              this.updateActive(({ mediaSourceEntity }) => {\n                  if (mediaSourceEntity) {\n                      mediaSourceEntity.readyState = readyState;\n                  }\n              });\n          }\n          set readyState(readyState) {\n              logAction(`playback.set.readyState ${readyState}`);\n              this.updateActive((active) => {\n                  active.readyState = readyState;\n              });\n          }\n          set ended(ended) {\n              logAction(`playback.set.ended ${ended}`);\n              this.updateActive((active) => {\n                  active.ended = ended;\n              });\n          }\n          set msDuration(duration) {\n              logAction('playback.set.msDuration');\n              this.updateActive((mediaElementEntity) => {\n                  mediaElementEntity.mediaSourceEntity.duration = duration;\n              });\n          }\n          set textTracksCreated(created) {\n              logAction('playback.set.textTracksCreated ${created}');\n              this.updateActive((mediaElementEntity) => {\n                  mediaElementEntity.textTracksCreated = created;\n              });\n          }\n          set expectedSbCount(expectedSbCount) {\n              logAction('playback.set.expectedSbCount');\n              this.updateActive((active) => {\n                  active.expectedSbCount = expectedSbCount;\n              });\n          }\n          set postFlushSeek(postFlushSeek) {\n              this.updateActive({ postFlushSeek });\n          }\n          setSeekToPos(seekToPos, fromEvent, discoSeqNum) {\n              logAction(`playback.set.seekToPos: ${seekToPos === null || seekToPos === void 0 ? void 0 : seekToPos.toFixed(3)} cc: ${discoSeqNum}`);\n              this.updateActive((entity) => {\n                  if (isFiniteNumber(seekToPos)) {\n                      entity.seekTo = { pos: seekToPos, fromEvent, discoSeqNum };\n                      entity.gotPlaying = false;\n                      entity.haveEnough = false;\n                  }\n                  else {\n                      entity.seekTo = null;\n                      entity.postFlushSeek = undefined;\n                  }\n                  if (fromEvent) {\n                      entity.seeking = isFiniteNumber(seekToPos);\n                  }\n              });\n          }\n          set seeking(seeking) {\n              logAction(`playback.set.seeking: ${seeking}`);\n              this.updateActive((entity) => {\n                  entity.seeking = seeking;\n              });\n          }\n          set paused(paused) {\n              logAction(`playback.set.paused: ${paused}`);\n              this.updateActive((entity) => {\n                  entity.paused = paused;\n                  if (paused) {\n                      entity.gotPlaying = false;\n                  }\n              });\n          }\n          // Got playing event\n          gotPlayingEvent() {\n              logAction('playback.set.playing');\n              this.updateActive((entity) => {\n                  if (!entity.paused) {\n                      entity.gotPlaying = true;\n                      entity.firstPlayTime = entity.firstPlayTime || performance.now();\n                  }\n              });\n          }\n          gotLoadStartEvent() {\n              logAction('playback.set.loadstart');\n              this.updateActive((entity) => {\n                  entity.gotLoadStart = true;\n              });\n          }\n          set desiredRate(desiredRate) {\n              logAction(`playback.set.desiredRate: ${desiredRate}`);\n              this.updateActive((active) => {\n                  active.desiredRate = desiredRate;\n              });\n          }\n          set haveEnough(haveEnough) {\n              logAction(`playback.set.haveEnough: ${haveEnough}`);\n              this.updateActive((active) => {\n                  active.haveEnough = haveEnough;\n              });\n          }\n          set flushing(flushing) {\n              logAction(`playback.set.flushing: ${flushing}`);\n              this.updateActive({ flushing });\n          }\n          set waitingForDisco(waitingForDisco) {\n              logAction(`playback.set.waitingForDisco: ${waitingForDisco}`);\n              this.updateActive((entity) => {\n                  if (entity) {\n                      entity.waitingForDisco = waitingForDisco;\n                  }\n              });\n          }\n          setSourceBufferUpdating(type) {\n              logAction(`playback.set.sourcebuffers[${SourceBufferNames[type]}].updating`);\n              this.updateActive(({ mediaSourceEntity }) => {\n                  var _a;\n                  const sbEntity = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[type];\n                  if (sbEntity) {\n                      sbEntity.updating = true;\n                      sbEntity.error = undefined;\n                  }\n              });\n          }\n          setTimestampOffset(type, timestampOffset) {\n              logAction(`playback.set.sourcebuffers[${SourceBufferNames[type]}].timestampOffset`);\n              this.updateActive(({ mediaSourceEntity }) => {\n                  var _a;\n                  const sbEntity = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[type];\n                  if (sbEntity) {\n                      sbEntity.timestampOffset = timestampOffset;\n                  }\n              });\n          }\n          setBufferedRangesUpdated(type, bufferedRanges, combinedBuffer, gotQuotaExceeded, config) {\n              logAction(`playback.set.sourcebuffers[${SourceBufferNames[type]}].bufferupdated`);\n              this.updateActive((mediaElementEntity) => {\n                  var _a;\n                  const mediaSourceEntity = mediaElementEntity === null || mediaElementEntity === void 0 ? void 0 : mediaElementEntity.mediaSourceEntity;\n                  const sbEntity = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[type];\n                  if (sbEntity) {\n                      const msDuration = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.duration;\n                      sbEntity.updating = false;\n                      sbEntity.bufferedRanges = [...bufferedRanges];\n                      mergeInflightSegment(sbEntity);\n                      // updateBufferedSegments even if bufferedRanges is empty\n                      updateBufferedSegments(sbEntity, gotQuotaExceeded, msDuration, config, this.logger);\n                  }\n                  mediaElementEntity.bufferedRanges = [...combinedBuffer];\n              });\n          }\n          setSourceBufferEntity(type, compatInfo) {\n              logAction(`playback.set.sourcebuffers[${SourceBufferNames[type]}].setSourceBufferEntity`);\n              this.updateActive(({ mediaSourceEntity }) => {\n                  if (!mediaSourceEntity)\n                      return;\n                  const { mimeType, audioCodec, videoCodec } = compatInfo;\n                  const sbEntity = {\n                      mimeType,\n                      audioCodec,\n                      videoCodec,\n                      updating: false,\n                      bufferedRanges: [],\n                      timestampOffset: 0,\n                      // Calculated\n                      inFlight: null,\n                      bufferedSegments: [],\n                      totalBytes: 0,\n                      maxTotalBytes: 0,\n                      gotQuotaExceeded: false,\n                      totalDuration: Infinity,\n                  };\n                  mediaSourceEntity.sourceBufferEntities[type] = sbEntity;\n              });\n          }\n          setInflightSegment(type, segment) {\n              logAction(`playback.set.sourcebuffers[${SourceBufferNames[type]}].setInflightSegment`);\n              this.updateActive(({ mediaSourceEntity }) => {\n                  var _a;\n                  const sbEntity = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[type];\n                  if (sbEntity) {\n                      sbEntity.inFlight = segment;\n                  }\n              });\n          }\n          setInitSegmentEntity(type, initSegmentEntity) {\n              logAction(`playback.set.sourcebuffers[${SourceBufferNames[type]}].setInitSegmentEntity`);\n              this.updateActive(({ mediaSourceEntity }) => {\n                  var _a;\n                  const sbEntity = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[type];\n                  if (sbEntity) {\n                      sbEntity.initSegmentInfo = initSegmentEntity;\n                  }\n              });\n          }\n          setSourceBufferError(type, error) {\n              logAction(`playback.set.sourcebuffers[${type}].error: ${error}`);\n              this.updateActive(({ mediaSourceEntity }) => {\n                  var _a;\n                  const sbEntity = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[type];\n                  if (sbEntity) {\n                      sbEntity.inFlight = null;\n                      sbEntity.updating = false;\n                      sbEntity.error = error;\n                  }\n              });\n          }\n          setStallInfo(stallInfo) {\n              logAction(`playback.set.stallInfo stalled=${stallInfo != null}`);\n              this.updateActive((active) => {\n                  active.stallInfo = stallInfo;\n              });\n          }\n          setNudgeInfo(nudgeInfo) {\n              logAction(`playback.set.nudgeInfo ${stringifyWithPrecision(nudgeInfo)}`);\n              this.updateActive((active) => {\n                  active.nudgeInfo = nudgeInfo;\n              });\n          }\n          /**\n           * Update water level information\n           * @param combined  Water level of combined buffer\n           * @param sbTuple   Water level of each source buffer\n           */\n          updateWaterLevels(combined, sbTuple) {\n              logAction('playback.set.updateWaterLevels');\n              this.updateActive((entity) => {\n                  entity.bufferMonitorInfo.waterLevelType = { combined, sbTuple: [...sbTuple] };\n              });\n          }\n          /**\n           * @param targetDurationSeconds The duration in seconds to use for determining low and high water.\n           *   Low water threshold is 1 target duration, high water threshold is Math.max(lowWater, maxBuffer - targetDuration)\n           */\n          set bufferMonitorTargetDuration(targetDurationSeconds) {\n              logAction(`playback.set.targetDuration: ${targetDurationSeconds}`);\n              this.updateActive((entity) => {\n                  if (isFiniteNumber(targetDurationSeconds) && targetDurationSeconds > 0) {\n                      const bufMonitorInfo = entity.bufferMonitorInfo;\n                      bufMonitorInfo.lowWaterLevelSeconds = Math.min(targetDurationSeconds, bufMonitorInfo.maxBufferSeconds);\n                      bufMonitorInfo.highWaterLevelSeconds = Math.max(bufMonitorInfo.lowWaterLevelSeconds, bufMonitorInfo.maxBufferSeconds - targetDurationSeconds);\n                  }\n              });\n          }\n          archiveParsedSubtitleFragmentRecord(persistentId, mediaSeqNum, fragCueRecord) {\n              logAction(`playback.cues.set persistentId ${persistentId} mediaSeqNum ${mediaSeqNum}: parsed ${fragCueRecord.count} time-range ${fragCueRecord.startTime}:${fragCueRecord.endTime}`);\n              this.updateActive((entity) => {\n                  let trackInfo = entity.mediaOptionParsedSubtitleRecord[persistentId];\n                  if (!trackInfo) {\n                      trackInfo = {};\n                      entity.mediaOptionParsedSubtitleRecord[persistentId] = trackInfo;\n                  }\n                  trackInfo[mediaSeqNum] = fragCueRecord;\n              });\n          }\n      }\n      function mergeInflightSegment(sbEntity) {\n          const inFlight = sbEntity.inFlight;\n          const mergedBufferSeg = sbEntity.bufferedSegments;\n          if (inFlight && isFiniteNumber(inFlight.startPTS) && isFiniteNumber(inFlight.endPTS)) {\n              mergeToBuffer(mergedBufferSeg, inFlight);\n          }\n          sbEntity.inFlight = null;\n      }\n      // Helper functions for updating buffered segments, modifies sbEntity.bufferedSegments in-place\n      function updateBufferedSegments(sbEntity, gotQuotaExceeded, msDuration, config, logger) {\n          const { maxBufferHole, bufferedSegmentEjectionToleranceMs } = config;\n          // Modify in-place since we do not read anyway\n          const mergedBufferSeg = sbEntity.bufferedSegments;\n          const realBuffered = sbEntity.bufferedRanges;\n          let totalBytes = 0;\n          let lastFragEjected = false;\n          let lastFrag;\n          if (realBuffered.length) {\n              for (let i = mergedBufferSeg.length - 1; i > -1; i--) {\n                  const segment = mergedBufferSeg[i];\n                  const notIframe = !segment.frag.iframe;\n                  if (notIframe && segment.frag.isLastFragment) {\n                      lastFrag = segment.frag;\n                  }\n                  const segmentDuration = segment.endPTS - segment.startPTS;\n                  if (segmentDuration <= 0) {\n                      mergedBufferSeg.splice(i, 1);\n                      logger === null || logger === void 0 ? void 0 : logger.warn(`Ejecting segment from bufferedSegments due to segmentDuration <= 0 > segment=${stringifyWithPrecision(segment)}`);\n                      lastFragEjected = segment.frag === lastFrag;\n                      continue; // Should never happen but...\n                  }\n                  const overlapping = getMaxOverlappingRange(realBuffered, segment);\n                  // startPTS/endPTS is sometimes a bit off from what is reported in buffered,\n                  // especially for audio. Add the byteLength approximation with overlap factor.\n                  if (overlapping) {\n                      // Estimate total bytes using all buffered time ranges\n                      const overlapStart = Math.max(overlapping.start, segment.startPTS);\n                      const overlapEnd = Math.min(overlapping.end, segment.endPTS);\n                      const appendedDuration = overlapEnd - overlapStart;\n                      totalBytes += (segment.bytes * appendedDuration) / segmentDuration;\n                      if (notIframe) {\n                          // ignore tiny overlaps\n                          if (appendedDuration < Math.min(segmentDuration, maxBufferHole)) {\n                              mergedBufferSeg.splice(i, 1);\n                              logger === null || logger === void 0 ? void 0 : logger.warn(`Ejecting segment from bufferedSegments due to tiny overlaps > segment=${stringifyWithPrecision(segment)}, bufferedRanges=${stringifyWithPrecision(realBuffered)}`);\n                              lastFragEjected = segment.frag === lastFrag;\n                              continue;\n                          }\n                          // Keep track of initial appended overlap, and remove the segment if the current overlap has changed\n                          // except when the segment duration was modified because of an overlapping append in mergeToBuffer\n                          const initialAppendedValue = segment.appendedDuration;\n                          const appendedDurationDelta = (initialAppendedValue || 0) - appendedDuration;\n                          // rdar://84943043 tolerance is used to avoid floating point arithmetic issues\n                          const tolerance = Math.min(bufferedSegmentEjectionToleranceMs * 0.001, segmentDuration);\n                          if (!initialAppendedValue) {\n                              segment.appendedDuration = appendedDuration;\n                          }\n                          else if (appendedDurationDelta > tolerance && appendedDuration !== segmentDuration) {\n                              // Eject, unless last segment and buffer end equals known mediaSink duration\n                              if (!segment.frag.isLastFragment || overlapEnd !== msDuration) {\n                                  mergedBufferSeg.splice(i, 1);\n                                  logger === null || logger === void 0 ? void 0 : logger.warn(`Ejecting segment from bufferedSegments due to change in current overlap > segment=${stringifyWithPrecision(segment)}, delta=${appendedDurationDelta}, bufferedRanges=${stringifyWithPrecision(realBuffered)}`);\n                                  lastFragEjected = segment.frag === lastFrag;\n                                  continue;\n                              }\n                          }\n                      }\n                  }\n                  else {\n                      logger === null || logger === void 0 ? void 0 : logger.warn(`Ejecting segment from bufferedSegments due to no overlap > segment=${stringifyWithPrecision(segment)}, bufferedRanges=${stringifyWithPrecision(realBuffered)}`);\n                      mergedBufferSeg.splice(i, 1);\n                      lastFragEjected = segment.frag === lastFrag;\n                  }\n              }\n          }\n          else if (mergedBufferSeg.length) {\n              logger === null || logger === void 0 ? void 0 : logger.info('Flushing buffered segments in response to flush');\n              mergedBufferSeg.splice(0, mergedBufferSeg.length); // flushed out\n          }\n          // if last frag was ejected this round, realBuffered[realBuffered.length - 1].end will not have the right totalduration.\n          // if everything was flushed out, totalduration will remain unchanged (lastFrag will be false)\n          sbEntity.totalDuration = lastFrag && !lastFragEjected && realBuffered.length > 0 ? realBuffered[realBuffered.length - 1].end : Infinity;\n          sbEntity.gotQuotaExceeded = sbEntity.gotQuotaExceeded || gotQuotaExceeded;\n          sbEntity.totalBytes = totalBytes;\n          sbEntity.maxTotalBytes = Math.max(sbEntity.totalBytes, sbEntity.maxTotalBytes);\n      }\n      // Merge the newly appended segment into what we think we already have buffered\n      // Assumed buffered has no overlaps already and is sorted by startPTS\n      // Modifies in-place\n      function mergeToBuffer(buffered, appended) {\n          let appendedAdded = false;\n          for (let i = buffered.length - 1; i > -1; i--) {\n              const seg = buffered[i];\n              const overlapStart = Math.max(appended.startPTS, seg.startPTS);\n              const overlapEnd = Math.min(appended.endPTS, seg.endPTS);\n              if (overlapStart >= overlapEnd) {\n                  continue;\n              }\n              const bytes = (1 - (overlapEnd - overlapStart) / (seg.endPTS - seg.startPTS)) * seg.bytes;\n              if (bytes <= 0) {\n                  buffered.splice(i, 1);\n                  continue;\n              }\n              seg.bytes = bytes;\n              if (seg.startPTS < appended.startPTS) {\n                  seg.endPTS = overlapStart;\n              }\n              else {\n                  seg.startPTS = overlapEnd;\n                  if (!appendedAdded) {\n                      buffered.splice(i, 0, appended);\n                      appendedAdded = true;\n                  }\n              }\n          }\n          if (!appendedAdded) {\n              buffered.push(appended);\n          }\n      }\n      /**\n       * Returns length of overlap of segment with given bufferedRange\n       */\n      function segmentOverlapLength(segment, range) {\n          return Math.min(segment.endPTS, range.end) - Math.max(segment.startPTS, range.start);\n      }\n      /**\n       * Returns the BufferedRange that has maximum ovelap with given segment.\n       */\n      function getMaxOverlappingRange(bufferedRanges, segment) {\n          let maxOverlappingRange = undefined;\n          let lastOverlapLength = 0;\n          // TODO: Use binary search over bufferedRanges rdar://89159252\n          for (const range of bufferedRanges) {\n              // Check only when there is overlap\n              if (range.start <= segment.endPTS && range.end > segment.startPTS) {\n                  const currentOverlapLength = segmentOverlapLength(segment, range);\n                  if (currentOverlapLength > lastOverlapLength) {\n                      maxOverlappingRange = range;\n                      lastOverlapLength = currentOverlapLength;\n                  }\n              }\n              else if (lastOverlapLength > 0) {\n                  // bufferedRanges is Normalized TimeRanges object i.e \"The ranges in such an object are ordered, don't overlap, and don't touch\"\n                  // No point iterating through rest of ranges if overlap is found previously and no overlap afterwards.\n                  break;\n              }\n          }\n          return maxOverlappingRange;\n      }\n    \n      function isIframeMediaFragment(frag) {\n          return frag != null && 'iframeMediaDuration' in frag && 'iframeMediaStart' in frag;\n      }\n      function fragEqual(a, b) {\n          return a === b || (a && b && a.itemId === b.itemId && a.mediaOptionId === b.mediaOptionId && a.mediaSeqNum === b.mediaSeqNum && a.discoSeqNum === b.discoSeqNum);\n      }\n      function fragPrint(frag) {\n          return JSON.stringify(frag, ['mediaOptionId', 'mediaSeqNum', 'discoSeqNum', 'start', 'duration']);\n      }\n    \n      function filterNullOrUndefined() {\n          return (source) => source.pipe(filter((x) => x != null), map((x) => x));\n      }\n    \n      function getVideoCodecRanking(videoCodec) {\n          if (MediaUtil.isDolby(videoCodec)) {\n              return VideoCodecRank.DOVI;\n          }\n          else if (MediaUtil.isHEVC(videoCodec)) {\n              return VideoCodecRank.HEVC;\n          }\n          else if (MediaUtil.isVP09(videoCodec)) {\n              return VideoCodecRank.VP09;\n          }\n          else if (MediaUtil.isAVC(videoCodec)) {\n              return VideoCodecRank.AVC;\n          }\n          else {\n              return VideoCodecRank.UNKNOWN;\n          }\n      }\n      function getVideoCodecFamily(videoCodec) {\n          return videoCodec === null || videoCodec === void 0 ? void 0 : videoCodec.split('.')[0];\n      }\n      function getAudioCodecRanking(audioCodec) {\n          if (MediaUtil.isALAC(audioCodec)) {\n              return AudioCodecRank.ALAC;\n          }\n          else if (MediaUtil.isFLAC(audioCodec)) {\n              return AudioCodecRank.FLAC;\n          }\n          else if (MediaUtil.isEC3(audioCodec)) {\n              return AudioCodecRank.EC3;\n          }\n          else if (MediaUtil.isAC3(audioCodec)) {\n              return AudioCodecRank.AC3;\n          }\n          else if (MediaUtil.isXHEAAC(audioCodec)) {\n              return AudioCodecRank.XHEAAC;\n          }\n          else if (MediaUtil.isAAC(audioCodec)) {\n              return AudioCodecRank.AAC;\n          }\n          else if (MediaUtil.isMP3(audioCodec)) {\n              return AudioCodecRank.MP3;\n          }\n          else {\n              return AudioCodecRank.UNKNOWN;\n          }\n      }\n      function getVideoRangeRanking(videoRange) {\n          if (videoRange === 'PQ') {\n              return VideoRangeRank.PQ;\n          }\n          else if (videoRange === 'HLG') {\n              return VideoRangeRank.HLG;\n          }\n          else if (videoRange === 'SDR') {\n              return VideoRangeRank.SDR;\n          }\n          else {\n              return VideoRangeRank.UNKNOWN;\n          }\n      }\n      function getAudioVideoCodecRanks(codecInfo) {\n          return { videoCodecRank: getVideoCodecRanking(codecInfo.videoCodec), audioCodecRank: getAudioCodecRanking(codecInfo.audioCodec) };\n      }\n      class MediaOptionRank {\n          constructor(...identifier) {\n              this.identifier = identifier;\n          }\n          ensureSameIdentifierLength(rank) {\n              if (this.identifier.length !== rank.identifier.length) {\n                  throw new Error(`Identifiers have non-matching lengths! (${this.identifier.length} vs ${rank.identifier.length})`);\n              }\n          }\n          isGreaterThan(rank) {\n              this.ensureSameIdentifierLength(rank);\n              for (let i = 0; i < this.identifier.length; ++i) {\n                  if (this.identifier[i] < rank.identifier[i]) {\n                      return false;\n                  }\n                  else if (this.identifier[i] > rank.identifier[i]) {\n                      return true;\n                  }\n              }\n              return false;\n          }\n          isEqualTo(rank) {\n              this.ensureSameIdentifierLength(rank);\n              return this.identifier.every((entry, i) => entry === rank.identifier[i]);\n          }\n      }\n    \n      function isIframeRate(rate) {\n          return isFiniteNumber(rate) && rate !== 0 && rate !== 1;\n      }\n    \n      class MutexBusyError extends Error {\n      }\n      const __executeAndUnlock = (value, update, unlock, operation) => {\n          if (!operation) {\n              // no operation() provided, caller should excplicitly call unlock()\n              return of(value);\n          }\n          let result;\n          let obs;\n          try {\n              result = operation(value, update);\n          }\n          catch (err) {\n              obs = throwError(() => err);\n          }\n          if (!obs) {\n              if (typeof result === 'undefined') {\n                  obs = of(value);\n              }\n              else {\n                  obs = from(result);\n              }\n          }\n          // auto-unlock if operation() has been called\n          return obs.pipe(finalize$1(unlock));\n      };\n      /**\n       * Mutex is a concept borrowed from multi-threaded programming. Although it's\n       * not the first time multi-thread syncing primitives are used in single\n       * threaded program. Python 3 for example has a collection of single threaded\n       * coroutine syncing primitives in the asyncio package. Any single threaded\n       * program with an event loop would have the problem of \"data race\" before and\n       * after the event loop context switch. Note that event loop achieves concurrent\n       * processing similar to system level process and thread scheduling on a single\n       * core. Therefore, classical syncing primitives are also applicable for event\n       * loops.\n       *\n       * IMPORTANT: Always justify your reason if you use Mutex in your code. The only\n       * permitable use-case is the protected operation can be called from different\n       * threads and only one can execute at one time. If the component has multiple\n       * such operations need this synchronization, please consider using command\n       * queue pattern instead of Mutex.\n       */\n      class Mutex {\n          /**\n           * Mutex can optionally carry the data it's protecting. Doing so can make it\n           * more explicit that the data should be accessed while holing a lock of this\n           * mutex.\n           * @param value data to be stored on the Mutex\n           */\n          constructor(value) {\n              this.value = value;\n              this.waiters = [];\n              this.wcounter = 0;\n              this.rcounter = 0;\n          }\n          lock(operation, tryLock = false) {\n              return this._lock(true, operation, tryLock);\n          }\n          /**\n           * Release a lock previously acquired on the mutex.\n           */\n          unlock() {\n              this._unlock(true);\n          }\n          readLock(operation, tryLock = false) {\n              return this._lock(false, operation, tryLock);\n          }\n          /**\n           * Release a read-only lock previously acquired on the mutex.\n           */\n          readUnlock() {\n              this._unlock(false);\n          }\n          _schedule() {\n              const _waitersToWake = [];\n              this.waiters = this.waiters.filter(waiter => {\n                  if (this._canLock(waiter.rw)) {\n                      if (waiter.rw) {\n                          ++this.wcounter;\n                      }\n                      else {\n                          ++this.rcounter;\n                      }\n                      _waitersToWake.push(waiter);\n                      return false;\n                  }\n                  return true;\n              });\n              for (const waiter of _waitersToWake) {\n                  waiter.observer.next(this.value);\n                  waiter.observer.complete();\n              }\n          }\n          _canLock(rw) {\n              return (rw && this.wcounter === 0 && this.rcounter === 0) || (!rw && this.wcounter === 0);\n          }\n          _lock(rw, operation, tryLock = false) {\n              if (typeof operation === 'boolean') {\n                  [tryLock, operation] = [operation, undefined];\n              }\n              const obs = new Observable(observer => {\n                  const canLock = this._canLock(rw);\n                  if (tryLock && !canLock) {\n                      throw new MutexBusyError();\n                  }\n                  if (canLock) {\n                      if (rw) {\n                          ++this.wcounter;\n                      }\n                      else {\n                          ++this.rcounter;\n                      }\n                      observer.next();\n                      observer.complete();\n                  }\n                  else {\n                      this.waiters.push({ rw, observer });\n                  }\n              });\n              if (operation) {\n                  return obs.pipe(mergeMap(() => __executeAndUnlock(this.value, newval => void (this.value = newval), () => this._unlock(rw), operation)));\n              }\n              return obs;\n          }\n          _unlock(rw) {\n              if (rw) {\n                  this.wcounter = Math.max(this.wcounter - 1, 0);\n              }\n              else {\n                  this.rcounter = Math.max(this.rcounter - 1, 0);\n              }\n              this._schedule();\n          }\n      }\n      /**\n       * WaitGroup is a concept borrowed from Golang used to wait for async routines\n       * to finish. We can use it to signal async shutdown completion to subscribers.\n       *\n       *      class Hls {\n       *        public destroy$ = new Subject<void>();\n       *        public destroyWG = new WaitGroup();\n       *        constructor() {\n       *          observableWithAsyncTeardown(this).pipe(\n       *            takeUntil(this.destroy$)   // chain its lifecycle to Hls\n       *          ).subscribe();\n       *        }\n       *        public destroy(): Promise<void> {\n       *          this.destroy$.next();\n       *          // all lifecyles chained below Hls will teardown. Async routines\n       *          // will be registered with hls.destroyWG.add()\n       *\n       *          return this.destroyWG.toPromise();\n       *          // returned promise will resolve when all async routines\n       *          // registered are finished with hls.destroyWG.done()\n       *        }\n       *      }\n       *      const observableWithAsyncTeardown = (hls: Hls) =>\n       *        new Observable<void>((subscriber) => {\n       *          return () => {            // teardown function\n       *            hls.destroyWG.add();    // register an async routine\n       *            setTimeout(() => {\n       *              console.log('async teardown finished');\n       *              hls.destroyWG.done(); // signal finish of a async routine\n       *            }, 1000);\n       *          };\n       *        });\n       *\n       * And there is a shorthand for Promise or Observable like async routine:\n       *\n       *     wg.wrap(promise).subscribe();\n       *\n       */\n      class WaitGroup extends Observable {\n          constructor() {\n              super((subscriber) => this._count$\n                  .pipe(\n              // emits only when count reaches to zero\n              filter((count) => count === 0), \n              // completes once count reaches to zero\n              take(1), \n              // convert to empty value (undefined)\n              mapTo(void 0))\n                  .subscribe(subscriber));\n              this._count$ = new BehaviorSubject(0);\n          }\n          /**\n           * Wrap an async operation to wait for.\n           * @param routine an async operation to wait for\n           */\n          wrap(routine) {\n              return defer(() => {\n                  this.add();\n                  return from(routine);\n              }).pipe(\n              // propagate error in the async routine\n              tap({ error: (e) => this._count$.error(e) }), \n              // decrement the count when the async routine finishes\n              finalize$1(() => this.done()));\n          }\n          /**\n           * Increase the wait counter.\n           * @param n delta to increase the counter\n           */\n          add(n = 1) {\n              this._count$.next(this._count$.value + n);\n          }\n          /**\n           * Decrease the wait counter.\n           * @param n delta to decrease the counter\n           */\n          done(n = 1) {\n              this._count$.next(this._count$.value - n);\n          }\n      }\n    \n      \n      const BufferHelper = {\n          isBuffered(buffered, position) {\n              for (let i = 0; buffered && i < buffered.length; i++) {\n                  if (position >= buffered.start(i) && position <= buffered.end(i)) {\n                      return true;\n                  }\n              }\n              return false;\n          },\n          /**\n           * Return Array of [ {start, end} ]\n           * @param media Something with a buffered TimeRanges property (HTMLMediaElement, SourceBuffer, etc)\n           */\n          timeRangesToBufferedRange(timeRanges) {\n              const bufferedRangeArray = [];\n              for (let ix = 0; timeRanges && ix < timeRanges.length; ix++) {\n                  bufferedRangeArray.push({\n                      start: timeRanges.start(ix),\n                      end: timeRanges.end(ix),\n                  });\n              }\n              return bufferedRangeArray;\n          },\n          subtitleBufferInfo(cues, pos, maxHoleDuration) {\n              if (cues) {\n                  const buffered = this.bufferedCues(cues);\n                  return this.getBufferedInfo(buffered, pos, maxHoleDuration);\n              }\n              return { len: 0, start: pos, end: pos, nextStart: undefined };\n          },\n          fragmentsBufferedInfo(bufferedFrags, pos, maxHoleDuration) {\n              const buffered = [];\n              for (const frag of bufferedFrags) {\n                  buffered.push({ start: frag.start, end: frag.start + frag.duration });\n              }\n              return this.getBufferedInfo(buffered, pos, maxHoleDuration);\n          },\n          bufferedCues(cues) {\n              const buffered = [];\n              if (cues) {\n                  for (let ix = 0; ix < cues.length; ix++) {\n                      buffered.push({ start: cues[ix].startTime, end: cues[ix].endTime });\n                  }\n              }\n              return buffered;\n          },\n          bufferedInfoFromMedia(media, pos, maxHoleDuration) {\n              return BufferHelper.getBufferedInfo(BufferHelper.timeRangesToBufferedRange(media.buffered), pos, maxHoleDuration);\n          },\n          getBufferedInfo(inBufferedRanges, pos, maxHoleDuration) {\n              const buffered2 = [];\n              // bufferStart and bufferEnd are buffer boundaries around current video position\n              let bufferLen, bufferStart, bufferEnd, bufferStartNext, i;\n              // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n              const bufferedRanges = inBufferedRanges.map(({ start, end }) => ({ start, end }));\n              bufferedRanges.sort((a, b) => {\n                  const diff = a.start - b.start;\n                  if (diff) {\n                      return diff;\n                  }\n                  return b.end - a.end;\n              });\n              // there might be some small holes between buffer time range\n              // consider that holes smaller than maxHoleDuration are irrelevant and build another\n              // buffer time range representations that discards those holes\n              for (i = 0; i < bufferedRanges.length; i++) {\n                  const buf2len = buffered2.length;\n                  if (buf2len) {\n                      const buf2end = buffered2[buf2len - 1].end;\n                      // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n                      if (bufferedRanges[i].start - buf2end < maxHoleDuration) {\n                          // merge overlapping time ranges\n                          // update lastRange.end only if smaller than item.end\n                          // e.g.  [ 1, 15] with  [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n                          // whereas [ 1, 8] with  [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n                          if (bufferedRanges[i].end > buf2end) {\n                              buffered2[buf2len - 1].end = bufferedRanges[i].end;\n                          }\n                      }\n                      else {\n                          // big hole\n                          buffered2.push(bufferedRanges[i]);\n                      }\n                  }\n                  else {\n                      // first value\n                      buffered2.push(bufferedRanges[i]);\n                  }\n              }\n              for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {\n                  const { start } = buffered2[i], { end } = buffered2[i];\n                  if (pos + maxHoleDuration >= start && pos < end) {\n                      // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n                      bufferStart = start;\n                      bufferEnd = end;\n                      bufferLen = bufferEnd - pos;\n                  }\n                  else if (pos + maxHoleDuration < start) {\n                      bufferStartNext = start;\n                      break;\n                  }\n              }\n              return {\n                  len: bufferLen,\n                  start: bufferStart,\n                  end: bufferEnd,\n                  nextStart: bufferStartNext,\n              };\n          },\n          toRangeString(bufferInfo) {\n              return `[${bufferInfo.start.toFixed(3)},${bufferInfo.end.toFixed(3)}]`;\n          },\n      };\n    \n      var StallType;\n      (function (StallType) {\n          StallType[\"Seek\"] = \"Seek\";\n          StallType[\"HighBuffer\"] = \"HighBuffer\";\n          StallType[\"LowBuffer\"] = \"LowBuffer\";\n      })(StallType || (StallType = {}));\n      var BufferWaterLevel;\n      (function (BufferWaterLevel) {\n          BufferWaterLevel[\"AlmostDry\"] = \"AlmostDry\";\n          BufferWaterLevel[\"LowWater\"] = \"LowWater\";\n          BufferWaterLevel[\"HighWater\"] = \"HighWater\";\n          BufferWaterLevel[\"AboveHighWater\"] = \"AboveHighWater\";\n      })(BufferWaterLevel || (BufferWaterLevel = {}));\n      const waterLevelToValue = {\n          [BufferWaterLevel.AlmostDry]: 0,\n          [BufferWaterLevel.LowWater]: 1,\n          [BufferWaterLevel.HighWater]: 2,\n          [BufferWaterLevel.AboveHighWater]: 3,\n      };\n      /**\n       * @returns whether from water level is > to water level\n       */\n      function waterLevelFell(from, to) {\n          return waterLevelToValue[from] > waterLevelToValue[to];\n      }\n    \n      /**\n       * Highest threshold less than waterLevelSec\n       * @param waterLevelSec The waterlevel\n       */\n      function getHighestThresholdBelowWater(waterLevelSec, info) {\n          const result = [\n              { threshold: info.highWaterLevelSeconds, level: BufferWaterLevel.HighWater },\n              { threshold: info.lowWaterLevelSeconds, level: BufferWaterLevel.LowWater },\n              { threshold: info.almostDryWaterLevelSeconds, level: BufferWaterLevel.AlmostDry },\n          ].find(({ threshold }) => {\n              return waterLevelSec > threshold;\n          });\n          return result;\n      }\n      /**\n       * Lowest threshold higher than waterLevelSec\n       * @param waterLevelSec The water level\n       */\n      function getLowestThresholdAboveWaterLevel(waterLevelSec, info) {\n          const result = [\n              { threshold: info.almostDryWaterLevelSeconds, level: BufferWaterLevel.AlmostDry },\n              { threshold: info.lowWaterLevelSeconds, level: BufferWaterLevel.LowWater },\n              { threshold: info.highWaterLevelSeconds, level: BufferWaterLevel.HighWater },\n              { threshold: Infinity, level: BufferWaterLevel.AboveHighWater },\n          ].find(({ threshold }) => {\n              return waterLevelSec <= threshold;\n          });\n          return result;\n      }\n      function updateWaterLevels(meQuery, maxBufferHole) {\n          const combined = getLowestThresholdAboveWaterLevel(meQuery.getCurrentWaterLevel(maxBufferHole), meQuery.bufferMonitorInfo).level;\n          const sbTuple = [null, null];\n          [SourceBufferType.Variant, SourceBufferType.AltAudio].forEach((sbType) => {\n              if (meQuery.sourceBufferEntityByType(sbType) != null) {\n                  sbTuple[sbType] = getLowestThresholdAboveWaterLevel(meQuery.getCurrentWaterLevelByType(sbType, maxBufferHole), meQuery.bufferMonitorInfo).level;\n              }\n          });\n          return { combined, sbTuple };\n      }\n      /**\n       * Observable that re-calculates water level when threshold or buffered range changes\n       */\n      function waterLevelChangedFromBuffer(meQuery, maxBufferHole) {\n          return combineQueries([meQuery.bufferMonitorThresholds$, meQuery.combinedBuffer$, meQuery.seeking$]).pipe(map(([thresholds]) => {\n              if (thresholds == null) {\n                  return null;\n              }\n              return updateWaterLevels(meQuery, maxBufferHole);\n          }));\n      }\n      /**\n       * Observable that re-calculates water level during regular playback\n       */\n      function waterLevelChangedFromPlayback(meQuery, maxBufferHole, logger) {\n          return combineQueries([meQuery.combinedBuffer$, meQuery.gotPlaying$, meQuery.seeking$, meQuery.waterLevelChangedForType$(null), meQuery.stallInfo$]).pipe(switchMap(([combinedBuffer, playing, seeking, waterLevelType, stallInfo]) => {\n              if (combinedBuffer.length === 0 || !playing || seeking || waterLevelType == null || stallInfo != null) {\n                  return EMPTY;\n              }\n              return scheduleWaterLevelCheck(meQuery, maxBufferHole);\n          }));\n      }\n      function scheduleWaterLevelCheck(meQuery, maxBufferHole, logger) {\n          // Combined water level should be minimum of the source buffers\n          const combinedWaterLevel = meQuery.getCurrentWaterLevel(maxBufferHole);\n          const thresholdInfo = getHighestThresholdBelowWater(combinedWaterLevel, meQuery.bufferMonitorInfo);\n          if (thresholdInfo) {\n              const { threshold } = thresholdInfo;\n              const delayMs = Math.ceil((combinedWaterLevel - threshold) * 1000);\n              return timer(delayMs).pipe(switchMap(() => {\n                  const newCombinedWaterLevel = meQuery.getCurrentWaterLevel(maxBufferHole);\n                  const newThresholdInfo = getHighestThresholdBelowWater(newCombinedWaterLevel, meQuery.bufferMonitorInfo);\n                  if ((newThresholdInfo === null || newThresholdInfo === void 0 ? void 0 : newThresholdInfo.level) === thresholdInfo.level) {\n                      // Didn't actually cross threshold, re-schedule check\n                      return scheduleWaterLevelCheck(meQuery, maxBufferHole);\n                  }\n                  return VOID;\n              }), map(() => {\n                  return updateWaterLevels(meQuery, maxBufferHole);\n              }));\n          }\n          return EMPTY;\n      }\n      /**\n       * Epic for updating the water level\n       */\n      function bufferMonitorEpic(meQuery, meStore, maxBufferHole, logger) {\n          return merge(waterLevelChangedFromBuffer(meQuery, maxBufferHole), waterLevelChangedFromPlayback(meQuery, maxBufferHole)).pipe(observeOn(asyncScheduler), tap(({ combined, sbTuple }) => {\n              meStore.updateWaterLevels(combined, sbTuple);\n          }));\n      }\n    \n      /**\n       * @brief Query interface to playback state\n       */\n      class MediaElementQuery extends QueryEntity {\n          constructor(mediaElement, mediaElementStore) {\n              super(mediaElementStore);\n              this.mediaElement = mediaElement;\n          }\n          get mediaElementDuration$() {\n              return this.selectActive(({ mediaElementDuration }) => mediaElementDuration);\n          }\n          get mediaElementDuration() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.mediaElementDuration) !== null && _b !== void 0 ? _b : Infinity;\n          }\n          get msDuration() {\n              var _a, _b;\n              return (_b = (_a = this.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.duration) !== null && _b !== void 0 ? _b : Infinity;\n          }\n          // return the smaller of all the sourceBuffer totaldurations\n          // return infinity if any of the source buffer is not fully buffered\n          get minSBDuration() {\n              var _a, _b;\n              let minDuration = Number.POSITIVE_INFINITY;\n              (_b = (_a = this.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.sourceBufferEntities) === null || _b === void 0 ? void 0 : _b.forEach((entity, index) => {\n                  if (entity) {\n                      // may be muxed or unmuxed\n                      if (isFiniteNumber(entity.totalDuration)) {\n                          // entity.totalDuration is a finite number if sb is fully buffered\n                          minDuration = Math.min(minDuration, entity.totalDuration);\n                      }\n                      else {\n                          // one of the SBs not fully buffered\n                          minDuration = Number.NEGATIVE_INFINITY;\n                      }\n                  }\n              });\n              return isFiniteNumber(minDuration) ? minDuration : Infinity;\n          }\n          get currentTime() {\n              return this.mediaElement.currentTime;\n          }\n          get clientWidth() {\n              return this.mediaElement.clientWidth;\n          }\n          get clientHeight() {\n              return this.mediaElement.clientHeight;\n          }\n          getBufferedDuration(maxBufferDuration = 0.5) {\n              const ranges = BufferHelper.timeRangesToBufferedRange(this.mediaElement.buffered);\n              const bufferInfo = BufferHelper.getBufferedInfo(ranges, this.currentTime, maxBufferDuration);\n              return bufferInfo.end - bufferInfo.start;\n          }\n          get mediaSourceEntity() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.mediaSourceEntity;\n          }\n          get msReadyState() {\n              var _a;\n              return (_a = this.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.readyState;\n          }\n          get sourceBufferEntities() {\n              var _a;\n              return (_a = this.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.sourceBufferEntities;\n          }\n          sourceBufferEntityByType(sbType) {\n              var _a;\n              return (_a = this.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[sbType];\n          }\n          initSegmentEntityByType(sbType) {\n              var _a;\n              return (_a = this.sourceBufferEntityByType(sbType)) === null || _a === void 0 ? void 0 : _a.initSegmentInfo;\n          }\n          get maxBufferSize() {\n              var _a, _b;\n              const entity = (_a = this.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[SourceBufferType.Variant];\n              let maxBufferSize = Infinity;\n              if (entity === null || entity === void 0 ? void 0 : entity.gotQuotaExceeded) {\n                  maxBufferSize = (_b = entity.maxTotalBytes) !== null && _b !== void 0 ? _b : Infinity;\n              }\n              return maxBufferSize;\n          }\n          get postFlushSeek() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.postFlushSeek;\n          }\n          get seekable() {\n              return this.mediaElement.seekable;\n          }\n          get desiredRate() {\n              var _a;\n              return ((_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.desiredRate) || 0;\n          }\n          get desiredRate$() {\n              return this.selectActive(({ desiredRate }) => desiredRate !== null && desiredRate !== void 0 ? desiredRate : 0);\n          }\n          get effectiveRate() {\n              if (this.isIframeRate) {\n                  return this.desiredRate;\n              }\n              return this.paused ? 0 : 1;\n          }\n          get playbackRate() {\n              return this.mediaElement.playbackRate;\n          }\n          get isIframeRate() {\n              const rate = this.desiredRate;\n              return isIframeRate(rate);\n          }\n          get isIframeRate$() {\n              return this.desiredRate$.pipe(map(isIframeRate));\n          }\n          get msObjectUrl$() {\n              return this.selectActive(({ mediaSourceEntity }) => mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.objectUrl).pipe(distinctUntilChanged());\n          }\n          get msReadyState$() {\n              return this.selectActive(({ mediaSourceEntity }) => { var _a; return (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.readyState) !== null && _a !== void 0 ? _a : null; });\n          }\n          get readyState() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.readyState) !== null && _b !== void 0 ? _b : 0;\n          }\n          get readyState$() {\n              return this.selectActive(({ readyState }) => readyState !== null && readyState !== void 0 ? readyState : 0);\n          }\n          get mediaSourceEntity$() {\n              return this.selectActive(({ mediaSourceEntity }) => mediaSourceEntity);\n          }\n          get expectedSbCount$() {\n              return this.selectActive(({ expectedSbCount }) => expectedSbCount);\n          }\n          get expectedSbCount() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.expectedSbCount;\n          }\n          get paused$() {\n              return this.selectActive(({ paused }) => paused);\n          }\n          get paused() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.paused) !== null && _b !== void 0 ? _b : true;\n          }\n          get playbackStarted() {\n              var _a;\n              return isFiniteNumber((_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.firstPlayTime);\n          }\n          get flushing$() {\n              return this.selectActive(({ flushing }) => flushing);\n          }\n          get flushing() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.flushing) !== null && _b !== void 0 ? _b : false;\n          }\n          get waitingForDisco$() {\n              return this.selectActive(({ waitingForDisco }) => waitingForDisco);\n          }\n          get waitingForDisco() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.waitingForDisco) !== null && _b !== void 0 ? _b : false;\n          }\n          get gotPlaying() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.gotPlaying) !== null && _b !== void 0 ? _b : false;\n          }\n          get gotPlaying$() {\n              return this.selectActive(({ gotPlaying }) => gotPlaying);\n          }\n          get gotLoadStart$() {\n              return this.selectActive(({ gotLoadStart }) => gotLoadStart);\n          }\n          get seekTo() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.seekTo;\n          }\n          get seekTo$() {\n              return this.selectActive(({ seekTo }) => seekTo);\n          }\n          get seeking() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.seeking) !== null && _b !== void 0 ? _b : false;\n          }\n          get seeking$() {\n              return this.selectActive(({ seeking }) => seeking);\n          }\n          get nudgeTarget$() {\n              return this.selectActive(({ nudgeInfo }) => nudgeInfo === null || nudgeInfo === void 0 ? void 0 : nudgeInfo.nudgeTarget);\n          }\n          get nudgeCount() {\n              var _a, _b, _c;\n              return (_c = (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.nudgeInfo) === null || _b === void 0 ? void 0 : _b.nudgeCount) !== null && _c !== void 0 ? _c : 0;\n          }\n          get sourceBufferEntities$() {\n              return this.selectActive(({ mediaSourceEntity }) => mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities);\n          }\n          sourceBufferEntityByType$(sbType) {\n              return this.selectActive(({ mediaSourceEntity }) => { var _a; return (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[sbType]; });\n          }\n          // Get info on what we think is currently in the buffer by type\n          bufferedSegmentsByType$(sbType) {\n              return this.selectActive(({ mediaSourceEntity }) => { var _a, _b, _c; return (_c = (_b = (_a = mediaSourceEntity === null || mediaSourceEntity === void 0 ? void 0 : mediaSourceEntity.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a[sbType]) === null || _b === void 0 ? void 0 : _b.bufferedSegments) !== null && _c !== void 0 ? _c : []; });\n          }\n          getBufferedSegmentsByType(sbType) {\n              var _a, _b;\n              return (_b = (_a = this.sourceBufferEntityByType(sbType)) === null || _a === void 0 ? void 0 : _a.bufferedSegments) !== null && _b !== void 0 ? _b : [];\n          }\n          // Get info on what we think is currently in both source buffers\n          get bufferedSegmentsTuple$() {\n              return combineQueries([this.bufferedSegmentsByType$(SourceBufferType.Variant), this.bufferedSegmentsByType$(SourceBufferType.AltAudio)]).pipe(debounceTime(10));\n          }\n          get timeupdate$() {\n              const target = fromEventTarget(this.mediaElement);\n              return target.event('timeupdate').pipe(observeOn(asyncScheduler), share(), throttleTime(125, undefined, { leading: true, trailing: true }), map((_) => this.currentTime), filter((pos) => isFiniteNumber(pos)));\n          }\n          get playingEvent$() {\n              const target = fromEventTarget(this.mediaElement);\n              return target.event('playing').pipe(map(() => undefined));\n          }\n          get mediaElementEntity$() {\n              return this.selectActive((entity) => Boolean(entity));\n          }\n          get ended$() {\n              return this.selectActive((entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.ended) !== null && _a !== void 0 ? _a : false; });\n          }\n          sbUpdating$(type) {\n              return this.selectActive((entity) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = entity === null || entity === void 0 ? void 0 : entity.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.sourceBufferEntities) === null || _b === void 0 ? void 0 : _b[type]) === null || _c === void 0 ? void 0 : _c.updating) !== null && _d !== void 0 ? _d : false; });\n          }\n          sbUpdating(type) {\n              var _a, _b, _c, _d, _e;\n              return (_e = (_d = (_c = (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.mediaSourceEntity) === null || _b === void 0 ? void 0 : _b.sourceBufferEntities) === null || _c === void 0 ? void 0 : _c[type]) === null || _d === void 0 ? void 0 : _d.updating) !== null && _e !== void 0 ? _e : false;\n          }\n          sbError$(type) {\n              return this.selectActive((entity) => { var _a, _b, _c; return (_c = (_b = (_a = entity === null || entity === void 0 ? void 0 : entity.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.sourceBufferEntities) === null || _b === void 0 ? void 0 : _b[type]) === null || _c === void 0 ? void 0 : _c.error; });\n          }\n          get updating$() {\n              return combineQueries([this.sbUpdating$(SourceBufferType.Variant), this.sbUpdating$(SourceBufferType.AltAudio)]).pipe(map((values) => values.some((updating) => updating)));\n          }\n          get bufferedRangeTuple$() {\n              return combineQueries([\n                  this.selectActive((entity) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = entity === null || entity === void 0 ? void 0 : entity.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.sourceBufferEntities) === null || _b === void 0 ? void 0 : _b[MediaOptionType.Variant]) === null || _c === void 0 ? void 0 : _c.bufferedRanges) !== null && _d !== void 0 ? _d : null; }),\n                  this.selectActive((entity) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = entity === null || entity === void 0 ? void 0 : entity.mediaSourceEntity) === null || _a === void 0 ? void 0 : _a.sourceBufferEntities) === null || _b === void 0 ? void 0 : _b[MediaOptionType.AltAudio]) === null || _c === void 0 ? void 0 : _c.bufferedRanges) !== null && _d !== void 0 ? _d : null; }),\n              ]);\n          }\n          getBufferedRangeByType(type) {\n              var _a, _b;\n              return (_b = (_a = this.sourceBufferEntities[type]) === null || _a === void 0 ? void 0 : _a.bufferedRanges) !== null && _b !== void 0 ? _b : [];\n          }\n          get combinedBuffer$() {\n              return this.selectActive((entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.bufferedRanges) !== null && _a !== void 0 ? _a : []; });\n          }\n          getBufferInfo(pos, maxBufferHole) {\n              var _a;\n              const bufferedRanges = (_a = this.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a.map((x) => x === null || x === void 0 ? void 0 : x.bufferedRanges);\n              const defaultInfo = { buffered: { start: pos, end: pos, len: 0 }, bufferedSegments: [] };\n              const res = [defaultInfo, defaultInfo];\n              if (!bufferedRanges) {\n                  return res;\n              }\n              bufferedRanges.forEach((ranges, type) => {\n                  var _a;\n                  if (ranges) {\n                      const bufferInfo = BufferHelper.getBufferedInfo(ranges, pos, maxBufferHole);\n                      const segments = (_a = this.sourceBufferEntities[type].bufferedSegments) !== null && _a !== void 0 ? _a : [];\n                      const bufferedSegments = segments.filter((s) => !(s.endPTS < bufferInfo.start || s.startPTS > bufferInfo.end));\n                      res[type] = { buffered: bufferInfo, bufferedSegments };\n                  }\n              });\n              return res;\n          }\n          getCombinedBufferInfo(pos, maxBufferHole) {\n              const entity = this.getActive();\n              if (entity) {\n                  return BufferHelper.getBufferedInfo(entity.bufferedRanges, pos, maxBufferHole);\n              }\n              return null;\n          }\n          get bufferMonitorInfo() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.bufferMonitorInfo) !== null && _b !== void 0 ? _b : null;\n          }\n          get bufferMonitorThresholds$() {\n              return this.selectActive((entity) => {\n                  const info = entity === null || entity === void 0 ? void 0 : entity.bufferMonitorInfo;\n                  if (!info) {\n                      return null;\n                  }\n                  const { almostDryWaterLevelSeconds, lowWaterLevelSeconds, highWaterLevelSeconds, maxBufferSeconds } = info;\n                  return { almostDryWaterLevelSeconds, lowWaterLevelSeconds, highWaterLevelSeconds, maxBufferSeconds };\n              }).pipe(distinctUntilChanged((a, b) => (a === null || a === void 0 ? void 0 : a.lowWaterLevelSeconds) === (b === null || b === void 0 ? void 0 : b.lowWaterLevelSeconds)));\n          }\n          get waterLevelType$() {\n              return this.selectActive((entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.bufferMonitorInfo.waterLevelType) !== null && _a !== void 0 ? _a : null; });\n          }\n          waterLevelForType(sbType) {\n              var _a, _b, _c;\n              return (_c = (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.bufferMonitorInfo.waterLevelType) === null || _b === void 0 ? void 0 : _b.sbTuple[sbType]) !== null && _c !== void 0 ? _c : null;\n          }\n          waterLevelChangedForType$(sbType) {\n              return this.waterLevelType$.pipe(map((waterLevelType) => {\n                  if (waterLevelType == null) {\n                      return null;\n                  }\n                  if (sbType == null) {\n                      return waterLevelType.combined;\n                  }\n                  return waterLevelType.sbTuple[sbType];\n              }));\n          }\n          /**\n           * @returns emits whether we crossed LowWaterLevel or AlmostDryWater thresholds\n           */\n          get fellBelowLowWater$() {\n              return this.waterLevelChangedForType$(SourceBufferType.Variant).pipe(pairwise(), map(([from, to]) => {\n                  return waterLevelFell(from, to) && (to === BufferWaterLevel.LowWater || to === BufferWaterLevel.AlmostDry);\n              }), withLatestFrom(this.seekTo$, this.waitingForDisco$), map(([fellBelowThreshold, seekTo, waitingForDisco]) => {\n                  return fellBelowThreshold && !isFiniteNumber(seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos) && !waitingForDisco;\n              }), startWith(false));\n          }\n          /**\n           * @returns whether the current position has buffer all the way up to the end\n           * FIXME: Gapless mode uses mediaElementDuration because current sb.totalduration may confuse item preloading\n           * (consider reseting sb.totalduration or use another variable to track preloading state)\n           */\n          isBufferedToEnd$(maxBufferHole, nonGapless = true) {\n              return combineQueries([\n                  this.combinedBuffer$,\n                  this.selectActive((entity) => entity.bufferMonitorInfo).pipe(filterNullOrUndefined(), \n                  // Threshold value\n                  map((bufferInfo) => (nonGapless ? bufferInfo.almostDryWaterLevelSeconds : Math.max(bufferInfo.almostDryWaterLevelSeconds, bufferInfo.lowWaterLevelSeconds / 2)))),\n                  this.seeking$,\n              ]).pipe(map(([combinedBuffer, closeToEndThreshold]) => {\n                  const totalSBBufferedDuration = this.minSBDuration;\n                  if (!combinedBuffer || (!isFiniteNumber(totalSBBufferedDuration) && nonGapless)) {\n                      return false;\n                  }\n                  // TODO: <rdar://78592207> may need to tweak this for gapless mode\n                  const combined = BufferHelper.getBufferedInfo(combinedBuffer, this.currentTime, maxBufferHole);\n                  const bufferEnd = combined.end;\n                  let duration;\n                  let ended;\n                  if (nonGapless) {\n                      // one last combined buffer duration check against known sb.totalduration (should be the same value)\n                      duration = totalSBBufferedDuration;\n                      ended = Math.abs(duration - bufferEnd) <= closeToEndThreshold; // remove closeToEndThreshould if we can confirm combined buffered len is as accurate as sb buffered len\n                  }\n                  else {\n                      duration = this.mediaElementDuration;\n                      ended = duration - bufferEnd <= closeToEndThreshold;\n                  }\n                  getLogger().trace('Fully buffered calculation duration=%d, bufferEnd=%d, closeToEndThreshold=%d ended=%d', totalSBBufferedDuration, bufferEnd, closeToEndThreshold, ended);\n                  return ended;\n              }), distinctUntilChanged());\n          }\n          needData$(maxBufferHole, inGaplessMode = false) {\n              const useMinSbDuration = !inGaplessMode;\n              return combineQueries([\n                  this.msReadyState$,\n                  this.waterLevelChangedForType$(null),\n                  this.isBufferedToEnd$(maxBufferHole, useMinSbDuration),\n                  this.bufferedRangeTuple$,\n                  this.seekTo$,\n                  this.mediaElementDuration$,\n              ]).pipe(debounceTime(10), \n              // observeOn(asyncScheduler), debounceTime already uses asyncScheduler\n              map(([readyState, waterLevelType, bufferedToEnd, _, seekTo]) => {\n                  if (readyState === 'closed') {\n                      return false; // Allow append if 'ended'\n                  }\n                  if (inGaplessMode) {\n                      getLogger().debug({ name: 'MediaQuery' }, 'Preloading is true, forcing needData to true');\n                      return true;\n                  }\n                  const haveRoomToLoad = waterLevelType == null || (!bufferedToEnd && waterLevelType !== BufferWaterLevel.AboveHighWater);\n                  const userIsActive = this.isIframeRate || !!seekTo; // buffered to end but user may seek or trickplay away to unbuffered ranges\n                  getLogger().debug({ name: 'MediaQuery' }, `needData = haveRoomToLoad ${haveRoomToLoad} = (bufferedToEnd: ${bufferedToEnd}, waterLevelType: ${waterLevelType}) or userIsActive ${userIsActive} = (isIframeRate: ${this.isIframeRate}, seekTo.pos: ${seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos})`);\n                  return haveRoomToLoad || (waterLevelType !== BufferWaterLevel.AboveHighWater && userIsActive);\n              }), tag('needData'));\n          }\n          getSourceBufferInfoAction(needData, anchorTime, switchContexts, maxBufferHole) {\n              const { currentTime, sourceBufferEntities, msReadyState } = this;\n              let bufferInfoTuple = [null, null];\n              if (!needData && switchContexts.every((x) => !(x === null || x === void 0 ? void 0 : x.userInitiated))) {\n                  return null;\n              }\n              if (msReadyState !== 'open' || !sourceBufferEntities || sourceBufferEntities[0] == null) {\n                  return { position: anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos, discoSeqNum: anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.discoSeqNum, bufferInfoTuple, switchContexts };\n              }\n              bufferInfoTuple = this.getBufferInfo(currentTime, maxBufferHole);\n              return { position: currentTime, discoSeqNum: anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.discoSeqNum, bufferInfoTuple, switchContexts };\n          }\n          get haveEnough() {\n              var _a, _b;\n              return (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.haveEnough) !== null && _b !== void 0 ? _b : false;\n          }\n          get haveEnough$() {\n              return this.selectActive(({ haveEnough }) => haveEnough);\n          }\n          static likelyToKeepUp(mediaElement, haveEnough, readyState) {\n              return haveEnough && readyState >= mediaElement.HAVE_FUTURE_DATA;\n          }\n          get playbackLikelyToKeepUp() {\n              return MediaElementQuery.likelyToKeepUp(this.mediaElement, this.haveEnough, this.readyState);\n          }\n          get playbackLikelyToKeepUp$() {\n              return combineQueries([this.haveEnough$, this.readyState$]).pipe(map(([haveEnough, readyState]) => MediaElementQuery.likelyToKeepUp(this.mediaElement, haveEnough, readyState)));\n          }\n          // Combined water level at current position\n          getCurrentWaterLevel(maxBufferHole) {\n              var _a, _b;\n              const currentTime = this.currentTime;\n              const bufferedRanges = (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.bufferedRanges) !== null && _b !== void 0 ? _b : [];\n              const bufferInfo = BufferHelper.getBufferedInfo(bufferedRanges, currentTime, maxBufferHole);\n              return bufferInfo.len;\n          }\n          //Returns buffer level info, this is only being used for QE logging.\n          getCombinedMediaSourceBufferInfo(maxBufferHole) {\n              var _a, _b, _c, _d;\n              const currentTime = this.currentTime;\n              const [variantBufferedRanges, altAudioBufferedRanges] = (_b = (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.mediaSourceEntity) === null || _b === void 0 ? void 0 : _b.sourceBufferEntities;\n              const variantBufferInfo = BufferHelper.getBufferedInfo((_c = variantBufferedRanges === null || variantBufferedRanges === void 0 ? void 0 : variantBufferedRanges.bufferedRanges) !== null && _c !== void 0 ? _c : [], currentTime, maxBufferHole);\n              const altAudioBufferInfo = BufferHelper.getBufferedInfo((_d = altAudioBufferedRanges === null || altAudioBufferedRanges === void 0 ? void 0 : altAudioBufferedRanges.bufferedRanges) !== null && _d !== void 0 ? _d : [], currentTime, maxBufferHole);\n              return [variantBufferInfo, altAudioBufferInfo];\n          }\n          // SourceBuffer water level at current position\n          getCurrentWaterLevelByType(sbType, maxBufferHole) {\n              var _a;\n              const currentTime = this.currentTime;\n              const sbEntity = this.sourceBufferEntityByType(sbType);\n              const bufferedRanges = (_a = sbEntity === null || sbEntity === void 0 ? void 0 : sbEntity.bufferedRanges) !== null && _a !== void 0 ? _a : [];\n              const bufferInfo = BufferHelper.getBufferedInfo(bufferedRanges, currentTime, maxBufferHole);\n              return bufferInfo.len;\n          }\n          /**\n           * For live, returns true, If the live update, has overlap with\n           * already appended buffer, and therefore can be played back without gap\n           */\n          canContinuePlaybackWithoutGap(details, lastUpdateMillis, playlistEstimate, maxBufferHole) {\n              if (details.type !== 'LIVE') {\n                  // even for EVENT, return true as predictedStartPosition will be 0.\n                  return true;\n              }\n              if (!details.ptsKnown) {\n                  return false;\n              }\n              const position = this.currentTime;\n              const predictedReceiveTime = performance.now() + playlistEstimate.avgPlaylistLoadTimeMs + details.targetduration * 1000;\n              const predictedStartPosition = details.fragments[0].start + (predictedReceiveTime - lastUpdateMillis) / 1000;\n              const bufferInfo = this.getCombinedBufferInfo(position, maxBufferHole);\n              let end = bufferInfo.end;\n              if (end >= details.fragments[0].start - maxBufferHole && end <= details.fragments[0].start + details.totalduration) {\n                  end = details.fragments[0].start + details.totalduration;\n              }\n              return predictedStartPosition <= end;\n          }\n          get stallInfo$() {\n              return this.selectActive((entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.stallInfo) !== null && _a !== void 0 ? _a : null; });\n          }\n          get textTracks() {\n              return this.mediaElement.textTracks;\n          }\n          get textTracksCreated$() {\n              return this.selectActive((entity) => entity === null || entity === void 0 ? void 0 : entity.textTracksCreated);\n          }\n          get mediaOptionParsedSubtitleRecord() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.mediaOptionParsedSubtitleRecord;\n          }\n          getParsedSubtitleRecordsForMediaOption(persistentId) {\n              if (!this.mediaOptionParsedSubtitleRecord)\n                  return null;\n              const subtitleParsedInfoDict = this.mediaOptionParsedSubtitleRecord[persistentId];\n              return subtitleParsedInfoDict ? subtitleParsedInfoDict : {};\n          }\n      }\n    \n      class MediaFunctions {\n          constructor(mediaSink, media, config, logger) {\n              this.mediaSink = mediaSink;\n              this.media = media;\n              this.logger = logger;\n              this.useCustomMediaFunctions = config.useCustomMediaFunctions;\n              this.overridePlaybackRate = config.overridePlaybackRate;\n          }\n          install() {\n              const media = this.media;\n              if (!media) {\n                  return;\n              }\n              // * guarantee original play, pause methods will be in media.originalPlay and media.originalPause.\n              // * always override media.play and media.pause with new methods.\n              if (this.useCustomMediaFunctions && media && media.play && media.pause) {\n                  // not a bogus media object for unit tests\n                  // always preserve the original play, pause methods\n                  if (!media.originalPlay) {\n                      media.originalPlay = media.play.bind(media);\n                  }\n                  if (!media.originalPause) {\n                      media.originalPause = media.pause.bind(media);\n                  }\n                  // always install new functions over old ones.\n                  this.logger.debug('install custom pause & play methods');\n                  media.play = () => {\n                      this.logger.debug('overridden play');\n                      this.mediaSink.checkForReplay();\n                      this.mediaSink.desiredRate = 1;\n                      const isPlaying = media.currentTime > 0 && !media.paused && !media.ended && media.readyState > 2 ? true : false;\n                      if (!isPlaying) {\n                          // media is not playing now, save the promise and handle whenever the originalPlay promise returns\n                          return new Promise((resolve, reject) => {\n                              if (!this.pendingPlayPromises) {\n                                  this.pendingPlayPromises = [];\n                              }\n                              this.pendingPlayPromises.push({ resolve, reject });\n                          });\n                      }\n                      else {\n                          return Promise.resolve();\n                      }\n                  };\n                  media.pause = () => {\n                      this.logger.debug('overridden pause');\n                      this.mediaSink.desiredRate = 0;\n                  };\n              }\n              if (typeof HTMLMediaElement === 'function' && this.overridePlaybackRate) {\n                  Object.defineProperty(media, 'playbackRate', {\n                      enumerable: true,\n                      configurable: true,\n                      get: function () {\n                          // pretend it's always 1 to all callers\n                          return 1;\n                      },\n                      set: function (newValue) {\n                          // allow passthrough set to signal trickplay mode to the media engine\n                          Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'playbackRate').set.call(this, newValue);\n                      },\n                  });\n              }\n              this.playPromise = null;\n              this.expectPauseEvent = this.expectPlayEvent = false;\n          }\n          uninstall() {\n              const media = this.media;\n              if (media) {\n                  if (media.originalPlay) {\n                      this.logger.debug('restore media.play');\n                      media.play = media.originalPlay;\n                      delete media.originalPlay;\n                  }\n                  if (media.originalPause) {\n                      this.logger.debug('restore media.pause');\n                      media.pause = media.originalPause;\n                      delete media.originalPause;\n                  }\n                  if (this.overridePlaybackRate) {\n                      media.playbackRate = 1; // restore original value\n                      delete media.playbackRate;\n                  }\n              }\n              this.playPromise = null;\n              this.expectPauseEvent = this.expectPlayEvent = false;\n          }\n          play() {\n              if (this.media) {\n                  const flushing = this.mediaSink.flushing;\n                  if (this.playPromise || flushing) {\n                      this.logger.warn(`Ignoring play command playPromise/flushing ${Boolean(this.playPromise)}/${flushing}`);\n                      return;\n                  }\n                  this.expectPlayEvent = this.expectPlayEvent || this.media.paused;\n                  this.logger.info(`play() expectPlayEvent=${this.expectPlayEvent}`);\n                  this.playPromise = this._mediaPlayInternal();\n                  if (this.playPromise) {\n                      this.playPromise\n                          .then(function () {\n                          this.logger.info('play() complete');\n                          this.playPromise = null;\n                          this._handlePendingPlayPromises(null);\n                      }.bind(this))\n                          .catch(function (err) {\n                          // Could be aborted by pause\n                          this.playPromise = null;\n                          this.expectPlayEvent = false;\n                          this._handlePendingPlayPromises(err || new Error('Play rejected for unknown reason'));\n                          if ((err === null || err === void 0 ? void 0 : err.name) === 'NotAllowedError') {\n                              this.logger.warn('play() not allowed, going back to rate 0');\n                              this.mediaSink.desiredRate = 0;\n                          }\n                          else {\n                              this.logger.error(`play() error: ${err === null || err === void 0 ? void 0 : err.message}`);\n                          }\n                      }.bind(this));\n                  }\n              }\n          }\n          pause() {\n              if (this.media) {\n                  this.logger.info(`pause() playPromise=${Boolean(this.playPromise)}`);\n                  if (this.playPromise) {\n                      // this.playPromise is cleared as soon\n                      // as it resolves in _mediaPlay so we shouldn't fall in here twice\n                      this.playPromise\n                          .then(() => {\n                          const mediaQuery = this.mediaSink.mediaQuery;\n                          if (this.mediaSink.desiredRate === 0 || (mediaQuery.seeking && !mediaQuery.playbackLikelyToKeepUp)) {\n                              this._mediaPauseInternal();\n                          }\n                      })\n                          .catch((error) => {\n                          this.logger.error(`Promise error in pause(): ${error.message}`);\n                      });\n                  }\n                  else {\n                      this._mediaPauseInternal();\n                  }\n              }\n          }\n          _handlePendingPlayPromises(err) {\n              var _a;\n              const count = (_a = this.pendingPlayPromises) === null || _a === void 0 ? void 0 : _a.length;\n              if (!err) {\n                  // resolve all pending promises\n                  for (let i = 0; i < count; i++) {\n                      this.pendingPlayPromises[i].resolve();\n                  }\n              }\n              else {\n                  // reject all pending promises\n                  for (let i = 0; i < count; i++) {\n                      this.pendingPlayPromises[i].reject(err);\n                  }\n              }\n              this.pendingPlayPromises = [];\n          }\n          _mediaPlayInternal() {\n              const playFn = this.media.originalPlay || this.media.play.bind(this.media);\n              return playFn();\n          }\n          _mediaPauseInternal() {\n              this.expectPauseEvent = this.expectPauseEvent || !this.media.paused;\n              this.logger.info(`pause() expectPauseEvent=${this.expectPauseEvent}`);\n              const pauseFn = this.media.originalPause || this.media.pause.bind(this.media);\n              return pauseFn();\n          }\n      }\n    \n      class MseError extends Error {\n      }\n      // Generic SourceBuffer error\n      class SourceBufferError extends HlsError {\n          constructor(details, fatal, reason, response, sbType) {\n              super(ErrorTypes.MEDIA_ERROR, details, fatal, reason, response);\n              this.sbType = sbType;\n              this.response = response;\n          }\n      }\n      // Got error when calling addSourceBuffer (unsupported format)\n      class CreateSourceBufferError extends SourceBufferError {\n          constructor(message, response, sbType, mediaOptionId) {\n              super(ErrorDetails.BUFFER_ADD_CODEC_ERROR, false, message, response, sbType);\n              this.mediaOptionId = mediaOptionId;\n              this.mediaOptionType = sourceBufferTypeToMediaOptionType(this.sbType);\n          }\n      }\n      class AppendBufferError extends SourceBufferError {\n          constructor(details, fatal, reason, response, sbType, isTimeout) {\n              super(details, fatal, reason, response, sbType);\n              this.isTimeout = isTimeout;\n              this.mediaOptionType = sourceBufferTypeToMediaOptionType(this.sbType);\n          }\n      }\n      class BufferFullError extends AppendBufferError {\n          constructor(reason, response, sbType, maxTotalBytes) {\n              super(ErrorDetails.BUFFER_FULL_ERROR, false, reason, response, sbType, false);\n              this.maxTotalBytes = maxTotalBytes;\n          }\n      }\n      class AppendTimeoutError extends AppendBufferError {\n          constructor(reason, response, sbType) {\n              super(ErrorDetails.BUFFER_APPEND_ERROR, false, reason, response, sbType, true);\n          }\n      }\n      // Got decode error during append\n      class MediaDecodeError extends AppendBufferError {\n          constructor(reason, response, sbType, mediaOptionId) {\n              super(ErrorDetails.BUFFER_APPEND_ERROR, false, reason, response, sbType, false);\n              this.mediaOptionId = mediaOptionId;\n              this.mediaOptionType = sourceBufferTypeToMediaOptionType(this.sbType);\n          }\n      }\n      class BufferStallError extends HlsError {\n          constructor(details, fatal, reason, response, stallType, bufferLen, nudgePosition = NaN) {\n              super(ErrorTypes.MEDIA_ERROR, details, fatal, reason, response);\n              this.stallType = stallType;\n              this.bufferLen = bufferLen;\n              this.nudgePosition = nudgePosition;\n              this.response = response;\n          }\n      }\n    \n      /**\n       * Observable SourceBuffer adapter that cleans up after itself on unsubscribe\n       * From src/mse-rxjs/sourcebuffer-adapter.ts\n       */\n      const APPEND_MAX_MS = 10000; // Failsafe append timeout value\n      class SourceBufferAdapter extends Observable {\n          constructor(mediaElementStore, mediaElementQuery, mediaElement, mediaSource, type, sourceBuffer, compatInfo, parentLogger, config) {\n              super((subscriber) => {\n                  const target = fromEventTarget(sourceBuffer);\n                  const logger = parentLogger.child({ sb: type });\n                  mediaElementStore.setSourceBufferEntity(type, compatInfo);\n                  if (compatInfo.mimeType.includes('audio/mpeg')) {\n                      this.updateMp3Timestamps = true;\n                  }\n                  const sub = merge(target.event('updatestart').pipe(tap(() => {\n                      logger.trace(`[sb${this.type}] updatestart`);\n                      mediaElementStore.setSourceBufferUpdating(type);\n                  })), \n                  // Note we need to do this to keep buffer data updated,\n                  // unless we start allowing abort() as part of teardown / finalize on append/remove\n                  target.event('updateend').pipe(observeOn(asyncScheduler), tap(() => {\n                      const bufferedRanges = BufferHelper.timeRangesToBufferedRange(sourceBuffer.buffered);\n                      const combinedBuffer = BufferHelper.timeRangesToBufferedRange(mediaElement.buffered);\n                      logger.trace(`[sb${this.type}] updateend`);\n                      mediaElementStore.setBufferedRangesUpdated(type, bufferedRanges, combinedBuffer, false, config);\n                  })), target.event('error').pipe(tap(() => {\n                      mediaElementStore.setSourceBufferError(type, 'Got source buffer error');\n                  })))\n                      .pipe(switchMap(() => EMPTY))\n                      .subscribe(subscriber);\n                  return () => {\n                      sub.unsubscribe();\n                      try {\n                          if (mediaSource.readyState === 'open') {\n                              sourceBuffer.abort();\n                          }\n                          mediaSource.removeSourceBuffer(sourceBuffer);\n                      }\n                      catch (err) {\n                          logger.error(`Error aborting SourceBuffer on unsubscribe: ${err.message}`);\n                      }\n                  };\n              });\n              this.mediaElementStore = mediaElementStore;\n              this.mediaElementQuery = mediaElementQuery;\n              this.mediaElement = mediaElement;\n              this.type = type;\n              this.sourceBuffer = sourceBuffer;\n              this.config = config;\n              this.updateMp3Timestamps = false;\n          }\n          get buffered() {\n              return this.sourceBuffer.buffered;\n          }\n          /**\n           * @param data The buffer to append\n           * @param segment Info about the segment. null means init segment\n           */\n          appendBuffer(data, segment) {\n              // Use defer so that on re-subscribe we will call appendBuffer again\n              return defer(() => {\n                  if (this.sourceBuffer.updating) {\n                      return this._waitForUpdateEndOrError().pipe(switchMap(() => this.appendBuffer(data, segment)));\n                  }\n                  return this._appendBufferAsync(data, segment);\n              });\n          }\n          _appendBufferAsync(data, segment) {\n              let startAppend = NaN;\n              let inFlight = null;\n              const mediaOptionId = 'startPTS' in segment ? segment.frag.mediaOptionId : segment.mediaOptionId;\n              try {\n                  if ('startPTS' in segment) {\n                      inFlight = { startPTS: segment.startPTS, endPTS: segment.endPTS, bytes: segment.bytes, frag: Object.assign({}, segment.frag) };\n                  }\n                  this.mediaElementStore.setInflightSegment(this.type, inFlight);\n                  startAppend = performance.now();\n                  this.sourceBuffer.appendBuffer(data);\n              }\n              catch (err) {\n                  // Synchronous errors come from prepare append algorithm\n                  // https://www.w3.org/TR/media-source/#sourcebuffer-prepare-append\n                  switch (err.code) {\n                      case 22: {\n                          // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n                          // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n                          this.mediaElementStore.setBufferedRangesUpdated(this.type, BufferHelper.timeRangesToBufferedRange(this.sourceBuffer.buffered), BufferHelper.timeRangesToBufferedRange(this.mediaElement.buffered), true, this.config);\n                          return throwError(new BufferFullError(err.message, ErrorResponses.AllocationFailed, this.type, this.maxTotalBytes));\n                      }\n                      default:\n                          this.mediaElementStore.setInflightSegment(this.type, null);\n                          if (this.mediaElement.error) {\n                              return throwError(new MediaDecodeError(err.message, ErrorResponses.VideoDecoderBadDataErr, this.type, mediaOptionId));\n                          }\n                          // 1. buffer removed from MediaSource\n                          // 2. updating === true\n                          // 3. other reason\n                          return throwError(err);\n                  }\n              }\n              return this._waitForUpdateEndOrError().pipe(map(() => ({\n                  startAppend: startAppend,\n                  endAppend: performance.now(),\n                  bytesAppend: data.byteLength,\n              })), timeout(APPEND_MAX_MS), catchError((err) => {\n                  if (err instanceof TimeoutError) {\n                      this.sourceBuffer.abort();\n                      err = new AppendTimeoutError(`Append took longer than ${APPEND_MAX_MS}ms`, ErrorResponses.InternalError, this.type);\n                  }\n                  else if (err instanceof SourceBufferError) {\n                      err = new MediaDecodeError('Decode error', ErrorResponses.VideoDecoderBadDataErr, this.type, mediaOptionId);\n                  }\n                  throw err; // always throw\n              }));\n          }\n          remove(start, end) {\n              return this._waitForUpdateEndOrError().pipe(switchMap(this._removeAsync.bind(this, start, end)));\n          }\n          _removeAsync(start, end) {\n              try {\n                  this.sourceBuffer.remove(start, end);\n              }\n              catch (err) {\n                  return throwError(new SourceBufferError(ErrorDetails.INTERNAL_EXCEPTION, false, err.message, ErrorResponses.InternalError, this.type));\n              }\n              return this._waitForUpdateEndOrError();\n          }\n          abort() {\n              try {\n                  this.sourceBuffer.abort();\n              }\n              catch (err) {\n                  return throwError(new SourceBufferError(ErrorDetails.INTERNAL_EXCEPTION, false, err.message, ErrorResponses.InternalError, this.type));\n              }\n              return this._waitForUpdateEndOrError();\n          }\n          get updating() {\n              return this.sourceBuffer.updating;\n          }\n          get timestampOffset() {\n              return this.sourceBuffer.timestampOffset;\n          }\n          set timestampOffset(value) {\n              this.sourceBuffer.timestampOffset = value;\n          }\n          /**\n           * Whether we ever got QuotaExceeded error\n           */\n          get gotQuotaExceeded() {\n              var _a, _b;\n              return (_b = (_a = this.mediaElementQuery.sourceBufferEntityByType(this.type)) === null || _a === void 0 ? void 0 : _a.gotQuotaExceeded) !== null && _b !== void 0 ? _b : false;\n          }\n          /**\n           * Which segments we think are in the buffer\n           */\n          get bufferedSegments() {\n              var _a, _b;\n              return (_b = (_a = this.mediaElementQuery.sourceBufferEntityByType(this.type)) === null || _a === void 0 ? void 0 : _a.bufferedSegments) !== null && _b !== void 0 ? _b : [];\n          }\n          /**\n           * Currently appended byte total\n           */\n          get totalBytes() {\n              var _a, _b;\n              return (_b = (_a = this.mediaElementQuery.sourceBufferEntityByType(this.type)) === null || _a === void 0 ? void 0 : _a.totalBytes) !== null && _b !== void 0 ? _b : 0;\n          }\n          /**\n           * Max number of bytes we estimate this SourceBuffer can hold\n           */\n          get maxTotalBytes() {\n              var _a, _b;\n              const maxTotalBytes = (_b = (_a = this.mediaElementQuery.sourceBufferEntityByType(this.type)) === null || _a === void 0 ? void 0 : _a.maxTotalBytes) !== null && _b !== void 0 ? _b : Infinity;\n              return this.gotQuotaExceeded ? maxTotalBytes : Infinity;\n          }\n          _waitForUpdateEndOrError() {\n              if (this.sourceBuffer.updating) {\n                  // Just in case we haven't fired updatestart yet\n                  this.mediaElementStore.setSourceBufferUpdating(this.type);\n              }\n              // Ensures we have up to date buffered range values by using updating$\n              return this.mediaElementQuery.sbUpdating$(this.type).pipe(filter((updating) => updating === false), withLatestFrom(this.mediaElementQuery.sbError$(this.type)), map(([_updating, error]) => {\n                  if (error) {\n                      throw new SourceBufferError(ErrorDetails.INTERNAL_EXCEPTION, false, 'Got error during sourceBuffer operation', ErrorResponses.InternalError, this.type);\n                  }\n                  return undefined;\n              }), take(1));\n          }\n      }\n    \n      /**\n       * Observable MediaSOurce adapter that cleans up after itself on unsubscribe\n       * From src/mse-rxjs/mediasource-adapter.ts\n       */\n      class MediaSourceAdapter extends Observable {\n          constructor(mediaElement, mediaElementStore, mediaElementQuery, mediaSource, logger) {\n              // Register for events. This updates the mediaElementStore and also sets up teardown\n              // when this object is unsubscribed from\n              super((subscriber) => {\n                  const target = fromEventTarget(mediaSource);\n                  const readyStateChange$ = merge(target.event('sourceopen'), target.event('sourceclose'), target.event('sourceended')).pipe(tap((event) => {\n                      var _a;\n                      // Vuze doesn't implement event\n                      const ms = (_a = event === null || event === void 0 ? void 0 : event.target) !== null && _a !== void 0 ? _a : mediaSource;\n                      const readyState = ms.readyState;\n                      mediaElementStore.msReadyState = readyState;\n                  }));\n                  const sourceBuffers$ = this.sourceBuffers$.pipe(switchMap((sbTuple) => {\n                      if (!sbTuple)\n                          return EMPTY;\n                      return merge(...sbTuple.filter((info) => info != null));\n                  }));\n                  const sub = merge(readyStateChange$, sourceBuffers$)\n                      .pipe(switchMap(() => EMPTY))\n                      .subscribe(subscriber);\n                  const objectUrl = URL.createObjectURL(mediaSource);\n                  mediaElement.src = objectUrl;\n                  logger.info(`set MediaSource ${objectUrl}`);\n                  mediaElementStore.setMediaSourceEntity(objectUrl, mediaSource.readyState);\n                  return () => {\n                      sub.unsubscribe();\n                      // Hand off clean up to teardownWorker to avoid race with clearMediaKeys\n                      logger.info(`remove MediaSource ${objectUrl}`);\n                      URL.revokeObjectURL(objectUrl);\n                      if (mediaElement.src === objectUrl) {\n                          mediaElement.removeAttribute('src');\n                          mediaElement.load();\n                          mediaElementStore.setMediaSourceEntity(null);\n                      }\n                      this.sourceBuffers$.next(null);\n                  };\n              });\n              this.mediaElement = mediaElement;\n              this.mediaElementStore = mediaElementStore;\n              this.mediaElementQuery = mediaElementQuery;\n              this.mediaSource = mediaSource;\n              this.logger = logger;\n              this.sourceBuffers$ = new BehaviorSubject(null);\n          }\n          get readyState() {\n              return this.mediaSource.readyState;\n          }\n          set duration(value) {\n              this.mediaSource.duration = value;\n          }\n          get duration() {\n              return this.mediaSource.duration;\n          }\n          endOfStream(error) {\n              this.mediaSource.endOfStream(error);\n          }\n          createSourceBuffers(compatInfoTuple, config) {\n              const mediaSource = this.mediaSource;\n              applyTransaction(() => {\n                  try {\n                      const newSbs = [null, null];\n                      compatInfoTuple.forEach((compatInfo, type) => {\n                          if (compatInfo) {\n                              const { mimeType, mediaOptionId } = compatInfo;\n                              let sb;\n                              try {\n                                  sb = mediaSource.addSourceBuffer(mimeType);\n                                  this.logger.info(`[${SourceBufferNames[type]}]: sourceBuffer added ${mimeType}`);\n                              }\n                              catch (err) {\n                                  throw new CreateSourceBufferError(err.message, ErrorResponses.IncompatibleAsset, type, mediaOptionId);\n                              }\n                              newSbs[type] = new SourceBufferAdapter(this.mediaElementStore, this.mediaElementQuery, this.mediaElement, this.mediaSource, type, sb, compatInfo, this.logger, config);\n                          }\n                      });\n                      this.sourceBuffers$.next(newSbs);\n                  }\n                  catch (err) {\n                      if (!(err instanceof HlsError)) {\n                          throw new MseError(`error initializing sourcebuffers ${err.message} readyState=${mediaSource.readyState}`);\n                      }\n                      throw err;\n                  }\n              });\n          }\n          get needSourceBuffers() {\n              return this.sourceBuffers$.value == null || this.sourceBuffers$.value[0] == null;\n          }\n          get sourceBuffers() {\n              return this.sourceBuffers$.value;\n          }\n          getSourceBufferByType(type) {\n              const sbAdapterTuple = this.sourceBuffers$.value;\n              if (!sbAdapterTuple) {\n                  return null;\n              }\n              return sbAdapterTuple[type];\n          }\n          updateLiveSeekableRange(start, end) {\n              const mediaSource = this.mediaSource;\n              if ((mediaSource === null || mediaSource === void 0 ? void 0 : mediaSource.setLiveSeekableRange) && (mediaSource === null || mediaSource === void 0 ? void 0 : mediaSource.readyState) === 'open') {\n                  this.logger.debug(`setLiveSeekableRange range called with ${start} to ${end}`);\n                  mediaSource.setLiveSeekableRange(start, end);\n              }\n          }\n          clearLiveSeekableRange() {\n              const mediaSource = this.mediaSource;\n              if ((mediaSource === null || mediaSource === void 0 ? void 0 : mediaSource.clearLiveSeekableRange) && (mediaSource === null || mediaSource === void 0 ? void 0 : mediaSource.readyState) === 'open') {\n                  this.logger.debug('clearLiveSeekableRange called');\n                  mediaSource.clearLiveSeekableRange();\n              }\n          }\n      }\n    \n      const MIN_STALL_CHECK_MS = 100; // Minimum time for next check\n      function shouldCheckForStall(pos, desiredRate, ended, combinedBuffer, seeking) {\n          const isBuffered = combinedBuffer.some((r) => r.start <= pos && r.end > pos);\n          return !(desiredRate !== 1 || ended || combinedBuffer.length === 0 || (seeking && !isBuffered));\n      }\n      /**\n       * monitors the media element for stalling in low and high buffer or on seek\n       * It will update media store with information about the stall if the position has not changed\n       * after the configured period. emits stall info if stall is detected, null if we're not stalled\n       */\n      function stallMonitor(logger, meQuery, config) {\n          const { lowBufferThreshold, lowBufferWatchdogPeriod, highBufferWatchdogPeriod, seekWatchdogPeriod } = config;\n          const shouldCheckForStall$ = combineQueries([meQuery.desiredRate$, meQuery.ended$, meQuery.combinedBuffer$, meQuery.seekTo$]).pipe(map((state) => {\n              const [desiredRate, ended, combinedBuffer, seekTo] = state;\n              const currentTime = meQuery.currentTime;\n              const seeking = isFinite(seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos);\n              return shouldCheckForStall(currentTime, desiredRate, ended, combinedBuffer, seeking);\n          }), distinctUntilChanged());\n          const combinedBufferChanged$ = meQuery.combinedBuffer$.pipe(map(() => {\n              return meQuery.getCurrentWaterLevel(0) <= config.lowBufferThreshold || !meQuery.haveEnough ? StallType.LowBuffer : StallType.HighBuffer;\n          }), distinctUntilChanged());\n          const gotStall$ = combineQueries([shouldCheckForStall$, meQuery.seekTo$, meQuery.gotPlaying$, combinedBufferChanged$]).pipe(switchMap((state) => {\n              const [shouldCheckForStall, seekTo, gotPlaying] = state;\n              logger.debug(`[stall] state=${stringifyWithPrecision({ shouldCheckForStall, seekTo, gotPlaying })}`);\n              if (!shouldCheckForStall) {\n                  return of(null);\n              }\n              // some systems need longer wait period for seeks / playback resume, use backoff period\n              const backoffSec = 1;\n              const nudgeCount = meQuery.nudgeCount;\n              const seekPeriodSec = seekWatchdogPeriod + nudgeCount * backoffSec;\n              const seeking = isFinite(seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos);\n              if (seeking || !gotPlaying) {\n                  logger.debug(`[stall] start seek stall watchdog period=${seekPeriodSec}s`);\n                  return startSeekStallWatchdog(meQuery, performance.now(), seekPeriodSec, lowBufferThreshold);\n              }\n              const highBufferPeriodSec = highBufferWatchdogPeriod + nudgeCount * backoffSec;\n              logger.debug(`[stall] start playing stall watchdog low period=${lowBufferWatchdogPeriod} high period=${highBufferPeriodSec}`);\n              return startPlayingStallWatchdog(meQuery, logger, lowBufferWatchdogPeriod, highBufferPeriodSec, lowBufferThreshold);\n          }));\n          const gotResume$ = gotStall$.pipe(filterNullOrUndefined(), withLatestFrom(meQuery.combinedBuffer$), switchMap(([stallInfo, combinedBuffer]) => {\n              logger.debug(`[stall] got stall ${stringifyWithPrecision(stallInfo)} buffered:${stringifyWithPrecision(combinedBuffer)}`);\n              return combineQueries([meQuery.seeking$, meQuery.paused$]);\n          }), switchMap(([seeking, paused]) => {\n              if (seeking || paused) {\n                  return EMPTY;\n              }\n              return meQuery.timeupdate$.pipe(pairwise(), filter(([a, b]) => isFiniteNumber(a) && isFiniteNumber(b) && b > a), take(1));\n          }), map(() => {\n              logger.info('[stall] resume from stall');\n              return null;\n          }));\n          return merge(gotStall$, gotResume$);\n      }\n      // start seek watchdog timer. Assumed that at start, seeking || !playing\n      // Fire if time from (seeking -> playing) or (seeked -> playing) >= seekWatchdogPeriod\n      function startSeekStallWatchdog(meQuery, tstalled, seekWatchdogPeriod, lowBufferThreshold) {\n          return timer(seekWatchdogPeriod * 1000).pipe(map(() => {\n              const currentTime = meQuery.currentTime;\n              const bufferInfo = meQuery.getCombinedBufferInfo(currentTime, 0);\n              return makeStallInfo(StallType.Seek, currentTime, tstalled, bufferInfo, lowBufferThreshold, meQuery.haveEnough);\n          }));\n      }\n      // start playing watchdog timer: when now - tlastCurrentTime > low or high buffer watchdog period\n      function startPlayingStallWatchdog(meQuery, logger, lowBufferWatchdogPeriod, highBufferWatchdogPeriod, lowBufferThreshold) {\n          // Current position hasn't changed for some period of time\n          return merge(of(meQuery.currentTime), meQuery.timeupdate$).pipe(switchMap((lastCurrentTime) => {\n              const tstalled = performance.now();\n              const bufferInfo = meQuery.getCombinedBufferInfo(lastCurrentTime, 0);\n              let type;\n              let watchdogPeriod; // How long from reference point to schedule the check\n              const bufferLenSec = bufferInfo.len;\n              // prettier-ignore\n              if ((bufferLenSec <= lowBufferThreshold) || !meQuery.haveEnough) {\n                  watchdogPeriod = lowBufferWatchdogPeriod;\n                  type = StallType.LowBuffer;\n              }\n              else {\n                  watchdogPeriod = highBufferWatchdogPeriod;\n                  type = StallType.HighBuffer;\n              }\n              const stallCheckMs = Math.max(MIN_STALL_CHECK_MS, watchdogPeriod * 1000);\n              return timer(stallCheckMs).pipe(map(() => {\n                  // Check once to see if playback has moved ahead before making stallInfo Object\n                  // On Roku 'timeupdate' event (aka meQuery.timeupdate$ triggers) are inconsistent.\n                  if (lastCurrentTime < meQuery.currentTime) {\n                      return null;\n                  }\n                  return makeStallInfo(type, lastCurrentTime, tstalled, bufferInfo, lowBufferThreshold, meQuery.haveEnough);\n              }));\n          }));\n      }\n      /**\n       * Check if we've changed positions since we armed the timers\n       */\n      function makeStallInfo(type, currentTime, tstalled, bufferInfo, lowBufferThreshold, haveEnough) {\n          const now = performance.now();\n          const stallDurationMs = now - tstalled;\n          const bufferLenSec = bufferInfo.len;\n          // prettier-ignore\n          const isLowBufferStall = (bufferLenSec <= lowBufferThreshold) || !haveEnough;\n          return { type, isLowBufferStall, tstalled, stallDurationMs, currentTime };\n      }\n    \n      class MediaSink extends Observable {\n          constructor(mediaElement, mediaElementStore, config, hlsGapless, logger, teardownWG$, rtcService) {\n              super((subscriber) => {\n                  this.logger.info('subscribe MediaSink');\n                  const config = this.config;\n                  const sessionId = mediaElementStore.startMediaSession(mediaElement, config.maxBufferLength, config.almostDryBufferSec, config.defaultTargetDuration);\n                  const mediaElementEvents$ = hookMediaElementsEvents(mediaElement, mediaElementStore, this._mediaQuery, this, this.hlsGapless, config, this.logger, this.rtcService);\n                  const mediaSource$ = this.mediaSource$.pipe(switchMap((ms) => ms || EMPTY));\n                  const seeks$ = this._mediaQuery.seekTo$.pipe(seekEpic(mediaElement, this._mediaQuery, this, this.config, this.logger));\n                  const rateChange$ = this._mediaQuery.desiredRate$.pipe(rateChangeEpic(mediaElement, this._mediaQuery, this));\n                  this.liveSeekableWindow = { start: NaN, end: NaN };\n                  // setup media functions overrides\n                  this.mediaFunctions = this.mediaFunctions || new MediaFunctions(this, mediaElement, config, this.logger);\n                  this.mediaFunctions.install();\n                  const stallHandling$ = merge(stallMonitor(this.logger, this._mediaQuery, this.config).pipe(tap((stallInfo) => {\n                      mediaElementStore.setStallInfo(stallInfo);\n                  })), this.mediaQuery.stallInfo$.pipe(stallEpic(this, mediaElementStore, this.config, this.logger)));\n                  const bufferMonitor$ = bufferMonitorEpic(this.mediaQuery, mediaElementStore, config.maxBufferHole);\n                  merge(mediaElementEvents$, mediaSource$, seeks$, rateChange$, stallHandling$, bufferMonitor$)\n                      .pipe(switchMapTo(EMPTY), finalize$1(() => {\n                      this.logger.info('finalize MediaSink');\n                      mediaElementStore.remove(sessionId);\n                      this.mediaFunctions.uninstall();\n                      this.mediaFunctions = undefined;\n                  }))\n                      .subscribe(subscriber); // Propagates any errors up\n                  // extra teardown ?\n              });\n              this.mediaElement = mediaElement;\n              this.mediaElementStore = mediaElementStore;\n              this.config = config;\n              this.hlsGapless = hlsGapless;\n              this.logger = logger;\n              this.teardownWG$ = teardownWG$;\n              this.rtcService = rtcService;\n              this.mediaSource$ = new BehaviorSubject(null);\n              // We use a Mutex here because only one setMediaKeys() can run at one time,\n              // and multiple setMediaKeys() operations can be queued for execution from\n              // different threads. Since it's the only type of operation needs\n              // synchronization in the MediaSink component, using a Mutex makes more sense\n              // than converting to command queue pattern.\n              this.mediaKeysMutex = new Mutex();\n              this._mediaQuery = new MediaElementQuery(mediaElement, mediaElementStore);\n              this.logger = logger.child({ name: 'mse' });\n              // Muze/Vuze: Need to create id3 text track before MEDIA_ATTACHED\n              this.createId3Track(mediaElement);\n              this.mediaFunctions = new MediaFunctions(this, mediaElement, config, this.logger);\n          }\n          get mediaSourceAdapter() {\n              return this.mediaSource$.value;\n          }\n          get sourceBuffers() {\n              var _a, _b;\n              return (_b = (_a = this.mediaSourceAdapter) === null || _a === void 0 ? void 0 : _a.sourceBuffers) !== null && _b !== void 0 ? _b : [];\n          }\n          get needSourceBuffers() {\n              return this.sourceBuffers[0] ? false : true;\n          }\n          get mediaQuery() {\n              return this._mediaQuery;\n          }\n          sourceBuffersBufferedRangeByType(type) {\n              var _a, _b;\n              const sb = (_b = (_a = this.mediaSourceAdapter) === null || _a === void 0 ? void 0 : _a.sourceBuffers) === null || _b === void 0 ? void 0 : _b[type];\n              if (sb) {\n                  return BufferHelper.timeRangesToBufferedRange(sb.sourceBuffer.buffered);\n              }\n              else {\n                  return null;\n              }\n          }\n          createId3Track(mediaElement) {\n              this.logger.info('create id3 texttrack');\n              this.id3Track = mediaElement.addTextTrack('metadata', 'id3');\n              this.id3Track.mode = 'hidden';\n          }\n          /**\n           * Check if mediaElementStore buffer values are in-sync with real SourceBuffer\n           * especially when trying to seek.\n           */\n          checkForInconsistentStoreBufferRangesAndUpdate() {\n              var _a, _b, _c, _d;\n              const mediaElementTimeRanges = BufferHelper.timeRangesToBufferedRange(this.mediaElement.buffered);\n              const realVariantBufferedRanges = this.sourceBuffersBufferedRangeByType(SourceBufferType.Variant);\n              const realAltAudioBufferedRanges = this.sourceBuffersBufferedRangeByType(SourceBufferType.AltAudio);\n              const storeVariantBufferedRanges = (_b = (_a = this.mediaQuery.sourceBufferEntityByType(SourceBufferType.Variant)) === null || _a === void 0 ? void 0 : _a.bufferedRanges) !== null && _b !== void 0 ? _b : null;\n              const storeAltAudioBufferedRanges = (_d = (_c = this.mediaQuery.sourceBufferEntityByType(SourceBufferType.AltAudio)) === null || _c === void 0 ? void 0 : _c.bufferedRanges) !== null && _d !== void 0 ? _d : null;\n              // If there is discrepency with any of sourceBufferRanges then update store values\n              if (this.shouldUpdateStoreValues(realVariantBufferedRanges, storeVariantBufferedRanges)) {\n                  this.logger.warn(`[${SourceBufferNames[SourceBufferType.Variant]}] SourceBuffer's loaded bufferedRanges ${JSON.stringify(realVariantBufferedRanges)} & mediaElementStore's bufferedRanges ${JSON.stringify(storeVariantBufferedRanges)} are out of sync!`);\n                  this.updateMediaElementStoreBufferedRanges(mediaElementTimeRanges, SourceBufferType.Variant);\n              }\n              if (this.shouldUpdateStoreValues(realAltAudioBufferedRanges, storeAltAudioBufferedRanges)) {\n                  this.logger.warn(`[${SourceBufferNames[SourceBufferType.AltAudio]}] SourceBuffer's loaded bufferedRanges ${JSON.stringify(realAltAudioBufferedRanges)} & mediaElementStore's bufferedRanges ${JSON.stringify(storeAltAudioBufferedRanges)} are out of sync!`);\n                  this.updateMediaElementStoreBufferedRanges(mediaElementTimeRanges, SourceBufferType.AltAudio);\n              }\n          }\n          shouldUpdateStoreValues(sbLoadedTimeRanges, storeBufferedRanges) {\n              if (sbLoadedTimeRanges == null && storeBufferedRanges == null) {\n                  return false;\n              }\n              // Unequal lengths then we need updating\n              if ((sbLoadedTimeRanges === null || sbLoadedTimeRanges === void 0 ? void 0 : sbLoadedTimeRanges.length) != (storeBufferedRanges === null || storeBufferedRanges === void 0 ? void 0 : storeBufferedRanges.length)) {\n                  return true;\n              }\n              // If there is discrepency with any of the loaded Ranges then update store values\n              return !!sbLoadedTimeRanges.find((sbCurrentLoadedTimeRange) => {\n                  const binarySearchcompareFunction = (storeCurrentInterval) => {\n                      if (sbCurrentLoadedTimeRange.start >= storeCurrentInterval.start && sbCurrentLoadedTimeRange.end <= storeCurrentInterval.end) {\n                          return 0;\n                      }\n                      else if (sbCurrentLoadedTimeRange.end < storeCurrentInterval.start) {\n                          return -1;\n                      }\n                      else {\n                          return 1;\n                      }\n                  };\n                  // Binary search as SourceBuffer.buffered is normalized TimeRanges object.\n                  const matchingStoreBufferedRange = BinarySearch.search(storeBufferedRanges, binarySearchcompareFunction);\n                  // If no match we need updating\n                  if (matchingStoreBufferedRange == null) {\n                      return true;\n                  }\n                  if (matchingStoreBufferedRange.start != sbCurrentLoadedTimeRange.start || matchingStoreBufferedRange.end != sbCurrentLoadedTimeRange.end) {\n                      return true;\n                  }\n              });\n          }\n          /**\n           * Update mediaElementStore with latest from SourceBuffers.\n           */\n          updateMediaElementStoreBufferedRanges(mediaElementBuffered, type) {\n              const sb = this.sourceBuffersBufferedRangeByType(type);\n              if (sb && !this.mediaQuery.sbUpdating(type)) {\n                  this.logger.info(`[${SourceBufferNames[type]}] Updating buffer status`);\n                  this.mediaElementStore.setBufferedRangesUpdated(type, sb, mediaElementBuffered, false, this.config);\n              }\n          }\n          destroyMediaSource() {\n              this.mediaSource$.next(null);\n          }\n          // Can stub over this for testing if needed\n          makeMediaSource() {\n              return new MediaSource();\n          }\n          openMediaSource(mediaSource) {\n              applyTransaction(() => {\n                  if (mediaSource) {\n                      const mediaAdapter = new MediaSourceAdapter(this.mediaElement, this.mediaElementStore, this.mediaQuery, mediaSource, this.logger);\n                      this.mediaSource$.next(mediaAdapter);\n                  }\n                  else {\n                      this.mediaSource$.next(null);\n                  }\n              });\n          }\n          createSourceBuffers(compatInfoTuple) {\n              this.logger.info(`createSourceBuffers ${JSON.stringify(compatInfoTuple.map((c) => c === null || c === void 0 ? void 0 : c.mimeType))}`);\n              const msAdapter = this.mediaSource$.value;\n              if (!msAdapter) {\n                  throw new Error('createSourceBuffers empty mediaSource');\n              }\n              msAdapter.createSourceBuffers(compatInfoTuple, this.config);\n          }\n          _waitForMediaSourceOpen(appendData) {\n              const msObjectUrl = this.mediaQuery.mediaSourceEntity.objectUrl; // msAdapter at the start of wait\n              return combineQueries([this.mediaQuery.msReadyState$, this.mediaQuery.msObjectUrl$]).pipe(switchMap(([state, msUrl]) => {\n                  if (msUrl !== msObjectUrl) {\n                      this.logger.info('media source changed while waiting');\n                      return of(null);\n                  }\n                  if (state === 'open' || state === 'ended') {\n                      // Can append again even if ended\n                      return of(appendData);\n                  }\n                  return EMPTY;\n              }));\n          }\n          get appendOrder() {\n              return this.mediaQuery.isIframeRate ? [SourceBufferType.Variant, SourceBufferType.AltAudio] : [SourceBufferType.AltAudio, SourceBufferType.Variant];\n          }\n          clearFlush(appendData) {\n              appendData.forEach((sbData) => {\n                  if (sbData) {\n                      // hls will not reset the MediaOptionSwitchContext if flushBeforeAppend is null/undefined.\n                      sbData.dataSeg.flushBeforeAppend = { start: 0, end: 0 };\n                  }\n              });\n          }\n          getSwitchPosition(appendData) {\n              return appendData.reduce((prevSwitchPos, next) => {\n                  const switchPos = next ? next.dataSeg.switchPosition : undefined;\n                  if (isFiniteNumber(switchPos)) {\n                      return isFiniteNumber(prevSwitchPos) ? Math.min(prevSwitchPos, switchPos) : switchPos;\n                  }\n                  else {\n                      return prevSwitchPos;\n                  }\n              }, undefined);\n          }\n          checkForReplay() {\n              const media = this.mediaElement;\n              // rdar://80790960 ([HLS JS 2.1 beta] Marcom - Retry playback fails). Pulled from 2.0 stream-controller.ts.\n              if (media.paused && !media.seeking && media.duration && media.currentTime && media.currentTime >= media.duration - this.config.maxTotalDurationTolerance) {\n                  this.seekTo = 0; // auto-restart if scrubber is at end of video. media.ended may be reset upon seek or append.\n              }\n          }\n          /**\n           * Reset media source if needed and wait for 'open'\n           * @returns an observable that emits AppendDataTuple if we should append, null if we something did a reset\n           */\n          resetMediaSourceIfNeeded(appendData) {\n              const { mediaQuery } = this;\n              const { sourceBufferEntities } = mediaQuery;\n              const { expectedSbCount } = mediaQuery.getActive();\n              if (!sourceBufferEntities || this.needSourceBuffers) {\n                  this.logger.info('need source buffers #disco');\n                  return this._waitForMediaSourceOpen(appendData);\n              }\n              const compatInfo = isCompatibleWithSourceBuffers(appendData, sourceBufferEntities, expectedSbCount, this.config.maxBufferHole, this.logger);\n              if (compatInfo.compatible) {\n                  this.logger.info('got compatible source buffers #disco');\n                  this.logger.qe({ critical: true, name: 'disco', data: { type: 'compatible' } });\n                  return this._waitForMediaSourceOpen(appendData);\n              }\n              let boundary = compatInfo.boundary;\n              const boundaryAllowance = compatInfo.allowance;\n              const requestedSwitchPos = this.getSwitchPosition(appendData);\n              if (isFiniteNumber(requestedSwitchPos)) {\n                  this.logger.info(`override boundary with switch position=${boundary.toFixed(3)}->${requestedSwitchPos}`);\n                  boundary = requestedSwitchPos;\n              }\n              if (!isFiniteNumber(boundary)) {\n                  this.logger.warn('not enough info #disco');\n                  return of(null);\n              }\n              this.logger.info(`start wait pos=${mediaQuery.currentTime.toFixed(3)} boundary=${boundary.toFixed(3)} allowance=${boundaryAllowance.toFixed(3)} #disco`);\n              this.logger.qe({ critical: true, name: 'disco', data: { type: 'incompatible' } });\n              const hitDiscoBoundary$ = race(\n              // Play or seek across boundary (0 tolerance)\n              waitFor(merge(of(mediaQuery.currentTime), mediaQuery.timeupdate$), (pos) => pos >= boundary), \n              // Stalled playback and we're close enough\n              waitFor(mediaQuery.stallInfo$.pipe(map((stallInfo) => { var _a; return (_a = stallInfo === null || stallInfo === void 0 ? void 0 : stallInfo.currentTime) !== null && _a !== void 0 ? _a : NaN; })), (pos) => pos >= boundary - boundaryAllowance - this.config.discontinuitySeekTolerance));\n              this.mediaElementStore.waitingForDisco = true;\n              return hitDiscoBoundary$.pipe(mapTo(boundary), switchMap((boundary) => {\n                  const startResetTime = performance.now();\n                  const currentTime = mediaQuery.currentTime;\n                  this.logger.info(`end wait pos=${currentTime.toFixed(3)} boundary=${boundary.toFixed(3)} #disco`);\n                  this.logger.qe({ critical: true, name: 'disco', data: { type: 'resetStart' } });\n                  const duration = this.msDuration;\n                  this.resetMediaSource(Math.max(currentTime, boundary), compatInfo.discoSeqNum);\n                  return this._waitForMediaSourceOpen(appendData).pipe(tap(() => {\n                      const resetDuration = performance.now() - startResetTime;\n                      this.logger.qe({ critical: true, name: 'disco', data: { type: 'resetComplete', resetDuration } });\n                      this.msDuration = duration;\n                  }));\n              }), finalize$1(() => {\n                  this.mediaElementStore.waitingForDisco = false;\n              }));\n          }\n          /**\n           * @brief External hard media reset\n           * @param position The position to seek to on reset. NaN means use current seekTo or currentTime. seekTo has precedence > currentTime\n           */\n          resetMediaSource(position = NaN, discoSeqNum) {\n              var _a, _b, _c;\n              this.logger.info(`resetMediaSource ${position} ${discoSeqNum}`);\n              if (!isFiniteNumber(position)) {\n                  position = (_b = (_a = this.mediaQuery.seekTo) === null || _a === void 0 ? void 0 : _a.pos) !== null && _b !== void 0 ? _b : this.mediaQuery.currentTime;\n              }\n              if (!isFiniteNumber(discoSeqNum)) {\n                  discoSeqNum = (_c = this.mediaQuery.seekTo) === null || _c === void 0 ? void 0 : _c.discoSeqNum;\n              }\n              if (this.sourceBuffers.length > 0) {\n                  this.openMediaSource(this.makeMediaSource());\n                  this.logger.info(`resetMediaSource seek=${position} cc=${discoSeqNum}`);\n                  this.setSeekToWithDiscontinuity(position, discoSeqNum); // always update after reset, use given cc\n              }\n          }\n          setExpectedSbCount(sbCount) {\n              this.mediaElementStore.expectedSbCount = sbCount;\n          }\n          appendInitSegments(appendData, appendErrorPolicy) {\n              const { mediaQuery, mediaElementStore, sourceBuffers, logger } = this;\n              const { sourceBufferEntities } = mediaQuery;\n              if (!sourceBuffers) {\n                  throw new Error('appendInitSegments: null sourceBuffers');\n              }\n              if (!sourceBufferEntities) {\n                  throw new Error('appendInitSegments: null sourceBufferEntities');\n              }\n              const initAppendOps$ = this.appendOrder\n                  .map((type) => {\n                  const sbDataTuple = appendData[type];\n                  if (!sbDataTuple)\n                      return;\n                  const sb = sourceBuffers[type];\n                  const sbAppendData = appendData[type];\n                  const currentSbEntity = sourceBufferEntities[type];\n                  const { initSeg } = sbAppendData;\n                  if (!currentSbEntity) {\n                      throw new Error(`appendInitSegments: sb[${SourceBufferNames[type]}] null currentSbEntity`);\n                  }\n                  if (!sb) {\n                      throw new Error(`appendInitSegments: sb[${SourceBufferNames[type]}] null source buffer`);\n                  }\n                  const curInitInfo = currentSbEntity.initSegmentInfo;\n                  const newInitInfo = cacheEntityToInfoEntity(initSeg);\n                  if (initSegmentEquals(newInitInfo, curInitInfo)) {\n                      logger.debug(`[${MediaOptionNames[type]}] skip init segment append ${JSON.stringify(newInitInfo)}`);\n                      return of(null); // noop\n                  }\n                  const mediaOptionType = sourceBufferTypeToMediaOptionType(type);\n                  return sb.appendBuffer(initSeg.data, initSeg).pipe(tap((am) => {\n                      logger.info(`[${MediaOptionNames[type]}] append init segment ${JSON.stringify(newInitInfo)} ${am === null || am === void 0 ? void 0 : am.startAppend}/${am === null || am === void 0 ? void 0 : am.endAppend}/${am === null || am === void 0 ? void 0 : am.bytesAppend}`);\n                      mediaElementStore.setInitSegmentEntity(type, newInitInfo);\n                  }), appendErrorPolicy(sb, mediaOptionType, initSeg.mediaOptionId, this.config, this.mediaQuery));\n              })\n                  .filter((initAppendOp) => Boolean(initAppendOp));\n              if (initAppendOps$.length === 0) {\n                  return of(null); // noop\n              }\n              return forkJoin(initAppendOps$);\n          }\n          appendDataSegments(appendData, appendErrorPolicy) {\n              const dataAppendOps$ = this.appendOrder\n                  .map((type) => {\n                  const sbDataTuple = appendData[type];\n                  const { mediaQuery, sourceBuffers, logger } = this;\n                  const { sourceBufferEntities } = mediaQuery;\n                  if (!sourceBuffers) {\n                      throw new Error('appendDataSegments: null sourceBuffers');\n                  }\n                  if (!sourceBufferEntities) {\n                      throw new Error('appendDataSegments: null sourceBufferEntities');\n                  }\n                  if (!sbDataTuple)\n                      return null;\n                  const sb = sourceBuffers[type];\n                  const sbAppendData = appendData[type];\n                  const currentSbEntity = sourceBufferEntities[type];\n                  if (!currentSbEntity) {\n                      throw new Error('appendDataSegments: null currentSbEntity');\n                  }\n                  const currentInitSegmentInfo = currentSbEntity.initSegmentInfo;\n                  const { dataSeg } = sbAppendData;\n                  if (!currentInitSegmentInfo) {\n                      throw new Error(`appendDataSegments: sb[${SourceBufferNames[type]}] null currentInitSegmentInfo`);\n                  }\n                  if (!currentSbEntity) {\n                      throw new Error(`appendDataSegments: sb[${SourceBufferNames[type]}] null currentSbEntity`);\n                  }\n                  if (!sb) {\n                      throw new Error(`appendDataSegments: sb[${SourceBufferNames[type]}] null source buffer`);\n                  }\n                  const timestampOffset = sb.timestampOffset;\n                  const startPTS = convertTimestampToSeconds(dataSeg.startPts) + timestampOffset;\n                  const endPTS = convertTimestampToSeconds(dataSeg.endPts) + timestampOffset;\n                  const firstKeyframePts = dataSeg.firstKeyframePts ? convertTimestampToSeconds(dataSeg.firstKeyframePts) + timestampOffset : undefined;\n                  const seginfo = {\n                      startPTS,\n                      endPTS,\n                      firstKeyframePts,\n                      bytes: dataSeg.data2 ? dataSeg.data1.byteLength + dataSeg.data2.byteLength : dataSeg.data1.byteLength,\n                      frag: {\n                          itemId: dataSeg.itemId,\n                          mediaOptionId: dataSeg.mediaOptionId,\n                          mediaSeqNum: dataSeg.mediaSeqNum,\n                          discoSeqNum: dataSeg.discoSeqNum,\n                          keyTagInfo: dataSeg.keyTagInfo,\n                          isLastFragment: dataSeg.isLastFragment,\n                          iframe: dataSeg.iframe,\n                          framesWithoutIDR: dataSeg.framesWithoutIDR,\n                          dropped: dataSeg.dropped,\n                      },\n                  };\n                  const mediaOptionType = sourceBufferTypeToMediaOptionType(type);\n                  let optionalFlush = VOID;\n                  const flushRange = sbDataTuple.dataSeg.flushBeforeAppend;\n                  if (flushRange && flushRange.start !== flushRange.end) {\n                      logger.info(`sb[${SourceBufferNames[type]}] flush [${flushRange.start},${flushRange.end}] before append`);\n                      optionalFlush = this.flushData(type, flushRange.start, flushRange.end);\n                  }\n                  return optionalFlush.pipe(switchMap(() => {\n                      const source = of(dataSeg.data1, dataSeg.data2).pipe(filterNullOrUndefined());\n                      return source.pipe(concatMap((data) => {\n                          logger.info(`[${MediaOptionNames[type]}] appending timestampOffset:${currentSbEntity.timestampOffset} segment:${stringifyWithPrecision({\n                            startPTS,\n                            endPTS,\n                            frag: fragPrint(dataSeg),\n                            key: redactUrl(dataSeg.keyTagInfo.uri),\n                        })}`);\n                          return sb.appendBuffer(data, seginfo).pipe(appendErrorPolicy(sb, mediaOptionType, dataSeg.mediaOptionId, this.config, this.mediaQuery));\n                      }));\n                  }), tap(() => {\n                      const bufferedRanges = mediaQuery.getBufferedRangeByType(type);\n                      logger.info(`[${MediaOptionNames[type]}] appended pos:${mediaQuery.currentTime.toFixed(3)} buffered:${stringifyWithPrecision(bufferedRanges)}`);\n                  }));\n              })\n                  .filter((dataAppendOp) => Boolean(dataAppendOp));\n              if (dataAppendOps$.length === 0) {\n                  return of(null); // noop\n              }\n              return forkJoin(dataAppendOps$);\n          }\n          setStoreSbTimeoffsets(appendDataTuple) {\n              const { mediaElementStore, sourceBuffers } = this;\n              sourceBuffers.forEach((sb, type) => {\n                  if (!sb || !appendDataTuple[type]) {\n                      return;\n                  }\n                  const { offsetTimestamp, dataSeg } = appendDataTuple[type];\n                  const startPts = convertTimestampToSeconds(dataSeg.startPts);\n                  let timestampOffset = convertTimestampToSeconds(offsetTimestamp) * -1;\n                  if (sb.updateMp3Timestamps) {\n                      // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n                      // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n                      // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue\n                      // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n                      const delta = Math.abs(sb.timestampOffset - startPts);\n                      // adjust timestamp offset if time delta is greater than 100ms\n                      if (delta > 0.1) {\n                          timestampOffset = startPts + timestampOffset;\n                      }\n                  }\n                  if (sb.timestampOffset !== timestampOffset) {\n                      this.logger.info(`${MediaOptionNames[type]} timestampOffset=${timestampOffset}`);\n                      sb.timestampOffset = timestampOffset;\n                      mediaElementStore.setTimestampOffset(type, sb.timestampOffset);\n                  }\n              });\n          }\n          adjustJaggedStart(appendData) {\n              var _a;\n              const { mediaQuery, logger } = this;\n              const { sourceBufferEntities, currentTime, seekTo } = mediaQuery;\n              const appendEndTime = appendData.reduce((end, append) => {\n                  return (append === null || append === void 0 ? void 0 : append.dataSeg.endPts) ? Math.min(diffSeconds(append.dataSeg.endPts, append.offsetTimestamp), end) : end;\n              }, Number.POSITIVE_INFINITY);\n              if (!sourceBufferEntities) {\n                  throw new Error('appendSourceBufferData null currentSbEntity');\n              }\n              const position = (seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos) || currentTime;\n              let seekToPos = NaN;\n              sourceBufferEntities.forEach((sbEntity, type) => {\n                  if (!sbEntity)\n                      return;\n                  const bufferInfo = BufferHelper.getBufferedInfo(sbEntity.bufferedRanges, position, 0);\n                  if (bufferInfo.len === 0) {\n                      const { nextStart } = bufferInfo;\n                      const tolerance = isFiniteNumber(this.config.jaggedSeekTolerance) ? this.config.jaggedSeekTolerance : 0;\n                      logger.warn(`sb[${SourceBufferNames[type]}] jagged start: ${nextStart} appendEndTime=${appendEndTime} current=${seekToPos} tolerance=${tolerance}`);\n                      if (isFiniteNumber(nextStart) && (!isFiniteNumber(seekToPos) || nextStart - seekToPos > tolerance)) {\n                          seekToPos = nextStart;\n                      }\n                  }\n              });\n              if (isFiniteNumber(seekToPos) && appendEndTime > seekToPos) {\n                  // when appendEndTime < seekToPos, no need to initiate jagged seek.\n                  // wait for subsequent append to fill the buffer.\n                  logger.warn(`[seek] jagged start, adjusting currentTime:${currentTime.toFixed(3)} seekTo=${(_a = seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos) === null || _a === void 0 ? void 0 : _a.toFixed(3)}->${seekToPos} appendEndTime=${appendEndTime}`);\n                  this.seekTo = seekToPos;\n              }\n          }\n          addCues(texttrackIdx, cues) {\n              const textTrack = this.mediaElement.textTracks[texttrackIdx];\n              if (textTrack) {\n                  cues.forEach((cue) => {\n                      textTrack.addCue(cue);\n                  });\n              }\n          }\n          _flushInternal(sb, start, end) {\n              return defer(() => {\n                  this.logger.info(`[${SourceBufferNames[sb.type]}] remove(${start},${end}) start`);\n                  return sb.remove(start, end);\n              }).pipe(tap(() => {\n                  this.logger.info(`[${SourceBufferNames[sb.type]}] remove(${start},${end}) end`);\n              }));\n          }\n          // Flush all source buffers\n          flushAll(start, end, force = false) {\n              if (this.sourceBuffers.length === 0) {\n                  return VOID;\n              }\n              return forkJoin(this.sourceBuffers.map((sb, type) => (sb ? this.flushData(type, start, end, force) : VOID))).pipe(mapTo(undefined));\n          }\n          flushData(sbType, start, end, force = false) {\n              var _a;\n              const { mediaQuery, logger } = this;\n              this.logger.info(`flushData ${start.toFixed(3)} ${end.toFixed(3)} updating=${(_a = mediaQuery.sourceBufferEntities) === null || _a === void 0 ? void 0 : _a.some((sb) => sb === null || sb === void 0 ? void 0 : sb.updating)}`);\n              return waitFor(mediaQuery.updating$, (updating) => updating === false).pipe(switchMap(() => {\n                  const { sourceBufferEntities } = mediaQuery;\n                  const sbEntity = sourceBufferEntities[sbType];\n                  if (sbEntity === null || sbEntity === void 0 ? void 0 : sbEntity.updating) {\n                      this.logger.warn(`trying to flush while updating ${sbType}`);\n                  }\n                  const sb = this.sourceBuffers[sbType];\n                  if (!sb) {\n                      return VOID;\n                  }\n                  let bufStart;\n                  let bufEnd;\n                  let flushes = VOID;\n                  const flushSingleRange = navigator.userAgent.toLowerCase().indexOf('firefox') === -1;\n                  this.flushing = true;\n                  if (flushSingleRange) {\n                      return this._flushInternal(sb, start, end);\n                  }\n                  // workaround firefox not able to properly flush multiple buffered range.\n                  for (let i = 0; i < sb.buffered.length; i++) {\n                      let flushStart;\n                      let flushEnd;\n                      bufStart = sb.buffered.start(i);\n                      bufEnd = sb.buffered.end(i);\n                      if (end === Infinity) {\n                          flushStart = start;\n                          flushEnd = end;\n                      }\n                      else {\n                          flushStart = Math.max(bufStart, start);\n                          flushEnd = Math.min(bufEnd, end);\n                      }\n                      /*\n                        sometimes sourcebuffer.remove() does not flush\n                        the exact expected time range.\n                        to avoid rounding issues/infinite loop,\n                        only flush buffer range of length greater than 500ms.\n                      */\n                      if (Math.min(flushEnd, bufEnd) > flushStart && (force || Math.min(flushEnd, bufEnd) - flushStart > 0.5)) {\n                          flushes = flushes.pipe(switchMapTo(this._flushInternal(sb, flushStart, flushEnd)));\n                      }\n                      else {\n                          logger.warn(`ignoring sb[${SourceBufferNames[sbType]}] flush ${flushStart},${flushEnd}`);\n                      }\n                  }\n                  return flushes;\n              }), finalize$1(() => {\n                  // clear flushing\n                  this.flushing = false;\n              }));\n          }\n          static convertInitSegToCompatInfo(initSeg) {\n              return {\n                  mimeType: initSeg.mimeType,\n                  audioCodec: initSeg.initParsedData.audioCodec,\n                  videoCodec: initSeg.initParsedData.videoCodec,\n                  startPTSSec: undefined,\n                  endPTSSec: undefined,\n                  discoSeqNum: initSeg.discoSeqNum,\n                  mediaOptionId: initSeg.mediaOptionId,\n              };\n          }\n          static combineAppendDataInfoWithCompatInfo(appendData, oldCompatInfoTuple, highestVideoCodec, logger = null) {\n              const newCompatInfo = [...oldCompatInfoTuple];\n              appendData.forEach((d, type) => ((d === null || d === void 0 ? void 0 : d.initSeg) ? (newCompatInfo[type] = MediaSink.convertInitSegToCompatInfo(d.initSeg)) : null));\n              const currentVideoCodecString = newCompatInfo[SourceBufferType.Variant].videoCodec;\n              const currentVideoCodecFamily = getVideoCodecFamily(currentVideoCodecString);\n              // Replace to highest video codec string.\n              if (highestVideoCodec && highestVideoCodec.has(currentVideoCodecFamily)) {\n                  // if configured to use highestCodec\n                  const highestVideoCodecString = highestVideoCodec.get(currentVideoCodecFamily);\n                  logger === null || logger === void 0 ? void 0 : logger.info(`override with highest video codec ${highestVideoCodecString}`);\n                  newCompatInfo[SourceBufferType.Variant].mimeType = newCompatInfo[SourceBufferType.Variant].mimeType.replace(currentVideoCodecString, highestVideoCodecString);\n                  newCompatInfo[SourceBufferType.Variant].videoCodec = highestVideoCodecString;\n                  logger === null || logger === void 0 ? void 0 : logger.info(`compatibility info overrridden from ${currentVideoCodecString} to ${newCompatInfo[SourceBufferType.Variant].videoCodec}/${newCompatInfo[SourceBufferType.Variant].mimeType}`);\n              }\n              return newCompatInfo;\n          }\n          convertSourceBufferEntitiesToCompatInfo(mediaQuery) {\n              const sbEntities = mediaQuery.sourceBufferEntities;\n              const compatInfos = [null, null];\n              sbEntities.forEach((sbEntity, type) => {\n                  var _a;\n                  if (!sbEntity)\n                      return;\n                  compatInfos[type] = {\n                      mimeType: sbEntity.mimeType,\n                      audioCodec: sbEntity.audioCodec,\n                      videoCodec: sbEntity.videoCodec,\n                      startPTSSec: undefined,\n                      endPTSSec: undefined,\n                      discoSeqNum: undefined,\n                      // right after resetMediaSource, sbEntity may not have initSegmentInfo yet.\n                      // mediaOptionId to be filled in by combineAppendDataInfoWithCompatInfo before createSourceBuffers.\n                      mediaOptionId: (_a = sbEntity.initSegmentInfo) === null || _a === void 0 ? void 0 : _a.mediaOptionId,\n                  };\n              });\n              return compatInfos;\n          }\n          appendData(appendData, appendErrorPolicy, highestVideoCodec) {\n              const { mediaQuery, logger } = this;\n              const oldCompatInfoTuple = this.convertSourceBufferEntitiesToCompatInfo(mediaQuery);\n              if (appendData.every((data) => data == null)) {\n                  return of([]); // noop\n              }\n              return this.resetMediaSourceIfNeeded(appendData).pipe(switchMap((appendData) => {\n                  if (!appendData) {\n                      return of(null); // Got an unexpected reset, stop what we're doing\n                  }\n                  // Don't want updating to trigger switchMap above which will abort the append below.\n                  return mediaQuery.updating$.pipe(filter((updating) => updating === false), take(1), mapTo(appendData));\n              }), switchMap((appendData) => {\n                  if (!appendData) {\n                      return of([]);\n                  }\n                  let bufferCreationStart = NaN;\n                  let bufferCreationEnd = NaN;\n                  if (this.needSourceBuffers) {\n                      bufferCreationStart = performance.now();\n                      const newCompatInfoTuple = MediaSink.combineAppendDataInfoWithCompatInfo(appendData, oldCompatInfoTuple, highestVideoCodec, logger);\n                      this.createSourceBuffers(newCompatInfoTuple);\n                      bufferCreationEnd = performance.now();\n                      logger.info(`[Buffers] source buffers created start/end: ${bufferCreationStart}/${bufferCreationEnd}`);\n                      this.clearFlush(appendData);\n                  }\n                  appendData.forEach((data) => {\n                      const mediaData = data === null || data === void 0 ? void 0 : data.dataSeg;\n                      if ((mediaData === null || mediaData === void 0 ? void 0 : mediaData.cues) && isFiniteNumber(mediaData === null || mediaData === void 0 ? void 0 : mediaData.texttrackIdx)) {\n                          this.addCues(mediaData.texttrackIdx, mediaData.cues);\n                      }\n                  });\n                  this.setStoreSbTimeoffsets(appendData);\n                  return concat(defer(() => this.appendInitSegments(appendData, appendErrorPolicy)), defer(() => this.appendDataSegments(appendData, appendErrorPolicy))).pipe(reduce((acc, value) => {\n                      acc.push(value);\n                      return acc;\n                  }, new Array()), map(([initSegmentMetrics, dataSegmentMetrics]) => {\n                      const metrics = [null, null];\n                      [SourceBufferType.Variant, SourceBufferType.AltAudio].forEach((type) => {\n                          if ((initSegmentMetrics === null || initSegmentMetrics === void 0 ? void 0 : initSegmentMetrics[type]) == null)\n                              return;\n                          const metric = {\n                              fragmentType: sourceBufferTypeToMediaOptionType(type),\n                              bufferCreationStart,\n                              bufferCreationEnd,\n                              startInitAppend: initSegmentMetrics[type].startAppend,\n                              endInitAppend: initSegmentMetrics[type].endAppend,\n                              initBytesAppend: initSegmentMetrics[type].bytesAppend,\n                              startDataAppend: dataSegmentMetrics[type].startAppend,\n                              endDataAppend: dataSegmentMetrics[type].endAppend,\n                              dataBytesAppend: dataSegmentMetrics[type].bytesAppend,\n                          };\n                          metrics[type] = metric;\n                      });\n                      return metrics;\n                  }), tap((_) => {\n                      this.adjustJaggedStart(appendData);\n                  }));\n              }), take(1));\n          }\n          endStream() {\n              // Will throw error if msReadyState !== open or any source buffer is updating\n              try {\n                  this.mediaSourceAdapter.endOfStream();\n              }\n              catch (err) {\n                  this.logger.warn(`endOfStream failed: ${err.message}`);\n              }\n          }\n          /**\n           * Set CDM on media element\n           * @param mediaKeys The CDM to attach, or null\n           */\n          setMediaKeys(mediaKeys) {\n              const { logger } = this;\n              return this.teardownWG$.wrap(this.mediaKeysMutex\n                  .lock(() => from(this.mediaElement.setMediaKeys(mediaKeys)))\n                  .pipe(tap(() => {\n                  logger.info(`[Keys] setMediaKeys(${mediaKeys}) success`);\n              }), retryWhen((errors) => errors.pipe(mergeMap((err, i) => {\n                  logger.info(`[Keys] setMediaKeys(${mediaKeys} fail ${err.message})`);\n                  if (i < 3) {\n                      logger.info(`[Keys] Retry setMediaKeys delay=${i * 100}`);\n                      return timer(i * 100);\n                  }\n                  throw err;\n              })))));\n          }\n          clearMediaKeys() {\n              return defer(() => {\n                  if (!this.mediaElement) {\n                      return VOID;\n                  }\n                  const isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;\n                  const src = this.mediaElement.src;\n                  if (isChrome) {\n                      //https://github.com/Dash-Industry-Forum/dash.js/issues/623\n                      this.mediaElement.src = '';\n                  }\n                  return this.setMediaKeys(null).pipe(tap(() => (this.mediaElement.src = src)));\n              });\n          }\n          set postFlushSeek(time) {\n              this.mediaElementStore.postFlushSeek = time;\n          }\n          schedulePostFlushSeek(newSeekTo) {\n              applyTransaction(() => {\n                  if (this.mediaQuery.seekTo) {\n                      // <rdar://89566883> forget unfinished internal seek\n                      this.seekTo = null; // this will also clear mediaSink.postFlushSeek\n                  }\n                  this.postFlushSeek = newSeekTo;\n              });\n          }\n          set seekTo(seekTo) {\n              this.mediaElementStore.setSeekToPos(seekTo, false);\n          }\n          setSeekToWithDiscontinuity(seekTo, discoSeqNum) {\n              this.mediaElementStore.setSeekToPos(seekTo, false, discoSeqNum);\n          }\n          nudgeSeek(seekTo, nudgeCount) {\n              applyTransaction(() => {\n                  this.mediaElementStore.setSeekToPos(seekTo, false);\n                  this.mediaElementStore.setNudgeInfo({ nudgeTarget: seekTo, nudgeCount });\n              });\n          }\n          set desiredRate(desiredRate) {\n              this.mediaElementStore.desiredRate = desiredRate;\n              // play / pause done in rateChange epic\n          }\n          toggleTrickPlaybackMode(enabled) {\n              // Override playbackRate value\n              if (this.config.overridePlaybackRate) {\n                  const mediaRate = enabled ? 2 : 1;\n                  try {\n                      this.mediaElement.playbackRate = mediaRate;\n                      this.logger.info({ name: 'iframes' }, `setting playbackRate to ${mediaRate}`);\n                  }\n                  catch (err) {\n                      this.logger.error({ name: 'iframes' }, `Exception when setting playbackRate=${mediaRate}: ${err.message}`);\n                  }\n              }\n              // Toggle mute value\n              const prev = this.muteValueOnTrickPlaybackToggle;\n              if (enabled && prev === undefined) {\n                  this.muteValueOnTrickPlaybackToggle = this.mediaElement.muted;\n                  this.mediaElement.muted = enabled;\n              }\n              else if (!enabled && prev !== undefined) {\n                  this.mediaElement.muted = prev;\n                  this.muteValueOnTrickPlaybackToggle = undefined;\n              }\n          }\n          play() {\n              this.logger.info('play()');\n              this.mediaFunctions.play();\n          }\n          pause() {\n              this.logger.info('pause()');\n              this.mediaFunctions.pause();\n          }\n          get expectPlayEvent() {\n              return this.mediaFunctions.expectPlayEvent;\n          }\n          set expectPlayEvent(value) {\n              this.mediaFunctions.expectPlayEvent = value;\n          }\n          get expectPauseEvent() {\n              return this.mediaFunctions.expectPauseEvent;\n          }\n          set expectPauseEvent(value) {\n              this.mediaFunctions.expectPauseEvent = value;\n          }\n          set textTracksCreated(created) {\n              const { mediaElementStore } = this;\n              mediaElementStore.textTracksCreated = created;\n          }\n          get msDuration() {\n              return this._mediaQuery.msDuration;\n          }\n          set msDuration(duration) {\n              try {\n                  const { mediaElementStore } = this;\n                  const mediaSource = this.mediaSource$.value;\n                  if (mediaSource.duration !== duration) {\n                      this.logger.debug(`set msduration ${duration}`);\n                      mediaSource.duration = duration;\n                      mediaElementStore.msDuration = duration;\n                  }\n              }\n              catch (err) {\n                  this.logger.warn(`Error setting duration ${err.message}`);\n              }\n          }\n          set haveEnough(haveEnough) {\n              this.mediaElementStore.haveEnough = haveEnough;\n          }\n          set flushing(flushing) {\n              this.mediaElementStore.flushing = flushing;\n          }\n          set bufferMonitorTargetDuration(durationSeconds) {\n              this.mediaElementStore.bufferMonitorTargetDuration = durationSeconds;\n          }\n          get textTracks() {\n              return this.mediaElement.textTracks;\n          }\n          get id3TextTrack() {\n              return this.id3Track;\n          }\n          addTextTrack(kind, label, language) {\n              return this.mediaElement.addTextTrack(kind, label, language);\n          }\n          dispatchEvent(e) {\n              return this.mediaElement.dispatchEvent(e);\n          }\n          get offsetWidth() {\n              return this.mediaElement.offsetWidth;\n          }\n          get offsetHeight() {\n              return this.mediaElement.offsetHeight;\n          }\n          getliveSeekableWindow() {\n              return this.liveSeekableWindow;\n          }\n          archiveParsedSubtitleFragmentRecord(persistentId, mediaSeqNum, fragCueRecord) {\n              return this.mediaElementStore.archiveParsedSubtitleFragmentRecord(persistentId, mediaSeqNum, fragCueRecord);\n          }\n          updateLiveSeekableRange(levelDetails) {\n              const fragments = levelDetails.fragments;\n              const len = fragments.length;\n              if (len > 1) {\n                  const start = Math.max(fragments[0].start, 0);\n                  const end = fragments[len - 1].start + fragments[len - 1].duration;\n                  this.mediaSource$.value.updateLiveSeekableRange(start, end);\n                  this.liveSeekableWindow.start = start;\n                  this.liveSeekableWindow.end = end;\n              }\n          }\n          clearLiveSeekableRange() {\n              this.mediaSource$.value.clearLiveSeekableRange();\n              this.liveSeekableWindow.start = NaN;\n              this.liveSeekableWindow.end = NaN;\n          }\n      }\n      /**\n       * @brief Translate media element events to store updates\n       */\n      const hookMediaElementsEvents = (mediaElement, mediaElementStore, mediaQuery, mediaSink, gaplessInstance, config, logger, rtcService) => {\n          if (!mediaElement)\n              return EMPTY;\n          const target = fromEventTarget(mediaElement);\n          return merge(target.event('durationchange').pipe(map((ev) => convertEvent(mediaElement, 'durationchange', ev)), tap((ev) => {\n              const media = ev.currentTarget;\n              mediaElementStore.mediaElementDuration = media.duration;\n          })), target.event('seeking').pipe(throttleTime(config.seekEventThrottleMs), map((ev) => convertEvent(mediaElement, 'seeking', ev)), tap((ev) => {\n              const media = ev.currentTarget;\n              const seekToValue = media.currentTime;\n              if (media.readyState >= media.HAVE_METADATA) {\n                  const seekTo = mediaQuery.seekTo;\n                  if (!seekTo || (!seekTo.fromEvent && Math.abs(seekTo.pos - seekToValue) > 0.00001)) {\n                      // Gapless Stuff\n                      if (gaplessInstance.inGaplessMode) {\n                          gaplessSeek(seekToValue, gaplessInstance, mediaSink, mediaElementStore, logger);\n                          return;\n                      }\n                      else {\n                          if (mediaSink &&\n                              // eslint-disable-next-line no-prototype-builtins\n                              mediaSink.hasOwnProperty('liveSeekableWindow') &&\n                              isFiniteNumber(mediaSink.getliveSeekableWindow().start) &&\n                              isFiniteNumber(mediaSink.getliveSeekableWindow().end) &&\n                              (seekToValue < mediaSink.getliveSeekableWindow().start || seekToValue > mediaSink.getliveSeekableWindow().end)) {\n                              // Adjust seek to within live window\n                              liveAdjustedSeek(seekToValue, mediaSink.getliveSeekableWindow().start, mediaSink.getliveSeekableWindow().end, config, mediaElementStore, logger);\n                          }\n                          else {\n                              mediaElementStore.setSeekToPos(seekToValue, true);\n                          }\n                      }\n                  }\n                  else {\n                      // seekTo is already set (not from event) so we just need to update seeking state until \"seeked\"\n                      mediaElementStore.seeking = true;\n                  }\n              }\n          })), target.event('seeked').pipe(map((ev) => convertEvent(mediaElement, 'seeked', ev)), tap(() => {\n              mediaElementStore.setSeekToPos(null, true);\n              const currentTime = mediaElement.currentTime;\n              if (isFiniteNumber(currentTime)) {\n                  logger.qe({ critical: true, name: 'seeked', data: { seekTo: currentTime.toFixed(3) } });\n              }\n          })), target.event('play').pipe(map((ev) => convertEvent(mediaElement, 'play', ev)), withLatestFrom(mediaQuery.desiredRate$), map(([ev, desiredRate]) => {\n              const media = ev.currentTarget;\n              mediaElementStore.paused = media.paused;\n              const expectPlayEvent = mediaSink.expectPlayEvent;\n              const allowSetRate = media.controls || config.nativeControlsEnabled;\n              logger.info(`media play desiredRate=${desiredRate} expectPlayEvent=${expectPlayEvent} allowed=${allowSetRate}`);\n              if (!expectPlayEvent && allowSetRate) {\n                  mediaSink.checkForReplay();\n                  mediaElementStore.desiredRate = 1;\n              }\n              mediaSink.expectPlayEvent = false;\n              return ev;\n          })), target.event('playing').pipe(map((ev) => convertEvent(mediaElement, 'playing', ev)), tap((ev) => {\n              const media = ev.currentTarget;\n              // log playing event immediately.\n              logger.qe({ critical: true, name: 'playerEvent', data: { type: ev.type, pos: media.currentTime.toFixed(3), dur: media.duration.toFixed(3) } });\n              mediaElementStore.paused = media.paused;\n              mediaElementStore.gotPlayingEvent();\n          })), target.event('loadstart').pipe(map((ev) => convertEvent(mediaElement, 'loadstart', ev)), tap(() => {\n              mediaElementStore.gotLoadStartEvent();\n          })), target.event('pause').pipe(map((ev) => convertEvent(mediaElement, 'pause', ev)), tap((ev) => {\n              const media = ev.currentTarget;\n              mediaElementStore.paused = media.paused;\n              const expectPauseEvent = mediaSink.expectPauseEvent;\n              const allowSetRate = media.controls || config.nativeControlsEnabled;\n              logger.info(`media pause desiredRate=${mediaQuery.desiredRate} expectPauseEvent=${expectPauseEvent} allowed=${allowSetRate}`);\n              if (!expectPauseEvent && allowSetRate) {\n                  mediaElementStore.desiredRate = 0;\n              }\n              mediaSink.expectPauseEvent = false;\n          })), \n          // readystate change events. May not be fired for all platforms so take\n          // with a grain of salt\n          target.event('loadedmetadata').pipe(map((ev) => convertEvent(mediaElement, 'loadedmetadata', ev))), // HAVE_METADATA\n          target.event('loadeddata').pipe(map((ev) => convertEvent(mediaElement, 'loadeddata', ev))), // HAVE_CURRENT_DATA\n          target.event('canplay').pipe(map((ev) => convertEvent(mediaElement, 'canplay', ev))), // HAVE_FUTURE_DATA\n          target.event('canplaythrough').pipe(map((ev) => convertEvent(mediaElement, 'canplaythrough', ev))), // HAVE_ENOUGH_DATA\n          target.event('waiting').pipe(map((ev) => convertEvent(mediaElement, 'waiting', ev))), // less than HAVE_CURRENT_DATA and not paused\n          target.event('emptied').pipe(map((ev) => convertEvent(mediaElement, 'emptied', ev))), // HAVE_NOTHING (media.load() was called)\n          target.event('error').pipe(map((ev) => convertEvent(mediaElement, 'error', ev)), concatMap((ev) => {\n              return throwError(mediaElement.error);\n          })), // HAVE_NOTHING\n          target.event('ended').pipe(map((ev) => convertEvent(mediaElement, 'ended', ev)))).pipe(withLatestFrom(mediaQuery.bufferedRangeTuple$), withTransaction(([ev, bufferedRanges]) => {\n              const media = ev.currentTarget;\n              const readyState = media.readyState;\n              mediaElementStore.readyState = readyState;\n              mediaElementStore.ended = media.ended;\n              logger.info(`media event: ${ev.type} pos:${media.currentTime.toFixed(3)} dur:${media.duration.toFixed(3)} buffered:${stringifyWithPrecision(bufferedRanges)} readyState:${readyState}`);\n              // playing event is logged immediately when event occurs, so skip it here\n              if (ev.type != 'playing') {\n                  logger.qe({ critical: true, name: 'playerEvent', data: { type: ev.type, pos: media.currentTime.toFixed(3), dur: media.duration.toFixed(3) } });\n              }\n          }), catchError((err) => {\n              if (err instanceof MediaError) {\n                  logger.warn(`mediaElementError, code: ${err.code}, message: ${err.message}`);\n                  rtcService === null || rtcService === void 0 ? void 0 : rtcService.handleMediaElementError(err);\n              }\n              else {\n                  logger.error(`media event error: ${err.message}`);\n              }\n              return EMPTY;\n          }), switchMapTo(NEVER), catchError((err) => {\n              if (err instanceof MediaError) {\n                  logger.warn(`mediaElementError, code: ${err.code}, message: ${err.message}`);\n                  return throwError(err); // re-throw media element errors for reporting\n              }\n              else {\n                  logger.error(`media event error: ${err.message}`);\n                  return EMPTY;\n              }\n          }));\n      };\n      // Helper function for seeking when in gapless mode\n      function gaplessSeek(seekToValue, gaplessInstance, mediaSink, mediaElementStore, logger) {\n          let seekValueAdjusted = false;\n          // Adjust seekToValue if needed\n          logger.debug(`seekTo before gapless adjust: ${seekToValue}, startOffset: ${gaplessInstance.playingItem.itemStartOffset}`);\n          if (seekToValue < gaplessInstance.playingItem.itemStartOffset) {\n              logger.warn(`[Gapless] Seeking past track boundary oldSeek=${seekToValue}, adjustedSeek=${gaplessInstance.playingItem.itemStartOffset}`);\n              seekToValue = gaplessInstance.playingItem.itemStartOffset;\n              seekValueAdjusted = true;\n          }\n          if (gaplessInstance.isPreloading) {\n              if (seekToValue > gaplessInstance.loadingItem.itemStartOffset) {\n                  logger.warn(`[Gapless] Seeking past track boundary oldSeek=${seekToValue}, adjustedSeek=${gaplessInstance.loadingItem.itemStartOffset}`);\n                  seekToValue = gaplessInstance.loadingItem.itemStartOffset;\n                  seekValueAdjusted = true;\n              }\n              // Unable to get the state before the seek event, hence need to dequeue on every seek.\n              gaplessInstance.dequeueSource('SeekToUnbufferedTimeRanges');\n          }\n          if (seekValueAdjusted) {\n              mediaSink.resetMediaSource(seekToValue);\n          }\n          else {\n              mediaElementStore.setSeekToPos(seekToValue, true);\n          }\n      }\n      // TODO consolidate this with live-position sanitizeLiveSeek\n      function liveAdjustedSeek(seekValue, liveSeekableWindowStart, liveSeekableWindowEnd, config, mediaElementStore, logger) {\n          let adjustedSeek = seekValue;\n          if (seekValue < liveSeekableWindowStart) {\n              adjustedSeek = liveSeekableWindowStart;\n          }\n          else if (seekValue > liveSeekableWindowEnd) {\n              let targetLatency = config.defaultTargetDuration;\n              if (isFiniteNumber(config.liveSyncDuration)) {\n                  targetLatency = config.liveSyncDuration;\n              }\n              else if (isFiniteNumber(config.liveSyncDurationCount)) {\n                  targetLatency = config.liveSyncDurationCount * config.defaultTargetDuration;\n              }\n              adjustedSeek = Math.max(0, liveSeekableWindowEnd - targetLatency);\n          }\n          logger.warn(`[live] liveAdjustedSeek seekTo:${toFixed(seekValue, 3)}, adjustedSeek:${toFixed(adjustedSeek, 3)}, liveWindowStart:${toFixed(liveSeekableWindowStart, 3)}, liveWindowEnd:${toFixed(liveSeekableWindowEnd, 3)}`);\n          mediaElementStore.setSeekToPos(adjustedSeek, true);\n      }\n      function getMatchingInfo(sbEntity, fragStart, fragEnd, discoSeqNum, mediaOptionId, logger) {\n          const buffered = sbEntity === null || sbEntity === void 0 ? void 0 : sbEntity.bufferedSegments;\n          if (!buffered) {\n              logger.warn('getMatchingInfo trying to query null sbEntity');\n              return null;\n          }\n          const seg = buffered.find((seg) => {\n              const matchDisco = seg.frag.discoSeqNum === discoSeqNum;\n              const overlap = Math.max(fragStart, seg.startPTS) < Math.min(fragEnd, seg.endPTS);\n              return matchDisco && overlap;\n          });\n          if (seg != null) {\n              const { audioCodec, videoCodec, mimeType } = sbEntity;\n              return { mimeType, audioCodec, videoCodec, startPTSSec: seg.startPTS, endPTSSec: seg.endPTS, discoSeqNum, mediaOptionId };\n          }\n          return null;\n      }\n      /**\n       * check whether the appendData is compatible with the curent source buffers.\n       * @param appendData the data to append. It is assumed that we will never have mismatched discoSeqNum for these two\n       * @param offsetTimestamp timestamp value that will be used to SourceBuffer.timestampOffset. Use for position calculation\n       * @param sourceBufferEntities info about the current set of buffers\n       * @param expectedSbCount the expected number of sourceBuffers\n       * @param logger a logger instance\n       * @returns compatible: if compatible with current source buffers\n       * boundary: the discontinuity boundary. NaN if we didn't get enough info\n       */\n      function isCompatibleWithSourceBuffers(appendData, sourceBufferEntities, expectedSbCount, gapTolerance, logger) {\n          var _a, _b;\n          const curSbCount = sourceBufferEntities.filter((sbEntity) => Boolean(sbEntity)).length;\n          const newSbCount = appendData.filter((sbDataTuple) => Boolean(sbDataTuple)).length;\n          const compatInfos = [null, null];\n          appendData.forEach((sbAppendData, type) => {\n              if (sbAppendData) {\n                  const { offsetTimestamp } = sbAppendData;\n                  const tsOffsetSec = convertTimestampToSeconds(offsetTimestamp);\n                  const mimeType = sbAppendData.initSeg.mimeType;\n                  const { audioCodec, videoCodec } = sbAppendData.initSeg.initParsedData;\n                  const { dataSeg } = sbAppendData;\n                  const startPTS = convertTimestampToSeconds(dataSeg.startPts) - tsOffsetSec;\n                  const endPTS = convertTimestampToSeconds(dataSeg.endPts) - tsOffsetSec;\n                  const discoSeqNum = dataSeg.discoSeqNum;\n                  compatInfos[type] = { audioCodec, videoCodec, mimeType, startPTSSec: startPTS, endPTSSec: endPTS, discoSeqNum, mediaOptionId: sbAppendData.initSeg.mediaOptionId };\n                  logger.trace(`compatInfos[${type}] = { ${audioCodec}, ${videoCodec}, ${mimeType}, ${startPTS}, ${endPTS}, ${discoSeqNum}, ${sbAppendData.initSeg.mediaOptionId}`);\n              }\n          });\n          let compatible = curSbCount === expectedSbCount;\n          let gotEnoughData = newSbCount === expectedSbCount;\n          // check appendData count against enabled tracks (expectedSbCount) instead of existing sourceBuffer counts (curSbCount).\n          // when switching between muxed and alt audio, curSbCount may be wrong and need a resetMediaSource before appending.\n          logger.trace(`mediaSink setup: enabledMediaOption# ${expectedSbCount} sourceBuffer# ${curSbCount} appendData# ${newSbCount}: compatible ${compatible} gotEnoughData ${gotEnoughData}`);\n          if (newSbCount === 1 && newSbCount < expectedSbCount && curSbCount !== 0) {\n              const curType = appendData[MediaOptionType.Variant] ? MediaOptionType.Variant : MediaOptionType.AltAudio;\n              const otherType = 1 - curType;\n              const curFrag = compatInfos[curType];\n              const foundFrag = (compatInfos[otherType] = getMatchingInfo(sourceBufferEntities[otherType], curFrag.startPTSSec, curFrag.endPTSSec, curFrag.discoSeqNum, curFrag.mediaOptionId, logger));\n              if (!foundFrag) {\n                  const iframeMode = (_b = (_a = appendData[MediaOptionType.Variant]) === null || _a === void 0 ? void 0 : _a.dataSeg) === null || _b === void 0 ? void 0 : _b.iframe;\n                  if (iframeMode && curType === MediaOptionType.Variant && compatInfos[curType]) {\n                      // in iframe mode, audio may have large loading gaps. Allow iframes to append even when no matching audio frag is present.\n                      const currentVideoCodec = sourceBufferEntities[curType].videoCodec;\n                      const newVideoCodec = compatInfos[curType].videoCodec;\n                      compatible = compatible && (currentVideoCodec === newVideoCodec || MediaUtil.isCompatibleVideoCodec(currentVideoCodec, newVideoCodec));\n                      if (compatible) {\n                          logger.info(`${MediaOptionNames[curType]} allow iframe=${currentVideoCodec}->${newVideoCodec} with no matching audio #disco`);\n                          return { compatible, boundary: NaN, allowance: NaN, discoSeqNum: compatInfos[curType].discoSeqNum };\n                      }\n                  }\n                  else {\n                      logger.warn(`${MediaOptionNames[curType]} No matching frag found ${stringifyWithPrecision(curFrag)} buffered=${stringifyWithPrecision(sourceBufferEntities[otherType].bufferedSegments.map((seg) => {\n                        const { mediaSeqNum, discoSeqNum } = seg.frag;\n                        return { mediaSeqNum, discoSeqNum, startPTS: seg.startPTS, endPTS: seg.endPTS };\n                    }))}`);\n                  }\n              }\n              else {\n                  logger.trace(`foundFrag = compatInfos[${otherType}] = { ${foundFrag.audioCodec}, ${foundFrag.videoCodec}, ${foundFrag.mimeType}, ${foundFrag.startPTSSec}, ${foundFrag.endPTSSec}, ${foundFrag.discoSeqNum}, ${foundFrag.mediaOptionId}`);\n              }\n              gotEnoughData = foundFrag != null;\n          }\n          let boundary = NaN;\n          let allowance = NaN;\n          let cc = NaN;\n          if (gotEnoughData) {\n              compatInfos.forEach((info, type) => {\n                  var _a;\n                  if (!info)\n                      return null;\n                  // to be used for incompat. discontinuity only:\n                  // set cc if all append & buffered data at this pos have the same cc\n                  // determine the next discontinuity sequence number after resetMediaSource\n                  if (!isFiniteNumber(cc)) {\n                      cc = info.discoSeqNum;\n                  }\n                  else if (cc !== info.discoSeqNum) {\n                      cc = NaN;\n                  }\n                  const currentSbEntity = sourceBufferEntities[type];\n                  if (!currentSbEntity) {\n                      compatible = false;\n                  }\n                  else {\n                      const currentAudioCodec = currentSbEntity.audioCodec;\n                      const currentVideoCodec = currentSbEntity.videoCodec;\n                      const { audioCodec: newAudioCodec, videoCodec: newVideoCodec } = info;\n                      compatible = compatible && (currentVideoCodec === newVideoCodec || MediaUtil.isCompatibleVideoCodec(currentVideoCodec, newVideoCodec));\n                      compatible = compatible && (currentAudioCodec === newAudioCodec || MediaUtil.isCompatibleAudioCodec(currentAudioCodec, newAudioCodec));\n                      logger.info(`${MediaOptionNames[type]} video=${currentVideoCodec}->${newVideoCodec} audio=${currentAudioCodec}->${newAudioCodec} start=${(_a = info.startPTSSec) === null || _a === void 0 ? void 0 : _a.toFixed(3)} #disco`);\n                  }\n                  if (isFiniteNumber(boundary)) {\n                      allowance = Math.abs(info.startPTSSec - boundary);\n                      boundary = Math.max(info.startPTSSec, boundary);\n                  }\n                  else {\n                      allowance = 0;\n                      boundary = info.startPTSSec;\n                  }\n              });\n          }\n          return { compatible: compatible && gotEnoughData, boundary, allowance, discoSeqNum: cc };\n      }\n      function seekEpic(mediaElement, mediaQuery, mediaSink, config, logger) {\n          logger = logger.child({ name: 'seek' });\n          return (seekTo$) => seekTo$.pipe(tap((seekTo) => logger.info(`seekTo=${JSON.stringify(seekTo)}`)), filter((seekTo) => seekTo && isFiniteNumber(seekTo.pos)), switchMap((seekTo) => {\n              return mediaQuery.readyState$.pipe(filter((readyState) => readyState >= mediaElement.HAVE_METADATA), take(1), mapTo(seekTo), switchMap(({ pos, fromEvent }) => {\n                  logger.info(`startSeek(${pos === null || pos === void 0 ? void 0 : pos.toFixed(3)},${fromEvent})`);\n                  mediaSink.checkForInconsistentStoreBufferRangesAndUpdate();\n                  if (!mediaElement.paused) {\n                      mediaSink.pause();\n                  }\n                  if (!fromEvent) {\n                      mediaElement.currentTime = pos;\n                  }\n                  return waitFor(mediaQuery.haveEnough$, (x) => x).pipe(mapTo({ pos, fromEvent }));\n              }), switchMap(({ pos, fromEvent }) => {\n                  const combinedBuffer = mediaQuery.getCombinedBufferInfo(pos, 0);\n                  const nextStart = combinedBuffer.nextStart;\n                  const applyNudge = !fromEvent || config.nudgeFromEventSeek;\n                  logger.info(`haveEnough readystate=${mediaQuery.readyState} fromEvent=${fromEvent} applyNudge=${applyNudge} nextStart ${nextStart} pos ${pos} combinedBuffer.len ${combinedBuffer.len}`);\n                  if (applyNudge && combinedBuffer.len === 0 && isFiniteNumber(nextStart) && nextStart > pos && nextStart - pos <= config.maxSeekHole) {\n                      logger.info(`haveEnough but current position not actually buffered, nudge ${pos.toFixed(3)}->${nextStart.toFixed(3)}`);\n                      mediaSink.seekTo = nextStart;\n                      return EMPTY;\n                  }\n                  return of(pos);\n              }), withLatestFrom(mediaQuery.desiredRate$), map(([pos, desiredRate]) => {\n                  logger.info(`completeSeek(${pos === null || pos === void 0 ? void 0 : pos.toFixed(3)}) readyState=${mediaElement.readyState} paused=${mediaElement.paused} desiredRate=${desiredRate}`);\n                  if (mediaElement.paused && desiredRate !== 0) {\n                      mediaSink.play();\n                  }\n              }), switchMapTo(EMPTY), catchError((err) => {\n                  logger.error(`error during seek ${err.message}`);\n                  return EMPTY;\n              }));\n          }));\n      }\n      function rateChangeEpic(mediaElement, mediaQuery, mediaSink, logger) {\n          return (rateChange$) => rateChange$.pipe(withLatestFrom(mediaQuery.seekTo$), switchMap(([rate, seekTo]) => {\n              if (isFiniteNumber(seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos)) {\n                  return EMPTY; // Taken care of by seekEpic\n              }\n              if (rate === 0) {\n                  if (!mediaElement.paused) {\n                      mediaSink.pause();\n                  }\n                  return EMPTY;\n              }\n              return waitFor(mediaQuery.haveEnough$, (x) => x).pipe(tap(() => {\n                  if (mediaElement.paused) {\n                      mediaSink.play();\n                  }\n              }));\n          }), switchMapTo(EMPTY));\n      }\n      function stallEpic(mediaSink, meStore, config, logger) {\n          return (stallInfo$) => stallInfo$.pipe(exhaustMap((stallInfo) => {\n              if (!stallInfo) {\n                  return of(NaN);\n              }\n              return nudgeSeek(mediaSink, meStore, config, logger);\n          }));\n      }\n      function nudgeSeek(mediaSink, meStore, config, logger) {\n          const meQuery = mediaSink.mediaQuery;\n          const gotUserSeek$ = combineQueries([meQuery.seekTo$, meQuery.nudgeTarget$]).pipe(filter(([seekTo, nudgeTarget]) => seekTo && isFiniteNumber(seekTo.pos) && isFiniteNumber(nudgeTarget) && (seekTo.pos < nudgeTarget || seekTo.pos - nudgeTarget > config.maxSeekHole)), mapTo(null));\n          return merge(gotUserSeek$, meQuery.stallInfo$).pipe(withLatestFrom(meQuery.desiredRate$), observeOn(asyncScheduler), map(([stallInfo, desiredRate], index) => {\n              if (!stallInfo) {\n                  return NaN;\n              }\n              const bufferInfo = meQuery.getCombinedBufferInfo(stallInfo.currentTime, 0); // maxBufferHole 0\n              const iframeMode = isIframeRate(desiredRate);\n              return nudgeIfNeeded(mediaSink, config, logger, stallInfo, bufferInfo, iframeMode, index);\n          }), takeWhile((nudgeTarget) => isFiniteNumber(nudgeTarget)), finalize$1(() => {\n              logger.debug('nudge seek finalize');\n              meStore.setNudgeInfo(null);\n          }));\n      }\n      function nudgeIfNeeded(mediaSink, config, logger, stallInfo, bufferInfo, iframeMode, nudgeRetry) {\n          const { type, isLowBufferStall, currentTime } = stallInfo;\n          const bufferLen = bufferInfo.len;\n          const jumpThreshold = config.maxSeekHole;\n          let nudgePosition = NaN;\n          if (isLowBufferStall) {\n              // if buffer len is below threshold, try to jump to start of next buffer range if close\n              // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)\n              const nextBufferStart = bufferInfo.nextStart - currentTime <= jumpThreshold ? bufferInfo.nextStart : Infinity; //this._ensureNudgeStartTimeForIncompatibleCC(bufferInfo.nextStart, currentTime, config.maxSeekHole);\n              if (isFiniteNumber(nextBufferStart)) {\n                  // next buffer is close ! adjust currentTime to nextBufferStart\n                  // this will ensure effective video decoding\n                  logger.info(`adjust currentTime from ${currentTime} to next buffered @ ${nextBufferStart}`);\n                  nudgePosition = nextBufferStart;\n              }\n              else if (mediaSink.mediaQuery.msDuration - currentTime < 0.1) {\n                  nudgePosition = currentTime + 0.1;\n              }\n          }\n          else {\n              // if (this.relaxHighBufferStallRule) {\n              //   this.relaxHighBufferStallRule--;\n              //   logger.log(`ignore stall. ${this.relaxHighBufferStallRule} free pass available. staying put @ ${media.currentTime}`);\n              //   payload = new BufferStallError(ErrorDetails.BUFFER_STALLED_ERROR, false,\n              //     'got buffer stalled error', ErrorResponses.VideoDecoderBadDataErr, type, bufferLen);\n              // } else\n              if (nudgeRetry < config.nudgeMaxRetry) {\n                  // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n                  nudgePosition = currentTime + config.nudgeOffset;\n              }\n              else if (iframeMode) {\n                  // maxed number of nudges - but in iframeMode\n                  logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, non fatal in iframeMode`);\n              }\n              else {\n                  logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n                  throw new BufferStallError(ErrorDetails.BUFFER_STALLED_ERROR, true, 'got fatal buffer error', ErrorResponses.VideoDecoderBadDataErr, type, bufferLen);\n              }\n          }\n          if (isFiniteNumber(nudgePosition)) {\n              logger.info(`stall ${type} nudge ${currentTime}->${nudgePosition} nudgeRetry=${nudgeRetry}`);\n              mediaSink.nudgeSeek(nudgePosition, nudgeRetry + 1);\n          }\n          return nudgePosition;\n      }\n    \n      /**\n       * @brief Service that manages playback state\n       */\n      // state for the service functions\n      const mediaElementStore = new MediaElementStore();\n      /**\n       * media component managment\n       */\n      const mediaElementServiceEpic = (makeMediaSource, config, gaplessInstance, logger, teardownWG$, rtcService) => (mediaElementSource$) => {\n          return mediaElementSource$.pipe(tag('playback.mediaElementServiceEpic.in'), switchMap((mediaElement) => {\n              if (!mediaElement) {\n                  return of(null);\n              }\n              const mediaSink = new MediaSink(mediaElement, mediaElementStore, config, gaplessInstance, logger, teardownWG$, rtcService);\n              mediaSink.openMediaSource(makeMediaSource());\n              return merge(of(mediaSink), mediaSink);\n          }), tag('playback.mediaElementServiceEpic.emit'));\n      };\n    \n      const displaySupportsHdr$ = () => {\n          if (typeof matchMedia === 'function') {\n              const mediaQueryList = matchMedia('(dynamic-range: high)');\n              const badQuery = matchMedia('bad query');\n              if (mediaQueryList.media !== badQuery.media) {\n                  return merge(of(mediaQueryList), fromEvent(mediaQueryList, 'change')).pipe(map((e) => e.matches));\n              }\n          }\n          // assume hdr is supported by display\n          return of(true);\n      };\n    \n      class PlatformQuery extends Query {\n          constructor(store) {\n              super(store);\n              this.store = store;\n              this.displaySupportsHdr$ = this.select('supportsHdr');\n              this.platformInfo$ = this.select('platformInfo');\n              this.viewportInfo$ = this.select('viewportInfo');\n          }\n          get platformInfo() {\n              return this.getValue().platformInfo;\n          }\n          get displaySupportsHdr() {\n              return this.getValue().supportsHdr;\n          }\n          get viewportInfo() {\n              return this.getValue().viewportInfo;\n          }\n      }\n    \n      function createInitialState() {\n          return { supportsHdr: true };\n      }\n      class PlatformStore extends Store {\n          constructor() {\n              super(createInitialState(), { name: 'platform', producerFn: produce_1 });\n          }\n      }\n    \n      class PlatformService {\n          constructor(store) {\n              this.store = store;\n          }\n          getQuery() {\n              return new PlatformQuery(this.store);\n          }\n          updateSupportsHdr(supported) {\n              this.store.update((state) => {\n                  state.supportsHdr = supported;\n              });\n          }\n          updatePlatformInfo(platformInfo) {\n              this.store.update({ platformInfo });\n          }\n          updateViewportInfo(viewportInfo) {\n              this.store.update((state) => {\n                  state.viewportInfo = viewportInfo;\n              });\n          }\n      }\n      const store = new PlatformStore();\n      let service$1 = null; // To be instantiated in platformService();\n      /***********************************************\n       * Static helper functions that specifically use the above singletons\n       */\n      function createPlatformQuery() {\n          return new PlatformQuery(store);\n      }\n      /**\n       * @returns The global instance of PlatformService that operates on global PlatformStore\n       */\n      function platformService() {\n          if (!service$1) {\n              service$1 = new PlatformService(store);\n          }\n          return service$1;\n      }\n      function listenForHdrUpdates(platformService) {\n          return displaySupportsHdr$().pipe(tap((supported) => {\n              platformService.updateSupportsHdr(supported);\n          }));\n      }\n    \n      // The vanilla RPCService uses old-school callback pattern to minimize the\n      // dependency surface in restricted environments, e.g. in Web Worker.\n      // However, if resource permitted, one can use this RPCServiceObservable wrapper\n      // to convert RPCService interface into Observable pattern for better\n      // interoperability with RxJs code.\n      class RPCServiceObservable extends Observable {\n          constructor(_vanillaRPC, teardownWG$) {\n              super(subscriber => {\n                  teardownWG$ === null || teardownWG$ === void 0 ? void 0 : teardownWG$.add();\n                  subscriber.add(this._handler$\n                      .pipe(mergeMap(([handler, args, callback]) => handler(...args).pipe(tap({\n                      next(result) {\n                          callback(result, null);\n                      },\n                      error(error) {\n                          callback(null, error);\n                      },\n                  }))))\n                      .subscribe());\n              });\n              this._vanillaRPC = _vanillaRPC;\n              this.teardownWG$ = teardownWG$;\n              this._handler$ = new Subject();\n          }\n          register(command, handler) {\n              const asyncHandler = (...args) => (callback) => {\n                  this._handler$.next([handler, args, callback]);\n              };\n              return this._vanillaRPC.register(command, asyncHandler);\n          }\n          invoke(command, args, transfer) {\n              return new Observable((subscriber) => {\n                  this._vanillaRPC.invoke(command, args, transfer)((result, error) => {\n                      if (error != null) {\n                          subscriber.error(error);\n                      }\n                      else {\n                          subscriber.next(result);\n                          subscriber.complete();\n                      }\n                  });\n              });\n          }\n      }\n    \n      // CryptoRPCClient only runs in main process, so I has more resources to include\n      // the RxJS as dependency and use the Observable pattern. So we can extend on\n      // RPCServiceObservable instead of the vanilla RPCService class.\n      class CryptoRPCClient extends RPCServiceObservable {\n          constructor(rpcService) {\n              super(rpcService);\n          }\n          decrypt(key, iv, alg, cipherText, options) {\n              return this.invoke('decrypt', [key, iv, alg, cipherText, options], [key, iv, cipherText]);\n          }\n      }\n    \n      class DemuxRPCClient extends RPCServiceObservable {\n          constructor(rpcService) {\n              super(rpcService);\n              this.rpcService = rpcService;\n              this.sessions = {};\n              this._onEvent = (demuxSessionID, event, data) => () => {\n                  if (this.sessions[demuxSessionID] != null) {\n                      this.sessions[demuxSessionID].observer.trigger(event, data);\n                  }\n              };\n              this.rpcService.register('demuxer.event', this._onEvent);\n          }\n          init(typeSupported, config, vendor) {\n              config = (({ maxSeekHole, maxBufferHole, audioPrimingDelay, stretchShortVideoTrack, forceKeyFrameOnDiscontinuity }) => ({\n                  maxSeekHole,\n                  maxBufferHole,\n                  audioPrimingDelay,\n                  stretchShortVideoTrack,\n                  forceKeyFrameOnDiscontinuity,\n              }))(config);\n              return this.invoke('demuxer.init', [typeSupported, config, vendor], []).pipe(map((demuxSessionID) => {\n                  const session = new DemuxRPCSession(this, demuxSessionID);\n                  this.sessions[demuxSessionID] = session;\n                  return session;\n              }));\n          }\n      }\n      class DemuxRPCSession {\n          constructor(rpc, demuxSessionID) {\n              this.rpc = rpc;\n              this.demuxSessionID = demuxSessionID;\n              this.observer = new Observer();\n          }\n          push(data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration, transfer) {\n              return this.rpc.invoke('demuxer.push', [this.demuxSessionID, data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration], transfer !== null && transfer !== void 0 ? transfer : [data]);\n          }\n          pushWithoutTransfer(data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration) {\n              return this.push(data, keyTagInfo, initSegment, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS, iframeMediaStart, iframeDuration, []);\n          }\n          destroy() {\n              this.observer.removeAllListeners();\n              this.rpc.invoke('demuxer.destroy', [this.demuxSessionID], []).subscribe();\n          }\n      }\n    \n      const createRPCClients = (rpcService) => ({\n          crypto: new CryptoRPCClient(rpcService),\n          mux: new DemuxRPCClient(rpcService),\n      });\n    \n      const LoggerRPCServer = (rpcService, logger) => {\n          rpcService.register('logger.log', (bindings, level, ...args) => (callback) => {\n              try {\n                  for (const b of bindings) {\n                      logger = logger.child(b);\n                  }\n                  if (typeof logger[level] === 'function') {\n                      // eslint-disable-next-line @typescript-eslint/ban-types\n                      logger[level](...args);\n                  }\n                  callback();\n              }\n              catch (err) {\n                  callback(undefined, err);\n              }\n          });\n      };\n    \n      // Inline service treat the client and server running in the same process, and\n      // just forward messages directly by function calls.\n      class RPCInlineService {\n          constructor() {\n              this.handlers = {};\n          }\n          register(command, handler) {\n              if (this.handlers[command] != null) {\n                  return false;\n              }\n              this.handlers[command] = handler;\n          }\n          unregister(command) {\n              if (this.handlers[command] != null) {\n                  return false;\n              }\n              delete this.handlers[command];\n          }\n          invoke(command, args) {\n              return (callback = RPCInlineService._fallbackCallback) => {\n                  try {\n                      if (this.handlers[command] == null) {\n                          throw new Error(`command ${command} not found`);\n                      }\n                      this.handlers[command](...args)(callback);\n                  }\n                  catch (error) {\n                      callback(undefined, error);\n                  }\n              };\n          }\n          teardown(done) {\n              this.handlers = null;\n              done();\n          }\n      }\n      RPCInlineService._fallbackCallback = (result, error) => {\n          if (error != null) {\n              throw error;\n          }\n      };\n    \n      const createRPCInlineService = (logger) => {\n          logger = logger.child({ name: 'InlineRPCService' });\n          const rpcService = new RPCInlineService();\n          new CryptoRPCServer(rpcService, logger);\n          new DemuxRPCServer(rpcService, logger);\n          logger.info('Inline RPCService has started');\n          return rpcService;\n      };\n      let worker;\n      const createRPCWorkerService = (logger) => {\n          if (!hasUMDWorker()) {\n              throw new Error('UMD WebWorker is not bundled in this file');\n          }\n          try {\n              if (worker == null) {\n                  const blob = new Blob(['var exports = {};var module = { exports: exports };function define(f){f()};define.amd = true;(' + __HLS_UMD_BUNDLE__.toString() + ')(true);'], {\n                      type: 'text/javascript',\n                  });\n                  const workerUrl = URL.createObjectURL(blob);\n                  worker = new Worker(workerUrl);\n              }\n              const rpcService = new RPCWorkerService(worker);\n              LoggerRPCServer(rpcService, logger.child({ name: 'WorkerRPCService' }));\n              return rpcService;\n          }\n          catch (err) {\n              throw new Error('Failed to create WebWorker');\n          }\n      };\n      const createRPCServiceWithFallbacks = (...fallbacks) => (logger) => {\n          for (let i = 0; i < fallbacks.length; i++) {\n              const create = fallbacks[i];\n              try {\n                  return create(logger);\n              }\n              catch (err) {\n                  if (i === fallbacks.length - 1) {\n                      throw err;\n                  }\n                  logger.warn(err);\n              }\n          }\n      };\n      const createRPCService = (logger) => {\n          return createRPCServiceWithFallbacks(createRPCWorkerService, createRPCInlineService)(logger);\n      };\n    \n      /*\n       * RTC types\n       *\n       * \n       */\n      /*\n       * Events that RTC sends out to the backend.\n       * https://confluence.sd.apple.com/display/ISM/Matchpoint+Event-Key+List\n       */\n      class RTCEventGroup {\n      }\n      RTCEventGroup.PlayEnded = 6101;\n      RTCEventGroup.Periodic = 6110;\n      RTCEventGroup.PlayStalled = 6103;\n      RTCEventGroup.KeySessionComplete = 6104;\n      RTCEventGroup.PlayLikelyToKeepUp = 6105;\n      RTCEventGroup.PlayRateChanged = 6106;\n      RTCEventGroup.PlayError = 6107;\n      RTCEventGroup.MediaEngineStalled = 6108;\n      RTCEventGroup.SwitchComplete = 6109;\n      RTCEventGroup.VariantEnded = 6111;\n      RTCEventGroup.NwError = 6202;\n      const RTCVideoQualityIndex = {\n          avc1: 1,\n          avc3: 1,\n          hvc1: { SDR: 2, HLG: 10, PQ: 11 },\n          hev1: { SDR: 2, HLG: 10, PQ: 11 },\n          vp09: { SDR: 3, HLG: 14, PQ: 13 },\n          dvh1: { PQ: 12 },\n      };\n    \n      const loggerName$5 = { name: 'rtc-component' };\n      class RTCComponent {\n          constructor(query, logger) {\n              this.query = query;\n              this.logger = logger;\n          }\n          setReportingAgent(reportingAgent) {\n              this.reportingAgent = reportingAgent;\n          }\n          sendPlayEnded(id) {\n              this.logger.debug(loggerName$5, `sendPlayEnded id=${id}`);\n              const method = RTCEventGroup.PlayEnded;\n              this.fillAndFire(method, this.query.playEnded(id));\n          }\n          sendPlayStalled(id) {\n              const method = RTCEventGroup.PlayStalled;\n              this.fillAndFire(method, this.query.playStalled(id));\n          }\n          sendMediaEngineStalled(id) {\n              const method = RTCEventGroup.MediaEngineStalled;\n              this.fillAndFire(method, this.query.mediaEngineStalled(id));\n          }\n          sendKeySessionComplete(id) {\n              const method = RTCEventGroup.KeySessionComplete;\n              this.fillAndFire(method, this.query.keySessionComplete(id));\n          }\n          sendPlayLikelyToKeepUp(id) {\n              const method = RTCEventGroup.PlayLikelyToKeepUp;\n              this.fillAndFire(method, this.query.playLikelyToKeepUp(id));\n          }\n          sendPlayRateChange(id) {\n              this.logger.debug(loggerName$5, `sendPlayRateChange id=${id}`);\n              const method = RTCEventGroup.PlayRateChanged;\n              this.fillAndFire(method, this.query.playRateChanged(id));\n          }\n          sendSwitchComplete(id) {\n              const method = RTCEventGroup.SwitchComplete;\n              this.fillAndFire(method, this.query.switchComplete(id));\n          }\n          sendVariantEnded(id) {\n              const method = RTCEventGroup.VariantEnded;\n              this.fillAndFire(method, this.query.variantEnded(id));\n          }\n          sendPlayError(id) {\n              const method = RTCEventGroup.PlayError;\n              this.fillAndFire(method, this.query.playError(id));\n          }\n          sendNwError(id) {\n              const method = RTCEventGroup.NwError;\n              this.fillAndFire(method, this.query.nwError(id));\n          }\n          sendPeriodic(id) {\n              const method = RTCEventGroup.Periodic;\n              this.fillAndFire(method, this.query.periodic(id));\n          }\n          fillAndFire(method, record) {\n              this.logger.debug(loggerName$5, 'RTC fillAndFire');\n              // don't send periodic event if there is no playtime or active fragment download time\n              if (method === RTCEventGroup.Periodic && !record.PlayTimeWC && !record.ADT) {\n                  this.logger.info(loggerName$5, `RTC Method: ${method}, Skipping due to no playback/download activity`);\n                  return;\n              }\n              const type = method === RTCEventGroup.PlayEnded || method === RTCEventGroup.Periodic ? 1 : 0;\n              this.logger.info(loggerName$5, `RTC Method: ${method}, Type:${type}`);\n              if (this.reportingAgent) {\n                  this.logger.debug(loggerName$5, 'Reporting Agent is set!');\n                  let eventPayload = {};\n                  Object.entries(record).forEach(([key, value]) => {\n                      // round all numeric values to two decimal points\n                      if (isFiniteNumber(value)) {\n                          value = Number(Number(value).toFixed(2));\n                      }\n                      // Extract keys from ServerInfo and populate the event payload; no other object types allowed. Ref: privacyAllowedLoadConfigHeaders\n                      if (typeof value === 'object') {\n                          if (key === 'ServerInfo') {\n                              Object.entries(value).forEach(([k, v]) => {\n                                  eventPayload[k] = v;\n                              });\n                          }\n                          else {\n                              this.logger.debug(loggerName$5, `Object type unsupported for key: ${key}`);\n                          }\n                      }\n                      else {\n                          eventPayload[key] = value;\n                      }\n                  });\n                  this.logger.debug(loggerName$5, 'RTC Method: %s, payload=%o', method, eventPayload);\n                  // copy record into extensible payload\n                  eventPayload = JSON.parse(JSON.stringify(eventPayload));\n                  try {\n                      this.reportingAgent.issueReportingEvent(method, eventPayload, type);\n                  }\n                  catch (err) {\n                      this.logger.info(loggerName$5, 'Cannot report, reportingAgent failed');\n                  }\n              }\n          }\n      }\n    \n      class RTCQuery extends QueryEntity {\n          constructor(rtcStore, logger) {\n              super(rtcStore);\n              this.logger = logger;\n          }\n          // generic getters\n          get activeEntity() {\n              return this.getActive();\n          }\n          entity(id) {\n              return this.getEntity(id);\n          }\n          playEnded(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.playEndedRecord;\n          }\n          periodic(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.periodicRecord;\n          }\n          playStalled(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.playStalledRecord;\n          }\n          mediaEngineStalled(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.mediaEngineStalledRecord;\n          }\n          keySessionComplete(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.keySessionCompleteRecord;\n          }\n          playLikelyToKeepUp(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.playLikelyToKeepUpRecord;\n          }\n          playRateChanged(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.playRateChangedRecord;\n          }\n          switchComplete(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.switchCompleteRecord;\n          }\n          variantEnded(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.variantEndedRecord;\n          }\n          playError(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.playErrorRecord;\n          }\n          nwError(id) {\n              var _a;\n              return (_a = this.getEntity(id)) === null || _a === void 0 ? void 0 : _a.nwErrorRecord;\n          }\n      }\n    \n      class RTCStore extends EntityStore {\n          constructor(logger) {\n              super({}, { name: 'rtc-store', idKey: 'itemId', producerFn: produce_1, resettable: true });\n              this.logger = logger;\n          }\n          /*\n           * Create an RTC Entity with the necessary records\n           */\n          createEntity(itemId) {\n              const rtcEntity = {\n                  itemId,\n                  sessionControlRecord: {\n                      state: 'RTC_STATE_INIT',\n                      rate: 0,\n                      oldRate: 0,\n                      eventStartTime: Date.now(),\n                      sessionStartTime: Date.now(),\n                      lastLikelyToKeepUpTime: Date.now(),\n                      lastPeriodicTime: Date.now(),\n                      playLikelyToKeepUpEventCounter: 1,\n                      periodicEventCounter: 1,\n                      activeKeySessions: {},\n                      intervalVariantList: {},\n                      sessionVariantList: {},\n                  },\n                  playEndedRecord: {},\n                  periodicRecord: {},\n                  playStalledRecord: {},\n                  keySessionCompleteRecord: {},\n                  playLikelyToKeepUpRecord: {},\n                  playRateChangedRecord: {},\n                  playErrorRecord: {},\n                  mediaEngineStalledRecord: {},\n                  switchCompleteRecord: {},\n                  variantEndedRecord: {},\n                  nwErrorRecord: {},\n              };\n              this.add(rtcEntity);\n          }\n          /*\n           * The below updates require an RTC event to be sent out, and hence an event payload needs to be prepared.\n           *    => PlayEnded (6101)\n           *    => Periodic (6110)\n           *    => PlayStalled (6103)\n           *    => KeySessionComplete (6104)\n           *    => PlayLikelyToKeepUp (6105)\n           *    => PlayRateChanged (6106)\n           *    => PlayError (6107)\n           *    => MediaEngineStalled (6108)\n           *    => SwitchComplete (6109)\n           *    => VariantEnded (6111)\n           *    => NwError (6202)\n           */\n          /* Indicates playback ended */\n          updateEnded(itemId) {\n              this._prepareEventPlayEnded(itemId);\n          }\n          /* Indicates periodic timer fired */\n          updatePeriodic(itemId, isFinal) {\n              this._prepareEventPeriodic(itemId, { isFinal });\n          }\n          /* Indicates playback stall due to bad network */\n          updateBufferStalled(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, variantEndedRecord, periodicRecord, playEndedRecord }) => {\n                  sessionControlRecord.rate = 0;\n                  variantEndedRecord.StallCount = (variantEndedRecord.StallCount || 0) + 1;\n                  periodicRecord.StallCount = (periodicRecord.StallCount || 0) + 1;\n                  playEndedRecord.StallCount = (playEndedRecord.StallCount || 0) + 1;\n              });\n              this._prepareEventPlayStalled(itemId, data);\n          }\n          /* Indicates identity key session success / failure */\n          updateSegmentKeyLoaded(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = {};\n                  const now = data.timestamp;\n                  keySessionInfo.keyFormat = 'identity';\n                  keySessionInfo.keyDeliveryTime = data.adt;\n                  keySessionInfo.currentMediaTime = data.currentTime;\n                  if (sessionControlRecord.state === 'RTC_STATE_INIT') {\n                      keySessionInfo.keyInitTime = now - sessionControlRecord.sessionStartTime;\n                  }\n                  sessionControlRecord.activeKeySessions[data.keyuri] = keySessionInfo;\n              });\n              this._prepareEventKeySessionComplete(itemId, data);\n          }\n          /* Indicates non-identity (FPS/Widevine/PlayReady) key session success / failure events */\n          updateLicenseResponseProcessed(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.licenseResponseProcessTime = data.timestamp - keySessionInfo.licenseResponseSubmitTime;\n                  sessionControlRecord.lastKeyDeliveryTime = keySessionInfo.keyDeliveryTime = data.timestamp - keySessionInfo.licenseChallengeStartTime;\n                  keySessionInfo.currentMediaTime = data.currentTime;\n                  sessionControlRecord.finishedKeyUri = data.keyuri;\n              });\n              this._prepareEventKeySessionComplete(itemId, data);\n          }\n          updateLicenseChallengeError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  sessionControlRecord.lastKeyErrorType = keySessionInfo.keyErrorType = 'licenseChallengeError';\n                  sessionControlRecord.finishedKeyUri = data.keyuri;\n              });\n              this._prepareEventKeySessionComplete(itemId, data);\n          }\n          updateLicenseResponseError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  sessionControlRecord.lastKeyErrorType = keySessionInfo.keyErrorType = 'licenseResponseError';\n                  sessionControlRecord.finishedKeyUri = data.keyuri;\n              });\n              this._prepareEventKeySessionComplete(itemId, data);\n          }\n          updateKeyAborted(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.keyErrorType = 'keyAborted';\n                  sessionControlRecord.finishedKeyUri = data.keyuri;\n              });\n              this._prepareEventKeySessionComplete(itemId, data);\n          }\n          /* Indicates likely to keep up */\n          updateCanPlay(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  // if (sessionControlRecord.state === 'RTC_STATE_PLAY') {\n                  //   /* Ignore if we're already in PLAY */\n                  //   return;\n                  // }\n              });\n              this._prepareEventPlayLikelyToKeepUp(itemId, data);\n          }\n          /* Indicates rate changed */\n          updateRateChanged(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  sessionControlRecord.rate = data.rate * 100;\n                  if (data.rate > 0 && sessionControlRecord.oldRate === 0) {\n                      if (!sessionControlRecord.playInfo) {\n                          sessionControlRecord.playInfo = [];\n                      }\n                      sessionControlRecord.playInfo.push({ latency: data.latency });\n                      // if curLevelUrl is not set at this point, we are in a scenario where the play event beats the levelSwitched event in a race\n                      // conditon. To avoid a crash, set the curLevelUrl here.\n                      if (!sessionControlRecord.curLevelUrl) {\n                          sessionControlRecord.curLevelUrl = data.url;\n                      }\n                  }\n              });\n              this._prepareEventPlayRateChanged(itemId, data);\n          }\n          /* Indicates play error */\n          updateMediaError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, periodicRecord, playEndedRecord }) => {\n                  periodicRecord.PlayerErrCount = (periodicRecord.PlayerErrCount || 0) + 1;\n                  playEndedRecord.PlayerErrCount = (playEndedRecord.PlayerErrCount || 0) + 1;\n                  if (data.fatal) {\n                      sessionControlRecord.rate = 0;\n                      periodicRecord.FatalPlayerErrCount = (periodicRecord.FatalPlayerErrCount || 0) + 1;\n                      playEndedRecord.FatalPlayerErrCount = (playEndedRecord.FatalPlayerErrCount || 0) + 1;\n                      playEndedRecord.ErrCode = data.details;\n                      playEndedRecord.ErrReason = data.code;\n                      playEndedRecord.ErrIsFatal = true;\n                      playEndedRecord.ErrDomain = 'mediaError';\n                  }\n              });\n              if (data.fatal) {\n                  this._prepareEventPlayError(itemId, data);\n              }\n              else {\n                  this.update(itemId, ({ sessionControlRecord }) => {\n                      // Non-fatal errors won't be sent immediately for each occurrence. Instead, they will be sent before the periodic event with the count of occurrences.\n                      // We send separate events if the error code and reason are different. For e.g. fragLoadError due to 403 and fragLoadError due to 404 are counted separately.\n                      const key = data.details + '/' + data.code;\n                      sessionControlRecord.nonFatalPlayErrList[key] = (sessionControlRecord.nonFatalPlayErrList[key] || 0) + 1;\n                  });\n              }\n          }\n          /* Indicates media element error */\n          updateMediaElementError(itemId, data) {\n              /*\n                  Parse the media element error message. Luna encodes ErrReason & ErrDetail as follows.\n                  \"message\": '{\n                    \"ErrReason\": -5001, // Luna error code\n                    \"ErrDetail\": \"0xce0defba\" // Third party error code\n                  }'\n          \n                  Note: mediaElementError is not inserted into the 6101 payload.\n              */\n              let errJson;\n              try {\n                  errJson = JSON.parse(data.message);\n              }\n              catch (error) {\n                  this.logger.warn(`message is not JSON, ignoring; ${data.message}`);\n              }\n              const mediaElemReason = errJson ? parseInt(errJson['ErrReason']) : null;\n              const mediaElemDetail = errJson ? parseInt(errJson['ErrDetail']) : null;\n              this._prepareEventPlayError(itemId, {\n                  domain: 'mediaElementError',\n                  mediaElemCode: data.code,\n                  mediaElemReason: mediaElemReason,\n                  mediaElemDetail: mediaElemDetail,\n                  // These are fixed values for mediaElementError and set in _prepareEventPlayError\n                  code: null,\n                  details: null,\n                  fatal: null,\n              });\n          }\n          /* Indicates plaback stall due to media engine problem */\n          updateMediaEngineStalled(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, variantEndedRecord, periodicRecord, playEndedRecord }) => {\n                  sessionControlRecord.rate = 0;\n                  variantEndedRecord.MediaEngineStallCount = (variantEndedRecord.MediaEngineStallCount || 0) + 1;\n                  periodicRecord.MediaEngineStallCount = (periodicRecord.MediaEngineStallCount || 0) + 1;\n                  playEndedRecord.MediaEngineStallCount = (playEndedRecord.MediaEngineStallCount || 0) + 1;\n              });\n              this._prepareEventMediaEngineStalled(itemId, data);\n          }\n          /* Indicates level switch complete */\n          updateLevelSwitched(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, switchCompleteRecord, periodicRecord, playEndedRecord }) => {\n                  periodicRecord.SwCnt = (periodicRecord.SwCnt || 0) + 1;\n                  playEndedRecord.SwCnt = (playEndedRecord.SwCnt || 0) + 1;\n                  const now = Date.now();\n                  const prevLevelUrl = sessionControlRecord.curLevelUrl;\n                  const curLevelUrl = data.url;\n                  const prevVarInfo = this._getVariantInfo(prevLevelUrl, sessionControlRecord);\n                  const curVarInfo = this._getVariantInfo(curLevelUrl, sessionControlRecord);\n                  let curSwDir;\n                  let iframes = false;\n                  if (prevLevelUrl) {\n                      if (curVarInfo.bandwidth < prevVarInfo.bandwidth) {\n                          curSwDir = 'Down';\n                      }\n                      else {\n                          curSwDir = 'Up';\n                      }\n                      iframes = curVarInfo.iframes;\n                  }\n                  switchCompleteRecord.BadSw = this._isBadSw(curSwDir, sessionControlRecord.lastSwitchDir || curSwDir, iframes, sessionControlRecord.lastLevelIsIframe || iframes, now, sessionControlRecord.lastSwitchTime || now, data.isSeeking);\n                  sessionControlRecord.lastSwitchDir = curSwDir;\n                  sessionControlRecord.lastSwitchTime = now;\n                  sessionControlRecord.lastLevelIsIframe = iframes;\n                  sessionControlRecord.curLevelUrl = curLevelUrl;\n                  sessionControlRecord.variantStartTimeMedia = data.currentTime;\n              });\n              this._prepareEventSwitchComplete(itemId, data);\n          }\n          /* Indicates level switch error */\n          updateLevelLoadError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, switchCompleteRecord, periodicRecord, playEndedRecord }) => {\n                  const now = Date.now();\n                  let curSwDir;\n                  let iframes = false;\n                  if (sessionControlRecord.curLevelUrl) {\n                      const prevVarInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                      const curVarInfo = this._getVariantInfo(data.url, sessionControlRecord);\n                      if (curVarInfo.bandwidth < prevVarInfo.bandwidth) {\n                          curSwDir = 'Down';\n                      }\n                      else {\n                          curSwDir = 'Up';\n                      }\n                      iframes = curVarInfo.iframes;\n                  }\n                  periodicRecord.SwCnt = (periodicRecord.SwCnt || 0) + 1;\n                  playEndedRecord.SwCnt = (playEndedRecord.SwCnt || 0) + 1;\n                  switchCompleteRecord.BadSw = this._isBadSw(curSwDir, sessionControlRecord.lastSwitchDir || curSwDir, iframes, sessionControlRecord.lastLevelIsIframe || iframes, now, sessionControlRecord.lastSwitchTime || now, data.isSeeking);\n                  switchCompleteRecord.SwFail = true;\n              });\n              this._prepareEventSwitchComplete(itemId, data);\n          }\n          /* Indicates variant end */\n          updateVariantEnd(itemId, data) {\n              this._prepareEventVariantEnded(itemId, data);\n          }\n          /* Indicates network error */\n          updateNwError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, periodicRecord, playEndedRecord }) => {\n                  periodicRecord.NwErrCount = (periodicRecord.NwErrCount || 0) + 1;\n                  playEndedRecord.NwErrCount = (playEndedRecord.NwErrCount || 0) + 1;\n                  if (data.fatal) {\n                      sessionControlRecord.rate = 0;\n                      periodicRecord.FatalNwErrCount = (periodicRecord.FatalNwErrCount || 0) + 1;\n                      playEndedRecord.FatalNwErrCount = (playEndedRecord.FatalNwErrCount || 0) + 1;\n                      playEndedRecord.ErrCode = data.details;\n                      playEndedRecord.ErrReason = data.code;\n                      playEndedRecord.ErrIsFatal = true;\n                      playEndedRecord.ErrDomain = 'networkError';\n                  }\n              });\n              if (data.fatal) {\n                  this._prepareEventNwError(itemId, data);\n              }\n              else {\n                  this.update(itemId, ({ sessionControlRecord }) => {\n                      // Non-fatal errors won't be sent immediately for each occurrence. Instead, they will be sent before the periodic event with the count of occurrences.\n                      // We send separate events if the error code and reason are different. For e.g. fragLoadError due to 403 and fragLoadError due to 404 are counted separately.\n                      const key = data.details + '/' + data.code;\n                      sessionControlRecord.nonFatalNwErrList[key] = (sessionControlRecord.nonFatalNwErrList[key] || 0) + 1;\n                  });\n              }\n          }\n          /*\n           * The below method is called after an event is sent out, to update the internal states.\n           */\n          finalize(itemId, event) {\n              switch (event) {\n                  case RTCEventGroup.PlayEnded: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.state = 'RTC_STATE_STOP';\n                          sessionControlRecord.oldRate = 0;\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.playEndedRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.Periodic: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.lastPeriodicTime = Date.now();\n                          sessionControlRecord.periodicEventCounter += 1;\n                          /* Re-initialize playtime for all levels */\n                          const levels = Object.keys(sessionControlRecord.intervalVariantList);\n                          levels.forEach((level) => {\n                              sessionControlRecord.intervalVariantList[level].playTime = 0;\n                          });\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.periodicRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.PlayStalled: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.state = 'RTC_STATE_STALL';\n                          sessionControlRecord.oldRate = 0;\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.playStalledRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.KeySessionComplete: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          delete sessionControlRecord.activeKeySessions[sessionControlRecord.finishedKeyUri];\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.keySessionCompleteRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.PlayLikelyToKeepUp: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          if (sessionControlRecord.state !== 'RTC_STATE_PLAY') {\n                              /* Ignore if we're already in PLAY */\n                              sessionControlRecord.state = 'RTC_STATE_CANPLAY';\n                              sessionControlRecord.lastLikelyToKeepUpTime = Date.now();\n                              sessionControlRecord.playLikelyToKeepUpEventCounter += 1;\n                          }\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.playLikelyToKeepUpRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.PlayRateChanged: {\n                      this.update(itemId, ({ sessionControlRecord, playEndedRecord, playStalledRecord, mediaEngineStalledRecord, playErrorRecord, nwErrorRecord }) => {\n                          if (sessionControlRecord.rate !== 0) {\n                              sessionControlRecord.state = 'RTC_STATE_PLAY';\n                              // reset the below keys as we resume playback\n                              delete playEndedRecord.LastStall;\n                              delete playEndedRecord.LastMediaEngineStall;\n                              delete playEndedRecord.LastPause;\n                              delete playErrorRecord.LastPause;\n                              delete nwErrorRecord.LastPause;\n                          }\n                          else {\n                              sessionControlRecord.state = 'RTC_STATE_PAUSE';\n                              // reset the below keys as we pause playback\n                              delete playStalledRecord.LastResume;\n                              delete mediaEngineStalledRecord.LastResume;\n                              delete playErrorRecord.LastResume;\n                              delete nwErrorRecord.LastResume;\n                          }\n                          /* Update the old rate */\n                          sessionControlRecord.oldRate = sessionControlRecord.rate;\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.playRateChangedRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.PlayError: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.state = 'RTC_STATE_PLAYERROR';\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.playErrorRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.MediaEngineStalled: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.state = 'RTC_STATE_MEDIAENGINESTALL';\n                          sessionControlRecord.oldRate = 0;\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.mediaEngineStalledRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.SwitchComplete: {\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.switchCompleteRecord = {};\n                          // record the level transition\n                          state.sessionControlRecord.prevLevelUrl = state.sessionControlRecord.curLevelUrl;\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.VariantEnded: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.decodedFramesForVariant = 0;\n                          sessionControlRecord.decodedFramesForVariantSampleCount = 0;\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.variantEndedRecord = {};\n                      });\n                      break;\n                  }\n                  case RTCEventGroup.NwError: {\n                      this.update(itemId, ({ sessionControlRecord }) => {\n                          sessionControlRecord.state = 'RTC_STATE_NWERROR';\n                      });\n                      /* Reset the event record */\n                      this.update(itemId, (state) => {\n                          state.nwErrorRecord = {};\n                      });\n                      break;\n                  }\n              }\n              /* Finally, reset the event clock */\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  sessionControlRecord.eventStartTime = Date.now();\n              });\n          }\n          /*\n           * The below updates don't involve an RTC event to be sent out.\n           * These updates just aggregate data in the store for various RTC records.\n           */\n          updatePlaybackInfo(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, periodicRecord, playEndedRecord }) => {\n                  if (data.droppedVideoFrames < sessionControlRecord.droppedVideoFrames) {\n                      // MSE counter reset, so reset ours too\n                      sessionControlRecord.droppedVideoFrames = 0;\n                  }\n                  if (data.decodedFrameCount < sessionControlRecord.decodedFrameCount) {\n                      // MSE counter reset, so reset ours too\n                      sessionControlRecord.decodedFrameCount = 0;\n                  }\n                  // we get the dropped frames and decoded frames from the MSE object every second. Calculate the current frame drop and frame rate.\n                  const curFrameDrop = data.droppedVideoFrames - (sessionControlRecord.droppedVideoFrames || 0);\n                  const decodedFramesPerSec = data.decodedFrameCount - (sessionControlRecord.decodedFrameCount || 0);\n                  sessionControlRecord.droppedVideoFrames = data.droppedVideoFrames;\n                  sessionControlRecord.decodedFrameCount = data.decodedFrameCount;\n                  // update the decode frames for the current variant to compute average decode frame count for the variant\n                  sessionControlRecord.decodedFramesForVariant += decodedFramesPerSec;\n                  sessionControlRecord.decodedFramesForVariantSampleCount += 1;\n                  if (curFrameDrop) {\n                      // if we drop 3 or more frames per second, then that's a group frame drop.\n                      if (curFrameDrop >= 3) {\n                          periodicRecord.GroupViFrDr = (periodicRecord.GroupViFrDr || 0) + curFrameDrop;\n                          periodicRecord.GroupViFrDrEvtCount = (periodicRecord.GroupViFrDrEvtCount || 0) + 1;\n                          playEndedRecord.GroupViFrDr = (playEndedRecord.GroupViFrDr || 0) + curFrameDrop;\n                          playEndedRecord.GroupViFrDrEvtCount = (playEndedRecord.GroupViFrDrEvtCount || 0) + 1;\n                      }\n                      else {\n                          periodicRecord.SparseViFrDr = (periodicRecord.SparseViFrDr || 0) + curFrameDrop;\n                          periodicRecord.SparseViFrDrEvtCount = (periodicRecord.SparseViFrDrEvtCount || 0) + 1;\n                          playEndedRecord.SparseViFrDr = (playEndedRecord.SparseViFrDr || 0) + curFrameDrop;\n                          playEndedRecord.SparseViFrDrEvtCount = (playEndedRecord.SparseViFrDrEvtCount || 0) + 1;\n                      }\n                  }\n              });\n          }\n          updateBufferAppended(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  if (!sessionControlRecord.bufferAppendInfo) {\n                      sessionControlRecord.bufferAppendInfo = [];\n                  }\n                  sessionControlRecord.bufferAppendInfo.push(data);\n              });\n          }\n          updateSeeked(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  if (!sessionControlRecord.seekInfo) {\n                      sessionControlRecord.seekInfo = [];\n                  }\n                  sessionControlRecord.seekInfo.push(data);\n              });\n          }\n          updateManifestParsed(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, periodicRecord, playEndedRecord }) => {\n                  periodicRecord.MasterPlaylistADT = (periodicRecord.MasterPlaylistADT || 0) + data.adt;\n                  playEndedRecord.MasterPlaylistADT = (playEndedRecord.MasterPlaylistADT || 0) + data.adt;\n                  const result = this._computeVariantInfo(data.levels);\n                  // update the common keys\n                  playEndedRecord.IsAudioOnly = data.isAudioOnly;\n                  playEndedRecord.IsGapless = data.isGapless;\n                  playEndedRecord.IsFirstItem = data.isFirstItem;\n                  playEndedRecord.ItemID = data.itemID;\n                  playEndedRecord.MaxVideoQltyIndex = result.maxVideoQltyIndex;\n                  playEndedRecord.MaxReWd = result.maxWidth;\n                  playEndedRecord.MaxReHt = result.maxHeight;\n                  sessionControlRecord.manifestData = { variantList: result.variantList, varListString: result.varListString };\n              });\n          }\n          updateFragLoaded(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, periodicRecord, playEndedRecord }) => {\n                  periodicRecord.MediaRequestsSent = (periodicRecord.MediaRequestsSent || 0) + 1;\n                  playEndedRecord.MediaRequestsSent = (playEndedRecord.MediaRequestsSent || 0) + 1;\n                  if (data.cdnServer) {\n                      const cdnServer = data.cdnServer.toLowerCase();\n                      if (cdnServer === 'aapl' || cdnServer === 'akam' || cdnServer === 'llnw') {\n                          playEndedRecord.LastMediaCDNServer = cdnServer;\n                      }\n                  }\n                  if (data.serverInfo) {\n                      playEndedRecord.ServerInfo = data.serverInfo;\n                  }\n                  if (!sessionControlRecord.segmentMimeTypes) {\n                      sessionControlRecord.segmentMimeTypes = [];\n                  }\n                  if (sessionControlRecord.segmentMimeTypes.find((mime) => mime == data.contentType) === undefined) {\n                      sessionControlRecord.segmentMimeTypes.push(data.contentType);\n                  }\n                  if (data.fragType === MediaOptionType.Variant) {\n                      // accumulate the 'main' (muxed) / 'video' (unmuxed) bytes & duration to calculate AvgVideoBitrate\n                      sessionControlRecord.variantVideoBytes = (sessionControlRecord.variantVideoBytes || 0) + data.bytes;\n                      sessionControlRecord.variantVideoDuration = (sessionControlRecord.variantVideoDuration || 0) + data.duration;\n                      sessionControlRecord.intervalVideoBytes = (sessionControlRecord.intervalVideoBytes || 0) + data.bytes;\n                      sessionControlRecord.intervalVideoDuration = (sessionControlRecord.intervalVideoDuration || 0) + data.duration;\n                      sessionControlRecord.sessionVideoBytes = (sessionControlRecord.sessionVideoBytes || 0) + data.bytes;\n                      sessionControlRecord.sessionVideoDuration = (sessionControlRecord.sessionVideoDuration || 0) + data.duration;\n                      sessionControlRecord.obrLast = (data.bytes * 8) / (data.duration / 1000);\n                      /* Update periodic record */\n                      periodicRecord.NetBytes = (periodicRecord.NetBytes || 0) + data.bytes;\n                      periodicRecord.ADT = (periodicRecord.ADT || 0) + data.adt;\n                      periodicRecord.SegmentProcessTime = (periodicRecord.SegmentProcessTime || 0) + data.processTime;\n                      /* Update playEnded record */\n                      playEndedRecord.ADT = (playEndedRecord.ADT || 0) + data.adt;\n                      playEndedRecord.NetBytes = (playEndedRecord.NetBytes || 0) + data.bytes;\n                      playEndedRecord.SegmentProcessTime = (playEndedRecord.SegmentProcessTime || 0) + data.processTime;\n                  }\n                  else if (data.fragType === MediaOptionType.AltAudio) {\n                      // accumulate the 'audio' bytes & duration to calculate AvgAudioBitrate\n                      sessionControlRecord.variantAudioBytes = (sessionControlRecord.variantAudioBytes || 0) + data.bytes;\n                      sessionControlRecord.variantAudioDuration = (sessionControlRecord.variantAudioDuration || 0) + data.duration;\n                      sessionControlRecord.intervalAudioBytes = (sessionControlRecord.intervalAudioBytes || 0) + data.bytes;\n                      sessionControlRecord.intervalAudioDuration = (sessionControlRecord.intervalAudioDuration || 0) + data.duration;\n                      sessionControlRecord.sessionAudioBytes = (sessionControlRecord.sessionAudioBytes || 0) + data.bytes;\n                      sessionControlRecord.sessionAudioDuration = (sessionControlRecord.sessionAudioDuration || 0) + data.duration;\n                  }\n              });\n          }\n          updateFragBuffered(itemId, data) {\n              this.update(itemId, ({ periodicRecord, playEndedRecord }) => {\n                  // use only 'main' (muxed) / 'video' (unmuxed) data to calculate below keys\n                  if (data.fragType === MediaOptionType.Variant) {\n                      /* Update periodic record */\n                      periodicRecord.SegmentParseTime = (periodicRecord.SegmentParseTime || 0) + data.parseTime;\n                      /* Update playEnded record */\n                      playEndedRecord.SegmentParseTime = (playEndedRecord.SegmentParseTime || 0) + data.parseTime;\n                  }\n              });\n          }\n          updateLevelLoaded(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, playLikelyToKeepUpRecord, periodicRecord, playEndedRecord }) => {\n                  playLikelyToKeepUpRecord.PlaylistADT = (playLikelyToKeepUpRecord.PlaylistADT || 0) + data.adt;\n                  periodicRecord.PlaylistADT = (periodicRecord.PlaylistADT || 0) + data.adt;\n                  playEndedRecord.PlaylistADT = (playEndedRecord.PlaylistADT || 0) + data.adt;\n                  periodicRecord.MaxPlaylistDT = data.adt > periodicRecord.MaxPlaylistDT ? data.adt : periodicRecord.MaxPlaylistDT;\n                  playEndedRecord.MaxPlaylistDT = data.adt > playEndedRecord.MaxPlaylistDT ? data.adt : playEndedRecord.MaxPlaylistDT;\n                  playEndedRecord.PlayType = data.playType;\n                  this._setTargetDuration(data.url, data.targetduration, sessionControlRecord);\n                  if (!sessionControlRecord.playlistMimeTypes) {\n                      sessionControlRecord.playlistMimeTypes = [];\n                  }\n                  if (sessionControlRecord.playlistMimeTypes.find((mime) => mime == data.contentType) === undefined) {\n                      sessionControlRecord.playlistMimeTypes.push(data.contentType);\n                  }\n                  const curLevelUrl = data.url;\n                  const curVarInfo = this._getVariantInfo(curLevelUrl, sessionControlRecord);\n                  // Initialize the variant info if it's not seen before\n                  if (!sessionControlRecord.intervalVariantList[curLevelUrl]) {\n                      sessionControlRecord.intervalVariantList[curLevelUrl] = Object.assign({}, curVarInfo);\n                  }\n                  if (!sessionControlRecord.sessionVariantList[curLevelUrl]) {\n                      sessionControlRecord.sessionVariantList[curLevelUrl] = Object.assign({}, curVarInfo);\n                  }\n              });\n          }\n          updateLevelsChanged(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, playEndedRecord }) => {\n                  const result = this._computeVariantInfo(data.levels);\n                  playEndedRecord.MaxVideoQltyIndex = result.maxVideoQltyIndex;\n                  playEndedRecord.MaxReWd = result.maxWidth;\n                  playEndedRecord.MaxReHt = result.maxHeight;\n                  sessionControlRecord.manifestData = { variantList: result.variantList, varListString: result.varListString };\n                  // Update bitrate rank in sessionVariantList and intervalVariantList\n                  Object.keys(result.variantList).forEach((url) => {\n                      if (sessionControlRecord.intervalVariantList[url]) {\n                          sessionControlRecord.intervalVariantList[url].brRnk = result.variantList[url].brRnk;\n                      }\n                      if (sessionControlRecord.sessionVariantList[url]) {\n                          sessionControlRecord.sessionVariantList[url].brRnk = result.variantList[url].brRnk;\n                      }\n                  });\n              });\n          }\n          updateLicenseChallengeRequested(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = {};\n                  const now = data.timestamp;\n                  keySessionInfo.licenseChallengeStartTime = now;\n                  // send the keyInitTime if we're initializing playback\n                  if (sessionControlRecord.state === 'RTC_STATE_INIT') {\n                      keySessionInfo.keyInitTime = now - sessionControlRecord.sessionStartTime;\n                  }\n                  sessionControlRecord.activeKeySessions[data.keyuri] = keySessionInfo;\n              });\n          }\n          updateLicenseChallengeReceived(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.licenseChallengeRequestTime = data.timestamp - keySessionInfo.licenseChallengeStartTime;\n              });\n          }\n          updateLicenseChallengeSubmitted(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.keyFormat = data.keyFormat;\n                  keySessionInfo.licenseChallengeSubmitTime = data.timestamp;\n              });\n          }\n          updateLicenseChallengeCreated(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.cdmVersion = data.cdmVersion;\n                  keySessionInfo.licenseChallengeCreationTime = data.timestamp - keySessionInfo.licenseChallengeSubmitTime;\n              });\n          }\n          updateLicenseResponseRequested(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.licenseResponseRequestTime = data.timestamp;\n              });\n          }\n          updateLicenseResponseReceived(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.licenseResponseReceiveTime = data.timestamp - keySessionInfo.licenseResponseRequestTime;\n              });\n          }\n          updateLicenseResponseSubmitted(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  keySessionInfo.licenseResponseSubmitTime = data.timestamp;\n              });\n          }\n          /*\n           * Private Methods\n           */\n          _prepareEventPlayEnded(itemId) {\n              this.update(itemId, ({ sessionControlRecord, playEndedRecord }) => {\n                  var _a;\n                  playEndedRecord.AvgVideoBitrate = ((sessionControlRecord.sessionVideoBytes || 0) * 8) / (sessionControlRecord.sessionVideoDuration || 1);\n                  playEndedRecord.AvgAudioBitrate = ((sessionControlRecord.sessionAudioBytes || 0) * 8) / (sessionControlRecord.sessionAudioDuration || 1);\n                  // round off NetBytes to the nearest 1000 to obscure the content size - as requested by privacy team.\n                  const netBytes = Math.round((playEndedRecord.NetBytes || 0) / 1000) * 1000;\n                  playEndedRecord.NetBytes = netBytes;\n                  const adt = playEndedRecord.ADT || 1;\n                  const processTime = playEndedRecord.ADT + playEndedRecord.SegmentProcessTime || 1;\n                  const parseTime = playEndedRecord.ADT + playEndedRecord.SegmentProcessTime + playEndedRecord.SegmentParseTime || 1;\n                  playEndedRecord.TWOBR = (netBytes * 8) / (adt / 1000);\n                  playEndedRecord.PerceivedTWOBR = (netBytes * 8) / (processTime / 1000);\n                  playEndedRecord.NetTWOBR = (netBytes * 8) / (parseTime / 1000);\n                  // Use the playtime for the current level too, before generating time weighted values\n                  const twVal = this._findTimeWeightedValues(sessionControlRecord.state === 'RTC_STATE_PLAY' ? Date.now() - sessionControlRecord.eventStartTime : 0, sessionControlRecord.sessionVariantList, sessionControlRecord.curLevelUrl);\n                  playEndedRecord.PlayerTWIBR = twVal.twIBR;\n                  playEndedRecord.PlayerTWIABR = twVal.twIABR;\n                  playEndedRecord.TWBitRk = twVal.twBRnk;\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  playEndedRecord.TargetDur = varInfo.targetduration;\n                  playEndedRecord.ReWd = varInfo.width;\n                  playEndedRecord.ReHt = varInfo.height;\n                  playEndedRecord.VariantList = (_a = sessionControlRecord.manifestData) === null || _a === void 0 ? void 0 : _a.varListString;\n                  let playlistMimeType = '';\n                  if (sessionControlRecord.playlistMimeTypes) {\n                      sessionControlRecord.playlistMimeTypes.forEach((item) => {\n                          playlistMimeType += item + ',';\n                      });\n                      playlistMimeType = playlistMimeType.slice(0, -1); // remove the trailing comma\n                  }\n                  let segmentMimeType = '';\n                  if (sessionControlRecord.segmentMimeTypes) {\n                      sessionControlRecord.segmentMimeTypes.forEach((item) => {\n                          segmentMimeType += item + ',';\n                      });\n                      segmentMimeType = segmentMimeType.slice(0, -1); // remove the trailing comma\n                  }\n                  playEndedRecord.PlaylistMimeType = playlistMimeType;\n                  playEndedRecord.SegmentMimeType = segmentMimeType;\n                  playEndedRecord.Rate = sessionControlRecord.rate;\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventPeriodic(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, periodicRecord, playEndedRecord }) => {\n                  var _a;\n                  periodicRecord.EventCounter = sessionControlRecord.periodicEventCounter;\n                  periodicRecord.PInterval = Date.now() - sessionControlRecord.lastPeriodicTime;\n                  periodicRecord.AvgVideoBitrate = ((sessionControlRecord.intervalVideoBytes || 0) * 8) / (sessionControlRecord.intervalVideoDuration || 1);\n                  periodicRecord.AvgAudioBitrate = ((sessionControlRecord.intervalAudioBytes || 0) * 8) / (sessionControlRecord.intervalAudioDuration || 1);\n                  let netBytes = periodicRecord.NetBytes || 0;\n                  if (data.isFinal) {\n                      // round off NetBytes to the nearest 1000 to obscure the content size - as requested by privacy team. (for periodic event, we need this only for the last event)\n                      periodicRecord.NetBytes = netBytes = Math.round(netBytes / 1000) * 1000;\n                  }\n                  const adt = periodicRecord.ADT || 1;\n                  const processTime = periodicRecord.ADT + periodicRecord.SegmentProcessTime || 1;\n                  const parseTime = periodicRecord.ADT + periodicRecord.SegmentProcessTime + periodicRecord.SegmentParseTime || 1;\n                  periodicRecord.TWOBR = (netBytes * 8) / (adt / 1000);\n                  periodicRecord.PerceivedTWOBR = (netBytes * 8) / (processTime / 1000);\n                  periodicRecord.NetTWOBR = (netBytes * 8) / (parseTime / 1000);\n                  // Use the playtime for the current level too, before generating time weighted values\n                  const twVal = this._findTimeWeightedValues(sessionControlRecord.state === 'RTC_STATE_PLAY' ? Date.now() - sessionControlRecord.eventStartTime : 0, sessionControlRecord.intervalVariantList, sessionControlRecord.curLevelUrl);\n                  periodicRecord.PlayerTWIBR = twVal.twIBR;\n                  periodicRecord.PlayerTWIABR = twVal.twIABR;\n                  periodicRecord.TWBitRk = twVal.twBRnk;\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  periodicRecord.TargetDur = varInfo.targetduration;\n                  periodicRecord.ReWd = varInfo.width;\n                  periodicRecord.ReHt = varInfo.height;\n                  periodicRecord.VariantList = (_a = sessionControlRecord.manifestData) === null || _a === void 0 ? void 0 : _a.varListString;\n                  periodicRecord.Rate = sessionControlRecord.rate;\n                  const stats = this._computeMediaStats(sessionControlRecord);\n                  if (stats) {\n                      periodicRecord.MedianBufferAppendLatency = stats.bufLatencyInfo.median;\n                      periodicRecord.MaxBufferAppendLatency = stats.bufLatencyInfo.max;\n                      periodicRecord.MedianBufferAppendSize = stats.bufSizeInfo.median;\n                      periodicRecord.MaxBufferAppendSize = stats.bufSizeInfo.max;\n                      periodicRecord.MedianSeekLatency = stats.seekLatencyInfo.median;\n                      periodicRecord.MaxSeekLatency = stats.seekLatencyInfo.max;\n                      periodicRecord.MedianPlayLatency = stats.playLatencyInfo.median;\n                      periodicRecord.MaxPlayLatency = stats.playLatencyInfo.max;\n                  }\n                  this._copyCommonKeys(periodicRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventPlayStalled(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, playStalledRecord, playEndedRecord }) => {\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  const now = Date.now();\n                  playStalledRecord.MediaDur = data.mediaDur;\n                  playStalledRecord.BitRnk = varInfo.brRnk;\n                  playStalledRecord.Codecs = varInfo.codecs;\n                  playStalledRecord.LastLikelyToKeepUp = now - sessionControlRecord.lastLikelyToKeepUpTime;\n                  playStalledRecord.LastSwitch = now - sessionControlRecord.lastSwitchTime;\n                  playStalledRecord.StallDetectionTime = data.stallDurationMs;\n                  playStalledRecord.StallType = data.type;\n                  playStalledRecord.BufferLength = data.bufferLen;\n                  if (playEndedRecord.ErrDomain === 'networkError') {\n                      playStalledRecord.NwErrTime = playEndedRecord.NwErrTime;\n                      playStalledRecord.NwErrCode = playEndedRecord.ErrCode;\n                  }\n                  playStalledRecord.LaSwDir = sessionControlRecord.lastSwitchDir;\n                  playStalledRecord.TargetDur = varInfo.targetduration;\n                  playStalledRecord.PlayerIABR = varInfo.avgBandwidth;\n                  playStalledRecord.PlayerIBR = varInfo.bandwidth;\n                  playStalledRecord.Rate = sessionControlRecord.rate;\n                  playStalledRecord.OBRLast = sessionControlRecord.obrLast;\n                  playStalledRecord.OBRMean = (playEndedRecord.NetBytes * 8) / (playEndedRecord.ADT / 1000);\n                  this._copyCommonKeys(playStalledRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventKeySessionComplete(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, keySessionCompleteRecord, playEndedRecord }) => {\n                  const keySessionInfo = sessionControlRecord.activeKeySessions[data.keyuri];\n                  if (!keySessionInfo) {\n                      this.logger.warn(`_prepareEventKeySessionComplete no keySessionInfo for ${redactUrl(data.keyuri)}`);\n                      return;\n                  }\n                  keySessionCompleteRecord.KeyFormat = keySessionInfo.keyFormat;\n                  keySessionCompleteRecord.CDMVersion = keySessionInfo.cdmVersion;\n                  keySessionCompleteRecord.LicenseChallengeRequestTime = keySessionInfo.licenseChallengeRequestTime;\n                  keySessionCompleteRecord.LicenseChallengeCreationTime = keySessionInfo.licenseChallengeCreationTime;\n                  keySessionCompleteRecord.LicenseResponseReceiveTime = keySessionInfo.licenseResponseReceiveTime;\n                  keySessionCompleteRecord.LicenseResponseProcessTime = keySessionInfo.licenseResponseProcessTime;\n                  keySessionCompleteRecord.KeyDeliveryTime = keySessionInfo.keyDeliveryTime;\n                  keySessionCompleteRecord.CurrentMediaTime = keySessionInfo.currentMediaTime * 1000;\n                  keySessionCompleteRecord.KeyInitTime = keySessionInfo.keyInitTime;\n                  keySessionCompleteRecord.KeyErrorType = keySessionInfo.keyErrorType;\n                  this._copyCommonKeys(keySessionCompleteRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventPlayLikelyToKeepUp(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, playLikelyToKeepUpRecord, playEndedRecord }) => {\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  playLikelyToKeepUpRecord.EventCounter = sessionControlRecord.playLikelyToKeepUpEventCounter;\n                  playLikelyToKeepUpRecord.PlayerIABR = varInfo.avgBandwidth;\n                  playLikelyToKeepUpRecord.PlayerIBR = varInfo.bandwidth;\n                  playLikelyToKeepUpRecord.MediaDur = data.mediaDur;\n                  playLikelyToKeepUpRecord.BitRnk = varInfo.brRnk;\n                  playLikelyToKeepUpRecord.Codecs = varInfo.codecs;\n                  playLikelyToKeepUpRecord.TargetDur = varInfo.targetduration;\n                  this._copyCommonKeys(playLikelyToKeepUpRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventPlayRateChanged(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, playRateChangedRecord, playEndedRecord }) => {\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  playRateChangedRecord.Rate = sessionControlRecord.rate;\n                  playRateChangedRecord.StNPT = data.currentTime;\n                  playRateChangedRecord.PlayerIABR = varInfo.avgBandwidth;\n                  playRateChangedRecord.PlayerIBR = varInfo.bandwidth;\n                  playRateChangedRecord.BitRnk = varInfo.brRnk;\n                  playRateChangedRecord.MediaDur = data.mediaDur;\n                  playRateChangedRecord.Codecs = varInfo.codecs;\n                  this._copyCommonKeys(playRateChangedRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventPlayError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, playErrorRecord, playEndedRecord }) => {\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  const now = Date.now();\n                  if (data.domain == 'mediaElementError') {\n                      playErrorRecord.ErrDomain = playErrorRecord.ErrCode = 'mediaElementError';\n                      playErrorRecord.ErrIsFatal = true;\n                      playErrorRecord.ErrCodeMediaElement = data.mediaElemCode;\n                      playErrorRecord.ErrReason = data.mediaElemReason;\n                      playErrorRecord.ErrDetail = data.mediaElemDetail;\n                  }\n                  else {\n                      playErrorRecord.ErrCode = data.details;\n                      playErrorRecord.ErrReason = data.code;\n                      playErrorRecord.ErrIsFatal = data.fatal;\n                      playErrorRecord.ErrDomain = 'mediaError';\n                  }\n                  playErrorRecord.PlayerErrCount = data.count || 1;\n                  playErrorRecord.BitRnk = varInfo.brRnk;\n                  playErrorRecord.MediaDur = data.mediaDur;\n                  playErrorRecord.PlayTime = playEndedRecord.PlayTime;\n                  playErrorRecord.PlayTimeWC = playEndedRecord.PlayTimeWC;\n                  playErrorRecord.PlayerIABR = varInfo.avgBandwidth;\n                  playErrorRecord.PlayerIBR = varInfo.bandwidth;\n                  playErrorRecord.LastLikelyToKeepUp = now - sessionControlRecord.lastLikelyToKeepUpTime;\n                  playErrorRecord.LastSwitch = now - sessionControlRecord.lastSwitchTime;\n                  playErrorRecord.VideoQltyIndex = varInfo.qltyIndex;\n                  playErrorRecord.Rate = sessionControlRecord.rate;\n                  playErrorRecord.KeyErrorType = sessionControlRecord.lastKeyErrorType;\n                  playErrorRecord.KeyDeliveryTime = sessionControlRecord.lastKeyDeliveryTime;\n                  this._copyCommonKeys(playErrorRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventMediaEngineStalled(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, mediaEngineStalledRecord, playEndedRecord }) => {\n                  const now = Date.now();\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  mediaEngineStalledRecord.MediaDur = data.mediaDur;\n                  mediaEngineStalledRecord.BitRnk = varInfo.brRnk;\n                  mediaEngineStalledRecord.Codecs = varInfo.codecs;\n                  mediaEngineStalledRecord.LastLikelyToKeepUp = now - sessionControlRecord.lastLikelyToKeepUpTime;\n                  mediaEngineStalledRecord.LastSwitch = now - sessionControlRecord.lastSwitchTime;\n                  mediaEngineStalledRecord.StallDetectionTime = data.stallDurationMs;\n                  mediaEngineStalledRecord.StallType = data.type;\n                  mediaEngineStalledRecord.BufferLength = data.bufferLen;\n                  mediaEngineStalledRecord.LaSwDir = sessionControlRecord.lastSwitchDir;\n                  mediaEngineStalledRecord.TargetDur = varInfo.targetduration;\n                  mediaEngineStalledRecord.PlayerIABR = varInfo.avgBandwidth;\n                  mediaEngineStalledRecord.PlayerIBR = varInfo.bandwidth;\n                  mediaEngineStalledRecord.Rate = sessionControlRecord.rate;\n                  mediaEngineStalledRecord.OBRLast = sessionControlRecord.obrLast;\n                  mediaEngineStalledRecord.OBRMean = (playEndedRecord.NetBytes * 8) / (playEndedRecord.ADT / 1000);\n                  this._copyCommonKeys(mediaEngineStalledRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventSwitchComplete(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, switchCompleteRecord, playEndedRecord }) => {\n                  const fromVarInfo = this._getVariantInfo(sessionControlRecord.prevLevelUrl, sessionControlRecord);\n                  const toVarInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  switchCompleteRecord.FrBitRnk = fromVarInfo.brRnk;\n                  switchCompleteRecord.ToBitRnk = toVarInfo.brRnk;\n                  switchCompleteRecord.TimeToBitrate = Date.now() - sessionControlRecord.sessionStartTime;\n                  switchCompleteRecord.MediaDur = data.mediaDur;\n                  switchCompleteRecord.Rate = sessionControlRecord.rate;\n                  switchCompleteRecord.PlayerIBR = toVarInfo.bandwidth;\n                  switchCompleteRecord.PlayerIABR = toVarInfo.avgBandwidth;\n                  switchCompleteRecord.LastPlayerIBR = fromVarInfo.bandwidth;\n                  switchCompleteRecord.LastPlayerIABR = fromVarInfo.avgBandwidth;\n                  switchCompleteRecord.ReWd = toVarInfo.width;\n                  switchCompleteRecord.ReHt = toVarInfo.height;\n                  this._copyCommonKeys(switchCompleteRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventVariantEnded(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, variantEndedRecord, playEndedRecord }) => {\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  variantEndedRecord.Rate = sessionControlRecord.rate;\n                  variantEndedRecord.VarAvgBitrate = varInfo.avgBandwidth;\n                  variantEndedRecord.VarPeakBitrate = varInfo.bandwidth;\n                  variantEndedRecord.VarBitRk = varInfo.brRnk;\n                  variantEndedRecord.VarSTTime = sessionControlRecord.variantStartTimeMedia;\n                  variantEndedRecord.VarEndTime = data.currentTime * 1000;\n                  variantEndedRecord.IFR = varInfo.framerate;\n                  variantEndedRecord.ODR = sessionControlRecord.decodedFramesForVariant / sessionControlRecord.decodedFramesForVariantSampleCount;\n                  variantEndedRecord.ReWd = varInfo.width;\n                  variantEndedRecord.ReHt = varInfo.height;\n                  variantEndedRecord.Codecs = varInfo.codecs;\n                  variantEndedRecord.AvgVideoBitrate = ((sessionControlRecord.variantVideoBytes || 0) * 8) / (sessionControlRecord.variantVideoDuration || 1);\n                  variantEndedRecord.AvgAudioBitrate = ((sessionControlRecord.variantAudioBytes || 0) * 8) / (sessionControlRecord.variantAudioDuration || 1);\n                  this._copyCommonKeys(variantEndedRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _prepareEventNwError(itemId, data) {\n              this.update(itemId, ({ sessionControlRecord, nwErrorRecord, playEndedRecord }) => {\n                  const varInfo = this._getVariantInfo(sessionControlRecord.curLevelUrl, sessionControlRecord);\n                  nwErrorRecord.ErrCode = data.details;\n                  nwErrorRecord.ErrReason = data.code;\n                  nwErrorRecord.ErrIsFatal = data.fatal;\n                  nwErrorRecord.NwErrCount = data.count || 1;\n                  nwErrorRecord.ErrDomain = 'networkError';\n                  nwErrorRecord.PlayTime = playEndedRecord.PlayTime;\n                  nwErrorRecord.PlayTimeWC = playEndedRecord.PlayTimeWC;\n                  nwErrorRecord.BitRnk = varInfo.brRnk;\n                  nwErrorRecord.Rate = sessionControlRecord.rate;\n                  nwErrorRecord.KeyErrorType = sessionControlRecord.lastKeyErrorType;\n                  nwErrorRecord.KeyDeliveryTime = sessionControlRecord.lastKeyDeliveryTime;\n                  this._copyCommonKeys(nwErrorRecord, playEndedRecord);\n              });\n              this._aggregateTimes(itemId);\n          }\n          _copyCommonKeys(dst, src) {\n              dst.PlayType = src.PlayType;\n              dst.LastMediaCDNServer = src.LastMediaCDNServer;\n              dst.MaxVideoQltyIndex = src.MaxVideoQltyIndex;\n              dst.MaxReWd = src.MaxReWd;\n              dst.MaxReHt = src.MaxReHt;\n              dst.IsGapless = src.IsGapless;\n              dst.IsAudioOnly = src.IsAudioOnly;\n              dst.IsFirstItem = src.IsFirstItem;\n              dst.ItemID = src.ItemID;\n              dst.ServerInfo = src.ServerInfo;\n          }\n          _computeVariantInfo(levels) {\n              const variantList = {};\n              let maxWidth = 0;\n              let maxHeight = 0;\n              let maxProd = 0;\n              let maxVideoQltyIndex = 0;\n              const maxNormalizedPeak = this._getMaxNormalizedPeak(levels);\n              levels.forEach((item) => {\n                  if (item.attrs) {\n                      const fourCC = this._getVideoFourCC(item.attrs.CODECS);\n                      const qltyIndex = this._getVideoQualityIndex(fourCC, item.attrs['VIDEO-RANGE']) || 0;\n                      const variantInfo = {\n                          codecs: item.attrs.CODECS,\n                          width: item.width,\n                          height: item.height,\n                          bandwidth: item.attrs.BANDWIDTH,\n                          avgBandwidth: item.attrs['AVERAGE-BANDWIDTH'],\n                          framerate: item.attrs['FRAME-RATE'],\n                          iframes: item.iframes,\n                          brRnk: this._getBitrateRank(item.attrs.BANDWIDTH, fourCC, maxNormalizedPeak),\n                          qltyIndex: qltyIndex,\n                          targetduration: 0,\n                          playTime: 0,\n                      };\n                      maxVideoQltyIndex = qltyIndex > maxVideoQltyIndex ? qltyIndex : maxVideoQltyIndex;\n                      // store variant data against the url\n                      variantList[item.url] = variantInfo;\n                  }\n                  const prod = item.width * item.height;\n                  if (prod > maxProd) {\n                      maxProd = prod;\n                      maxWidth = item.width;\n                      maxHeight = item.height;\n                  }\n              });\n              const varListString = Object.keys(variantList).length > 0\n                  ? Object.values(variantList)\n                      .map((item) => item.bandwidth + ':' + item.avgBandwidth)\n                      .join(',')\n                  : undefined;\n              return { variantList: variantList, varListString: varListString, maxVideoQltyIndex: maxVideoQltyIndex, maxWidth: maxWidth, maxHeight: maxHeight };\n          }\n          _getMaxNormalizedPeak(levels) {\n              let maxNormalizedPeak = 0;\n              levels.forEach((level) => {\n                  const attrs = level.attrs;\n                  if (attrs) {\n                      const peak = attrs.BANDWIDTH || 0;\n                      const normPeak = this._getNormalizedPeak(peak, this._getVideoFourCC(attrs.CODECS));\n                      const curMax = Math.max(peak, normPeak);\n                      maxNormalizedPeak = curMax > maxNormalizedPeak ? curMax : maxNormalizedPeak;\n                  }\n              });\n              return maxNormalizedPeak;\n          }\n          _getNormalizedPeak(peak, fourCC) {\n              // Normalization factor for avc family is 1 and for hevc/dolby family is 1.5.\n              return typeof RTCVideoQualityIndex[fourCC] === 'object' ? peak * 1.5 : peak * 1;\n          }\n          _getVideoFourCC(codecs) {\n              return codecs\n                  ? codecs\n                      .split(',')\n                      .map((item) => item.split('.')[0].trim())\n                      .find((item) => !!RTCVideoQualityIndex[item])\n                  : codecs;\n          }\n          _getVideoQualityIndex(fourCC, range) {\n              return typeof RTCVideoQualityIndex[fourCC] === 'object' ? RTCVideoQualityIndex[fourCC][range] : RTCVideoQualityIndex[fourCC];\n          }\n          _getBitrateRank(peak, fourCC, maxNormalizedPeak) {\n              const normPeak = Math.max(1, this._getNormalizedPeak(peak, fourCC));\n              return Math.ceil((normPeak * 100) / maxNormalizedPeak);\n          }\n          _findTimeWeightedValues(playTime, list, curLevel) {\n              const result = { twBRnk: 0, twIBR: 0, twIABR: 0 };\n              if (list) {\n                  let totalBitRk = 0;\n                  let totalTWIB = 0;\n                  let totalPlaytime = 0;\n                  let totalTWIAB = 0;\n                  let totalPlaytimeForAvgBw = 0;\n                  Object.values(list).forEach((item) => {\n                      let varPlayTime = item.playTime;\n                      if (item === list[curLevel]) {\n                          varPlayTime += playTime || 0;\n                      }\n                      if (varPlayTime) {\n                          totalTWIB += item.bandwidth * varPlayTime;\n                          totalBitRk += item.brRnk * varPlayTime;\n                          totalPlaytime += varPlayTime;\n                          // Avg bandwidth is optional, use its playtime only if it's reported\n                          if (item.avgBandwidth) {\n                              totalTWIAB += item.avgBandwidth * varPlayTime;\n                              totalPlaytimeForAvgBw += varPlayTime;\n                          }\n                      }\n                  });\n                  if (totalPlaytime) {\n                      result.twBRnk = totalBitRk / totalPlaytime;\n                      result.twIBR = totalTWIB / totalPlaytime;\n                  }\n                  if (totalTWIAB && totalPlaytimeForAvgBw) {\n                      result.twIABR = totalTWIAB / totalPlaytimeForAvgBw;\n                  }\n              }\n              return result;\n          }\n          _computeMediaStats(record) {\n              const bufferAppendInfo = record.bufferAppendInfo;\n              let latencies = [];\n              const sizes = [];\n              if (bufferAppendInfo && bufferAppendInfo.forEach) {\n                  bufferAppendInfo.forEach((item) => {\n                      latencies.push(item.latency);\n                      sizes.push(item.size);\n                  });\n              }\n              const bufLatencyInfo = this._computeStats(latencies);\n              const bufSizeInfo = this._computeStats(sizes);\n              // calculate seek stats\n              const seekInfo = record.seekInfo;\n              latencies = [];\n              if (seekInfo && seekInfo.forEach) {\n                  record.seekInfo.forEach((item) => latencies.push(item.latency));\n              }\n              const seekLatencyInfo = this._computeStats(latencies);\n              // calculate play stats\n              const playInfo = record.playInfo;\n              latencies = [];\n              if (playInfo && playInfo.forEach) {\n                  record.playInfo.forEach((item) => latencies.push(item.latency));\n              }\n              const playLatencyInfo = this._computeStats(latencies);\n              return { bufLatencyInfo, bufSizeInfo, seekLatencyInfo, playLatencyInfo };\n          }\n          _computeStats(inputArr) {\n              let max;\n              let median;\n              if (inputArr) {\n                  const arr = inputArr.filter((value) => value > 0); // ensure there are only positive values\n                  if (arr.length > 0) {\n                      max = arr.reduce((a, b) => {\n                          return Math.max(a, b);\n                      });\n                      const len = arr.length;\n                      const sortedArr = arr.sort((a, b) => a - b);\n                      const mid = Math.ceil(len / 2);\n                      median = len % 2 === 0 ? (sortedArr[mid] + sortedArr[mid - 1]) / 2 : sortedArr[mid - 1];\n                  }\n              }\n              return { max, median };\n          }\n          _getVariantInfo(url, record) {\n              return url && record.manifestData && record.manifestData.variantList && record.manifestData.variantList[url] ? record.manifestData.variantList[url] : {};\n          }\n          _setTargetDuration(url, targetduration, record) {\n              if (url && record.manifestData && record.manifestData.variantList && record.manifestData.variantList[url]) {\n                  record.manifestData.variantList[url].targetduration = targetduration;\n              }\n          }\n          _isBadSw(curSwDir, lastSwitchDir, curLevelIsIframe, lastLevelIsIframe, curSwitchTime, lastSwitchTime, isSeeking) {\n              const minSwitchWindow = 10000; // if we reverse the switch direction within this window, it's considered as a bad switch\n              let isBadSw = false;\n              if (curSwitchTime - lastSwitchTime < minSwitchWindow && lastSwitchDir !== curSwDir && lastLevelIsIframe === curLevelIsIframe && !isSeeking) {\n                  isBadSw = true;\n              }\n              return isBadSw;\n          }\n          _aggregateTimes(itemId) {\n              this.update(itemId, ({ sessionControlRecord, playLikelyToKeepUpRecord, playStalledRecord, mediaEngineStalledRecord, switchCompleteRecord, playRateChangedRecord, variantEndedRecord, playErrorRecord, nwErrorRecord, periodicRecord, playEndedRecord, }) => {\n                  const now = Date.now();\n                  const eventTime = now - sessionControlRecord.eventStartTime;\n                  const state = sessionControlRecord.state;\n                  switch (state) {\n                      case 'RTC_STATE_INIT': {\n                          playLikelyToKeepUpRecord.StartupTime = (playLikelyToKeepUpRecord.StartupTime || 0) + eventTime;\n                          periodicRecord.InitTime = (periodicRecord.InitTime || 0) + eventTime;\n                          playEndedRecord.InitTime = (playEndedRecord.InitTime || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_CANPLAY': {\n                          playRateChangedRecord.StartupTime = (playRateChangedRecord.StartupTime || 0) + eventTime;\n                          periodicRecord.InitTime = (periodicRecord.InitTime || 0) + eventTime;\n                          playEndedRecord.InitTime = (playEndedRecord.InitTime || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_PAUSE': {\n                          periodicRecord.PauseTime = (periodicRecord.PauseTime || 0) + eventTime;\n                          playEndedRecord.PauseTime = (playEndedRecord.PauseTime || 0) + eventTime;\n                          playRateChangedRecord.LastPause = (playRateChangedRecord.LastPause || 0) + eventTime;\n                          playEndedRecord.LastPause = (playEndedRecord.LastPause || 0) + eventTime;\n                          playErrorRecord.LastPause = (playErrorRecord.LastPause || 0) + eventTime;\n                          nwErrorRecord.LastPause = (nwErrorRecord.LastPause || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_STALL': {\n                          variantEndedRecord.StallTime = (variantEndedRecord.StallTime || 0) + eventTime;\n                          periodicRecord.StallTime = (periodicRecord.StallTime || 0) + eventTime;\n                          playEndedRecord.StallTime = (playEndedRecord.StallTime || 0) + eventTime;\n                          playRateChangedRecord.LastStall = (playRateChangedRecord.LastStall || 0) + eventTime;\n                          playErrorRecord.LastStall = (playErrorRecord.LastStall || 0) + eventTime;\n                          playEndedRecord.LastStall = (playEndedRecord.LastStall || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_MEDIAENGINESTALL': {\n                          variantEndedRecord.MediaEngineStallTime = (variantEndedRecord.MediaEngineStallTime || 0) + eventTime;\n                          periodicRecord.MediaEngineStallTime = (periodicRecord.MediaEngineStallTime || 0) + eventTime;\n                          playEndedRecord.MediaEngineStallTime = (playEndedRecord.MediaEngineStallTime || 0) + eventTime;\n                          playRateChangedRecord.LastMediaEngineStall = (playRateChangedRecord.LastMediaEngineStall || 0) + eventTime;\n                          playErrorRecord.LastMediaEngineStall = (playErrorRecord.LastMediaEngineStall || 0) + eventTime;\n                          playEndedRecord.LastMediaEngineStall = (playEndedRecord.LastMediaEngineStall || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_NWERROR': {\n                          playEndedRecord.NwErrTime = (playEndedRecord.NwErrTime || 0) + eventTime;\n                          periodicRecord.NwErrTime = (periodicRecord.NwErrTime || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_PLAYERROR': {\n                          periodicRecord.PlayErrTime = (periodicRecord.PlayErrTime || 0) + eventTime;\n                          playEndedRecord.PlayErrTime = (playEndedRecord.PlayErrTime || 0) + eventTime;\n                          break;\n                      }\n                      case 'RTC_STATE_PLAY': {\n                          playRateChangedRecord.RateChangePlayTime = (playRateChangedRecord.RateChangePlayTime || 0) + eventTime;\n                          switchCompleteRecord.PlayTime = (switchCompleteRecord.PlayTime || 0) + eventTime;\n                          switchCompleteRecord.PlayTimeLastSW = (switchCompleteRecord.PlayTimeLastSW || 0) + eventTime * (sessionControlRecord.oldRate / 100);\n                          playStalledRecord.LastResume = (playStalledRecord.LastResume || 0) + eventTime;\n                          mediaEngineStalledRecord.LastResume = (mediaEngineStalledRecord.LastResume || 0) + eventTime;\n                          playErrorRecord.LastResume = (playErrorRecord.LastResume || 0) + eventTime;\n                          nwErrorRecord.LastResume = (nwErrorRecord.LastResume || 0) + eventTime;\n                          variantEndedRecord.VarPlayTimeWC = (variantEndedRecord.VarPlayTimeWC || 0) + eventTime;\n                          variantEndedRecord.VarPlayTime = (variantEndedRecord.VarPlayTime || 0) + eventTime * (sessionControlRecord.oldRate / 100);\n                          periodicRecord.PlayTimeWC = (periodicRecord.PlayTimeWC || 0) + eventTime;\n                          periodicRecord.PlayTime = (periodicRecord.PlayTime || 0) + eventTime * (sessionControlRecord.oldRate / 100);\n                          playEndedRecord.PlayTimeWC = (playEndedRecord.PlayTimeWC || 0) + eventTime;\n                          playEndedRecord.PlayTime = (playEndedRecord.PlayTime || 0) + eventTime * (sessionControlRecord.oldRate / 100);\n                          // Update stall playtime\n                          mediaEngineStalledRecord.PlayTime = playEndedRecord.PlayTime;\n                          playStalledRecord.PlayTime = playEndedRecord.PlayTime;\n                          // Update the playtime for the current level to calculate time weighted values\n                          const curLevelUrl = sessionControlRecord.curLevelUrl;\n                          let variantInfo = sessionControlRecord.intervalVariantList[curLevelUrl];\n                          variantInfo.playTime = (variantInfo.playTime || 0) + eventTime;\n                          variantInfo = sessionControlRecord.sessionVariantList[curLevelUrl];\n                          variantInfo.playTime = (variantInfo.playTime || 0) + eventTime;\n                          break;\n                      }\n                  }\n              });\n          }\n      }\n    \n      const loggerName$4 = { name: 'rtc-service' };\n      const defaultIntervalValue = 300000;\n      /*\n       * @brief RTC service is responsible for subscribing to queries and updating the RTC store.\n       */\n      class RTCService {\n          constructor(hls, config, accessLog, logger) {\n              this.hls = hls;\n              this.config = config;\n              this.accessLog = accessLog;\n              this.logger = logger;\n              this.destroy$ = new Subject();\n              this.isSeeking = false;\n              this.seekStart = null;\n              this.periodicInterval = config.rtcIntervalTimeout ? config.rtcIntervalTimeout : defaultIntervalValue;\n              this.intervalFunc = null;\n              this.rtcStore = new RTCStore(this.logger);\n              this.rtcQuery = new RTCQuery(this.rtcStore, this.logger);\n              this.rtcComponent = new RTCComponent(this.rtcQuery, this.logger);\n              accessLog.setRTCQuery(this.rtcQuery);\n              this.subscribeAndUpdateStore();\n              this.registerForEvents();\n          }\n          destroy() {\n              this.destroy$.next();\n              this.clearPeriodic();\n              this.rtcStore.reset();\n          }\n          detachMedia() {\n              this.clearPeriodic();\n              let t = 0;\n              try {\n                  // if detach was as a result of an error, this will throw.\n                  t = this.hls.realCurrentTime;\n                  this.logger.qe({ critical: true, name: 'playEnded', data: { itemId: this.rtcEventItemId(true) } });\n                  this.rtcStore.updateVariantEnd(this.rtcEventItemId(true), { currentTime: t });\n                  this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.VariantEnded);\n                  this.rtcStore.updatePeriodic(this.rtcEventItemId(true), true);\n                  this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.Periodic);\n                  this.rtcStore.updateEnded(this.rtcEventItemId(true));\n                  this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.PlayEnded);\n              }\n              catch (err) {\n                  this.logger.warn(loggerName$4, err);\n              }\n          }\n          handleError(error) {\n              var _a, _b;\n              let newError;\n              if (error instanceof HlsError) {\n                  newError = error;\n              }\n              else {\n                  newError = new ExceptionError(true, error.message, ErrorResponses.InternalError);\n              }\n              if (newError instanceof PlaylistNetworkError && !newError.fatal) {\n                  this.rtcStore.updateLevelLoadError(this.rtcEventItemId(), { url: newError.url, mediaDur: this.hls.bufferedDuration, isSeeking: this.isSeeking });\n                  this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.SwitchComplete);\n              }\n              else if (newError.type === ErrorTypes.NETWORK_ERROR) {\n                  this.rtcStore.updateNwError(this.rtcEventItemId(), { fatal: newError.fatal, details: newError.details, code: (_a = newError.response) === null || _a === void 0 ? void 0 : _a.code });\n                  this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.NwError);\n              }\n              else {\n                  this.rtcStore.updateMediaError(this.rtcEventItemId(), { fatal: newError.fatal, details: newError.details, code: (_b = newError.response) === null || _b === void 0 ? void 0 : _b.code });\n                  this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.PlayError);\n              }\n          }\n          handleMediaElementError(err) {\n              this.rtcStore.updateMediaElementError(this.rtcEventItemId(), err);\n              this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.PlayError);\n          }\n          handleFragLoaded(frag, stats) {\n              var _a;\n              this.logger.trace(loggerName$4, 'MediaFragment=%o, Stats=%o', fragPrint(frag), stats);\n              if (!this.checkMediaOptionType(frag.mediaOptionType)) {\n                  return;\n              }\n              if (frag.itemId !== this.rtcEventItemId()) {\n                  this.logger.warn(loggerName$4, `Frag id does not match current item id. Frag Id=${frag.itemId}, playing id=${this.rtcEventItemId(true)}, loading id=${(_a = this.hls.loadingItem) === null || _a === void 0 ? void 0 : _a.itemId}`);\n              }\n              const adt = stats.tload - stats.trequest;\n              const processTime = stats.tload - stats.tfirst;\n              const serverInfo = this.serverInfoInstance ? this.serverInfoInstance : {};\n              this.rtcStore.updateFragLoaded(frag.itemId, {\n                  fragType: frag.mediaOptionType,\n                  bytes: stats.loaded,\n                  duration: frag.duration,\n                  adt: adt,\n                  processTime: processTime,\n                  contentType: stats.contentType,\n                  cdnServer: stats.cdnServer,\n                  serverInfo: serverInfo,\n              });\n              this.accessLog.updateFragLoaded(frag.itemId, this.isSeeking, {\n                  fragType: frag.mediaOptionType,\n                  bytes: stats.loaded,\n                  duration: frag.duration,\n                  adt: adt,\n                  processTime: processTime,\n                  startPTS: frag.start,\n                  endPTS: frag.start + frag.duration,\n              });\n          }\n          handleFragBuffered(metric) {\n              this.logger.trace(loggerName$4, 'Frag Buffered, metrics=%o', metric);\n              if (!this.checkMediaOptionType(metric.fragmentType)) {\n                  return;\n              }\n              const parseTime = metric.endDataAppend - metric.startDataAppend;\n              this.rtcStore.updateFragBuffered(this.rtcEventItemId(), { fragType: metric.fragmentType, bytes: metric.dataBytesAppend, parseTime: parseTime });\n          }\n          handleLevelLoaded(mediaOptionDetails, stats) {\n              if (!mediaOptionDetails) {\n                  // This happens on Safari and FireFox, browsers that block autoplay.\n                  // rdar://82312973\n                  this.logger.warn(`handleLevelLoaded called with mediaOptionDetails as ${mediaOptionDetails}`);\n                  return;\n              }\n              if (mediaOptionDetails.itemId !== this.rtcEventItemId()) {\n                  this.logger.warn(loggerName$4, `media option id does not match current item id. media Id=${mediaOptionDetails.itemId}, current id=${this.rtcEventItemId}`);\n              }\n              if (mediaOptionDetails.mediaOptionType === MediaOptionType.Variant) {\n                  const adt = stats.tload - stats.trequest;\n                  this.rtcStore.updateLevelLoaded(this.rtcEventItemId(), {\n                      url: mediaOptionDetails.url,\n                      targetduration: mediaOptionDetails.targetduration,\n                      adt: adt,\n                      contentType: stats.contentType,\n                      playType: mediaOptionDetails.type,\n                  });\n              }\n          }\n          handleLevelSwitched(data) {\n              const levelData = { url: data.url, isSeeking: this.isSeeking, mediaDur: this.hls.bufferedDuration, currentTime: this.hls.realCurrentTime };\n              this.logger.trace(loggerName$4, `RTC level Switched, oldVariant: ${data.oldVariant}, newVariant: ${data.newVariant}`);\n              if (data.oldVariant) {\n                  // Playing variant ended.\n                  this.rtcStore.updateVariantEnd(this.rtcEventItemId(), { currentTime: this.hls.realCurrentTime });\n                  this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.VariantEnded);\n              }\n              // Playback switched to new variant.\n              this.rtcStore.updateLevelSwitched(this.rtcEventItemId(), levelData);\n              this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.SwitchComplete);\n          }\n          handleLevelSwitching(levelUrl) {\n              this.levelSwitchingUrl = levelUrl;\n          }\n          handleLevelsChanged(variantList) {\n              this.logger.trace(loggerName$4, 'Levels Changed Levels=%o', variantList);\n              this.rtcStore.updateLevelsChanged(this.rtcEventItemId(), { levels: variantList });\n          }\n          handleManifestParsed(manifestParsedData) {\n              var _a;\n              this.logger.trace(loggerName$4, 'RTC Manifest Parsed, levels=%o, stats=%o', manifestParsedData.levels, manifestParsedData.stats);\n              const adt = manifestParsedData.stats.tload - manifestParsedData.stats.trequest;\n              this.rtcStore.updateManifestParsed(this.rtcEventItemId(), {\n                  levels: manifestParsedData.levels,\n                  adt: adt,\n                  contentType: manifestParsedData.stats.contentType,\n                  isAudioOnly: this.hls.inGaplessMode,\n                  isGapless: this.hls.inGaplessMode,\n                  isFirstItem: this.hls.isFirstItem,\n                  itemID: (((_a = this.hls.reportingAgent) === null || _a === void 0 ? void 0 : _a.SessionID) || guid()) + '-' + this.rtcEventItemId(),\n              });\n              this.logger.qe({\n                  critical: true,\n                  name: 'gapless',\n                  data: {\n                      isGapless: this.hls.inGaplessMode,\n                      isAudioOnly: this.hls.inGaplessMode,\n                      isFirstItem: this.hls.isFirstItem,\n                      sessionId: this.hls.sessionID,\n                      itemId: this.rtcEventItemId(),\n                  },\n              });\n          }\n          handleSeek(event) {\n              this.logger.trace(loggerName$4, `RTC seek event: ${event}`);\n              if (event === 'SEEKING') {\n                  this.isSeeking = true;\n                  this.seekStart = Date.now();\n              }\n              else if (event === 'SEEKED') {\n                  // seeked update store\n                  this.isSeeking = false;\n                  let latency = 0;\n                  if (this.seekStart) {\n                      latency = Date.now() - this.seekStart;\n                  }\n                  this.seekStart = null;\n                  this.logger.trace(loggerName$4, `RTC seeked, latency=${latency}`);\n                  this.rtcStore.updateSeeked(this.rtcEventItemId(true), { latency: latency });\n              }\n          }\n          handleDesiredRateChanged(oldRate, newRate) {\n              if (newRate === 0 || (Math.abs(oldRate) > 1 && Math.abs(newRate) > 1)) {\n                  /* Desired rate to actual rate transition is immediate for the following\n                      - any rate to 0\n                      - between any trick play rates (2x <-> 4x etc.)\n                    So, update the store right away.\n                  */\n                  this.logger.trace(loggerName$4, `RTC rate changed oldRate=${oldRate} newRate=${newRate}`);\n                  this.logger.qe({ critical: true, name: 'rateChanged', data: { oldRate, newRate } });\n                  this.rtcStore.updateRateChanged(this.rtcEventItemId(true), {\n                      rate: newRate,\n                      latency: 0,\n                      mediaDur: this.hls.bufferedDuration,\n                      currentTime: this.hls.realCurrentTime,\n                      url: this.levelSwitchingUrl,\n                  });\n                  this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.PlayRateChanged);\n              }\n              else if (oldRate !== 1 && newRate === 1) {\n                  // moving from pause/trickplay to playing rate\n                  this.playStart = Date.now();\n              }\n              /* Save the desired rate and wait for playback to switch to that rate (store update happens later for those cases) */\n              this.oldRate = oldRate;\n              this.newRate = newRate;\n          }\n          handleVariantBufferAppended(timestampOffset, totalBytes) {\n              this.logger.trace(loggerName$4, 'RTC Variant Buffer Appended');\n              let latency = 0;\n              if (timestampOffset) {\n                  latency = Date.now() - timestampOffset;\n              }\n              this.rtcStore.updateBufferAppended(this.rtcEventItemId(), { latency: latency, size: totalBytes });\n          }\n          handleStalled(stallInfo, bufferLen) {\n              this.logger.trace(loggerName$4, 'Stall Info data=%o', stallInfo);\n              const data = { type: stallInfo.type, stallDurationMs: stallInfo.stallDurationMs, bufferLen: bufferLen, mediaDur: this.hls.bufferedDuration };\n              const state = this.rtcQuery.getEntity(this.rtcEventItemId(true)).sessionControlRecord.state;\n              if (stallInfo.type === StallType.LowBuffer || (stallInfo.type === StallType.Seek && stallInfo.isLowBufferStall)) {\n                  // Low Buffer Stall\n                  if (state !== 'RTC_STATE_PLAY') {\n                      // don't report stall events if we're not playing\n                      this.logger.info(loggerName$4, `skipping low buffer stall event because we're not playing, state: ${state}`);\n                  }\n                  else {\n                      this.rtcStore.updateBufferStalled(this.rtcEventItemId(true), data);\n                      this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.PlayStalled);\n                  }\n              }\n              else {\n                  // High Buffer Stall\n                  if (state !== 'RTC_STATE_PLAY') {\n                      // don't report stall events if we're not playing\n                      this.logger.info(loggerName$4, `skipping high buffer stall event because we're not playing, state: ${state}`);\n                  }\n                  else {\n                      this.rtcStore.updateMediaEngineStalled(this.rtcEventItemId(true), data);\n                      this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.MediaEngineStalled);\n                  }\n              }\n          }\n          handlePlaybackInfo(droppedVideoFrames, decodedFrameCount) {\n              this.logger.trace(loggerName$4, `RTC Playback Info, droppedVideoFrames=${droppedVideoFrames}, decodedFrameCount=${decodedFrameCount}`);\n              this.rtcStore.updatePlaybackInfo(this.rtcEventItemId(true), { droppedVideoFrames: droppedVideoFrames, decodedFrameCount: decodedFrameCount });\n              this.accessLog.updatePlaybackInfo(this.rtcEventItemId(true), { droppedVideoFrames: droppedVideoFrames, decodedFrameCount: decodedFrameCount });\n          }\n          checkMediaOptionType(mediaOptionType) {\n              if (mediaOptionType === MediaOptionType.Variant || mediaOptionType === MediaOptionType.AltAudio) {\n                  return true;\n              }\n              else {\n                  this.logger.error(loggerName$4, 'Should not have media option type = \"%s\" in RTC', MediaOptionNames[mediaOptionType]);\n                  return false;\n              }\n          }\n          // Return currently playing id or loading item id if preloading.\n          // Force return playing id if forcePlayingId is set to true.\n          rtcEventItemId(forcePlayingId = false) {\n              if (this.hls.isPreloading) {\n                  if (forcePlayingId) {\n                      return this.hls.playingItem.itemId;\n                  }\n                  return this.hls.loadingItem.itemId;\n              }\n              return this.hls.currentItem.itemId;\n          }\n          subscribeAndUpdateStore() {\n              this.hls.publicQueries$\n                  .pipe(switchMap(([, mediaElementQuery]) => {\n                  return this.mediaElementQueryListener(mediaElementQuery);\n              }), takeUntil(this.destroy$))\n                  .subscribe();\n              this.hls.itemQueue.activeItemById$\n                  .pipe(tap((item) => {\n                  var _a, _b;\n                  if (item) {\n                      // if this is an internal build, always send RTC\n                      // if D&U flag is true, use the configuration\n                      // if there is no userInfo use the configuration\n                      let enableRtc = false;\n                      if (this.hls.userInfo) {\n                          if (this.hls.userInfo.internalBuild) {\n                              enableRtc = true;\n                          }\n                          else if (this.hls.userInfo.diagnosticsAndUsage) {\n                              enableRtc = this.config.enableRtcReporting;\n                          }\n                      }\n                      else {\n                          enableRtc = this.config.enableRtcReporting;\n                      }\n                      if (enableRtc) {\n                          // set reporting agent.\n                          const reportingAgent = this.hls.reportingAgent;\n                          if (reportingAgent) {\n                              this.rtcComponent.setReportingAgent(reportingAgent);\n                              this.logger.qe({ critical: true, name: 'rtcStart', data: { baseSessionId: reportingAgent.SessionID, itemId: (_a = this.hls.itemQueue.activeItem) === null || _a === void 0 ? void 0 : _a.itemId } });\n                          }\n                          else {\n                              this.logger.warn(loggerName$4, '[RTCA] - Reporting is enabled but reportingAgent is null');\n                          }\n                      }\n                      else {\n                          // RTC is disabled.\n                          this.rtcComponent.setReportingAgent(null);\n                          this.logger.info(loggerName$4, '[RTCA] - Reporting is disabled');\n                      }\n                      this.serverInfoInstance = null;\n                      // create new entity with item.itemId\n                      const id = item.itemId;\n                      this.rtcStore.createEntity(id);\n                      // if this is the first item or we are not in gapless mode, start the periodic timer\n                      if (this.hls.isFirstItem || !this.hls.inGaplessMode) {\n                          this.setPeriodic(id);\n                      }\n                      this.logger.trace(`RTC Manifest loading: ${(_b = this.hls.itemQueue.activeItem) === null || _b === void 0 ? void 0 : _b.url}`);\n                  }\n              }), takeUntil(this.destroy$))\n                  .subscribe();\n          }\n          itemTransitioned(oldItem, newItem) {\n              // item transitioned\n              this.logger.trace(loggerName$4, `RTC Item transitioned oldItem=${oldItem} newItem=${newItem}`);\n              this.rtcStore.updateVariantEnd(oldItem, { currentTime: this.hls.realCurrentTime });\n              this.sendAndFinalize(oldItem, RTCEventGroup.VariantEnded);\n              this.rtcStore.updatePeriodic(oldItem, true);\n              this.sendAndFinalize(oldItem, RTCEventGroup.Periodic);\n              this.rtcStore.updateEnded(oldItem);\n              this.sendAndFinalize(oldItem, RTCEventGroup.PlayEnded);\n              // attach/subscribe to timer for periodic events. Note set periodic calls clearPeriodic\n              this.setPeriodic(newItem);\n          }\n          mediaElementQueryListener(mediaElementQuery) {\n              const playingSource$ = mediaElementQuery.gotPlaying$.pipe(tap((playing) => {\n                  if (playing) {\n                      const oldRate = this.oldRate;\n                      const newRate = this.newRate || 1; // set 1 for default cases, e.g. autoplay\n                      if (Math.abs(oldRate) > 1 && Math.abs(newRate) > 1) {\n                          return; // Ignore gotPlaying notifications for transition between trick play rates\n                      }\n                      this.logger.info(loggerName$4, `RTC rate changed oldRate=${oldRate} newRate=${newRate}`);\n                      this.logger.qe({ critical: true, name: 'rateChanged', data: { oldRate, newRate } });\n                      this.rtcStore.updateCanPlay(this.rtcEventItemId(true), { mediaDur: this.hls.bufferedDuration });\n                      this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.PlayLikelyToKeepUp);\n                      this.rtcStore.updateRateChanged(this.rtcEventItemId(true), {\n                          rate: newRate,\n                          latency: isFiniteNumber(this.playStart) ? Date.now() - this.playStart : 0,\n                          mediaDur: this.hls.bufferedDuration,\n                          currentTime: this.hls.realCurrentTime,\n                          url: this.levelSwitchingUrl,\n                      });\n                      this.sendAndFinalize(this.rtcEventItemId(true), RTCEventGroup.PlayRateChanged);\n                  }\n              }));\n              return playingSource$;\n          }\n          // Event based\n          registerForEvents() {\n              const target = fromEventTarget(this.hls, this);\n              merge(target.event(HlsEvent.KEY_REQUEST_STARTED, this.keyRequestStarted, this), target.event(HlsEvent.KEY_LOADED, this.keyLoaded, this)).pipe(takeUntil(this.destroy$)).subscribe();\n          }\n          keyRequestStarted(data) {\n              this.logger.trace(loggerName$4, 'RTC key request started %o', data);\n              data.timestamp = Date.now();\n              this.rtcStore.updateLicenseChallengeRequested(this.rtcEventItemId(), data);\n          }\n          keyLoaded(data) {\n              this.logger.trace(loggerName$4, 'RTC key loaded, data: %o', data);\n              data.timestamp = Date.now();\n              data.currentTime = this.hls.realCurrentTime;\n              this.rtcStore.updateSegmentKeyLoaded(this.rtcEventItemId(), data);\n          }\n          // End of Event based\n          // Key session handler methods\n          licenseChallengeReceived(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseChallenge received data: %o', data);\n              this.rtcStore.updateLicenseChallengeReceived(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri });\n          }\n          licenseChallengeSubmitted(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseChallenge submitted data: %o', data);\n              this.rtcStore.updateLicenseChallengeSubmitted(this.rtcEventItemId(), { timestamp: Date.now(), keyFormat: data.keyFormat, keyuri: data.keyuri });\n          }\n          licenseChallengeCreated(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseChallenge created data: %o', data);\n              this.rtcStore.updateLicenseChallengeCreated(this.rtcEventItemId(), { timestamp: Date.now(), cdmVersion: data.cdmVersion, keyuri: data.keyuri });\n              this.rtcStore.updateLicenseResponseRequested(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri }); // both licenseChallengeCreated and licenseResponseRequested happen simultaneouly\n          }\n          licenseResponseSubmitted(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseResponse submitted data: %o', data);\n              this.rtcStore.updateLicenseResponseReceived(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri }); // both licenseResponseReceived and licenseResponseSubmitted happen simultaneouly\n              this.rtcStore.updateLicenseResponseSubmitted(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri });\n          }\n          licenseResponseProcessed(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseResponse processed data: %o', data);\n              this.rtcStore.updateLicenseResponseProcessed(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri, currentTime: this.hls.realCurrentTime });\n              this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.KeySessionComplete);\n          }\n          licenseChallengeError(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseChallenge error data: %o', data);\n              this.rtcStore.updateLicenseChallengeError(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri });\n              this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.KeySessionComplete);\n          }\n          licenseResponseError(data) {\n              this.logger.trace(loggerName$4, 'RTC licenseResponse error data: %o', data);\n              this.rtcStore.updateLicenseResponseError(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri });\n              this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.KeySessionComplete);\n          }\n          keyAborted(data) {\n              var _a;\n              this.logger.trace(loggerName$4, 'RTC key aborted data: %o', data);\n              if (((_a = this.rtcQuery.getEntity(this.rtcEventItemId())) === null || _a === void 0 ? void 0 : _a.sessionControlRecord.activeKeySessions[data.keyuri]) != null) {\n                  this.rtcStore.updateKeyAborted(this.rtcEventItemId(), { timestamp: Date.now(), keyuri: data.keyuri });\n                  this.sendAndFinalize(this.rtcEventItemId(), RTCEventGroup.KeySessionComplete);\n              }\n              else {\n                  this.logger.warn(`keyAbort called without active key session ${redactUrl(data.keyuri)}`);\n              }\n          }\n          // End of key session handler methods\n          setPeriodic(id) {\n              this.clearPeriodic();\n              this.intervalFunc = setInterval(this.handlePeriodic.bind(this, id), this.periodicInterval);\n          }\n          handlePeriodic(id) {\n              this.logger.trace(loggerName$4, `sendPeriodic id=${id}`);\n              this.rtcStore.updatePeriodic(id, false);\n              this.sendAndFinalize(id, RTCEventGroup.Periodic);\n          }\n          clearPeriodic() {\n              if (this.intervalFunc) {\n                  clearInterval(this.intervalFunc);\n              }\n              this.intervalFunc = null;\n          }\n          sendAndFinalize(id, rtcEvent) {\n              this.accessLog.addPlayTime(id);\n              switch (rtcEvent) {\n                  case RTCEventGroup.PlayEnded:\n                      this.rtcComponent.sendPlayEnded(id);\n                      break;\n                  case RTCEventGroup.Periodic:\n                      this.rtcComponent.sendPeriodic(id);\n                      break;\n                  case RTCEventGroup.PlayStalled:\n                      this.accessLog.updateStallCount(id);\n                      this.rtcComponent.sendPlayStalled(id);\n                      break;\n                  case RTCEventGroup.KeySessionComplete:\n                      this.rtcComponent.sendKeySessionComplete(id);\n                      break;\n                  case RTCEventGroup.PlayLikelyToKeepUp:\n                      this.accessLog.updateCanPlay(id);\n                      this.rtcComponent.sendPlayLikelyToKeepUp(id);\n                      break;\n                  case RTCEventGroup.PlayRateChanged:\n                      this.rtcComponent.sendPlayRateChange(id);\n                      break;\n                  case RTCEventGroup.PlayError:\n                      this.accessLog.addToErrorLog(id, 'mediaError');\n                      this.rtcComponent.sendPlayError(id);\n                      break;\n                  case RTCEventGroup.MediaEngineStalled:\n                      this.accessLog.updateMediaEngineStallCount(id);\n                      this.rtcComponent.sendMediaEngineStalled(id);\n                      break;\n                  case RTCEventGroup.SwitchComplete:\n                      this.accessLog.addToAccessLog(id);\n                      this.rtcComponent.sendSwitchComplete(id);\n                      break;\n                  case RTCEventGroup.VariantEnded:\n                      this.rtcComponent.sendVariantEnded(id);\n                      break;\n                  case RTCEventGroup.NwError:\n                      this.accessLog.addToErrorLog(id, 'networkError');\n                      this.rtcComponent.sendNwError(id);\n                      break;\n                  default:\n                      this.logger.error(loggerName$4, `Unknown rtc event eventGroupId:${id}`);\n                      return;\n              }\n              this.rtcStore.finalize(id, rtcEvent);\n          }\n      }\n    \n      const genericTimeWeightedAggregation = (power) => {\n          return (entries, windowStartTimestamp) => {\n              let totalValue = 0;\n              let totalWeight = 0;\n              for (const { timestamp, value } of entries) {\n                  // Math.max(0, ...) to guard against privacy.resistFingerprinting or privacy.reduceTimerPrecision,\n                  //   which may leave expired entries in the array.\n                  const weight = Math.pow(Math.max(0, timestamp - windowStartTimestamp) / 1000, power);\n                  totalValue += weight * value;\n                  totalWeight += weight;\n              }\n              return totalValue / totalWeight;\n          };\n      };\n      const AggregationImplementations = {\n          'uniform-time-weighted': genericTimeWeightedAggregation(0),\n          'linear-time-weighted': genericTimeWeightedAggregation(1),\n          'quadratic-time-weighted': genericTimeWeightedAggregation(2),\n      };\n    \n      /**\n       * Returns a new array of intervals where overlapping intervals are joined together\n       *   into non-overlapping intervals.\n       * @param intervals An array of intervals\n       * @param join A function that takes in two overlapping intervals and joins them\n       *\n       * @note this function only joins strict overlaps, interval pairs such as ((1, 2), (2, 3))\n       *   are not joined.\n       */\n      function accumulateBW(intervals) {\n          const sorted_intervals = [...intervals].sort((a, b) => {\n              if (a.start !== b.start) {\n                  return a.start - b.start;\n              }\n              else {\n                  return a.end - b.end;\n              }\n          });\n          const result = [];\n          const insertEntry = function (arr, entry) {\n              if (!arr.length) {\n                  arr.push(entry);\n                  return;\n              }\n              for (let i = 0; i < arr.length; i++) {\n                  if (arr[i].start > entry.start || (arr[i].start === entry.start && arr[i].end > entry.end)) {\n                      arr.splice(i, 0, entry);\n                      break;\n                  }\n              }\n          };\n          while (sorted_intervals.length) {\n              const interval = sorted_intervals[0];\n              sorted_intervals.shift();\n              let lastInterval;\n              if (result.length) {\n                  lastInterval = result[result.length - 1];\n              }\n              if (result.length === 0 || lastInterval.end <= interval.start) {\n                  // No overlap\n                  result.push(interval);\n              }\n              else if (interval.start === lastInterval.start) {\n                  // Overlap with same start\n                  if (interval.end === lastInterval.end) {\n                      // same end also .. so just accumulate\n                      lastInterval.bitsPerSec += interval.bitsPerSec;\n                  }\n                  else if (!(interval.end < lastInterval.end)) {\n                      // End of interval in consideration is larger than last interval.\n                      // Accumulate for the overlap.  create an new entry for\n                      // extended part and insert it back in sorted entries.\n                      lastInterval.bitsPerSec += interval.bitsPerSec;\n                      interval.start = lastInterval.end;\n                      insertEntry(sorted_intervals, interval);\n                  }\n              }\n              else {\n                  // there is initial part that does not overlap\n                  const prevend = lastInterval.end;\n                  const prevBitsPerSec = lastInterval.bitsPerSec;\n                  lastInterval.end = interval.start;\n                  // make a new entry for the overlap\n                  const entry = {\n                      start: interval.start,\n                      end: Math.min(prevend, interval.end),\n                      bitsPerSec: interval.bitsPerSec + prevBitsPerSec,\n                  };\n                  result.push(entry);\n                  if (prevend !== interval.end) {\n                      // create new entry for the extended part and insert it back\n                      // in sorted entries.\n                      let start = 0, end = 0, bitsPerSec = 0;\n                      if (prevend < interval.end) {\n                          start = prevend;\n                          end = interval.end;\n                          bitsPerSec = interval.bitsPerSec;\n                      }\n                      else {\n                          start = interval.end;\n                          end = prevend;\n                          bitsPerSec = prevBitsPerSec;\n                      }\n                      const newEntry = { start, end, bitsPerSec };\n                      insertEntry(sorted_intervals, newEntry);\n                  }\n              }\n          }\n          return result;\n      }\n    \n      class HistoryBasedBandwidthEstimator {\n          constructor(windowSize, aggregationMethod = 'quadratic-time-weighted', initValue = {\n              avgLatencyMs: NaN,\n              avgBandwidth: NaN,\n          }) {\n              this.windowSize = windowSize;\n              this.aggregationMethod = aggregationMethod;\n              this.latencyEntries = [];\n              this.bandwidthEntries = [];\n              this.minEntries = 1;\n              this.cleanUpExpiredEntries = this.cleanUpExpiredEntries.bind(this);\n              this.bwSubject = new BehaviorSubject(initValue);\n          }\n          get estimate$() {\n              return this.bwSubject.asObservable();\n          }\n          record(details) {\n              // logger.debug(`Recording Bandwidth entry: ${JSON.stringify(details)}`);\n              const { trequest, tfirst, tload, bitsDownloaded } = details;\n              if (trequest === tload) {\n                  return;\n              }\n              this.recordLatency(trequest, tfirst);\n              // tfirst tends to be delayed in the beginning of playback, which\n              // inflates bandwidth estimation (especially for small downloads)\n              // Thus we use trequest to get a more stable measurement of\n              // bandwidth. Note that this will decrease the bandwidth\n              // estimation by a little (~3% on a 40Mbps network at the office).\n              this.recordBandwidth(trequest, tload, (bitsDownloaded * 1000) / (tload - trequest));\n              if (this.bwSubject.closed) {\n                  return;\n              }\n              const estimate = this.getEstimate();\n              this.bwSubject.next(estimate);\n          }\n          getEstimate() {\n              if (this.latencyEntries.length < this.minEntries) {\n                  return {\n                      avgLatencyMs: NaN,\n                      avgBandwidth: NaN,\n                  };\n              }\n              const windowStartTimestamp = performance.now() - this.windowSize;\n              const aggregationFn = AggregationImplementations[this.aggregationMethod];\n              const latencyEntries = this.latencyEntries.map(({ start, end }) => ({\n                  timestamp: end,\n                  value: end - start,\n                  duration: 1,\n              }));\n              this.bandwidthEntries = accumulateBW(this.bandwidthEntries);\n              const bandwidthEntries = this.bandwidthEntries.map(({ start, end, bitsPerSec }) => ({\n                  timestamp: end,\n                  duration: 1,\n                  value: bitsPerSec, // bits\n              }));\n              return {\n                  avgLatencyMs: aggregationFn(latencyEntries, windowStartTimestamp),\n                  avgBandwidth: aggregationFn(bandwidthEntries, windowStartTimestamp),\n              };\n          }\n          getLatest() {\n              if (this.latencyEntries.length === 0) {\n                  return {\n                      avgLatencyMs: NaN,\n                      avgBandwidth: NaN,\n                  };\n              }\n              const lastLatency = this.latencyEntries[this.latencyEntries.length - 1];\n              const lastBw = this.bandwidthEntries[this.bandwidthEntries.length - 1];\n              return {\n                  avgLatencyMs: lastLatency.end - lastLatency.start,\n                  avgBandwidth: lastBw.bitsPerSec,\n              };\n          }\n          recordLatency(start, end) {\n              this.latencyEntries.push({ start, end });\n              this.updateCleanupTimeout(end);\n          }\n          recordBandwidth(start, end, bitsPerSec) {\n              this.bandwidthEntries.push({ start, end, bitsPerSec });\n              this.updateCleanupTimeout(end);\n          }\n          setCleanupTimeout(cleanupTimestamp) {\n              this.cleanupTimeout = setTimeout(this.cleanUpExpiredEntries, Math.max(cleanupTimestamp - performance.now(), 0));\n              this.cleanupTimestamp = cleanupTimestamp;\n          }\n          clearCleanupTimeout() {\n              if (typeof this.cleanupTimeout !== 'undefined') {\n                  clearTimeout(this.cleanupTimeout);\n                  this.cleanupTimeout = undefined;\n              }\n              this.cleanupTimestamp = undefined;\n          }\n          updateCleanupTimeout(timestamp) {\n              const cleanupTimestamp = timestamp + this.windowSize;\n              if (!this.cleanupTimestamp || cleanupTimestamp < this.cleanupTimestamp) {\n                  this.clearCleanupTimeout();\n                  this.setCleanupTimeout(cleanupTimestamp);\n              }\n          }\n          cleanUpExpiredEntries() {\n              this.clearCleanupTimeout();\n              const windowStartTimestamp = performance.now() - this.windowSize;\n              this.latencyEntries = this.latencyEntries.filter((entry) => entry.end >= windowStartTimestamp);\n              this.bandwidthEntries = this.bandwidthEntries.filter((entry) => entry.end >= windowStartTimestamp);\n              // during cleanup\n              if (!this.bwSubject.closed) {\n                  this.bwSubject.next(this.getEstimate());\n              }\n              if (this.latencyEntries.length > 0 || this.bandwidthEntries.length > 0) {\n                  const timestampOfEarliestEntry = Math.min(...this.latencyEntries.map((entry) => entry.end), ...this.bandwidthEntries.map((entry) => entry.end));\n                  this.updateCleanupTimeout(timestampOfEarliestEntry);\n              }\n          }\n          destroy() {\n              this.clearCleanupTimeout();\n          }\n      }\n    \n      /**\n       * Helper functions that deal with storing data on device storage.\n       */\n      const PersistStats = {\n          setCombinedEstimate: function (hlsStorage, estimate, serviceName) {\n              const logger = getLogger();\n              if (typeof hlsStorage.storage.set === 'undefined') {\n                  logger.warn('storage.set is not supported! Not persisting bandwidth estimates');\n                  return;\n              }\n              // splitting into two different records\n              const bwStorageKey = hlsStorage.bandwidthHistoryStorageKey;\n              const bwEstimate = { avgLatencyMs: estimate.avgLatencyMs, avgBandwidth: estimate.avgBandwidth };\n              const bwRecord = Object.assign({}, bwEstimate, { expires: Date.now() + hlsStorage.bandwidthHistoryTTL });\n              try {\n                  hlsStorage.storage.set(bwStorageKey, JSON.stringify(bwRecord));\n              }\n              catch (err) {\n                  logger.warn(`Error stringifying! Not persisting bandwidth estimates: ${err.message}`);\n              }\n              const serviceStats = {\n                  maxDuration: estimate.maxDurationSec,\n                  avgFragParseTimeMs: estimate.avgParseTimeMs,\n                  avgFragBufferCreationDelayMs: estimate.avgBufferCreateMs,\n                  avgPlaylistLoadTimeMs: estimate.avgPlaylistLoadTimeMs,\n                  avgPlaylistParseTimeMs: estimate.avgPlaylistParseTimeMs,\n                  avgInitFragAppendMs: estimate.avgInitFragAppendMs,\n                  avgDataFragAppendMs: estimate.avgDataFragAppendMs,\n              };\n              let storageKey = hlsStorage.storageKeyPrefix;\n              if (serviceName) {\n                  storageKey += serviceName;\n              }\n              try {\n                  hlsStorage.storage.set(storageKey, JSON.stringify(serviceStats));\n              }\n              catch (err) {\n                  logger.warn(`Error stringifying! Not persisting bandwidth estimates: ${err.message}`);\n              }\n          },\n          getCombinedEstimate: function (hlsStorage, serviceName) {\n              const logger = getLogger();\n              let combinedEstimate = {};\n              if (typeof hlsStorage.storage.get === 'undefined') {\n                  logger.warn('storage.get is not supported! unable to retreive bandwidth estimates');\n                  return this.convertStorageJsonToCombinedEstimate(combinedEstimate);\n              }\n              try {\n                  let bwParsed = JSON.parse(hlsStorage.storage.get(hlsStorage.bandwidthHistoryStorageKey));\n                  if ((bwParsed === null || bwParsed === void 0 ? void 0 : bwParsed.expires) && bwParsed.expires < Date.now()) {\n                      bwParsed = null;\n                  }\n                  else {\n                      bwParsed = { avgLatencyMs: bwParsed === null || bwParsed === void 0 ? void 0 : bwParsed.avgLatencyMs, avgBandwidth: bwParsed === null || bwParsed === void 0 ? void 0 : bwParsed.avgBandwidth };\n                  }\n                  combinedEstimate = Object.assign(Object.assign({}, combinedEstimate), bwParsed);\n              }\n              catch (err) {\n                  logger.warn(`Unable to get persisted bandwidth history: ${err.message}`);\n              }\n              let storageKey = hlsStorage.storageKeyPrefix;\n              if (serviceName) {\n                  storageKey += serviceName;\n              }\n              try {\n                  const restEstimateParsed = JSON.parse(hlsStorage.storage.get(storageKey));\n                  combinedEstimate = Object.assign(Object.assign({}, combinedEstimate), restEstimateParsed);\n              }\n              catch (err) {\n                  logger.warn(`Unable to get persisted bandwidth history: ${err.message}`);\n              }\n              return this.convertStorageJsonToCombinedEstimate(combinedEstimate);\n          },\n          convertStorageJsonToCombinedEstimate: function (storageJson) {\n              const combinedEstimate = {\n                  avgLatencyMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgLatencyMs) || NaN,\n                  avgBandwidth: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgBandwidth) || NaN,\n                  maxDurationSec: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.maxDuration) || NaN,\n                  avgParseTimeMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgFragParseTimeMs) || NaN,\n                  avgBufferCreateMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgFragBufferCreationDelayMs) || NaN,\n                  avgPlaylistLoadTimeMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgPlaylistLoadTimeMs) || NaN,\n                  avgPlaylistParseTimeMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgPlaylistParseTimeMs) || NaN,\n                  avgInitFragAppendMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgInitFragAppendMs) || NaN,\n                  avgDataFragAppendMs: (storageJson === null || storageJson === void 0 ? void 0 : storageJson.avgDataFragAppendMs) || NaN,\n              };\n              return combinedEstimate;\n          },\n          getBandwidthEstimate: function (hlsStorage, serviceName) {\n              const estimate = this.getCombinedEstimate(hlsStorage, serviceName);\n              const bwEstimate = { avgLatencyMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgLatencyMs, avgBandwidth: estimate === null || estimate === void 0 ? void 0 : estimate.avgBandwidth };\n              if (!isFiniteNumber(bwEstimate.avgLatencyMs)) {\n                  bwEstimate.avgLatencyMs = NaN;\n              }\n              if (!isFiniteNumber(bwEstimate.avgBandwidth)) {\n                  bwEstimate.avgBandwidth = NaN;\n              }\n              return bwEstimate;\n          },\n          getPlaylistEstimate: function (hlsStorage, serviceName) {\n              const estimate = this.getCombinedEstimate(hlsStorage, serviceName);\n              const playlistEstimate = { avgPlaylistLoadTimeMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgPlaylistLoadTimeMs, avgPlaylistParseTimeMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgPlaylistParseTimeMs };\n              if (!isFiniteNumber(playlistEstimate.avgPlaylistLoadTimeMs)) {\n                  playlistEstimate.avgPlaylistLoadTimeMs = NaN;\n              }\n              if (!isFiniteNumber(playlistEstimate.avgPlaylistParseTimeMs)) {\n                  playlistEstimate.avgPlaylistParseTimeMs = NaN;\n              }\n              return playlistEstimate;\n          },\n          getFragEstimate: function (hlsStorage, serviceName) {\n              const estimate = this.getCombinedEstimate(hlsStorage, serviceName);\n              const fragEstimate = { maxDurationSec: estimate === null || estimate === void 0 ? void 0 : estimate.maxDurationSec, avgParseTimeMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgParseTimeMs };\n              if (!isFiniteNumber(fragEstimate.maxDurationSec)) {\n                  fragEstimate.maxDurationSec = NaN;\n              }\n              if (!isFiniteNumber(fragEstimate.avgParseTimeMs)) {\n                  fragEstimate.avgParseTimeMs = NaN;\n              }\n              return fragEstimate;\n          },\n          getBufferEstimate: function (hlsStorage, serviceName) {\n              const estimate = this.getCombinedEstimate(hlsStorage, serviceName);\n              const bufferEstimate = {\n                  avgBufferCreateMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgBufferCreateMs,\n                  avgInitFragAppendMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgInitFragAppendMs,\n                  avgDataFragAppendMs: estimate === null || estimate === void 0 ? void 0 : estimate.avgDataFragAppendMs,\n              };\n              if (!isFiniteNumber(bufferEstimate.avgBufferCreateMs)) {\n                  bufferEstimate.avgBufferCreateMs = NaN;\n              }\n              if (!isFiniteNumber(bufferEstimate.avgInitFragAppendMs)) {\n                  bufferEstimate.avgInitFragAppendMs = NaN;\n              }\n              if (!isFiniteNumber(bufferEstimate.avgDataFragAppendMs)) {\n                  bufferEstimate.avgDataFragAppendMs = NaN;\n              }\n              return bufferEstimate;\n          },\n      };\n      var PersistStats$1 = PersistStats;\n    \n      // Accumulator for doing simple stats\n      class SimpleAccumulator {\n          constructor(_minSamples = 0) {\n              this._minSamples = _minSamples;\n              this._sum = 0;\n              this._max = Number.NEGATIVE_INFINITY;\n              this._numSamples = 0;\n          }\n          get avg() {\n              if (this._numSamples < this._minSamples) {\n                  return NaN;\n              }\n              return this._sum / this._numSamples;\n          }\n          get max() {\n              return this.count > 0 ? this._max : NaN;\n          }\n          get count() {\n              return this._numSamples;\n          }\n          reset() {\n              this._sum = 0;\n              this._numSamples = 0;\n              this._max = Number.NEGATIVE_INFINITY;\n          }\n          add(value) {\n              this._sum += value;\n              this._max = Math.max(this._max, value);\n              ++this._numSamples;\n          }\n      }\n    \n      /**\n       * @brief Query interface to the stats store\n       */\n      class StatsQuery extends QueryEntity {\n          constructor(statsStore, id) {\n              super(statsStore);\n              this.id = id;\n          }\n          getBandwidthEstimate(hlsStorage, serviceName) {\n              var _a;\n              const bwEstimate = Object.assign({}, (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.bandwidthEstimate);\n              if (isFiniteNumber(bwEstimate.avgBandwidth) && isFiniteNumber(bwEstimate.avgLatencyMs)) {\n                  return bwEstimate;\n              }\n              // fallback: check in persistent storage\n              if (hlsStorage) {\n                  const parsedEstimate = PersistStats.getBandwidthEstimate(hlsStorage, serviceName);\n                  if (!isFiniteNumber(bwEstimate.avgBandwidth)) {\n                      bwEstimate.avgBandwidth = parsedEstimate.avgBandwidth;\n                  }\n                  if (!isFiniteNumber(bwEstimate.avgLatencyMs)) {\n                      bwEstimate.avgLatencyMs = parsedEstimate.avgLatencyMs;\n                  }\n              }\n              return bwEstimate;\n          }\n          getPlaylistEstimate(hlsStorage, serviceName) {\n              var _a;\n              const playlistEstimate = Object.assign({}, (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.playlistEstimate);\n              const checkValidity = (playlistEstimate) => {\n                  return isFiniteNumber(playlistEstimate.avgPlaylistLoadTimeMs) && isFiniteNumber(playlistEstimate.avgPlaylistParseTimeMs);\n              };\n              if (checkValidity(playlistEstimate)) {\n                  return playlistEstimate;\n              }\n              // fallback: check in persistent storage\n              if (hlsStorage) {\n                  const parsedEstimate = PersistStats.getPlaylistEstimate(hlsStorage, serviceName);\n                  if (!isFiniteNumber(playlistEstimate.avgPlaylistLoadTimeMs)) {\n                      playlistEstimate.avgPlaylistLoadTimeMs = parsedEstimate.avgPlaylistLoadTimeMs;\n                  }\n                  if (!isFiniteNumber(playlistEstimate.avgPlaylistParseTimeMs)) {\n                      playlistEstimate.avgPlaylistParseTimeMs = parsedEstimate.avgPlaylistParseTimeMs;\n                  }\n                  if (checkValidity(playlistEstimate)) {\n                      return playlistEstimate;\n                  }\n                  //pick config default\n                  if (!isFiniteNumber(playlistEstimate.avgPlaylistLoadTimeMs)) {\n                      playlistEstimate.avgPlaylistLoadTimeMs = hlsStorage.statDefaults.playlistLoadTimeMs;\n                  }\n                  if (!isFiniteNumber(playlistEstimate.avgPlaylistParseTimeMs)) {\n                      playlistEstimate.avgPlaylistParseTimeMs = hlsStorage.statDefaults.playlistParseTimeMs;\n                  }\n              }\n              return playlistEstimate;\n          }\n          getBufferEstimate(hlsStorage, serviceName) {\n              var _a;\n              const bufferEstimate = Object.assign({}, (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.bufferEstimate);\n              const checkValidity = (bufferEstimate) => {\n                  return isFiniteNumber(bufferEstimate.avgBufferCreateMs) && isFiniteNumber(bufferEstimate.avgDataFragAppendMs) && isFiniteNumber(bufferEstimate.avgInitFragAppendMs);\n              };\n              if (checkValidity(bufferEstimate)) {\n                  return bufferEstimate;\n              }\n              // fallback: check in persistent storage\n              if (hlsStorage) {\n                  const parsedEstimate = PersistStats.getBufferEstimate(hlsStorage, serviceName);\n                  if (!isFiniteNumber(bufferEstimate.avgBufferCreateMs)) {\n                      bufferEstimate.avgBufferCreateMs = parsedEstimate.avgBufferCreateMs;\n                  }\n                  if (!isFiniteNumber(bufferEstimate.avgDataFragAppendMs)) {\n                      bufferEstimate.avgDataFragAppendMs = parsedEstimate.avgDataFragAppendMs;\n                  }\n                  if (!isFiniteNumber(bufferEstimate.avgInitFragAppendMs)) {\n                      bufferEstimate.avgInitFragAppendMs = parsedEstimate.avgInitFragAppendMs;\n                  }\n                  if (checkValidity(bufferEstimate)) {\n                      return bufferEstimate;\n                  }\n                  //pick config default\n                  if (!isFiniteNumber(bufferEstimate.avgBufferCreateMs)) {\n                      bufferEstimate.avgBufferCreateMs = hlsStorage.statDefaults.fragBufferCreationDelayMs;\n                  }\n                  if (!isFiniteNumber(bufferEstimate.avgDataFragAppendMs)) {\n                      bufferEstimate.avgDataFragAppendMs = hlsStorage.statDefaults.dataFragAppendMs;\n                  }\n                  if (!isFiniteNumber(bufferEstimate.avgInitFragAppendMs)) {\n                      bufferEstimate.avgInitFragAppendMs = hlsStorage.statDefaults.initFragAppendMs;\n                  }\n              }\n              return bufferEstimate;\n          }\n          getFragEstimate(hlsStorage, serviceName) {\n              var _a;\n              const fragEstimate = Object.assign({}, (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.fragEstimate);\n              const checkValidity = (fragEstimate) => {\n                  return isFiniteNumber(fragEstimate.maxDurationSec) && isFiniteNumber(fragEstimate.avgParseTimeMs);\n              };\n              if (checkValidity(fragEstimate)) {\n                  return fragEstimate;\n              }\n              // fallback: check in persistent storage\n              if (hlsStorage) {\n                  const parsedEstimate = PersistStats.getFragEstimate(hlsStorage, serviceName);\n                  if (!isFiniteNumber(fragEstimate.maxDurationSec)) {\n                      fragEstimate.maxDurationSec = parsedEstimate.maxDurationSec;\n                  }\n                  if (!isFiniteNumber(fragEstimate.avgParseTimeMs)) {\n                      fragEstimate.avgParseTimeMs = parsedEstimate.avgParseTimeMs;\n                  }\n                  if (checkValidity(fragEstimate)) {\n                      return fragEstimate;\n                  }\n                  //pick config default\n                  if (!isFiniteNumber(fragEstimate.maxDurationSec)) {\n                      fragEstimate.maxDurationSec = hlsStorage.defaultTargetDuration;\n                  }\n                  if (!isFiniteNumber(fragEstimate.avgParseTimeMs)) {\n                      fragEstimate.avgParseTimeMs = hlsStorage.statDefaults.fragParseTimeMs;\n                  }\n              }\n              return fragEstimate;\n          }\n          getCombinedEstimate() {\n              return Object.assign(Object.assign(Object.assign(Object.assign({}, this.getFragEstimate()), this.getPlaylistEstimate()), this.getBufferEstimate()), this.getBandwidthEstimate());\n          }\n          // getters\n          get statsEntity() {\n              return this.getEntity(this.id);\n          }\n          get bandwidthSample() {\n              var _a;\n              return (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.bandwidthSample;\n          }\n          get bandwidthStatus() {\n              var _a;\n              return (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.bandwidthStatus;\n          }\n          get fragSample() {\n              var _a;\n              return (_a = this.statsEntity) === null || _a === void 0 ? void 0 : _a.fragSample;\n          }\n          // Aggregated data\n          get bandwidthEstimate$() {\n              return this.selectEntity(this.id, 'bandwidthEstimate');\n          }\n          get fragEstimate$() {\n              return this.selectEntity(this.id, 'fragEstimate');\n          }\n          get playlistEstimate$() {\n              return this.selectEntity(this.id, 'playlistEstimate');\n          }\n          get bufferEstimate$() {\n              return this.selectEntity(this.id, 'bufferEstimate');\n          }\n          // Individual samples\n          get bandwidthSample$() {\n              return this.selectEntity(this.id, ({ bandwidthSample }) => bandwidthSample).pipe(filterNullOrUndefined());\n          }\n          get fragSample$() {\n              return this.selectEntity(this.id, ({ fragSample }) => fragSample).pipe(filterNullOrUndefined());\n          }\n          get playlistSample$() {\n              return this.selectEntity(this.id, ({ playlistSample }) => playlistSample).pipe(filterNullOrUndefined());\n          }\n          get bufferMetric$() {\n              return this.selectEntity(this.id, ({ bufferMetric }) => bufferMetric).pipe(filterNullOrUndefined());\n          }\n      }\n    \n      /**\n       * @brief Backing store for stats\n       */\n      /**\n       * @brief Store that keeps track of stats measured for network requests,\n       * demuxing, and buffering\n       */\n      class StatsStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'stats-store', producerFn: produce_1 });\n          }\n          set statsEntity(statsEntity) {\n              logAction('statsStore.set.stats');\n              applyTransaction(() => {\n                  this.add(statsEntity);\n                  this.setActive(statsEntity.id);\n              });\n          }\n          set playlistSample(playlistSample) {\n              logAction(`stats.set.playlistSample: ${playlistSample}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.playlistSample = playlistSample;\n              });\n          }\n          set bandwidthSample(bandwidthSample) {\n              logAction(`stats.set.bandwidthSample: ${bandwidthSample}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.bandwidthSample = bandwidthSample;\n                  statsEntity.bandwidthStatus.bandwidthSampleCount += 1;\n                  statsEntity.bandwidthStatus.instantBw = (bandwidthSample.loaded * 8000) / (bandwidthSample.tload - bandwidthSample.trequest);\n              });\n          }\n          set fragSample(fragSample) {\n              logAction(`stats.set.fragSample: ${fragSample}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.fragSample = fragSample;\n              });\n          }\n          set bufferMetric(bufferMetric) {\n              logAction(`stats.set.bufferMetric: ${bufferMetric}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.bufferMetric = bufferMetric;\n              });\n          }\n          set bandwidthEstimate(bandwidthEstimate) {\n              logAction(`stats.set.bandwidthEstimate: ${bandwidthEstimate}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.bandwidthEstimate = bandwidthEstimate;\n              });\n          }\n          set fragEstimate(fragEstimate) {\n              logAction(`stats.set.fragEstimate: ${fragEstimate}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.fragEstimate = fragEstimate;\n              });\n          }\n          set playlistEstimate(playlistEstimate) {\n              logAction(`stats.set.playlistEstimate: ${playlistEstimate}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.playlistEstimate = playlistEstimate;\n              });\n          }\n          set bufferEstimate(bufferEstimate) {\n              logAction(`stats.set.bufferEstimate: ${bufferEstimate}`);\n              this.updateActive((statsEntity) => {\n                  statsEntity.bufferEstimate = bufferEstimate;\n              });\n          }\n      }\n    \n      /**\n       * @brief Service for managing stats samples and estimates\n       */\n      class StatsService {\n          constructor(statsStore) {\n              this.statsStore = statsStore;\n          }\n          getQuery() {\n              return new QueryEntity(this.statsStore);\n          }\n          getQueryForItem(itemId) {\n              return new StatsQuery(this.statsStore, itemId);\n          }\n          remove(itemId) {\n              this.statsStore.remove(itemId);\n          }\n          removeAll() {\n              this.statsStore.remove();\n          }\n          setBandwidthSample(bandwidthSample) {\n              this.statsStore.bandwidthSample = bandwidthSample;\n          }\n          setFragSample(fragSample) {\n              this.statsStore.fragSample = fragSample;\n          }\n          setPlaylistSample(playlistSample) {\n              this.statsStore.playlistSample = playlistSample;\n          }\n          setBufferMetric(bufferMetric) {\n              this.statsStore.bufferMetric = bufferMetric;\n          }\n          setBandwidthEstimate(bandwidthEstimate) {\n              this.statsStore.bandwidthEstimate = bandwidthEstimate;\n          }\n          setFragEstimate(fragEstimate) {\n              this.statsStore.fragEstimate = fragEstimate;\n          }\n          setPlaylistEstimate(playlistEstimate) {\n              this.statsStore.playlistEstimate = playlistEstimate;\n          }\n          setBufferEstimate(bufferEstimate) {\n              this.statsStore.bufferEstimate = bufferEstimate;\n          }\n      }\n      const statsStore = new StatsStore();\n      let statsService = null; //\n      const createStatsQuery = (id) => {\n          return new StatsQuery(statsStore, id);\n      };\n      function statsServiceSingleton() {\n          if (!statsService) {\n              statsService = new StatsService(statsStore);\n          }\n          return statsService;\n      }\n      const initializeStatsFunc = (itemId) => {\n          const statsQuery = createStatsQuery(itemId);\n          if (statsQuery.hasEntity(itemId)) {\n              return of(statsQuery);\n          }\n          return addStatsEntity(statsStore, itemId);\n      };\n      function addStatsEntity(statsStore, itemId) {\n          logAction('stats.loading');\n          statsStore.setLoading(true);\n          const statsEntity = {\n              id: itemId,\n              // bandwidthSample: { trequest: 0, tfirst: 0, tload: 0, loaded: 0, total: 0, complete: true },\n              bandwidthEstimate: { avgLatencyMs: NaN, avgBandwidth: NaN },\n              bandwidthStatus: { bandwidthSampleCount: 0, instantBw: NaN },\n              // fragSample: { duration: 0, parseTimeMs: 0 },\n              fragEstimate: { maxDurationSec: NaN, avgParseTimeMs: NaN },\n              // playlistSample: { playlistLoadTimeMs: 0, playlistParseTimeMs: 0 },\n              playlistEstimate: { avgPlaylistLoadTimeMs: NaN, avgPlaylistParseTimeMs: NaN },\n              // bufferMetric: {\n              //   fragmentType: MediaOptionType.Variant,\n              //   startInitAppend: 0,\n              //   endInitAppend: 0,\n              //   initBytesAppend: 0,\n              //   startDataAppend: 0,\n              //   endDataAppend: 0,\n              //   dataBytesAppend: 0,\n              //   bufferCreationStart: 0,\n              //   bufferCreationEnd: 0,\n              // },\n              bufferEstimate: {\n                  avgBufferCreateMs: NaN,\n                  avgInitFragAppendMs: NaN,\n                  avgDataFragAppendMs: NaN,\n              },\n          };\n          statsStore.statsEntity = statsEntity;\n          statsStore.setLoading(false);\n          logAction('stats.loaded');\n      }\n      /**\n       * @brief Service that retrieves past stats and seeds\n       * the current sample and add to the store\n       */\n      /*\n      export const initializeStats = () => (pipelineActionSource$: Observable<[RootPlaylistQuery, MediaElementQuery]>) => {\n        return pipelineActionSource$.pipe(\n          tag('stats.initializing'),\n            switchMap(item => {\n            if (!item) return EMPTY;\n    \n            const { itemId } = item;\n            // const configurationQuery = createConfigurationQuery();\n            const statsQuery = createStatsQuery(itemId);\n            if(statsQuery.hasEntity(itemId)) {\n              return of(statsQuery);\n            }\n            statsStore.setLoading(true);\n            return of(item).pipe(\n              map(() => {\n                logAction(`stats.loaded`);\n                // TODO get it from persistent store\n                // or rebuild from configs\n                const statsEntity: StatsEntity = {\n                  id: itemId,\n                  bandwidthSample: {trequest: 0, tparsed: 0, tfirst: 0, tload: 0, loaded: 0},\n                  bandwidthEstimate: {avgLatencyMs: 0, avgBandwidth: 0},\n                  fragSample: { duration: 0, parseTimeMs: 0, bufferCreationDelayMs: 0, bufferTimeMs: 0},\n                  fragEstimate:  { maxDuration: 0, maxParseTimeMs: 0, maxBufferCreationDelayMs: 0, maxBufferTimeMs: 0 },\n                  playlistSample: { playlistLoadTimeMs: 10 },\n                  playlistEstimate: { maxPlaylistLoadTimeMs: 10}\n                };\n                statsStore.statsEntity = statsEntity;\n                return statsQuery;\n              }),\n              finalize(() => {\n                statsStore.setLoading(false);\n              })\n            );\n          }),\n          tag('stats.initialized'),\n        );\n      }\n      */\n    \n      function objectIsEqual(a, b) {\n          if (a === b)\n              return true;\n          if (!a || !b)\n              return false;\n          let same = Object.keys(a).length === Object.keys(b).length;\n          for (const k of Object.keys(a)) {\n              same = same && ((isNaN(a[k]) && isNaN(b[k])) || a[k] === b[k]);\n          }\n          return same;\n      }\n      /**\n         Stats processing Epic. Listens to samples (bandwidth, playlist,\n         frag) and processes the data and sends back estimates to the store\n      */\n      const statsBandwidthProcessingEpic = (config, statsService, logger) => (bandwidthSampleSource$) => {\n          return new Observable((subscriber) => {\n              let historyBasedBandwidthEstimator = new HistoryBasedBandwidthEstimator(config.bandwidthHistoryWindowSize, config.bandwidthHistoryAggregationMethod, { avgLatencyMs: NaN, avgBandwidth: NaN });\n              const estimate$ = historyBasedBandwidthEstimator.estimate$;\n              const sub = merge(\n              // feed the estimator\n              bandwidthSampleSource$.pipe(filter((sample) => sample.complete), tap((sample) => {\n                  logger.qe({\n                      critical: true,\n                      name: 'bandwidthRecordDetails',\n                      data: {\n                          type: MediaOptionNames[sample.mediaOptionType],\n                          observedBitrateExcludingLatency: ((sample.loaded * 8) / (sample.tload - sample.tfirst)) * 1000,\n                          observedBitrate: ((sample.loaded * 8) / (sample.tload - sample.trequest)) * 1000,\n                      },\n                  });\n              }), map((bandwidthSample) => ({\n                  trequest: bandwidthSample.trequest,\n                  tfirst: bandwidthSample.tfirst,\n                  tload: bandwidthSample.tload,\n                  bitsDownloaded: bandwidthSample.loaded * 8,\n              })), tag('statsBandwidthProcessingEpic.in'), switchMap((value) => {\n                  historyBasedBandwidthEstimator.record(value);\n                  return EMPTY;\n              })), estimate$.pipe(distinctUntilChanged(), tag('statsBandwidthProcessingEpic.change'), tap((value) => {\n                  if (statsService) {\n                      statsService.setBandwidthEstimate(value);\n                      logger.qe({ critical: true, name: 'bandwidthEstimate', data: { bandwidthEstimate: value } });\n                  }\n              }))).subscribe(subscriber);\n              return () => {\n                  sub.unsubscribe();\n                  historyBasedBandwidthEstimator.destroy();\n                  historyBasedBandwidthEstimator = undefined;\n              };\n          });\n      };\n      const statsFragProcessingEpic = (config, statsService) => (fragSampleSource$) => {\n          return fragSampleSource$.pipe(tag('statsFragProcessingEpic.in'), scan((acc, sample) => {\n              acc.durationSec.add(sample.durationSec);\n              acc.fragParseMs.add(sample.parseTimeMs);\n              return acc;\n          }, {\n              durationSec: new SimpleAccumulator(),\n              fragParseMs: new SimpleAccumulator(config.minFragmentCount),\n          }), map((value) => ({\n              maxDurationSec: value.durationSec.max,\n              avgParseTimeMs: value.fragParseMs.avg,\n          })), distinctUntilChanged(objectIsEqual), tap((estimate) => statsService.setFragEstimate(estimate)));\n      };\n      const statsPlaylistProcessingEpic = (config, statsService) => (playlistSampleSource$) => {\n          return playlistSampleSource$.pipe(tag('statsPlaylistProcessingEpic.in'), scan((acc, sample) => {\n              acc.playlistLoadTimeMs.add(sample.playlistLoadTimeMs);\n              acc.playlistParseTimeMs.add(sample.playlistParseTimeMs);\n              return acc;\n          }, {\n              playlistLoadTimeMs: new SimpleAccumulator(config.minPlaylistCount),\n              playlistParseTimeMs: new SimpleAccumulator(config.minPlaylistCount),\n          }), map((value) => ({\n              avgPlaylistLoadTimeMs: value.playlistLoadTimeMs.avg,\n              avgPlaylistParseTimeMs: value.playlistParseTimeMs.avg,\n          })), distinctUntilChanged(objectIsEqual), tap((estimate) => {\n              statsService.setPlaylistEstimate(estimate);\n          }));\n      };\n      const statsBufferProcessingEpic = (config, statsService) => (bufferMetricSource$) => {\n          return bufferMetricSource$.pipe(tag('statsBufferMetricProcessingEpic.in'), scan((acc, metric) => {\n              if (isFiniteNumber(metric.bufferCreationStart) && isFiniteNumber(metric.bufferCreationEnd)) {\n                  acc.bufferCreateMs.add(metric.bufferCreationEnd - metric.bufferCreationStart);\n              }\n              if (isFiniteNumber(metric.startInitAppend) && isFiniteNumber(metric.endInitAppend)) {\n                  acc.initFragAppendMs.add(metric.endInitAppend - metric.startInitAppend);\n              }\n              if (isFiniteNumber(metric.startDataAppend) && isFiniteNumber(metric.endDataAppend)) {\n                  acc.dataFragAppendMs.add(metric.endDataAppend - metric.startDataAppend);\n              }\n              return acc;\n          }, {\n              // Seed value\n              bufferCreateMs: new SimpleAccumulator(),\n              initFragAppendMs: new SimpleAccumulator(),\n              dataFragAppendMs: new SimpleAccumulator(config.minFragmentCount),\n          }), map((value) => ({\n              avgBufferCreateMs: value.bufferCreateMs.avg,\n              avgInitFragAppendMs: value.initFragAppendMs.avg,\n              avgDataFragAppendMs: value.dataFragAppendMs.avg,\n          })), distinctUntilChanged(objectIsEqual), tap((estimate) => {\n              statsService.setBufferEstimate(estimate);\n          }));\n      };\n      function statsProcessor(config, statsService, item, logger) {\n          return new Observable((subscriber) => {\n              initializeStatsFunc(item.itemId);\n              const statsQuery = createStatsQuery(item.itemId);\n              const { fragSample$, playlistSample$, bandwidthSample$, bufferMetric$ } = statsQuery;\n              merge(playlistSample$.pipe(observeOn(asyncScheduler), statsPlaylistProcessingEpic(config, statsService)), bandwidthSample$.pipe(observeOn(asyncScheduler), statsBandwidthProcessingEpic(config, statsService, logger)), fragSample$.pipe(observeOn(asyncScheduler), statsFragProcessingEpic(config, statsService)), bufferMetric$.pipe(observeOn(asyncScheduler), statsBufferProcessingEpic(config, statsService)))\n                  .pipe(switchMapTo(EMPTY))\n                  .subscribe(subscriber);\n              return () => {\n                  PersistStats$1.setCombinedEstimate(config, Object.assign(Object.assign(Object.assign(Object.assign({}, statsQuery.getFragEstimate()), statsQuery.getPlaylistEstimate()), statsQuery.getBufferEstimate()), statsQuery.getBandwidthEstimate()), item.serviceName);\n                  statsService.remove(item.itemId);\n              };\n          });\n      }\n    \n      /**\n       * MediaSource helper\n       */\n      function getMediaSource() {\n          return window.MediaSource || window.WebKitMediaSource;\n      }\n    \n      /**\n       * MediaSource helper\n       */\n      function isSupported() {\n          try {\n              const mediaSource = getMediaSource();\n              const sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;\n              const isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n              // if SourceBuffer is exposed ensure its API is valid\n              // safari and old version of Chrome do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n              const sourceBufferValidAPI = !sourceBuffer || (sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function');\n              return !!isTypeSupported && !!sourceBufferValidAPI;\n          }\n          catch (_a) {\n              return false;\n          }\n      }\n    \n      /*\n       * Media Element Helper: Contains wrapper class information for HTMLMediaElement\n       *\n       * \n       */\n      const MediaElementHelper = {\n          isWebkitMediaElement(media) {\n              return 'webkitDroppedFrameCount' in media;\n          },\n          isHtmlVideoElement(media) {\n              return 'getVideoPlaybackQuality' in media;\n          },\n          timeRangeToArray(timeRange) {\n              const rangeArr = [];\n              for (let i = 0; i < timeRange.length; i++) {\n                  rangeArr.push([timeRange.start(i), timeRange.end(i)]);\n              }\n              return rangeArr;\n          },\n      };\n    \n      /*\n       * Access Log Types\n       *\n       * \n       */\n      const loggerName$3 = { name: 'access-log' };\n      class AccessLog {\n          constructor(hls, sessionID) {\n              this.hls = hls;\n              this.sessionID = sessionID;\n              this.rtcQuery = null;\n              this.accessLogData = this.createAccessLogEntry();\n              this.accesslog = [];\n              this.errorlog = [];\n          }\n          destroy() {\n              this.rtcQuery = null;\n              this.accesslog = [];\n              this.errorlog = [];\n              this.accessLogData = undefined;\n              this.accessLogReporter = undefined;\n          }\n          setRTCQuery(query) {\n              this.rtcQuery = query;\n          }\n          setupReporter(appData) {\n              this.accessLogReporter = { SessionID: this.sessionID, ClientName: appData === null || appData === void 0 ? void 0 : appData.clientName, ServiceName: appData === null || appData === void 0 ? void 0 : appData.serviceName };\n          }\n          addPlayTime(itemId) {\n              var _a;\n              const entity = (_a = this.rtcQuery) === null || _a === void 0 ? void 0 : _a.getEntity(itemId);\n              if (!entity) {\n                  return;\n              }\n              const sessionControlRecord = entity.sessionControlRecord;\n              if (sessionControlRecord.state === 'RTC_STATE_PLAY') {\n                  this.accessLogData.PlayTimeWC = (this.accessLogData.PlayTimeWC || 0) + sessionControlRecord.eventStartTime;\n              }\n              getLogger().trace(loggerName$3, 'accessLogData playtime: %d', this.accessLogData.PlayTimeWC);\n          }\n          updatePlaybackInfo(itemId, data) {\n              this.accessLogData.ViFrDr = this.rtcQuery.getEntity(itemId).sessionControlRecord.droppedVideoFrames || 0;\n              getLogger().trace(loggerName$3, 'accessLogData Framedrop: %d', this.accessLogData.ViFrDr);\n          }\n          updateStallCount(itemId) {\n              const state = this.rtcQuery.getEntity(itemId).sessionControlRecord.state;\n              if (state !== 'RTC_STATE_PLAY') {\n                  // don't report stall events if we're not playing\n                  getLogger().info(loggerName$3, `skipping low buffer stall event because we're not playing, state: ${state}`);\n                  return;\n              }\n              this.accessLogData.StallCount++;\n          }\n          updateMediaEngineStallCount(itemId) {\n              const state = this.rtcQuery.getEntity(itemId).sessionControlRecord.state;\n              if (state !== 'RTC_STATE_PLAY') {\n                  // don't report stall events if we're not playing\n                  getLogger().info(loggerName$3, `skipping high buffer stall event because we're not playing, state: ${state}`);\n                  return;\n              }\n              this.accessLogData.MediaEngineStallCount++;\n          }\n          updateCanPlay(itemId) {\n              this.accessLogData.StartupTime = this.rtcQuery.getEntity(itemId).sessionControlRecord.eventStartTime;\n          }\n          updateFragLoaded(itemId, isSeeking, data) {\n              // use only 'main' (muxed) / 'video' (unmuxed) data to calculate below keys\n              if (data.fragType === MediaOptionType.Variant) {\n                  this.accessLogData.NetBytes += data.bytes;\n                  this.accessLogData.ADT += data.adt;\n                  //this._accessLogData.SegmentProcessTime += data.processTime;\n                  const accessLogBitrateStats = this.aggregateFragObserverdBitrate(data, ++this.accessLogData.fragmentCnt, this.accessLogData.NetBytes, this.accessLogData.ADT);\n                  this.accessLogData.OBRLast = accessLogBitrateStats.obrLast;\n                  this.accessLogData.OBRMean = accessLogBitrateStats.obrMean;\n                  this.aggregateFragMinMaxBitrate(this.accessLogData, accessLogBitrateStats.obr);\n                  const currentTime = this.hls.realCurrentTime;\n                  if (currentTime > data.startPTS && !isSeeking) {\n                      this.accessLogData.overdue++;\n                  }\n                  if (this.hasGap(data.startPTS, data.endPTS, this.accessLogData.lastStartPTS, this.accessLogData.lastEndPTS)) {\n                      // New continuous playback stream due to timejump\n                      getLogger().info(loggerName$3, 'summarize stats for seek to startPTS: ' + data.startPTS + 's');\n                      this.addToAccessLog(itemId);\n                  }\n                  if (!this.accessLogData.startPTS) {\n                      // mark first ever fragment start time for fresh access log entry\n                      this.accessLogData.startPTS = data.startPTS;\n                  }\n                  // Remember last loaded fragment start and end time to detect new seek later\n                  this.accessLogData.lastStartPTS = data.startPTS;\n                  this.accessLogData.lastEndPTS = data.endPTS;\n                  // accumulate the 'main' (muxed) / 'video' (unmuxed) bytes & duration to calculate AvgVideoBitrate\n                  this.accessLogData.videoBytes += data.bytes;\n                  this.accessLogData.videoDuration += data.duration;\n              }\n              else if (data.fragType === MediaOptionType.AltAudio) {\n                  // accumulate the 'audio' bytes & duration to calculate AvgAudioBitrate\n                  this.accessLogData.audioBytes += data.bytes;\n                  this.accessLogData.audioDuration += data.duration;\n              }\n              getLogger().trace(loggerName$3, 'Fragloaded, accessLogData=%o', this.accessLogData);\n          }\n          addToAccessLog(itemId) {\n              const varInfo = this.getVariantInfo(itemId);\n              const url = this.rtcQuery.getEntity(itemId).sessionControlRecord.curLevelUrl;\n              const playType = this.rtcQuery.getEntity(itemId).playEndedRecord.PlayType;\n              if (!url || url === '') {\n                  // Too early, fields may be undefined.\n                  return;\n              }\n              const translatedData = this.translateToAccessLogItem(itemId, url, varInfo, playType);\n              if (translatedData) {\n                  const overage = this.accesslog.length - 20;\n                  if (overage > 0) {\n                      this.accesslog.splice(0, overage); // trim access log entries\n                  }\n                  this.accesslog.push(translatedData);\n                  getLogger().trace(loggerName$3, 'accesslog=%o', this.accesslog);\n              }\n              // reset accessLogData after we added an entry to the log\n              this.accessLogData = this.createAccessLogEntry();\n              const recordMediaDur = this.rtcQuery.getEntity(itemId).switchCompleteRecord.MediaDur;\n              this.accessLogData.lastMediaDur = recordMediaDur ? recordMediaDur : this.hls.bufferedDuration;\n          }\n          addToErrorLog(itemId, domain) {\n              var _a;\n              const entity = (_a = this.rtcQuery) === null || _a === void 0 ? void 0 : _a.getEntity(itemId);\n              if (!entity) {\n                  return;\n              }\n              let code;\n              if (domain === 'mediaError') {\n                  code = Number(entity.playErrorRecord.ErrCode);\n              }\n              else {\n                  // else if (networkError)\n                  code = Number(entity.nwErrorRecord.ErrCode);\n              }\n              const errorInfo = { domain, code };\n              const url = entity.sessionControlRecord.curLevelUrl;\n              const translatedData = this.translateToErrorLogItem(itemId, url, errorInfo);\n              if (translatedData) {\n                  const overage = this.errorlog.length - 20;\n                  if (overage > 0) {\n                      this.errorlog.splice(0, overage); // trim error log entries\n                  }\n                  this.errorlog.push(translatedData);\n                  getLogger().trace(loggerName$3, 'errorlog=%o', this.errorlog);\n              }\n          }\n          getAccessLog(itemId) {\n              var _a;\n              const finalAccessLog = this.accesslog.slice(0); // Make a copy of the access log array\n              const entity = (_a = this.rtcQuery) === null || _a === void 0 ? void 0 : _a.getEntity(itemId);\n              if (finalAccessLog && entity) {\n                  // Add the current \"open\" variant entry\n                  const url = entity.sessionControlRecord.curLevelUrl;\n                  if (url && url !== '') {\n                      const varInfo = this.getVariantInfo(itemId);\n                      const translatedData = this.translateToAccessLogItem(itemId, url, varInfo, this.rtcQuery.getEntity(itemId).playEndedRecord.PlayType);\n                      if (translatedData) {\n                          translatedData['c-provisional-entry'] = true; // mark item as incomplete\n                          finalAccessLog.push(translatedData);\n                      }\n                  }\n              }\n              return finalAccessLog;\n          }\n          get errorLog() {\n              return this.errorlog;\n          }\n          createAccessLogEntry() {\n              const entry = {\n                  fragmentCnt: 0,\n                  overdue: 0,\n                  startPTS: 0,\n                  obrMax: 0,\n                  obrMin: 0,\n                  audioBytes: 0,\n                  audioDuration: 0,\n                  videoBytes: 0,\n                  videoDuration: 0,\n                  svrAddrChanged: 0,\n                  svrAddr: '',\n                  PlayTimeWC: 0,\n                  ViFrDr: 0,\n                  StallCount: 0,\n                  MediaEngineStallCount: 0,\n                  ADT: 0,\n                  NetBytes: 0,\n                  StartupTime: 0,\n                  OBRMean: 0,\n                  OBRLast: 0,\n              };\n              return entry;\n          }\n          convertStringObjectToPrimitive(str) {\n              // Prevent crashing Netflix because it assumes url is always a valid string\n              let output;\n              if (!str) {\n                  output = '';\n              }\n              else if (typeof str === 'object') {\n                  output = str.toString();\n              }\n              else {\n                  output = str;\n              }\n              return output;\n          }\n          updateSvrAddrStats(url) {\n              const urlParts = URLToolkit$1.parseURL(url);\n              if (urlParts && urlParts.netLoc) {\n                  const portLoc = urlParts.netLoc.indexOf(':');\n                  let svrAddr = portLoc >= 0 ? urlParts.netLoc.slice(0, portLoc) : urlParts.netLoc;\n                  if (svrAddr.startsWith('//')) {\n                      svrAddr = svrAddr.slice(2);\n                  }\n                  if (!this.accessLogData.svrAddr) {\n                      this.accessLogData.svrAddrChanged = 0;\n                  }\n                  else if (svrAddr !== this.accessLogData.svrAddr) {\n                      this.accessLogData.svrAddrChanged++;\n                  }\n                  // server address\n                  this.accessLogData.svrAddr = svrAddr;\n              }\n          }\n          translateToAccessLogItem(itemId, url, varInfo, playType) {\n              const uri = this.convertStringObjectToPrimitive(url);\n              this.updateSvrAddrStats(uri);\n              // accumulated duration of the media downloaded, in seconds\n              let currentMediaDur = this.rtcQuery.getEntity(itemId).switchCompleteRecord.MediaDur;\n              if (!currentMediaDur) {\n                  // total data downloaded after seek, or live/last access log entry\n                  currentMediaDur = this.hls.bufferedDuration;\n              }\n              if (!currentMediaDur) {\n                  currentMediaDur = 0;\n              }\n              const item = {\n                  // User info -- Internal use only. Commented out to prevent leaking project via access log serviceName (com.apple.hlsjs.airplay)\n                  // item['c-client-name'] = this._accessLogReporter.ClientName;\n                  // item['c-service-identifier'] = this._accessLogReporter.ServiceName;\n                  // Server related\n                  uri: uri,\n                  's-ip': this.accessLogData.svrAddr,\n                  's-ip-changes': this.accessLogData.svrAddrChanged,\n                  // number of network read requests over WWAN, mediaRequestsWWAN. Not sure if TV is connected via WiFi.\n                  'sc-wwan-count': -1,\n                  // transfer duration\n                  'c-transfer-duration': this.accessLogData.ADT,\n                  // number of bytes transferred\n                  bytes: this.accessLogData.NetBytes,\n                  // number of media requests\n                  'c-total-media-requests': this.accessLogData.fragmentCnt,\n                  // Playback related\n                  // GUID identifies playback session\n                  'cs-guid': this.accessLogReporter.SessionID,\n                  // start time\n                  'c-start-time': this.accessLogData.startPTS,\n                  // startup time\n                  'c-startup-time': this.accessLogData.StartupTime,\n                  // duration watched (in seconds)\n                  'c-duration-watched': this.accessLogData.PlayTimeWC / 1000,\n                  // number of dropped video frames\n                  'c-frames-dropped': this.accessLogData.ViFrDr,\n                  // total number of playback stalls encountered\n                  'c-stalls': this.accessLogData.StallCount + this.accessLogData.MediaEngineStallCount,\n                  // subtract total data downloaded since last access log entry, if available\n                  'c-duration-downloaded': this.accessLogData.lastMediaDur ? currentMediaDur - this.accessLogData.lastMediaDur : currentMediaDur,\n                  // total number of times the download of the segments took too long\n                  'c-overdue': this.accessLogData.overdue,\n                  // video trackâ€™s average bit rate, in bits per second 'c-avg-video-bitrate'\n                  'c-avg-video-bitrate': (this.accessLogData.videoBytes * 8) / (this.accessLogData.videoDuration || 1),\n                  // maximum observed segment download bit rate 'c-observed-max-bitrate'\n                  'c-observed-max-bitrate': this.accessLogData.obrMax,\n                  // minimum observed segment download bit rate 'c-observed-min-bitrate'\n                  'c-observed-min-bitrate': this.accessLogData.obrMin,\n                  // throughput, in bits per second, required to play the stream, as advertised by the server.\n                  'sc-indicated-bitrate': varInfo.bandwidth ? varInfo.bandwidth : 0,\n                  // average throughput, in bits per second, required to play the stream, as advertised by the server\n                  'sc-indicated-avg-bitrate': varInfo.avgBandwidth ? varInfo.avgBandwidth : 0,\n                  // empirical throughput, in bits per second, across all media downloaded.\n                  'c-observed-bitrate': this.accessLogData.OBRMean,\n                  // bandwidth that caused a switch (up or down) 'c-switch-bitrate'\n                  'c-switch-bitrate': this.accessLogData.OBRLast,\n                  // mark item as complete\n                  'c-provisional-entry': false,\n              };\n              // playback type\n              item['s-playback-type'] = playType;\n              // audio trackâ€™s average bit rate, in bits per second 'c-avg-audio-bitrate'\n              if (this.accessLogData.audioBytes) {\n                  // don't show this for muxed content\n                  item['c-avg-audio-bitrate'] = (this.accessLogData.audioBytes * 8) / (this.accessLogData.audioDuration || 1);\n              }\n              return item;\n          }\n          translateToErrorLogItem(itemId, url, errorInfo) {\n              const uri = this.convertStringObjectToPrimitive(url);\n              this.updateSvrAddrStats(uri); // extract URL host name to svrAddr attribute\n              const item = {\n                  date: new Date(),\n                  'cs-guid': this.accessLogReporter.SessionID + '-' + itemId,\n                  uri: uri,\n                  's-ip': this.accessLogData.svrAddr,\n                  status: '' + errorInfo.code,\n                  domain: errorInfo.domain,\n              };\n              return item;\n          }\n          hasGap(newStartPTS, newEndPTS, oldStartPTS, oldEndPTS) {\n              if (typeof newStartPTS === 'undefined' || typeof oldStartPTS === 'undefined') {\n                  // ignore initSegment and newly create access log entry\n                  return false;\n              }\n              // seek gap is at least 1 second\n              return newStartPTS - oldEndPTS > 1 || oldStartPTS - newEndPTS > 1;\n          }\n          aggregateFragObserverdBitrate(data, fragments, bytes, adt) {\n              const obr = (bytes * 8) / (adt / 1000);\n              const obrLast = (data.bytes * 8) / (data.adt / 1000);\n              const obrMean = obr / fragments;\n              return { obr: obr, obrLast: obrLast, obrMean: obrMean };\n          }\n          aggregateFragMinMaxBitrate(target, obr) {\n              if (!target.obrMax || obr > target.obrMax) {\n                  target.obrMax = obr;\n              }\n              if (!target.obrMin || obr < target.obrMin) {\n                  target.obrMin = obr;\n              }\n          }\n          getVariantInfo(itemId) {\n              var _a;\n              const url = this.rtcQuery.getEntity(itemId).sessionControlRecord.curLevelUrl;\n              const variantList = (_a = this.rtcQuery.getEntity(itemId).sessionControlRecord.manifestData) === null || _a === void 0 ? void 0 : _a.variantList;\n              return url && variantList && variantList[url] ? variantList[url] : {};\n          }\n      }\n    \n      const loadMediaFragment = (mediaFragment, config, loadPolicy, onProgress, requestServerInfo, extendMaxTTFB) => {\n          var _a;\n          const { absoluteUrl, byteRangeOffset, discoSeqNum, keyTagInfo, iframe, isInitSegment } = mediaFragment;\n          const url = absoluteUrl;\n          const { method } = keyTagInfo;\n          const { start, end } = byteRangeOffset;\n          const loadConfig = getLoadConfig({ url }, loadPolicy);\n          let byteRangeStart = start;\n          let byteRangeEnd = end;\n          let resetIV = false;\n          let byterange = !isFiniteNumber(start) && !isFiniteNumber(end) ? undefined : byteRangeOffset;\n          if (method === 'AES-128' && end && (iframe || isInitSegment)) {\n              // Map fragment encrypted with method 'AES-128', when served with HTTP Range, has the unencrypted size specified in the range. Modify the range to ensure we read the padding bytes as well.\n              /**\n               * Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n               *\n               * If the encryption METHOD is AES-128 and the Media Segment is part of\n               * an I-frame Playlist (Section 4.4.3.6) and it has an EXT-X-BYTERANGE\n               * tag applied to it, special care needs to be taken in loading and\n               * decrypting the segment, because the resource identified by the URI is\n               * encrypted in 16-byte blocks from the start of the resource.\n               *\n               * The decrypted I-frame can be recovered by first widening its byte\n               * range, as specified by the EXT-X-BYTERANGE tag, so that it starts and\n               * ends on 16-byte boundaries from the start of the resource.\n               * */\n              const fragmentLen = end - start;\n              if (fragmentLen % 16) {\n                  byteRangeEnd = end + (16 - (fragmentLen % 16));\n              }\n              /**\n               * Next, the byte range is widened further to include a 16-byte block at\n               * the beginning of the range.  This 16-byte block allows the correct IV\n               * for the following block to be calculated.\n               * */\n              if (start !== 0) {\n                  resetIV = true;\n                  byteRangeStart = start - 16;\n              }\n              byterange = { start: byteRangeStart, end: byteRangeEnd };\n          }\n          let collectServerInstanceInfo = undefined;\n          if (requestServerInfo && isFiniteNumber(mediaFragment.mediaSeqNum) && mediaFragment.mediaOptionType === MediaOptionType.Variant) {\n              // Sanitize the list\n              collectServerInstanceInfo = [];\n              (_a = loadConfig.reportHTTPResponseHeaders) === null || _a === void 0 ? void 0 : _a.forEach(function (header) {\n                  if (privacyAllowedLoadConfigHeaders.includes(header)) {\n                      collectServerInstanceInfo.push(header);\n                  }\n                  else {\n                      getLogger().warn({ name: 'load-media-fragment' }, `${header} is not in approved privacy list. Actions required.`);\n                  }\n              });\n              if (collectServerInstanceInfo.length === 0) {\n                  collectServerInstanceInfo = undefined;\n              }\n          }\n          const context = {\n              url: url,\n              byteRangeOffset: byterange,\n              checkContentLength: true,\n              extendMaxTTFB: extendMaxTTFB,\n              collectServerInstanceInfo: collectServerInstanceInfo,\n              onProgress,\n              xhrSetup: config.xhrSetup,\n          };\n          return fromUrlArrayBuffer(context, loadConfig).pipe(map(([loadedData, bwSample, serverInfo]) => {\n              if (resetIV) {\n                  const buf = loadedData;\n                  mediaFragment.keyTagInfo.iv = new Uint8Array(buf.slice(0, 16)); // First 16 bytes -> IV\n                  loadedData = buf.slice(16); // rest is the actual fragment\n              }\n              return [mediaFragment, loadedData, bwSample, serverInfo];\n          }), convertToFragmentNetworkError(mediaFragment, false));\n      };\n    \n      const kKeySystemIdToPropertiesMap = {\n          clearkey: ClearKeySystemProperties,\n          fairplaystreaming: FairPlayStreamingKeySystemProperties,\n          playready: PlayReadyKeySystemProperties,\n          widevine: WidevineKeySystemProperties,\n      };\n      /**\n       * Get the EXT-X-KEY:FORMAT value associated with the key system\n       * @param keySystemId Identifier string to request keyFormatString property for\n       */\n      const KeySystemFactory = {\n          getKeySystemFormat(keySystemId) {\n              const properties = kKeySystemIdToPropertiesMap[keySystemId];\n              return properties ? properties.keyFormatString : '';\n          },\n          getKeySystemSecurityLevel(keySystemId) {\n              const properties = kKeySystemIdToPropertiesMap[keySystemId];\n              return properties ? properties.securityLevels : null;\n          },\n      };\n    \n      const decryptmethods = { NONE: '', 'AES-128': '', 'ISO-23001-7': '', 'SAMPLE-AES': '', 'SAMPLE-AES-CTR': '' };\n      function isDecryptMethod(tagValue) {\n          if (!tagValue) {\n              return false;\n          }\n          return tagValue in decryptmethods;\n      }\n    \n      const HdcpLevels = {\n          NONE: 0,\n          'TYPE-0': 1,\n          'TYPE-1': 2,\n          'TYPE-2': 3,\n      };\n      function isHdcpLevel(x) {\n          return x in HdcpLevels;\n      }\n      function hdcpLevelToInt(hdcpLevel) {\n          if (hdcpLevel == null) {\n              return 4;\n          }\n          return HdcpLevels[hdcpLevel];\n      }\n    \n      const SessionDataKey = {\n          CHAPTER: 'com.apple.hls.chapters',\n          TITLE: 'com.apple.hls.title',\n          TITLE_DESCRIPTIONS: 'com.apple.hls.description',\n          EPISODE_TITLE: 'com.apple.hls.episode-title',\n          ARTWORK: 'com.apple.hls.poster',\n          ROTTEN_TOMATOES_RATING: 'com.apple.hls.rt-rating',\n          ROTTEN_TOMATOES_AUDIENCE_SCORE: 'com.apple.hls.rt-audience-score',\n          GENRE: 'com.apple.hls.genre',\n          RELEASE_DATE: 'com.apple.hls.release-date',\n          CONTENT_RATING_BADGE: 'com.apple.hls.rating-tag',\n          OTHER_TEXT_BADGES: 'com.apple.hls.other-tags',\n          FORMAT: 'com.apple.hls.format',\n          QUALITY: 'com.apple.hls.quality',\n          ACCESSIBILITY: 'com.apple.hls.accessibility',\n      };\n      const isSessionDataItem = (item) => 'DATA-ID' in item;\n    \n      const VideoRangeValues = ['SDR', 'PQ', 'HLG'];\n      function isVideoRange(vr) {\n          return vr != null && VideoRangeValues.includes(vr);\n      }\n    \n      /*\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const bcp47ShortestLangCode = {\n          afr: 'af',\n          aka: 'ak',\n          amh: 'am',\n          ara: 'ar',\n          arg: 'an',\n          asm: 'as',\n          ava: 'av',\n          ave: 'ae',\n          aym: 'ay',\n          aze: 'az',\n          bam: 'bm',\n          bel: 'be',\n          ben: 'bn',\n          bih: 'bh',\n          bod: 'bo',\n          bos: 'bs',\n          bre: 'br',\n          bul: 'bg',\n          cat: 'ca',\n          ces: 'cs',\n          cha: 'ch',\n          che: 'ce',\n          chu: 'cu',\n          chv: 'cv',\n          cor: 'kw',\n          cos: 'co',\n          cre: 'cr',\n          cym: 'cy',\n          dan: 'da',\n          deu: 'de',\n          div: 'dv',\n          dzo: 'dz',\n          ell: 'el',\n          eng: 'en',\n          epo: 'eo',\n          est: 'et',\n          eus: 'eu',\n          ewe: 'ee',\n          fao: 'fo',\n          fas: 'fa',\n          fin: 'fi',\n          fra: 'fr',\n          fry: 'fy',\n          ful: 'ff',\n          gla: 'gd',\n          gle: 'ga',\n          glg: 'gl',\n          glv: 'gv',\n          grn: 'gn',\n          guj: 'gu',\n          hat: 'ht',\n          heb: 'he',\n          her: 'hz',\n          hin: 'hi',\n          hmo: 'ho',\n          hrv: 'hr',\n          hun: 'hu',\n          hye: 'hy',\n          ibo: 'ig',\n          ido: 'io',\n          iii: 'ii',\n          iku: 'iu',\n          ile: 'ie',\n          ina: 'ia',\n          ind: 'id',\n          isl: 'is',\n          ita: 'it',\n          jav: 'jv',\n          jpn: 'ja',\n          kal: 'kl',\n          kan: 'kn',\n          kas: 'ks',\n          kat: 'ka',\n          kau: 'kr',\n          kaz: 'kk',\n          khm: 'km',\n          kik: 'ki',\n          kin: 'rw',\n          kir: 'ky',\n          kom: 'kv',\n          kon: 'kg',\n          kor: 'ko',\n          kua: 'kj',\n          kur: 'ku',\n          lao: 'lo',\n          lat: 'la',\n          lav: 'lv',\n          lim: 'li',\n          lit: 'lt',\n          ltz: 'lb',\n          lub: 'lu',\n          lug: 'lg',\n          mah: 'mh',\n          mal: 'ml',\n          mar: 'mr',\n          mkd: 'mk',\n          mlg: 'mg',\n          mlt: 'mt',\n          mol: 'mo',\n          mon: 'mn',\n          mri: 'mi',\n          msa: 'ms',\n          mya: 'my',\n          nav: 'nv',\n          nbl: 'nr',\n          nde: 'nd',\n          ndo: 'ng',\n          nep: 'ne',\n          nld: 'nl',\n          nno: 'nn',\n          nob: 'nb',\n          nya: 'ny',\n          oci: 'oc',\n          oji: 'oj',\n          ori: 'or',\n          orm: 'om',\n          oss: 'os',\n          pan: 'pa',\n          pli: 'pi',\n          pol: 'pl',\n          por: 'pt',\n          pus: 'ps',\n          que: 'qu',\n          roh: 'rm',\n          ron: 'ro',\n          run: 'rn',\n          rus: 'ru',\n          san: 'sa',\n          sin: 'si',\n          slk: 'sk',\n          slv: 'sl',\n          sme: 'se',\n          snd: 'sd',\n          som: 'so',\n          spa: 'es',\n          sqi: 'sq',\n          srd: 'sc',\n          srp: 'sr',\n          sun: 'su',\n          swa: 'sw',\n          swe: 'sv',\n          tah: 'ty',\n          tam: 'ta',\n          tat: 'tt',\n          tel: 'te',\n          tgk: 'tg',\n          tgl: 'tl',\n          tha: 'th',\n          tir: 'ti',\n          ton: 'to',\n          tuk: 'tk',\n          tur: 'tr',\n          uig: 'ug',\n          ukr: 'uk',\n          urd: 'ur',\n          uzb: 'uz',\n          ven: 've',\n          vie: 'vi',\n          wln: 'wa',\n          yid: 'yi',\n          zha: 'za',\n          zho: 'zh',\n      };\n      const bcp47Utils = {\n          isLanguageCode(value) {\n              return value in bcp47ShortestLangCode;\n          },\n          shortenLanguageCode(langTag) {\n              let shortenedLangTag;\n              if (langTag) {\n                  const langCodePos = langTag.indexOf('-');\n                  const langCode = langCodePos >= 0 ? langTag.slice(0, langCodePos) : langTag;\n                  if (bcp47Utils.isLanguageCode(langCode)) {\n                      shortenedLangTag = bcp47ShortestLangCode[langCode];\n                  }\n                  if (!shortenedLangTag) {\n                      shortenedLangTag = langCode;\n                  }\n                  if (langCodePos > 0) {\n                      const theRest = langTag.slice(langCodePos + 1);\n                      shortenedLangTag += '-' + theRest;\n                  }\n              }\n              return shortenedLangTag;\n          },\n      };\n    \n      const RichestMedia = {\n          getRichestVideoCodec(videoCodecList) {\n              if (!videoCodecList || !videoCodecList.length) {\n                  return undefined;\n              }\n              const sortedCodecs = videoCodecList.sort((codec1, codec2) => getVideoCodecRanking(codec2) - getVideoCodecRanking(codec1));\n              return sortedCodecs && sortedCodecs.length ? sortedCodecs[0] : undefined;\n          },\n          getRichestAudioCodec(audioCodecList) {\n              if (!audioCodecList || !audioCodecList.length) {\n                  return undefined;\n              }\n              const sortedCodecs = audioCodecList.sort((codec1, codec2) => getAudioCodecRanking(codec2) - getAudioCodecRanking(codec1));\n              return sortedCodecs && sortedCodecs.length ? sortedCodecs[0] : undefined;\n          },\n          getRichestChannelLayoutForGroupId(audioGroupId, audioMediaOptions) {\n              if (!audioGroupId || !audioMediaOptions || !audioMediaOptions.length) {\n                  return undefined;\n              }\n              let channels = undefined;\n              const tracksforGroupdId = audioMediaOptions.filter((track) => track.groupId === audioGroupId);\n              if (tracksforGroupdId && tracksforGroupdId.length) {\n                  const sortedTracksForGroupId = tracksforGroupdId.sort((track1, track2) => MediaUtil.getChannelCount(track2.channels) - MediaUtil.getChannelCount(track1.channels));\n                  if (sortedTracksForGroupId && sortedTracksForGroupId.length) {\n                      channels = sortedTracksForGroupId[0].channels;\n                  }\n              }\n              return channels;\n          },\n      };\n    \n      function _formatError(msg) {\n          return new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.STEERING_MANIFEST_PARSING_ERROR, false, msg, ErrorResponses.FormatError);\n      }\n      function validatePathwayID(pathwayID) {\n          if (typeof pathwayID !== 'string') {\n              return _formatError('invalid steering manifest PATHWAY-PRIORITY list item data type');\n          }\n          if (!/^[\\w\\-\\.]+$/.test(pathwayID)) {\n              return _formatError('steering manifest contains invalid pathway ID: ' + pathwayID);\n          }\n          return void 0;\n      }\n    \n      /*\n       * Fragment\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      class FragmentBuilder {\n          // public backtracked?: boolean;\n          // public dropped?: number;\n          // public startDTS?: number;\n          // public startPTS?: number;\n          // public endDTS?: number;\n          // public endPTS?: number;\n          // public deltaPTS?: number;\n          // public autoLevel?: boolean;\n          // public bitrateTest?: boolean;\n          // public loader?: any; // TODO: fix any\n          // public loadSuccess?: boolean;\n          // public data?: Uint8Array;\n          // public iframeMediaStart?: number;\n          // public iframeMediaDuration?: number;\n          // public trackId?: number; // used by subtitle-stream-controller, should be moved\n          // public loaded: number; // used by fragment loader\n          // public itemId: string;\n          constructor(inheritQuery) {\n              this._url = null;\n              this._programDateTime = null;\n              this._byteRange = null;\n              this.relurl = null;\n              this.baseurl = null;\n              this.isInitSegment = false;\n              this.mediaSeqNum = NaN;\n              this.cc = NaN;\n              this.iframe = false;\n              this.bitrate = NaN;\n              this.start = NaN;\n              this.duration = NaN;\n              this.lastByteRangeEndOffset = NaN;\n              this.inheritQuery = inheritQuery;\n              this.tagList = new Array();\n              this.iframe = false;\n          }\n          getMediaFragment(itemId, mediaOptionId, mediaOptionType) {\n              var _a;\n              const fragment = {\n                  mediaOptionType,\n                  absoluteUrl: this.url,\n                  start: this.start,\n                  duration: this.duration,\n                  mediaSeqNum: this.mediaSeqNum,\n                  discoSeqNum: this.cc,\n                  mediaOptionId,\n                  itemId,\n                  isLastFragment: false,\n                  isInitSegment: this.isInitSegment,\n              };\n              if ((_a = this.byteRange) === null || _a === void 0 ? void 0 : _a.length) {\n                  fragment.byteRangeOffset = { start: this.byteRangeStartOffset, end: this.byteRangeEndOffset };\n              }\n              if (this.iframe) {\n                  fragment.iframe = this.iframe;\n              }\n              if (this.levelkey) {\n                  fragment.keyTagInfo = this.levelkey;\n              }\n              if (this.programDateTime) {\n                  fragment.programDateTime = this.programDateTime;\n              }\n              return fragment;\n          }\n          // static getStartEndString(frag: Fragment) {\n          //   return `[${toFixed(frag.startDTS || frag.start, 3)},${toFixed(frag.endPTS || frag.start + frag.duration, 3)}]`;\n          // }\n          /*\n           * @returns whether this fragment is equivalent to another fragment\n           */\n          // equals(fragInfo: Fragment) {\n          //   return fragInfo.mediaSeqNum === this.mediaSeqNum && fragInfo.levelId === this.levelId;\n          // }\n          get url() {\n              if (!this._url && this.relurl && this.baseurl) {\n                  this._url = URLToolkit$1.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true, inheritQuery: this.inheritQuery });\n              }\n              return this._url;\n          }\n          set url(value) {\n              this._url = value;\n          }\n          get programDateTime() {\n              if (!this._programDateTime && this.rawProgramDateTime) {\n                  this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));\n              }\n              return this._programDateTime;\n          }\n          get byteRange() {\n              if (!this._byteRange) {\n                  const byteRange = new Array(2);\n                  if (this.rawByteRange) {\n                      const params = this.rawByteRange.split('@', 2);\n                      if (params.length === 1) {\n                          const { lastByteRangeEndOffset } = this;\n                          byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0;\n                      }\n                      else {\n                          byteRange[0] = parseInt(params[1]);\n                      }\n                      byteRange[1] = parseInt(params[0]) + byteRange[0];\n                  }\n                  this._byteRange = byteRange;\n              }\n              return this._byteRange;\n          }\n          get byteRangeStartOffset() {\n              return this.byteRange[0];\n          }\n          get byteRangeEndOffset() {\n              return this.byteRange[1];\n          }\n          get rangeString() {\n              if (this.start >= 0 && this.duration >= 0) {\n                  return `${this.start.toFixed(2)}-${(this.start + this.duration).toFixed(2)}`;\n              }\n              return 'N/A';\n          }\n          // useful for a consistent logging message tag\n          get fragTag() {\n              return `sn/cc/levelId: ${this.mediaSeqNum}/${this.cc}`;\n          }\n      }\n    \n      const MediaSelectionHelper = {\n          parseMediaCharacteristics(mediaCharacteristics) {\n              return mediaCharacteristics ? mediaCharacteristics.split(/\\s*,\\s*/) : new Array();\n          },\n          addMediaToSelectionArray(mediaSelectionGroup, mediaEntry, nextPersistentID) {\n              if (typeof mediaSelectionGroup === 'undefined') {\n                  return -1;\n              }\n              const mediaSelectionGroupOptionArray = mediaSelectionGroup.MediaSelectionGroupOptions;\n              let mediaSelectionOption = mediaSelectionGroupOptionArray.find((mediaSelectionOption) => mediaSelectionOption.MediaSelectionOptionsMediaType === mediaEntry.mediaType &&\n                  mediaSelectionOption.MediaSelectionOptionsName === mediaEntry.name &&\n                  mediaSelectionOption.MediaSelectionOptionsExtendedLanguageTag === mediaEntry.lang\n              // TODO: need ISO 639 code - MediaSelectionOptionsLanguageCode\n              );\n              if (!mediaSelectionOption) {\n                  mediaSelectionOption = {\n                      MediaSelectionOptionsMediaType: mediaEntry.mediaType,\n                      MediaSelectionOptionsExtendedLanguageTag: mediaEntry.lang,\n                      MediaSelectionOptionsIsDefault: mediaEntry.default,\n                      MediaSelectionOptionsName: mediaEntry.name,\n                      MediaSelectionOptionsPersistentID: nextPersistentID,\n                      MediaSelectionOptionsTaggedMediaCharacteristics: mediaEntry.characteristics,\n                  };\n                  if (mediaEntry.mediaType === MediaTypeFourCC.SUBTITLE) {\n                      mediaSelectionOption.MediaSelectionOptionsDisplaysNonForcedSubtitles = mediaEntry.forced ? Allowed.NO : Allowed.YES;\n                  }\n                  nextPersistentID++; // created a new group, increment the next ID\n                  mediaSelectionGroupOptionArray.push(mediaSelectionOption);\n              }\n              mediaEntry.persistentID = mediaSelectionOption.MediaSelectionOptionsPersistentID;\n              return nextPersistentID;\n          },\n          addDefaultClosedCaptionOption(queueItemId, playlistSubtitleTracks, subtitleMediaSelectionGroup, nextPersistentID) {\n              const mediaEntry = {\n                  // only 1 text track\n                  itemId: queueItemId,\n                  mediaOptionType: MediaOptionType.Subtitle,\n                  id: 0,\n                  mediaOptionId: 'cc1_' + guid(),\n                  mediaType: MediaTypeFourCC.CLOSEDCAPTION,\n                  inStreamID: 'CC1',\n                  groupId: 'cc',\n                  name: 'English-CC',\n                  type: 'CLOSED-CAPTIONS',\n                  default: false,\n                  autoselect: false,\n                  forced: false,\n                  lang: 'en',\n                  // 'public.easy-to-read' is not default in CoreMedia\n                  characteristics: ['public.accessibility.transcribes-spoken-dialog', 'public.accessibility.describes-music-and-sound'],\n                  persistentID: nextPersistentID,\n              };\n              playlistSubtitleTracks.push(mediaEntry);\n              MediaSelectionHelper.addMediaToSelectionArray(subtitleMediaSelectionGroup, mediaEntry, nextPersistentID);\n          },\n      };\n    \n      const StringTags = {\n          NAME: '',\n          TYPE: '',\n          DEFAULT: '',\n          AUTOSELECT: '',\n          FORCED: '',\n          LANGUAGE: '',\n          URI: '',\n          AUDIO: '',\n          'VIDEO-RANGE': '',\n          'CLOSED-CAPTIONS': '',\n          CODECS: '',\n          BYTERANGE: '',\n          'INSTREAM-ID': '',\n          'GROUP-ID': '',\n          CHANNELS: '',\n          CHARACTERISTICS: '',\n          KEYFORMAT: '',\n          KEYFORMATVERSIONS: '',\n          'DATA-ID': '',\n          VALUE: '',\n          METHOD: '',\n          'HDCP-LEVEL': '',\n          'ALLOWED-CPC': '',\n          SUBTITLES: '',\n          // ext-daterange\n          ID: '',\n          CLASS: '',\n          'START-DATE': '',\n          'END-DATE': '',\n          'END-ON-NEXT': '',\n          // content-steering\n          'SERVER-URI': '',\n          'PATHWAY-ID': '',\n      };\n      const IntegerTags = {\n          BANDWIDTH: NaN,\n          'AVERAGE-BANDWIDTH': NaN,\n      };\n      const FloatTags = {\n          'TIME-OFFSET': NaN,\n          'FRAME-RATE': NaN,\n          SCORE: NaN,\n          'PLANNED-DURATION': NaN,\n          DURATION: NaN,\n      };\n      const HexTags = {\n          IV: null,\n      };\n      const ResolutionTags = {\n          RESOLUTION: null,\n      };\n    \n      /*\n       * 2019 Apple Inc. All rights reserved.\n       */\n      const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\n      const ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g;\n      // T is a string union type of keys\n      // K is the value type\n      class TagParser {\n          constructor(validTags) {\n              this.validTags = validTags;\n          }\n          isKey(tag) {\n              return tag in this.validTags;\n          }\n          trySetValue(tag, tagValue, outBag) {\n              if (this.isKey(tag)) {\n                  outBag[tag] = this.parseFunc(tagValue);\n                  return true;\n              }\n              return false;\n          }\n      }\n      class StringTagParser extends TagParser {\n          parseFunc(tag) {\n              return tag;\n          }\n      }\n      class IntegerTagParser extends TagParser {\n          parseFunc(tagValue) {\n              const parsedValue = parseInt(tagValue);\n              if (parsedValue > Number.MAX_SAFE_INTEGER) {\n                  return Infinity;\n              }\n              return parsedValue;\n          }\n      }\n      class FloatTagParser extends TagParser {\n          constructor() {\n              super(...arguments);\n              this.parseFunc = parseFloat;\n          }\n      }\n      class HexTagParser extends TagParser {\n          parseFunc(tagValue) {\n              let stringValue = (tagValue || '0x').slice(2);\n              stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n              const value = new Uint8Array(stringValue.length / 2);\n              for (let i = 0; i < stringValue.length / 2; i++) {\n                  const val = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n                  if (!isFiniteNumber(val)) {\n                      return undefined;\n                  }\n                  value[i] = val;\n              }\n              return value;\n          }\n      }\n      class ResolutionTagParser extends TagParser {\n          parseFunc(tagValue) {\n              const res = DECIMAL_RESOLUTION_REGEX.exec(tagValue);\n              let resolution;\n              if (res !== null) {\n                  resolution = {\n                      width: parseInt(res[1], 10),\n                      height: parseInt(res[2], 10),\n                  };\n              }\n              return resolution;\n          }\n      }\n      class PlaylistTagParser {\n          static parseTags(input) {\n              let match;\n              const parsedTags = {};\n              if (!input) {\n                  return parsedTags;\n              }\n              ATTR_LIST_REGEX.lastIndex = 0;\n              while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n                  const tag = match[1].toUpperCase(), quote = '\"';\n                  let value = match[2];\n                  if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {\n                      value = value.slice(1, -1);\n                  }\n                  for (const tagParser of PlaylistTagParser.tagParsers) {\n                      if (tagParser.trySetValue(tag, value, parsedTags)) {\n                          break;\n                      }\n                  }\n              }\n              return parsedTags;\n          }\n      }\n      PlaylistTagParser.tagParsers = [new StringTagParser(StringTags), new IntegerTagParser(IntegerTags), new FloatTagParser(FloatTags), new HexTagParser(HexTags), new ResolutionTagParser(ResolutionTags)];\n    \n      /*\n       * Playlist Parser\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      // https://regex101.com is your friend\n      const HlsRegex = {\n          ExtractVariableParameter: /{\\$(.*?)}/g,\n          LevelPlaylistFast: /#EXTINF:(\\d*(?:\\.\\d+)?)(?:,(.*))?|(?!#)(\\S.+)|#EXT-X-BYTERANGE: *(.+)|#EXT-X-PROGRAM-DATE-TIME:(.+)|#EXT-X-BITRATE:(.+)|#EXT-X-DATERANGE:(.+)|#.*/g,\n          LevelPlaylistSlow: /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\\d+))|(?:#EXT-X-(TARGETDURATION): *(\\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\\d+))|(?:#EXT-X-(MAP):(.+))|(?:#EXT-X-(I-FRAMES)-ONLY)|(?:#EXT-X-(DEFINE):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\\r?\\n?/,\n          MasterPlaylist: /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)|#EXT-X-I-FRAME-STREAM-INF:([^\\r\\n]+)|#EXT-X-DEFINE:([^\\n\\r]*)|#EXT-X-CONTENT-STEERING:([^\\n\\r]*)/g,\n          MasterPlaylistAlternateMedia: /#EXT-X-MEDIA:(.*)/g,\n          SessionData: /#EXT-X-SESSION-DATA[^:]*:(.*)/g,\n          SessionKeys: /#EXT-X-SESSION-KEY:([^\\n\\r]*)/g,\n          VARIABLE_PLAYLIST_REGEX: /(NAME|VALUE)=\\\"(.*)\\\",(NAME|VALUE)=\\\"(.*)\\\"|(IMPORT)=\\\"(.*)\\\"/,\n      };\n      function resolve(url, baseUrl, inheritQuery) {\n          return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true, inheritQuery });\n      }\n      function tryDecodeBase64Metadata(data) {\n          let decodedObj;\n          try {\n              decodedObj = JSON.parse(NumericEncodingUtils$1.base64DecodeToStr(data));\n          }\n          catch (err) {\n              // logger.error(`Error ${err} decoding metadata value: '${data}'`);\n              decodedObj = data;\n          }\n          return decodedObj;\n      }\n      class PlaylistParser {\n          static isValidPlaylist(playlist) {\n              return playlist.indexOf('#EXTM3U') === 0;\n          }\n          static isMediaPlaylist(playlist) {\n              return playlist.indexOf('#EXTINF:') > 0 || playlist.indexOf('#EXT-X-PLAYLIST-TYPE:') > 0;\n          }\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n          static replaceVariables(input, variableMap) {\n              let updatedString, error = false;\n              if (input && variableMap) {\n                  updatedString = input.replace(HlsRegex.ExtractVariableParameter, (result) => {\n                      HlsRegex.ExtractVariableParameter.lastIndex = 0;\n                      const variable = HlsRegex.ExtractVariableParameter.exec(result);\n                      const property = variable[1];\n                      // eslint-disable-next-line no-prototype-builtins\n                      if (property && variableMap.hasOwnProperty(property)) {\n                          return variableMap[property];\n                      }\n                      error = true;\n                  });\n              }\n              return { updatedString, error };\n          }\n          static parseDecryptData(decryptparams, baseurl, keySystemPreference) {\n              var _a;\n              const keyAttrs = PlaylistTagParser.parseTags(decryptparams);\n              const decryptmethod = isDecryptMethod(keyAttrs.METHOD) ? keyAttrs.METHOD : null;\n              const decryptformat = (_a = keyAttrs.KEYFORMAT) !== null && _a !== void 0 ? _a : null;\n              if (decryptmethod && PlaylistParser.shouldSelectKeyTag(decryptformat, decryptmethod, keySystemPreference)) {\n                  const decrypturi = keyAttrs.URI;\n                  const decryptiv = keyAttrs.IV ? keyAttrs.IV : null;\n                  if (decrypturi) {\n                      // if there's an IV specified, make sure it's valid\n                      if (keyAttrs.IV && !decryptiv) {\n                          const playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, `Invalid IV: ${keyAttrs.IV}`, ErrorResponses.PlaylistErrorInvalidEntry);\n                          playlistParsingError.url = baseurl;\n                          throw playlistParsingError;\n                      }\n                  }\n                  // do not use inheritQuery on key URIs\n                  const resolvedUri = decrypturi ? URLToolkit.buildAbsoluteURL(baseurl, decrypturi, { alwaysNormalize: true }) : baseurl;\n                  const decryptformatversions = (keyAttrs.KEYFORMATVERSIONS ? keyAttrs.KEYFORMATVERSIONS : '1').split('/').map(Number).filter(isFinite);\n                  return new DecryptData(decryptmethod, resolvedUri, decryptiv, decryptformat, decryptformatversions);\n              }\n          }\n          /*\n           *  Utility method to pick a desired key system based on the app preference, EXT-X-KEY tag values.\n           */\n          static shouldSelectKeyTag(decryptformat, decryptmethod, keySystemPreference) {\n              // If it's Segment encryption or No encryption, just select that key system\n              // There is no app preference, so select the key system from the manifest\n              // Now try to match the app preference with the key system in the manifest\n              return 'AES-128' === decryptmethod || 'NONE' === decryptmethod || null == keySystemPreference || decryptformat === KeySystemFactory.getKeySystemFormat(keySystemPreference);\n          }\n          static optOutClosedCaption(levels) {\n              let noClosedCaption = false;\n              let hasVideo = false;\n              if (levels) {\n                  // may be null for playlist with 1 audio only track\n                  for (let i = 0; i < levels.length; ++i) {\n                      const levelInfo = levels[i];\n                      if (levelInfo.videoCodec) {\n                          hasVideo = true;\n                          if (levelInfo.iframes !== true && levelInfo.closedcaption && levelInfo.closedcaption.toLowerCase() === 'none') {\n                              noClosedCaption = true; // 'CLOSED-CAPTION=NONE' must be present in all levels if it exists in one.\n                              break;\n                          }\n                      }\n                  }\n              }\n              return !hasVideo || noClosedCaption;\n          }\n          static parseRootPlaylistAlternateMediaOptions(queueItemId, playlist, baseurl, levels, inheritQuery, masterVariableList) {\n              let result;\n              let playlistParsingError;\n              const audioMediaSelectionGroup = {\n                  MediaSelectionGroupAllowEmptySelection: 1,\n                  MediaSelectionGroupMediaCharacteristics: ['public.audible'],\n                  MediaSelectionGroupMediaType: MediaTypeFourCC.AUDIO,\n                  MediaSelectionGroupOptions: [],\n              };\n              const subtitleMediaSelectionGroup = {\n                  MediaSelectionGroupAllowEmptySelection: 1,\n                  MediaSelectionGroupMediaCharacteristics: ['public.legible'],\n                  MediaSelectionGroupMediaType: MediaTypeFourCC.SUBTITLE,\n                  MediaSelectionGroupOptions: [],\n              };\n              const alternateMediaInfo = {\n                  videoAlternateOptions: [],\n                  audioAlternateOptions: [],\n                  subtitleAlternateOptions: [],\n                  audioMediaSelectionGroup,\n                  subtitleMediaSelectionGroup,\n              };\n              let nextPersistentID = 0;\n              HlsRegex.MasterPlaylistAlternateMedia.lastIndex = 0;\n              while ((result = HlsRegex.MasterPlaylistAlternateMedia.exec(playlist)) != null) {\n                  const updatedAttrList = PlaylistParser.replaceVariables(result[1], masterVariableList);\n                  if (updatedAttrList.error) {\n                      playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.LEVEL_LOAD_ERROR, true, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE.text, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE);\n                      break;\n                  }\n                  const attrs = PlaylistTagParser.parseTags(updatedAttrList.updatedString);\n                  let mediaType = MediaTypeFourCC.UNKNOWN;\n                  let inStreamID;\n                  let trackArray;\n                  let mediaSelectionGroup;\n                  const characteristics = MediaSelectionHelper.parseMediaCharacteristics(attrs.CHARACTERISTICS);\n                  const groupId = attrs['GROUP-ID'];\n                  const channels = attrs.CHANNELS;\n                  let groupCodecList;\n                  let mediaOptionType = null;\n                  switch (attrs.TYPE) {\n                      case 'VIDEO':\n                          mediaType = MediaTypeFourCC.VIDEO;\n                          // mediaOptionType = TODO\n                          trackArray = alternateMediaInfo.videoAlternateOptions;\n                          // no selection options yet\n                          break;\n                      case 'AUDIO':\n                          mediaType = MediaTypeFourCC.AUDIO;\n                          mediaOptionType = MediaOptionType.AltAudio;\n                          trackArray = alternateMediaInfo.audioAlternateOptions;\n                          mediaSelectionGroup = audioMediaSelectionGroup;\n                          const matchingLevel = levels.find((level) => level.audioGroupId === groupId);\n                          groupCodecList = matchingLevel ? matchingLevel.audioCodecList : [];\n                          break;\n                      case 'SUBTITLES':\n                          mediaType = MediaTypeFourCC.SUBTITLE;\n                          mediaOptionType = MediaOptionType.Subtitle;\n                          trackArray = alternateMediaInfo.subtitleAlternateOptions;\n                          mediaSelectionGroup = subtitleMediaSelectionGroup;\n                          break;\n                      case 'CLOSED-CAPTIONS':\n                          mediaType = MediaTypeFourCC.CLOSEDCAPTION;\n                          mediaOptionType = MediaOptionType.Subtitle;\n                          inStreamID = attrs['INSTREAM-ID'];\n                          trackArray = alternateMediaInfo.subtitleAlternateOptions;\n                          mediaSelectionGroup = subtitleMediaSelectionGroup;\n                          break;\n                  }\n                  const mediaEntry = {\n                      itemId: queueItemId,\n                      mediaOptionType,\n                      mediaType,\n                      groupId,\n                      channels,\n                      groupCodecList,\n                      name: attrs.NAME,\n                      type: attrs.TYPE,\n                      default: attrs.DEFAULT === 'YES',\n                      autoselect: attrs.AUTOSELECT === 'YES',\n                      forced: attrs.FORCED === 'YES',\n                      characteristics,\n                      persistentID: nextPersistentID,\n                      id: trackArray ? trackArray.length : 0,\n                      mediaOptionId: `${attrs.NAME}_${groupId}_${nextPersistentID}`,\n                      lang: bcp47Utils.shortenLanguageCode(attrs.LANGUAGE),\n                  };\n                  if (attrs.URI) {\n                      mediaEntry.url = resolve(attrs.URI, baseurl, inheritQuery);\n                  }\n                  if (!mediaEntry.name) {\n                      mediaEntry.name = mediaEntry.lang;\n                      if (mediaEntry.mediaType === MediaTypeFourCC.CLOSEDCAPTION) {\n                          mediaEntry.name += ' CC';\n                      }\n                  }\n                  if (mediaEntry.mediaType === MediaTypeFourCC.CLOSEDCAPTION && inStreamID) {\n                      mediaEntry.inStreamID = inStreamID;\n                  }\n                  if (trackArray) {\n                      mediaEntry.id = trackArray.length;\n                      trackArray.push(mediaEntry);\n                  }\n                  nextPersistentID = MediaSelectionHelper.addMediaToSelectionArray(mediaSelectionGroup, mediaEntry, nextPersistentID);\n              }\n              if (alternateMediaInfo.subtitleAlternateOptions.length === 0 && !PlaylistParser.optOutClosedCaption(levels)) {\n                  MediaSelectionHelper.addDefaultClosedCaptionOption(queueItemId, alternateMediaInfo.subtitleAlternateOptions, subtitleMediaSelectionGroup, nextPersistentID);\n              }\n              return { alternateMediaInfo, playlistParsingError };\n          }\n          static parseMediaOptionPlaylist(playlist, baseurl, inheritQuery = true, keySystemPreference, masterVariableList, itemId, mediaOptionId, mediaOptionType, logger, fragStartTime = 0, // itemStartOffset\n          iFrameStreamInf = false) {\n              var _a, _b;\n              let currentSN = 0;\n              let totalduration = 0;\n              const levelDetails = {\n                  itemId,\n                  mediaOptionId,\n                  mediaOptionType,\n                  type: '',\n                  version: 0,\n                  url: baseurl,\n                  initSegments: {},\n                  fragments: [],\n                  liveOrEvent: true,\n                  startSN: 0,\n                  endSN: 0,\n                  iframesOnly: iFrameStreamInf,\n                  targetduration: 0,\n                  totalduration: 0,\n                  averagetargetduration: 0,\n                  ptsKnown: false,\n              };\n              let decryptData = new DecryptData('NONE', baseurl, null, null, null);\n              let isKeySystemSelected = false;\n              let isEncrypted = false;\n              let cc = 0;\n              let prevFrag = null;\n              let frag = new FragmentBuilder(inheritQuery);\n              let result;\n              let ix;\n              let activeBitrate = 0;\n              let lastProgramDateTime; // Latest unmatched PROGRAM-DATE-TIME tag\n              const tempVariableList = {};\n              let unprocessedRelURL;\n              let playlistParsingError;\n              let prevInitSegment;\n              let ensureMapForDiscontinuity = true;\n              let ensureMapRefresh = true;\n              HlsRegex.LevelPlaylistFast.lastIndex = 0;\n              const incompatibleAssetError = () => new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, 'Invalid key system preference for the playlist', ErrorResponses.IncompatibleAsset);\n              while ((result = HlsRegex.LevelPlaylistFast.exec(playlist)) !== null) {\n                  const duration = result[1];\n                  if (duration) {\n                      // INF\n                      frag.duration = parseFloat(duration);\n                      // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939\n                      const title = (' ' + result[2]).slice(1);\n                      frag.title = title ? title : null;\n                      frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n                  }\n                  else if (result[3]) {\n                      // url\n                      if (isFiniteNumber(frag.duration)) {\n                          const sn = currentSN++;\n                          // frag.type = type;\n                          frag.start = totalduration + fragStartTime;\n                          frag.levelkey = decryptData;\n                          if (isEncrypted && !isKeySystemSelected) {\n                              playlistParsingError = incompatibleAssetError();\n                              break;\n                          }\n                          // The decrypt data has been associated with the fragment, reset the key system selected flag.\n                          // So that if the key changes for the future segments, we can select it.\n                          isKeySystemSelected = false;\n                          isEncrypted = false;\n                          frag.mediaSeqNum = sn;\n                          // frag.levelId = levelId; // persistent level id\n                          frag.cc = cc;\n                          frag.iframe = levelDetails.iframesOnly;\n                          frag.baseurl = baseurl;\n                          // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939\n                          unprocessedRelURL = PlaylistParser.replaceVariables((' ' + result[3]).slice(1), tempVariableList);\n                          if (unprocessedRelURL.error) {\n                              playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.LEVEL_LOAD_ERROR, true, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE.text, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE);\n                              break;\n                          }\n                          frag.relurl = unprocessedRelURL.updatedString;\n                          // bitrate for fragment\n                          frag.bitrate = isFiniteNumber(frag.byteRangeEndOffset) ? ((frag.byteRangeEndOffset - frag.byteRangeStartOffset) * 8) / frag.duration : activeBitrate;\n                          if (lastProgramDateTime != null) {\n                              frag.rawProgramDateTime = lastProgramDateTime;\n                              frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n                              const dt = frag.programDateTime.getTime();\n                              levelDetails.programDateTimeMap = (_a = levelDetails.programDateTimeMap) !== null && _a !== void 0 ? _a : {};\n                              levelDetails.programDateTimeMap[dt] = frag.mediaSeqNum;\n                              levelDetails.dateMediaTimePairs = (_b = levelDetails.dateMediaTimePairs) !== null && _b !== void 0 ? _b : [];\n                              levelDetails.dateMediaTimePairs.push([dt, frag.start]);\n                              lastProgramDateTime = undefined;\n                          }\n                          levelDetails.fragments.push(frag.getMediaFragment(itemId, mediaOptionId, mediaOptionType));\n                          prevFrag = frag;\n                          totalduration += frag.duration;\n                          // implicit init segment for iframes or after a discontinuity\n                          if (ensureMapForDiscontinuity || !levelDetails.initSegments[cc] || ensureMapRefresh) {\n                              if (levelDetails.iframesOnly && frag.byteRangeStartOffset > 0 && !levelDetails.initSegments[cc] && !ensureMapRefresh) {\n                                  const ifrag = new FragmentBuilder(inheritQuery);\n                                  ifrag.url = frag.url;\n                                  // allow the init segment to be up to 7 * 188 (must be multiples of 188)\n                                  ifrag.rawByteRange = Math.min(frag.byteRangeStartOffset, 1316) + '@0';\n                                  ifrag.baseurl = baseurl;\n                                  // ifrag.levelId = levelId;\n                                  // ifrag.type = type;\n                                  ifrag.isInitSegment = true;\n                                  ifrag.cc = cc;\n                                  ifrag.levelkey = decryptData;\n                                  ifrag.iframe = true;\n                                  if (isEncrypted && !isKeySystemSelected) {\n                                      playlistParsingError = incompatibleAssetError();\n                                      break;\n                                  }\n                                  // The decrypt data has been associated with the fragment, reset the key system selected flag.\n                                  // So that if the key changes for the future segments, we can select it.\n                                  isKeySystemSelected = false;\n                                  isEncrypted = false;\n                                  levelDetails.initSegments[cc] = ifrag.getMediaFragment(itemId, mediaOptionId, mediaOptionType);\n                                  logger.info(`generated implicit initSegment in cc ${cc}`);\n                              }\n                              else if (prevInitSegment) {\n                                  if (isFiniteNumber(prevInitSegment.discoSeqNum)) {\n                                      // use the last cc's *declared* initSegment (for fmp4 when MAP for a discontinuity is not defined)\n                                      logger.info(`assume initSegment from ${prevInitSegment.discoSeqNum} in cc ${cc}`);\n                                  }\n                                  // deferred assignment of cc\n                                  prevInitSegment.discoSeqNum = cc;\n                                  levelDetails.initSegments[cc] = prevInitSegment;\n                              }\n                          }\n                          ensureMapForDiscontinuity = false;\n                          ensureMapRefresh = false;\n                          frag = new FragmentBuilder(inheritQuery);\n                      }\n                  }\n                  else if (result[4]) {\n                      // X-BYTERANGE\n                      frag.rawByteRange = (' ' + result[4]).slice(1);\n                      if (prevFrag) {\n                          const lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;\n                          if (lastByteRangeEndOffset) {\n                              frag.lastByteRangeEndOffset = lastByteRangeEndOffset;\n                          }\n                      }\n                  }\n                  else if (result[5]) {\n                      // PROGRAM-DATE-TIME\n                      // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939\n                      lastProgramDateTime = (' ' + result[5]).slice(1);\n                  }\n                  else if (result[6]) {\n                      // X-BITRATE\n                      // Note that we assume that if this tag exists in the playlist then it should exist for every fragment\n                      const parsedBitrate = parseInt(result[6]);\n                      if (isFiniteNumber(parsedBitrate)) {\n                          activeBitrate = parsedBitrate * 1000;\n                      }\n                  }\n                  else if (result[7]) {\n                      // DATERANGE\n                      const rawDaterange = result[7];\n                      const daterangeTags = PlaylistTagParser.parseTags(rawDaterange);\n                      if (daterangeTags.ID) {\n                          if (!levelDetails.daterangeTags) {\n                              levelDetails.daterangeTags = {};\n                          }\n                          levelDetails.daterangeTags[daterangeTags.ID] = daterangeTags;\n                      }\n                  }\n                  else {\n                      result = result[0].match(HlsRegex.LevelPlaylistSlow);\n                      for (ix = 1; ix < result.length; ix++) {\n                          if (result[ix] !== undefined) {\n                              break;\n                          }\n                      }\n                      // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939\n                      const unprocessedValue1 = PlaylistParser.replaceVariables((' ' + result[ix + 1]).slice(1), tempVariableList);\n                      const unprocessedValue2 = PlaylistParser.replaceVariables((' ' + result[ix + 2]).slice(1), tempVariableList);\n                      if (unprocessedValue1.error || unprocessedValue2.error) {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.LEVEL_LOAD_ERROR, true, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE.text, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE);\n                          break;\n                      }\n                      const value1 = unprocessedValue1.updatedString;\n                      const value2 = unprocessedValue2.updatedString;\n                      switch (result[ix]) {\n                          case '#':\n                              frag.tagList.push(value2 ? [value1, value2] : [value1]);\n                              break;\n                          case 'PLAYLIST-TYPE':\n                              levelDetails.type = value1.toUpperCase();\n                              if (levelDetails.type === 'VOD') {\n                                  levelDetails.liveOrEvent = false;\n                              }\n                              break;\n                          case 'MEDIA-SEQUENCE':\n                              if (levelDetails.fragments.length === 0) {\n                                  currentSN = levelDetails.startSN = parseInt(value1);\n                              }\n                              break;\n                          case 'TARGETDURATION':\n                              levelDetails.targetduration = parseFloat(value1);\n                              break;\n                          case 'VERSION':\n                              levelDetails.version = parseInt(value1);\n                              break;\n                          case 'EXTM3U':\n                              break;\n                          case 'ENDLIST':\n                              levelDetails.liveOrEvent = false;\n                              break;\n                          case 'DIS':\n                              cc++;\n                              frag.tagList.push(['DIS']);\n                              ensureMapForDiscontinuity = true;\n                              break;\n                          case 'DISCONTINUITY-SEQ':\n                              cc = parseInt(value1);\n                              break;\n                          case 'KEY':\n                              // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4\n                              const decryptparams = value1;\n                              isEncrypted = true;\n                              if (!isKeySystemSelected) {\n                                  try {\n                                      decryptData = PlaylistParser.parseDecryptData(decryptparams, baseurl, keySystemPreference);\n                                  }\n                                  catch (error) {\n                                      playlistParsingError = error;\n                                  }\n                                  if (decryptData) {\n                                      // Now mark that the key system has been selected. No more playing around with decryptData\n                                      isKeySystemSelected = true;\n                                  }\n                              }\n                              // if (!isKeySystemSelected || !decryptData) {\n                              //   logger.warn(`[Keys] Not selecting EXT-X-KEY tag : ${decryptparams}, IsKeySystemSelected: ${isKeySystemSelected}`);\n                              // }\n                              break;\n                          case 'START':\n                              const startParams = value1;\n                              const startAttrs = PlaylistTagParser.parseTags(startParams);\n                              const startTimeOffset = startAttrs['TIME-OFFSET'];\n                              // TIME-OFFSET can be 0\n                              if (isFiniteNumber(startTimeOffset)) {\n                                  levelDetails.startTimeOffset = startTimeOffset;\n                              }\n                              break;\n                          case 'I-FRAMES':\n                              levelDetails.iframesOnly = true;\n                              break;\n                          case 'MAP':\n                              const mapAttrs = PlaylistTagParser.parseTags(value1);\n                              frag.relurl = mapAttrs.URI;\n                              frag.rawByteRange = mapAttrs.BYTERANGE;\n                              frag.baseurl = baseurl;\n                              // frag.levelId = levelId;\n                              frag.isInitSegment = true;\n                              frag.levelkey = decryptData; // TODO: handle MAP before KEY\n                              if (isEncrypted && !isKeySystemSelected) {\n                                  playlistParsingError = incompatibleAssetError();\n                                  break;\n                              }\n                              // The decrypt data has been associated with the fragment, reset the key system selected flag.\n                              // So that if the key changes for the future segments, we can select it.\n                              isKeySystemSelected = false;\n                              isEncrypted = false;\n                              // The occurence of map indicates that it applies to all\n                              // media fragments that follows until the next map. The\n                              // DISCONTINUITY tag can come before or after or never\n                              // relative to MAP tag.\n                              // Common Scenario DISCO -> MAP -> FRAGMENT1 -> Fragment 2\n                              // Uncommon Scenario Map -> Disco -> FRAGMENTS (live case)\n                              // Defer insertion into initSegments[cc] until media\n                              // fragments are seen\n                              prevInitSegment = frag.getMediaFragment(itemId, mediaOptionId, mediaOptionType);\n                              ensureMapRefresh = true;\n                              // logger.info(`creating new initSegment`);\n                              frag = new FragmentBuilder(inheritQuery);\n                              break;\n                          case 'DEFINE':\n                              const defineList = HlsRegex.VARIABLE_PLAYLIST_REGEX.exec(value1);\n                              const name = 'NAME' === defineList[1] ? defineList[2] : defineList[4], value = 'VALUE' === defineList[1] ? defineList[2] : defineList[4], importName = defineList[5], importValue = defineList[6];\n                              // eslint-disable-next-line no-prototype-builtins\n                              if (!name && !value && importName === 'IMPORT' && masterVariableList.hasOwnProperty(importValue)) {\n                                  tempVariableList[importValue] = masterVariableList[importValue];\n                                  // eslint-disable-next-line no-prototype-builtins\n                              }\n                              else if (name && !importName && defineList[1] !== defineList[3] && !tempVariableList.hasOwnProperty(name)) {\n                                  tempVariableList[name] = value;\n                              }\n                              else {\n                                  playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorMissingImportReference.text, ErrorResponses.PlaylistErrorMissingImportReference);\n                                  break;\n                              }\n                              break;\n                      }\n                  }\n                  // frag.itemId = this.itemId;\n              }\n              frag = prevFrag;\n              // logger.info('found ' + levelDetails.fragments.length + ' fragments');\n              if (frag && !frag.relurl) {\n                  levelDetails.fragments.pop();\n                  totalduration -= frag.duration;\n              }\n              if (!levelDetails.liveOrEvent && levelDetails.fragments.length > 0) {\n                  levelDetails.fragments[levelDetails.fragments.length - 1].isLastFragment = true;\n              }\n              levelDetails.totalduration = totalduration;\n              levelDetails.averagetargetduration = totalduration / levelDetails.fragments.length;\n              levelDetails.endSN = currentSN - 1;\n              return { mediaOptionDetails: levelDetails, playlistParsingError };\n          }\n          static parseRootPlaylist(queueItemId, playlist, baseurl, inheritQuery) {\n              var _a;\n              const levelArray = [];\n              const masterVariableList = {};\n              let contentSteeringOption = null;\n              let result;\n              let updatedURI;\n              let updatedAttrList;\n              let playlistParsingError;\n              let scoreAvailable = true;\n              HlsRegex.MasterPlaylist.lastIndex = 0;\n              while ((result = HlsRegex.MasterPlaylist.exec(playlist)) != null) {\n                  // result[4] -> regex capture group 4, i.e. EXT-X-DEFINE\n                  if (result[4]) {\n                      // result[1] -> NAME/VALUE keyword, result[2] -> value of result[1], result[3] -> NAME/VALUE keyword,\n                      // result[4] -> value of result[3], result[5] -> IMPORT keyword, result[6] -> value of IMPORT\n                      result = HlsRegex.VARIABLE_PLAYLIST_REGEX.exec(result[4]);\n                      const name = result[1] === 'NAME' ? result[2] : result[4], value = result[1] === 'VALUE' ? result[2] : result[4], importName = result[5];\n                      // eslint-disable-next-line no-prototype-builtins\n                      if (name && !masterVariableList.hasOwnProperty(name) && !importName && result[1] !== result[3]) {\n                          masterVariableList[name] = value;\n                      }\n                      else {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE.text, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE);\n                          break;\n                      }\n                  }\n                  else if (result[5]) {\n                      // result[5] -> regex capture group 5, i.e. EXT-X-CONTENT-STEERING\n                      const updatedAttrList = PlaylistParser.replaceVariables(result[5], masterVariableList);\n                      if (updatedAttrList.error) {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE.text, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE);\n                          break;\n                      }\n                      const attrs = PlaylistTagParser.parseTags(updatedAttrList.updatedString);\n                      if (typeof attrs['SERVER-URI'] !== 'string') {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorInvalidSERVERURI.text, ErrorResponses.PlaylistErrorInvalidSERVERURI);\n                          break;\n                      }\n                      if (attrs['PATHWAY-ID'] != null && typeof attrs['PATHWAY-ID'] !== 'string') {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorInvalidPATHWAYID.text, ErrorResponses.PlaylistErrorInvalidPATHWAYID);\n                          break;\n                      }\n                      contentSteeringOption = {\n                          serverURI: resolve(attrs['SERVER-URI'], baseurl, false),\n                          initPathwayID: attrs['PATHWAY-ID'] || '.',\n                      };\n                  }\n                  else {\n                      // result[1] -> regex capture group 1, i.e. EXT-X-STREAM-INF\n                      // otherwise, result[3] -> regex capture group 3, i.e. EXT-X-I-FRAME-STREAM-INF\n                      updatedAttrList = PlaylistParser.replaceVariables(result[1] || result[3], masterVariableList);\n                      const attrs = PlaylistTagParser.parseTags(updatedAttrList.updatedString);\n                      // result[2] -> regex capture group 2, i.e. URI to be read from the new line (for EXT-X-STREAM-INF)\n                      // otherwise, arrts.URI -> URI to be read from the attributes (for EXT-X-I-FRAME-STREAM-INF)\n                      updatedURI = PlaylistParser.replaceVariables(result[2] || attrs.URI, masterVariableList);\n                      if (updatedAttrList.error || updatedURI.error) {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE.text, ErrorResponses.PlaylistErrorInvalidEXTXDEFINE);\n                          break;\n                      }\n                      if ((attrs.SCORE !== undefined && !isFiniteNumber(attrs.SCORE)) || attrs.SCORE < 0) {\n                          playlistParsingError = new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, ErrorResponses.PlaylistErrorInvalidSCORE.text, ErrorResponses.PlaylistErrorInvalidSCORE);\n                          scoreAvailable = false;\n                          break;\n                          // if SCORE attribute is missing in any level, default to bandwidth\n                      }\n                      else if (scoreAvailable && attrs.SCORE === undefined) {\n                          // logger.warn('SCORE attribute missing in one of the levels, defaulting to bandwidth selection');\n                          scoreAvailable = false;\n                      }\n                      const bandwidth = attrs.BANDWIDTH;\n                      const avgBandwidth = attrs['AVERAGE-BANDWIDTH'];\n                      const bitrate = avgBandwidth || bandwidth;\n                      const videoRange = (_a = attrs['VIDEO-RANGE']) !== null && _a !== void 0 ? _a : 'SDR';\n                      if (!isVideoRange(videoRange)) {\n                          // Skip this one.\n                          continue;\n                      }\n                      // Note this is different from audio persistentId; this is an arbitrarily calculated value based on bitrate and index\n                      const mediaOptionId = `level_${(bitrate || 0) + (levelArray.length % 1000) / 1000}`;\n                      const levelInfo = {\n                          itemId: queueItemId,\n                          mediaOptionId,\n                          mediaOptionType: MediaOptionType.Variant,\n                          attrs,\n                          url: resolve(updatedURI.updatedString, baseurl, inheritQuery),\n                          name: attrs.NAME,\n                          audioGroupId: attrs.AUDIO,\n                          subtitleGroupId: attrs.SUBTITLES,\n                          iframes: !!result[3],\n                          bandwidth,\n                          avgBandwidth,\n                          bitrate,\n                          videoRange,\n                          frameRate: attrs['FRAME-RATE'],\n                          allowedCPCMap: PlaylistParser.parseAllowedCPC(attrs['ALLOWED-CPC']),\n                          closedcaption: attrs['CLOSED-CAPTIONS'],\n                          levelCodec: attrs.CODECS,\n                          score: attrs.SCORE,\n                          pathwayID: attrs['PATHWAY-ID'] || '.',\n                      };\n                      const hdcpString = attrs['HDCP-LEVEL'];\n                      if (isHdcpLevel(hdcpString)) {\n                          levelInfo.hdcpLevel = hdcpString;\n                      }\n                      const resolution = attrs.RESOLUTION;\n                      if (resolution) {\n                          levelInfo.width = resolution.width;\n                          levelInfo.height = resolution.height;\n                      }\n                      if (attrs.CODECS) {\n                          levelInfo.videoCodecList = new Array();\n                          levelInfo.audioCodecList = new Array();\n                          const codecs = attrs.CODECS.split(/[ ,]+/);\n                          const { length } = codecs;\n                          for (let i = 0; i < length; i++) {\n                              const codec = codecs[i];\n                              const prefix = codec.slice(0, 4);\n                              switch (prefix) {\n                                  case 'avc1':\n                                      levelInfo.videoCodec = MediaUtil.avc1toavcoti(codec);\n                                      levelInfo.videoCodecList.push(levelInfo.videoCodec);\n                                      break;\n                                  case 'avc3':\n                                  case 'dvav':\n                                  case 'dva1':\n                                  // HEVC\n                                  case 'hev1': // eslint-disable-line\n                                  case 'hvc1':\n                                  case 'dvh1':\n                                  case 'dvhe':\n                                  case 'vp09':\n                                      levelInfo.videoCodec = codec;\n                                      levelInfo.videoCodecList.push(levelInfo.videoCodec);\n                                      break;\n                                  case 'mp4a':\n                                  case 'ec-3':\n                                  case 'ac-3':\n                                      levelInfo.audioCodec = codec;\n                                      levelInfo.audioCodecList.push(levelInfo.audioCodec);\n                                      break;\n                                  default:\n                                      // logger.warn(`Unrecognized codec ${codec}`);\n                                      levelInfo.audioCodec = codec; // Just set it to whatever, maybe it will work.\n                                      levelInfo.audioCodecList.push(levelInfo.audioCodec);\n                                      break;\n                              }\n                          }\n                          if (levelInfo.audioCodecList.length > 1) {\n                              levelInfo.audioCodec = RichestMedia.getRichestAudioCodec(levelInfo.audioCodecList);\n                          }\n                          if (levelInfo.videoCodecList.length > 1) {\n                              levelInfo.videoCodec = RichestMedia.getRichestVideoCodec(levelInfo.videoCodecList);\n                          }\n                      }\n                      if ((playlistParsingError = validatePathwayID(levelInfo.pathwayID)) != null) {\n                          break;\n                      }\n                      levelArray.push(levelInfo);\n                  }\n              }\n              return { variantMediaOptions: levelArray, contentSteeringOption, masterVariableList, playlistParsingError, scoreAvailable };\n          }\n          /**\n           * Encryption Stuff\n           */\n          static parseAllowedCPC(allowedCPCString) {\n              if (typeof allowedCPCString !== 'string') {\n                  return null;\n              }\n              const allowedCPCMap = {};\n              allowedCPCString.split(',').forEach((keyFormatToCPCListStr) => {\n                  const splitList = keyFormatToCPCListStr.split(':');\n                  let keyFormat, cpcStr;\n                  if (splitList.length === 2) {\n                      // The keyformat\n                      keyFormat = splitList[0].trim();\n                      cpcStr = splitList[1].trim();\n                  }\n                  else if (splitList.length > 2) {\n                      cpcStr = splitList[splitList.length - 1].trim();\n                      splitList.pop();\n                      keyFormat = splitList.join(':');\n                  }\n                  else {\n                      return;\n                  }\n                  if (keyFormat in allowedCPCMap) {\n                      return;\n                  }\n                  let cpcLabels = new Array();\n                  if (cpcStr !== '') {\n                      cpcLabels = cpcStr.split('/').map((cpcLabel) => cpcLabel.trim());\n                  }\n                  allowedCPCMap[keyFormat] = cpcLabels;\n              });\n              return allowedCPCMap;\n          }\n          static parseSessionKeys(playlist, baseurl, keySystemPreference) {\n              let result;\n              const sessionKeys = [];\n              HlsRegex.SessionData.lastIndex = 0;\n              while ((result = HlsRegex.SessionKeys.exec(playlist))) {\n                  try {\n                      const decryptData = PlaylistParser.parseDecryptData(result[1], baseurl, keySystemPreference);\n                      if (decryptData && decryptData.isEncrypted) {\n                          sessionKeys.push(decryptData);\n                      }\n                  }\n                  catch (error) {\n                      // PlaylistParsingError: \"Invalid IV...\"\n                  }\n              }\n              return sessionKeys;\n          }\n          //#region session data\n          static parseSessionData(sessionDataString, baseurl) {\n              let result;\n              const sessionDataItemList = [];\n              const existingItems = new Set();\n              HlsRegex.SessionData.lastIndex = 0;\n              while ((result = HlsRegex.SessionData.exec(sessionDataString)) != null) {\n                  const attrs = PlaylistTagParser.parseTags(result[1]);\n                  attrs.LANGUAGE = bcp47Utils.shortenLanguageCode(attrs.LANGUAGE);\n                  const uniqueKey = attrs.LANGUAGE ? attrs['DATA-ID'] + '|' + attrs.LANGUAGE : undefined;\n                  if (isSessionDataItem(attrs)) {\n                      if (!uniqueKey || !existingItems.has(uniqueKey)) {\n                          // Prevent duplicated DATA-ID & LANGUAGE pair.\n                          // If LANGUAGE is absent, duplicated DATA-ID items may be okay.\n                          if (attrs['DATA-ID'] === SessionDataKey.OTHER_TEXT_BADGES) {\n                              attrs.VALUE = tryDecodeBase64Metadata(attrs.VALUE);\n                          }\n                          sessionDataItemList.push(attrs);\n                          if (uniqueKey) {\n                              existingItems.add(uniqueKey);\n                          }\n                      }\n                  }\n                  else {\n                      const logger = getLogger();\n                      logger.error(`Error processing DATA-ID ${attrs['DATA-ID']} and LANGUAGE ${attrs.LANGUAGE}`);\n                  }\n              }\n              const sessionData = {\n                  itemList: sessionDataItemList,\n                  baseUrl: baseurl,\n              };\n              return sessionData;\n          }\n      }\n      //#endregion session data\n      var PlaylistParser$1 = PlaylistParser;\n    \n      const fromUrlText = (requestCtx, loadConfig, extendMaxTTFB) => {\n          const ctx = Object.assign(Object.assign({}, requestCtx), { method: 'GET', responseType: 'text', extendMaxTTFB: extendMaxTTFB });\n          const url = ctx.url;\n          if (isCustomUrl(url)) {\n              const customUrlLoader = getCustomUrlLoader();\n              return customUrlLoader.load(ctx, loadConfig).pipe(map((res) => {\n                  const responseText = res.data.response.data.toString();\n                  return {\n                      responseText,\n                      responseURL: res.data.response.uri,\n                      stats: res.stats,\n                  };\n              }));\n          }\n          else {\n              return fromXMLHttpRequest(ctx, loadConfig).pipe(map(([xhr, stats]) => ({\n                  responseText: xhr.responseText,\n                  responseURL: xhr.responseURL,\n                  stats: stats,\n              })));\n          }\n      };\n    \n      const loadMediaOptionDetails = (mediaOption, itemStartOffset, config, loadPolicy, logger, keySystemPreference, statsService, masterVariableList, extendMaxTTFB) => {\n          const { url, itemId, mediaOptionId, mediaOptionType, iframes = false } = mediaOption;\n          const loadConfig = getLoadConfig(mediaOption, loadPolicy);\n          return fromUrlText({ url, xhrSetup: config.xhrSetup }, loadConfig, extendMaxTTFB).pipe(map(({ responseText: rawPlaylist, responseURL: rURL, stats }) => {\n              logger.debug(`media playlist url: ${url}, baseUrl: ${rURL}`);\n              if (!rURL) {\n                  logger.warn('Missing response url. Reusing request url as base url');\n                  rURL = url;\n              }\n              const t1 = performance.now();\n              const parsed = PlaylistParser.parseMediaOptionPlaylist(rawPlaylist, rURL, true, keySystemPreference, masterVariableList, itemId, mediaOptionId, mediaOptionType, logger, itemStartOffset, iframes);\n              updatePlaylistAttributes(parsed.mediaOptionDetails);\n              const t2 = performance.now();\n              const { mediaOptionDetails } = parsed;\n              const playlistSample = {\n                  playlistLoadTimeMs: stats.tload - stats.trequest,\n                  playlistParseTimeMs: t2 - t1,\n              };\n              statsService.setPlaylistSample(playlistSample);\n              const results = { mediaOptionDetails, stats };\n              return results;\n          }), convertToPlaylistNetworkError(mediaOptionType, mediaOptionId, false, url));\n      };\n    \n      const decryptMediaFragment = (mediaFragment, data, config, logger, crypto) => {\n          return of(data).pipe(switchMap((data) => {\n              const { keyTagInfo, isInitSegment, iframe, byteRangeOffset } = mediaFragment;\n              const { method } = keyTagInfo;\n              const { start, end } = byteRangeOffset;\n              if (method === 'AES-128') {\n                  if (keyTagInfo.uri && !keyTagInfo.iv && (!keyTagInfo.format || keyTagInfo.format === 'identity')) {\n                      keyTagInfo.iv = createInitializationVector(mediaFragment.mediaSeqNum);\n                  }\n                  const cipherText = data;\n                  const key = keyTagInfo.key.buffer;\n                  const iv = keyTagInfo.iv.buffer;\n                  // For Iframes and Initsegments, byterange indicates the plainText length - ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n                  // For media segments, byterange indicates the length of the cipherText, and the decrypt method will remove the padding to recover the plainText length\n                  const plainTextLength = end && (iframe || isInitSegment) ? end - start : undefined;\n                  /* WebCrypto is the default choice. However, we use JSCrypto in the following scenarios.\n                  1. WebCrypto disabled via config.\n                  2. Due to [rdar://73772133], Iframes or Initsegment served via byte-ranges.\n                  */\n                  const useJSCrypto = !config.enableWebCrypto || !!plainTextLength;\n                  const keyCopy = key.slice(0); // Copy the Key and IV for the webworker.\n                  const ivCopy = iv.slice(0); // Copy the Key and IV for the webworker.\n                  const options = { useJSCrypto, plainTextLength };\n                  return crypto.decrypt(keyCopy, ivCopy, 'AES-CBC', cipherText, options);\n              }\n              else {\n                  // If method is not AES-128, just return the original buffer\n                  return of(data);\n              }\n          }));\n      };\n      /**\n       * Utility method to create an initialization vector from integer\n       * @param ivValue  128-bit unsigned int representing initialization vector\n       * @returns {Uint8Array} Buffer representation of the IV\n       */\n      function createInitializationVector(ivValue) {\n          const uint8View = new Uint8Array(16);\n          for (let i = 12; i < 16; i++) {\n              uint8View[i] = (ivValue >> (8 * (15 - i))) & 255;\n          }\n          return uint8View;\n      }\n    \n      function fragIsInDetails(details, parsedFrag) {\n          const fragments = details.fragments;\n          const fragIdx = parsedFrag.mediaSeqNum - details.startSN;\n          return fragIdx >= 0 && fragIdx < details.fragments.length && fragEqual(parsedFrag, fragments[fragIdx]);\n      }\n      /**\n       * Update fragment lookup table\n       */\n      function updateFragPTSDTS(details, parsedFrag, startOffset, iframeMode, cpyModified = false, forceUpdateAll = false) {\n          if (!fragIsInDetails(details, parsedFrag)) {\n              return;\n          }\n          const fragIdx = parsedFrag.mediaSeqNum - details.startSN;\n          let fragments = details.fragments;\n          let frag = fragments[fragIdx];\n          const { startDtsTs, startPts, endPts } = parsedFrag;\n          if (cpyModified) {\n              fragments = details.fragments = details.fragments.slice(); // shallow cpy\n              frag = fragments[fragIdx] = Object.assign({}, frag);\n          }\n          frag.startDtsTs = startDtsTs;\n          frag.startPts = startPts;\n          frag.endPts = endPts;\n          if (iframeMode || frag.isIframeStart !== undefined) {\n              frag.isIframeStart = iframeMode;\n          }\n          frag.start = startOffset;\n          frag.duration = diffSeconds(endPts, startPts);\n          // adjust fragment PTS/duration from seqnum-1 to frag 0\n          for (let i = fragIdx, canContinue = true; i > 0 && (forceUpdateAll || canContinue); i--) {\n              canContinue = updatePTS(fragments, i, i - 1, iframeMode, startPts.timescale, cpyModified);\n          }\n          // adjust fragment PTS/duration from seqnum to last frag\n          for (let i = fragIdx, canContinue = true; i < fragments.length - 1 && (forceUpdateAll || canContinue); i++) {\n              canContinue = updatePTS(fragments, i, i + 1, iframeMode, startPts.timescale, cpyModified);\n          }\n          const endFrag = fragments[fragments.length - 1];\n          details.totalduration = endFrag.start + endFrag.duration - fragments[0].start;\n          details.ptsKnown = true;\n      }\n      /**\n       *\n       * @param fragments   fragment list\n       * @param fromIdx     index inside fragments of the reference fragment\n       * @param toIdx       index inside fragments of the fragment to modify\n       * @param iframeMode  (optional) the iframeMode when this was called\n       * @param timescale   (optional) use timescale for deciding if value is changed enough to update\n       * @param cpyModified (optional) whether we should make a copy of the fragment rather than modify in place\n       * @returns whether it should continue iterating\n       */\n      function updatePTS(fragments, fromIdx, toIdx, iframeMode, timescale, cpyModified = false) {\n          const fragFrom = fragments[fromIdx];\n          let fragTo = fragments[toIdx];\n          const forceUpdateStartTime = iframeMode != null && fragTo.isIframeStart != null && fragTo.isIframeStart !== iframeMode && fragTo.discoSeqNum === fragFrom.discoSeqNum;\n          let newStart = fragTo.start;\n          // Update all frag start times in disco after iframe transition or unknown pts\n          if (forceUpdateStartTime || fragTo.startPts == null) {\n              if (toIdx > fromIdx) {\n                  newStart = fragFrom.start + fragFrom.duration;\n              }\n              else {\n                  newStart = Math.max(fragFrom.start - fragTo.duration, 0);\n              }\n          }\n          const precision = isFiniteNumber(timescale) ? 1 / timescale : Number.EPSILON;\n          const timeChanged = Math.abs(fragTo.start - newStart) > precision;\n          if (forceUpdateStartTime || timeChanged) {\n              // Never update duration. These are parsed values.\n              if (cpyModified) {\n                  fragTo = fragments[toIdx] = Object.assign({}, fragTo);\n              }\n              if (timeChanged) {\n                  fragTo.start = newStart;\n              }\n              if (forceUpdateStartTime) {\n                  fragTo.isIframeStart = iframeMode;\n              }\n              return true;\n          }\n          return false;\n      }\n      function updateDateToMediaTimeMap(details) {\n          if (details.programDateTimeMap) {\n              details.dateMediaTimePairs = [];\n              for (const [dtStr, sn] of Object.entries(details.programDateTimeMap)) {\n                  const dt = Number(dtStr);\n                  const frag = details.fragments[sn - details.startSN];\n                  if (frag) {\n                      const startTime = frag.start;\n                      details.dateMediaTimePairs.push([dt, startTime]);\n                  }\n              }\n              details.dateMediaTimePairs.sort((a, b) => {\n                  return a[0] - b[0];\n              });\n          }\n      }\n    \n      class SimpleListFilter {\n          constructor(option) {\n              this.option = option;\n          }\n          get name() {\n              return this.option.name;\n          }\n          get priority() {\n              return this.option.priority;\n          }\n          get expiry() {\n              return this.option.expiry;\n          }\n          filter(originalList, options) {\n              const context = (this.option.initFn && this.option.initFn(originalList, options)) || (options ? Object.assign({}, options) : {});\n              let filteredList = originalList;\n              if (this.option.firstPassFn) {\n                  originalList.forEach((value, index) => this.option.firstPassFn(value, index, context, originalList));\n              }\n              if (this.option.filterFn) {\n                  filteredList = originalList.filter((value, index) => this.option.filterFn(value, index, context, originalList));\n              }\n              if ((this.option.filterFn == null || filteredList.length === 0) && this.option.minSortingFn) {\n                  filteredList = originalList.sort((a, b) => this.option.minSortingFn(a, b, context, originalList));\n              }\n              if (this.option.finalFn) {\n                  this.option.finalFn(filteredList, context, originalList);\n              }\n              return filteredList;\n          }\n      }\n      function applyFilters(originalList, filters, options) {\n          return (filters || []).reduce((list, filter) => filter.filter(list, options), Array.from(originalList));\n      }\n      function isExpired(expiry, now) {\n          return now >= expiry;\n      }\n      function sortFilters(filters) {\n          const cpy = [...filters];\n          return cpy.sort((a, b) => {\n              var _a, _b;\n              const priorityA = (_a = a.priority) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER;\n              const priorityB = (_b = b.priority) !== null && _b !== void 0 ? _b : Number.MAX_SAFE_INTEGER;\n              return priorityA - priorityB;\n          });\n      }\n    \n      function getPreferredList(preferredHost, filteredMediaOptionList) {\n          return filteredMediaOptionList.filter((x) => { var _a; return hasMatchingHost(preferredHost, (_a = x.url) !== null && _a !== void 0 ? _a : null); });\n      }\n      function newRemoveFilter() {\n          return new SimpleListFilter({\n              name: 'Remove Filter',\n              priority: 0,\n              filterFn: (value, index, options) => {\n                  return !options || options.removed.every((mediaOptionId) => value.mediaOptionId !== mediaOptionId);\n              },\n          });\n      }\n      function newPenaltyBoxFilter() {\n          return new SimpleListFilter({\n              name: 'Penalty Box Filter',\n              priority: 1,\n              filterFn: (value, index, options) => {\n                  const now = performance.now();\n                  return !options || options.penaltyBoxQueue.every((info) => isExpired(info.expiry, now) || value.mediaOptionId !== info.mediaOptionId);\n              },\n          });\n      }\n      function newCompatibleIdsFilter() {\n          return new SimpleListFilter({\n              name: 'Compatible IDs Filter',\n              priority: 1,\n              filterFn: (value, index, options) => {\n                  return !options || options.compatibleIds == null || options.compatibleIds.some((id) => id === value.mediaOptionId);\n              },\n          });\n      }\n      function makeCommonFilters() {\n          // prettier-ignore\n          return [\n              newRemoveFilter(),\n              newPenaltyBoxFilter(),\n              newCompatibleIdsFilter(),\n          ];\n      }\n      /**\n       * @brief Query used to get the filtered media option list for a given media option type.\n       */\n      class MediaOptionListQuery extends QueryEntity {\n          constructor(store, itemId, mediaOptionType) {\n              super(store);\n              this.itemId = itemId;\n              this.mediaOptionType = mediaOptionType;\n              this.allowFilters = this._initFilters();\n          }\n          /**\n           * Get the unfiltered media option list\n           */\n          get mediaOptionList() {\n              var _a;\n              return ((_a = this.mediaOptionListInfo) === null || _a === void 0 ? void 0 : _a.mediaOptions) || null;\n          }\n          get mediaOptionList$() {\n              return this.mediaOptionListInfo$.pipe(map(({ mediaOptions }) => mediaOptions));\n          }\n          mediaOptionFromId(mediaOptionId) {\n              var _a, _b;\n              const list = (_a = this.mediaOptionList) !== null && _a !== void 0 ? _a : [];\n              return (_b = list.find((option) => option.mediaOptionId === mediaOptionId)) !== null && _b !== void 0 ? _b : null;\n          }\n          _getFilteredList(mediaOptionListInfo) {\n              const mediaOptionList = mediaOptionListInfo.mediaOptions;\n              return applyFilters(mediaOptionList, this.allowFilters, mediaOptionListInfo);\n          }\n          /**\n           * Get the filtered media option list\n           */\n          get filteredMediaOptionList() {\n              return this.mediaOptionListInfo ? this._getFilteredList(this.mediaOptionListInfo) : null;\n          }\n          get filteredMediaOptionList$() {\n              return this.mediaOptionListInfo$.pipe(switchMap((mediaOptionListInfo) => {\n                  const fire$ = [VOID];\n                  const now = performance.now();\n                  for (const penalty of mediaOptionListInfo.penaltyBoxQueue) {\n                      if (isFiniteNumber(penalty.expiry) && penalty.expiry > now) {\n                          fire$.push(timer(penalty.expiry - now));\n                      }\n                  }\n                  return merge(...fire$).pipe(map(() => {\n                      return this._getFilteredList(mediaOptionListInfo);\n                  }));\n              }), distinctUntilArrayItemChanged());\n          }\n          /**\n           * Get the filtered media option list that also has a hostname matching the preferred host\n           */\n          get preferredMediaOptionList() {\n              return this.filteredMediaOptionList ? getPreferredList(this.preferredHost, this.filteredMediaOptionList) : [];\n          }\n          get preferredMediaOptionList$() {\n              return combineQueries([this.preferredHost$, this.filteredMediaOptionList$]).pipe(map(([preferredHost, filteredMediaOptionList]) => {\n                  return getPreferredList(preferredHost, filteredMediaOptionList);\n              }));\n          }\n          /**\n           * @param fromId Media option id used as reference for the switch\n           * @returns The new host to switch to, or the current host if not switching\n           */\n          getNewHost(fromId) {\n              const fallback = this.getFallbackVariant(fromId, false, true);\n              if (fallback === null || fallback === void 0 ? void 0 : fallback.url) {\n                  return getHostName(fallback.url);\n              }\n              return this.preferredHost;\n          }\n      }\n    \n      function isHDRLevel(levelInfo) {\n          return levelInfo.videoRange === 'PQ' || levelInfo.videoRange === 'HLG';\n      }\n      function isIframeLevel(option) {\n          return isMatchingIframeLevel(true, option);\n      }\n      function isMatchingIframeLevel(iframeMode, option) {\n          return option.iframes === iframeMode;\n      }\n      /**\n       * Sort function for variants. Ordering determines how ABR mediaOptionList is stored.\n       * Order will be preserved even after filtering\n       *\n       * @param variantList The list to sort\n       * @param hasScore Use SCORE to sort the list\n       * @returns Sorted list\n       */\n      function sortVariants(variantList, hasScore) {\n          const cpy = [...variantList];\n          if (hasScore) {\n              // ascending order by score, then descending order by bitrate\n              cpy.sort((a, b) => {\n                  return a.score - b.score || b.bitrate - a.bitrate;\n              });\n          }\n          else {\n              // bitrate in ascending order\n              cpy.sort((a, b) => {\n                  return a.bitrate - b.bitrate;\n              });\n          }\n          return cpy;\n      }\n      var Rank;\n      (function (Rank) {\n          Rank[Rank[\"Better\"] = 1] = \"Better\";\n          Rank[Rank[\"Same\"] = 0] = \"Same\";\n          Rank[Rank[\"Worse\"] = -1] = \"Worse\";\n      })(Rank || (Rank = {}));\n      /**\n       * @param fromVariant The variant we're switching from. We will try to choose something with similar bitrate in all cases\n       * @param hasScore Whether we should consider SCORE attribute when comparing candidates\n       * @param candidate Candidate to consider\n       * @param currentBest Current best candidate\n       * @returns Better if candidate is better than currentBest, Same if candidate is same as currentBest, else Worse\n       */\n      function compareCandidate(fromVariant, hasScore, candidate, currentBest) {\n          // TODO: handle SCORE\n          if (!currentBest || (candidate.bitrate > currentBest.bitrate && candidate.bitrate <= fromVariant.bitrate)) {\n              return Rank.Better;\n          }\n          else if (candidate.bitrate === currentBest.bitrate) {\n              return Rank.Same;\n          }\n          return Rank.Worse;\n      }\n      function rankComparison(matchA, matchB) {\n          if (matchA && !matchB) {\n              return -1;\n          }\n          else if (!matchA && matchB) {\n              return 1;\n          }\n          return 0;\n      }\n      function sortFallbackVariants(variantList, fromVariant, hasScore) {\n          const cpy = [...variantList];\n          const fromHost = getHostName(fromVariant.url);\n          const fromAudioGroup = fromVariant.audioGroupId;\n          // sort score or bitrate in descending order\n          // tie breaker: hostname, then audioGroup\n          cpy.sort((a, b) => {\n              let rank = 0;\n              const useScore = hasScore && isFiniteNumber(a.score) && isFiniteNumber(b.score);\n              const ABetterThanB = useScore ? a.score > b.score && a.score <= fromVariant.score : a.bitrate > b.bitrate && a.bitrate <= fromVariant.bitrate;\n              const AEqualB = useScore ? a.score === b.score : a.bitrate === b.bitrate;\n              if (ABetterThanB) {\n                  rank = -1;\n              }\n              else if (AEqualB) {\n                  const AmatchHost = hasMatchingHost(fromHost, a.url);\n                  const BmatchHost = hasMatchingHost(fromHost, b.url);\n                  rank = rankComparison(AmatchHost, BmatchHost);\n                  if (rank === 0) {\n                      const AmatchGroup = !fromAudioGroup || a.audioGroupId === fromAudioGroup;\n                      const BmatchGroup = !fromAudioGroup || b.audioGroupId === fromAudioGroup;\n                      rank = rankComparison(AmatchGroup, BmatchGroup);\n                  }\n              }\n              else {\n                  rank = 1;\n              }\n              return rank;\n          });\n          return cpy;\n      }\n      function newHDRFilter() {\n          return new SimpleListFilter({\n              name: 'HDR Filter',\n              priority: 1,\n              filterFn: (value, index, options) => {\n                  return !options || (options.hasHdrLevels && options.preferHDR) === isHDRLevel(value);\n              },\n          });\n      }\n      function isSizeWithinTolerance(variant, viewportInfo) {\n          const TOLERANCE_FACTOR = 1.35; // Value inherited from native stack\n          return (variant.width < viewportInfo.width * TOLERANCE_FACTOR &&\n              variant.height < viewportInfo.height * TOLERANCE_FACTOR &&\n              variant.width * variant.height < viewportInfo.width * viewportInfo.height * TOLERANCE_FACTOR);\n      }\n      function newViewportFilter() {\n          return new SimpleListFilter({\n              name: 'Viewport Filter',\n              priority: 1,\n              firstPassFn: (value, index, context) => {\n                  if (context && value && !value.iframes && value.videoCodec) {\n                      // Find the lowest non-iframe level with video\n                      const lowestBitrate = !context.lowestBitrate || value.bitrate < context.lowestBitrate ? value.bitrate : context.lowestBitrate;\n                      context.lowestBitrate = lowestBitrate;\n                  }\n              },\n              filterFn: (value, index, context) => {\n                  if (!value || !context || !context.viewportInfo || !value.videoCodec || !context.lowestBitrate) {\n                      // Don't apply this filter\n                      return true;\n                  }\n                  // Allow only the sizes within tolerance or if it's the lowest bitrate\n                  return isSizeWithinTolerance({ width: value.width, height: value.height }, context.viewportInfo) || value.bitrate === context.lowestBitrate;\n              },\n          });\n      }\n      function newHDCPFilter() {\n          return new SimpleListFilter({\n              name: 'HDCP Filter',\n              priority: 2,\n              filterFn: (value, index, options) => {\n                  return !options || !isHdcpLevel(options.maxHdcpLevel) || hdcpLevelToInt(value.hdcpLevel) < hdcpLevelToInt(options.maxHdcpLevel);\n              },\n          });\n      }\n      class VariantMediaOptionListQuery extends MediaOptionListQuery {\n          constructor(store, itemId) {\n              super(store, itemId, MediaOptionType.Variant);\n          }\n          static makeFilters() {\n              // prettier-ignore\n              return sortFilters(makeCommonFilters().concat([\n                  newHDRFilter(),\n                  newViewportFilter(),\n                  newHDCPFilter(),\n                  // TODO: Fix rdar://81171922 and re-enable content steering\n                  // newPathwayFilter(),\n              ]));\n          }\n          _initFilters() {\n              return VariantMediaOptionListQuery.kAllowFilters;\n          }\n          get preferredHost() {\n              var _a, _b;\n              return (_b = (_a = this.mediaOptionListInfo) === null || _a === void 0 ? void 0 : _a.preferredHost) !== null && _b !== void 0 ? _b : null;\n          }\n          get preferredHost$() {\n              return this.selectEntity(this.itemId, (entity) => {\n                  var _a;\n                  return (_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionListTuple[MediaOptionType.Variant].preferredHost) !== null && _a !== void 0 ? _a : null;\n              });\n          }\n          get mediaOptionListInfo() {\n              var _a, _b;\n              return (_b = (_a = this.getEntity(this.itemId)) === null || _a === void 0 ? void 0 : _a.mediaOptionListTuple[MediaOptionType.Variant]) !== null && _b !== void 0 ? _b : null;\n          }\n          get mediaOptionListInfo$() {\n              return this.selectEntity(this.itemId, (entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionListTuple) === null || _a === void 0 ? void 0 : _a[MediaOptionType.Variant]; }).pipe(filterNullOrUndefined());\n          }\n          get hdrMode$() {\n              return this.mediaOptionListInfo$.pipe(map((info) => {\n                  return info.preferHDR === true && info.hasHdrLevels;\n              }), distinctUntilChanged());\n          }\n          get maxHdcpLevel$() {\n              return this.selectEntity(this.itemId, (entity) => {\n                  var _a;\n                  const info = (_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionListTuple) === null || _a === void 0 ? void 0 : _a[MediaOptionType.Variant];\n                  return info === null || info === void 0 ? void 0 : info.maxHdcpLevel;\n              }).pipe(distinctUntilChanged());\n          }\n          // excludingOptions is useful for skipping visited variants in successive getFallbackVariant\n          listFallbackVariants(fromId, sdrOnly, shouldSwitchHosts, shouldDownswitch, excludingOptions = undefined) {\n              var _a;\n              const mediaOptionListInfo = this.mediaOptionListInfo;\n              const fromVariant = (_a = this.mediaOptionList) === null || _a === void 0 ? void 0 : _a.find((x) => x.mediaOptionId === fromId);\n              if (!fromVariant || !mediaOptionListInfo) {\n                  return null;\n              }\n              const filteredList = this.makeFilteredListFromVariant(fromVariant, sdrOnly, excludingOptions);\n              if (!filteredList) {\n                  return null;\n              }\n              const fromHost = getHostName(fromVariant.url);\n              const hasScore = mediaOptionListInfo.hasScore;\n              return VariantMediaOptionListQuery._listFallbackVariants(filteredList, fromVariant, fromHost, hasScore, shouldSwitchHosts, shouldDownswitch, excludingOptions);\n          }\n          // excludingOptions is useful for skipping visited variants in successive getFallbackVariant\n          getFallbackVariant(fromId, sdrOnly, shouldSwitchHosts, excludingOptions = undefined) {\n              var _a;\n              const mediaOptionListInfo = this.mediaOptionListInfo;\n              const fromVariant = (_a = this.mediaOptionList) === null || _a === void 0 ? void 0 : _a.find((x) => x.mediaOptionId === fromId);\n              if (!fromVariant || !mediaOptionListInfo) {\n                  return null;\n              }\n              const filteredList = this.makeFilteredListFromVariant(fromVariant, sdrOnly, excludingOptions);\n              if (!filteredList) {\n                  return null;\n              }\n              const fromHost = getHostName(fromVariant.url);\n              const hasScore = mediaOptionListInfo.hasScore;\n              return VariantMediaOptionListQuery._getFallbackVariant(filteredList, fromVariant, fromHost, hasScore, shouldSwitchHosts);\n          }\n          makeFilteredListFromVariant(fromVariant, sdrOnly, excludingOptions = undefined) {\n              let mediaOptionListInfo = this.mediaOptionListInfo;\n              if (!fromVariant || !this.mediaOptionList || !mediaOptionListInfo) {\n                  return null;\n              }\n              mediaOptionListInfo = Object.assign(Object.assign({}, mediaOptionListInfo), { includeAllEligiblePathways: true });\n              const originalList = Array.from(this.mediaOptionList);\n              let filteredList = sdrOnly ? applyFilters(originalList, this.allowFilters, Object.assign(Object.assign({}, mediaOptionListInfo), { preferHDR: false, compatibleIds: null })) : this._getFilteredList(mediaOptionListInfo);\n              if (!filteredList) {\n                  return null;\n              }\n              if (excludingOptions && excludingOptions.length > 0) {\n                  filteredList = filteredList.filter((option) => !excludingOptions.includes(option.mediaOptionId));\n              }\n              return filteredList;\n          }\n          get hasIframes() {\n              var _a, _b;\n              return (_b = (_a = this.mediaOptionListInfo) === null || _a === void 0 ? void 0 : _a.hasIframeLevels) !== null && _b !== void 0 ? _b : false;\n          }\n          /**\n           * @returns true if fromId is an HDR level and we can switch to a SDR level\n           */\n          canSwitchToSDR(fromId, shouldSwitchHosts, shouldDownswitch = false) {\n              const mediaOptionListInfo = this.mediaOptionListInfo;\n              if (!this.mediaOptionList || !mediaOptionListInfo) {\n                  return false;\n              }\n              const fromVariant = this.mediaOptionFromId(fromId);\n              if (!fromVariant) {\n                  return false;\n              }\n              if (!isHDRLevel(fromVariant)) {\n                  return false;\n              }\n              const fromHost = getHostName(fromVariant.url);\n              // Get filtered list but override hdr preference to false\n              const originalList = Array.from(this.mediaOptionList);\n              const filteredList = applyFilters(originalList, this.allowFilters, Object.assign(Object.assign({}, mediaOptionListInfo), { preferHDR: false, compatibleIds: null }));\n              const hasScore = mediaOptionListInfo.hasScore;\n              return VariantMediaOptionListQuery._getFallbackVariant(filteredList, fromVariant, fromHost, hasScore, shouldSwitchHosts, shouldDownswitch) != null;\n          }\n          // Generic helper function for finding a fallback given a filtered list and the failing variant\n          static _listFallbackVariants(filteredList, fromVariant, fromHost, hasScore, shouldSwitchHosts, shouldDownswitch = false, excludingOptions = null) {\n              // shouldDownswitch: On timeout we want to pick variant with bitrate lower than currently being downloaded\n              let needFromVariant = false;\n              const candidateList = filteredList.filter((candidate) => {\n                  const validCandidate = candidate.iframes === fromVariant.iframes && (!shouldSwitchHosts || !hasMatchingHost(fromHost, candidate.url));\n                  const lesserTier = shouldDownswitch ? candidate.bitrate < fromVariant.bitrate : candidate.bitrate <= fromVariant.bitrate;\n                  const success = validCandidate && lesserTier;\n                  if (fromVariant.mediaOptionId === candidate.mediaOptionId) {\n                      needFromVariant = success; // if needed, add fromVariant to the top of candidateList later\n                      return false;\n                  }\n                  return success;\n              });\n              const result = sortFallbackVariants(candidateList, fromVariant, hasScore);\n              if (needFromVariant && (!excludingOptions || !excludingOptions.includes(fromVariant.mediaOptionId))) {\n                  result.unshift(fromVariant); // put fromVariant at the top if not excluded\n              }\n              return result;\n          }\n          // Generic helper function for finding a fallback given a filtered list and the failing variant\n          static _getFallbackVariant(filteredList, fromVariant, fromHost, hasScore, shouldSwitchHosts, shouldDownswitch = false) {\n              // Choose best option between these two\n              let newVariant = null;\n              // On timeout we want to pick variant with bitrate lower than currently being downloaded\n              if (shouldDownswitch) {\n                  filteredList = filteredList.filter((option) => option.bitrate < fromVariant.bitrate);\n              }\n              const candidateList = filteredList.filter((candidate) => candidate.mediaOptionId !== fromVariant.mediaOptionId && candidate.iframes === fromVariant.iframes);\n              if (shouldSwitchHosts && fromHost != null) {\n                  // Choose from different host\n                  for (const candidate of candidateList) {\n                      if (compareCandidate(fromVariant, hasScore, candidate, newVariant) === Rank.Better && !hasMatchingHost(fromHost, candidate.url)) {\n                          newVariant = candidate;\n                      }\n                  }\n              }\n              else {\n                  // Choose best one from any host. Tie breaker favors current host\n                  // If hosts are same between candidates, favor same audio group\n                  for (const candidate of candidateList) {\n                      const rank = compareCandidate(fromVariant, hasScore, candidate, newVariant);\n                      if (rank === Rank.Better ||\n                          (rank === Rank.Same && hasMatchingHost(fromHost, candidate.url) && (!hasMatchingHost(fromHost, newVariant.url) || candidate.audioGroupId === fromVariant.audioGroupId))) {\n                          newVariant = candidate;\n                      }\n                  }\n              }\n              return newVariant;\n          }\n          // Get media option matching the input mediaOption groupID\n          getMatchingVariant(fromId, mediaOption) {\n              const fromVariant = this.mediaOptionFromId(fromId);\n              const fromHost = getHostName(fromVariant === null || fromVariant === void 0 ? void 0 : fromVariant.url);\n              const whichGroup = mediaOption.mediaOptionType === MediaOptionType.AltAudio ? 'audioGroupId' : 'subtitleGroupId';\n              let bestCandidate = null;\n              const hasScore = this.mediaOptionListInfo.hasScore;\n              for (const candidate of this.filteredMediaOptionList) {\n                  if (candidate[whichGroup] !== mediaOption.groupId) {\n                      continue;\n                  }\n                  if (!fromVariant) {\n                      bestCandidate = candidate; // First mediaOption with matching groupId\n                      break;\n                  }\n                  const rank = compareCandidate(fromVariant, hasScore, candidate, bestCandidate);\n                  if (rank === Rank.Better ||\n                      (rank === Rank.Same && bestCandidate.mediaOptionId !== fromVariant.mediaOptionId && (candidate.mediaOptionId === fromVariant.mediaOptionId || hasMatchingHost(fromHost, candidate.url)))) {\n                      bestCandidate = candidate;\n                  }\n              }\n              return bestCandidate;\n          }\n          get currentPathwayID() {\n              var _a;\n              return (_a = this.mediaOptionListInfo) === null || _a === void 0 ? void 0 : _a.currentPathwayID;\n          }\n      }\n      VariantMediaOptionListQuery.kAllowFilters = VariantMediaOptionListQuery.makeFilters();\n    \n      /**\n       * Error handling policies. This file handles general error handling\n       *\n       * @copyright 2018 Apple Inc. All rights reserved.\n       */\n      /**\n       * @brief Common error actions\n       */\n      var NetworkErrorAction;\n      (function (NetworkErrorAction) {\n          NetworkErrorAction[NetworkErrorAction[\"DoNothing\"] = 0] = \"DoNothing\";\n          NetworkErrorAction[NetworkErrorAction[\"SendEndCallback\"] = 1] = \"SendEndCallback\";\n          NetworkErrorAction[NetworkErrorAction[\"SendAlternateToPenaltyBox\"] = 2] = \"SendAlternateToPenaltyBox\";\n          NetworkErrorAction[NetworkErrorAction[\"RemoveAlternatePermanently\"] = 3] = \"RemoveAlternatePermanently\";\n          NetworkErrorAction[NetworkErrorAction[\"InsertDiscontinuity\"] = 4] = \"InsertDiscontinuity\";\n          NetworkErrorAction[NetworkErrorAction[\"RetryRequest\"] = 5] = \"RetryRequest\";\n      })(NetworkErrorAction || (NetworkErrorAction = {}));\n      /**\n       * PenaltyBox or Remove only. Additional flags for determining what we should do\n       */\n      var ErrorActionFlags;\n      (function (ErrorActionFlags) {\n          ErrorActionFlags[ErrorActionFlags[\"MoveAllAlternatesMatchingHost\"] = 1] = \"MoveAllAlternatesMatchingHost\";\n          ErrorActionFlags[ErrorActionFlags[\"MoveAllAlternatesMatchingHDCP\"] = 2] = \"MoveAllAlternatesMatchingHDCP\";\n          ErrorActionFlags[ErrorActionFlags[\"SwitchToSDR\"] = 4] = \"SwitchToSDR\";\n      })(ErrorActionFlags || (ErrorActionFlags = {}));\n      /**\n       * Modify the error action if we have no fallbacks to switch to\n       *\n       * @param errorAction Original error action\n       * @param errorCode The error code\n       */\n      function _modifyErrorActionIfLastValidVariantInternal(errorAction, errorCode) {\n          switch (errorAction) {\n              case NetworkErrorAction.SendAlternateToPenaltyBox:\n                  errorAction = NetworkErrorAction.RetryRequest;\n                  if (errorCode === 401 ||\n                      errorCode === 403 ||\n                      errorCode === 407 ||\n                      errorCode === ErrorResponses.CorruptStream.code ||\n                      errorCode === ErrorResponses.LivePlaylistUpdateError.code // We've already retried up to max at this point\n                  ) {\n                      errorAction = NetworkErrorAction.SendEndCallback;\n                  }\n                  break;\n              case NetworkErrorAction.RemoveAlternatePermanently:\n                  errorAction = NetworkErrorAction.SendEndCallback;\n                  break;\n          }\n          return errorAction;\n      }\n      /**\n       * Common code to modify if it's the last variant of its kind in the controller\n       * @param originalAction  Original action from getActionForCommonError\n       * @param isPrefetch Was a prefetch (or not needed immediately for playback)\n       * @param errorCode The error code\n       * @param mediaOptionId Option id\n       * @param mediaOptionType The type\n       * @param rootQuery Root playlist query\n       */\n      function modifyErrorActionIfCurrentLevelIsLastValidLevel(originalAction, isPrefetch, errorCode, mediaOptionId, mediaOptionType, rootQuery, rootService, isTimeout = false) {\n          const mediaListQuery = rootQuery.mediaOptionListQueries[mediaOptionType];\n          const shouldSwitchHosts = (originalAction.errorActionFlags & ErrorActionFlags.MoveAllAlternatesMatchingHost) != 0;\n          const mediaOption = rootQuery.mediaOptionListQueries[mediaOptionType].mediaOptionFromId(mediaOptionId);\n          const fallbackMediaOptions = rootService.getFallbackMediaOptionTupleFromMediaOptionId(rootQuery, mediaOptionType, mediaOptionId, mediaOption.backingMediaOptionId, false, shouldSwitchHosts, isTimeout);\n          let { errorAction, errorActionFlags } = originalAction;\n          if (!rootQuery.isValidMediaOptionTuple(fallbackMediaOptions)) {\n              if (!isPrefetch) {\n                  errorAction = _modifyErrorActionIfLastValidVariantInternal(errorAction, errorCode);\n                  errorActionFlags = 0;\n              }\n              if (mediaListQuery instanceof VariantMediaOptionListQuery) {\n                  const mediaOption = mediaListQuery.mediaOptionFromId(mediaOptionId);\n                  if (mediaOption.iframes === true) {\n                      errorAction = NetworkErrorAction.DoNothing;\n                      errorActionFlags = 0;\n                      rootService.logger.debug(`[modifyErrorAction] skip error handling for iframes; isPrefetch ${isPrefetch} fallback ${fallbackMediaOptions}`);\n                  }\n                  else if (!isPrefetch && rootService.canSwitchToSDR(rootQuery, mediaOptionId, shouldSwitchHosts, isTimeout)) {\n                      errorAction = originalAction.errorAction;\n                      errorActionFlags = ErrorActionFlags.SwitchToSDR;\n                      rootService.logger.debug(`[modifyErrorAction] switchToSDR; isPrefetch ${isPrefetch} fallback ${fallbackMediaOptions} isTimeout ${isTimeout}`);\n                  }\n              }\n          }\n          else if (hasMatchingHost(mediaListQuery.preferredHost, fallbackMediaOptions[mediaOptionType].url)) {\n              errorActionFlags &= ~ErrorActionFlags.MoveAllAlternatesMatchingHost;\n              rootService.logger.debug(`[modifyErrorAction] matched preferredHost ${mediaListQuery.preferredHost}; isPrefetch ${isPrefetch} fallback ${fallbackMediaOptions}`);\n          }\n          return { errorAction, errorActionFlags };\n      }\n      // Get default error action based on error codes\n      function _getActionForCommonNetworkError(errorCode) {\n          let errorAction;\n          let errorActionFlags = 0;\n          switch (errorCode) {\n              case 0:\n                  // 0 is sometimes returned as a CORS error or a \"muted\" error when \"--disable-web-security --ignore-certificate-errors\" are used in Chrome.\n                  errorAction = NetworkErrorAction.SendAlternateToPenaltyBox;\n                  errorActionFlags = ErrorActionFlags.MoveAllAlternatesMatchingHost;\n                  break;\n              case 410:\n                  errorAction = NetworkErrorAction.RemoveAlternatePermanently;\n                  break;\n              case 500: // Internal Server error\n              case 502: // Bad gateway\n              case 503: // Service unavailable\n              case 504: // Gateway timeout\n              case 404: // NotFound\n              case 409: // Conflict\n              case 401: // Unauthorized\n              case 403: // Forbidden\n              case 407: // Proxy error\n              case ErrorResponses.LivePlaylistUpdateError.code: // -12888\n              case ErrorResponses.PlaylistNotReceived.code: // -12884\n              default:\n                  errorAction = NetworkErrorAction.SendAlternateToPenaltyBox;\n                  errorActionFlags = 0;\n                  break;\n          }\n          return { errorAction, errorActionFlags };\n      }\n      /**\n       * Modify the error action if we think we're going to take too long....\n       *\n       * @param error The error\n       * @param originalAction The original action\n       * @param isPrefetch true if this is not for playback but optimistic load\n       * @param maxTimeouts The maximum number of consecutive timeouts allowed\n       * @param rootQuery The root playlist query\n       * @return modified error action\n       */\n      function _modifyActionOnTimeout(error, originalAction, isPrefetch, maxTimeouts, rootQuery) {\n          var _a, _b;\n          let { errorAction, errorActionFlags } = originalAction;\n          if (error.isTimeout) {\n              const { mediaOptionType } = error;\n              const consecutiveTimeouts = (_b = (_a = rootQuery.getErrorInfoByType(mediaOptionType)) === null || _a === void 0 ? void 0 : _a.timeouts['load']) !== null && _b !== void 0 ? _b : 0;\n              if (!isPrefetch && consecutiveTimeouts >= maxTimeouts) {\n                  // this.logger.warn(`Hit max consecutive penalty due to timeout count: ${error.details}`);\n                  errorAction = NetworkErrorAction.DoNothing; // don't treat timeouts as fatal, if the NW conditions don't improve, low buffer will lead to end playback\n                  errorActionFlags = 0;\n              }\n          }\n          return { errorAction, errorActionFlags };\n      }\n      /**\n       * Get the policy for a manifest load error\n       * @param error The error\n       */\n      function getActionForManifestError(error) {\n          let { errorAction, errorActionFlags } = _getActionForCommonNetworkError(error.response.code);\n          errorAction = _modifyErrorActionIfLastValidVariantInternal(errorAction, error.response.code);\n          errorActionFlags = 0; // cannot default to a backup CDN for manifest\n          // this.logger.info(`Manifest error ${errorAction}`);\n          return { errorAction, errorActionFlags };\n      }\n      /**\n       * Get the policy for a playlist load error\n       * @param error The error\n       * @param isPrefetch true if this is not critical for playback. For instance i-frame\n       * @param maxTimeouts The maximum number of consecutive timeouts allowed\n       * @param rootQuery The root playlist query\n       * @returns The action to perform\n       */\n      function getActionForPlaylistOrFragError(error, isPrefetch, maxTimeouts, rootQuery, rootService) {\n          const errorCode = error.response.code;\n          let result = _getActionForCommonNetworkError(errorCode);\n          const { mediaOptionId, mediaOptionType } = error;\n          if (isPrefetch) {\n              // Do not modify on last level in prefetch mode\n              result.errorActionFlags &= ~ErrorActionFlags.MoveAllAlternatesMatchingHost;\n          }\n          else {\n              result = _modifyActionOnTimeout(error, result, isPrefetch, maxTimeouts, rootQuery);\n          }\n          result = modifyErrorActionIfCurrentLevelIsLastValidLevel(result, isPrefetch, errorCode, mediaOptionId, mediaOptionType, rootQuery, rootService, error.isTimeout);\n          // rootService.logger.info(`[${error.type}] Got playlist error ${errorCode} ${error.message} ${JSON.stringify(result)}`);\n          return result;\n      }\n      /**\n       * Handle a network error due to crypt key failure\n       * @param error     KeyError\n       * @param mediaOptionId One of the media options associated with this error\n       * @param mediaOptionType The media option type associated with the media option id\n       * @param rootQuery The root query to use\n       */\n      function getActionForCryptKeyNetworkError(error, mediaOptionId, mediaOptionType, rootQuery, rootService) {\n          let action = {\n              errorAction: NetworkErrorAction.SendAlternateToPenaltyBox,\n              errorActionFlags: 0,\n          };\n          if (error instanceof KeyRequestTimeoutError) {\n              action.errorAction = NetworkErrorAction.SendAlternateToPenaltyBox;\n          }\n          else {\n              const isOkToRetry = error.isOkToRetry;\n              const isHDCPError = error.keyErrorReason === KeyRequestErrorReason.OutputRestricted;\n              if (isHDCPError) {\n                  action.errorAction = NetworkErrorAction.RemoveAlternatePermanently;\n                  action.errorActionFlags |= ErrorActionFlags.MoveAllAlternatesMatchingHDCP;\n              }\n              else if (!isOkToRetry) {\n                  action.errorAction = NetworkErrorAction.RemoveAlternatePermanently;\n              }\n              else {\n                  action = _getActionForCommonNetworkError(error.code);\n              }\n          }\n          // Don't force host switch for key errors\n          action.errorActionFlags &= ~ErrorActionFlags.MoveAllAlternatesMatchingHost;\n          const enabledOptionId = rootQuery.enabledMediaOptionIdByType(mediaOptionType);\n          if (mediaOptionId === enabledOptionId) {\n              return modifyErrorActionIfCurrentLevelIsLastValidLevel(action, false, error.code, enabledOptionId, mediaOptionType, rootQuery, rootService, error.isTimeout);\n          }\n          else {\n              return action;\n          }\n      }\n      /**\n       * Common error action handling. use if error can't be handled automatically by handleErrorCommon.\n       * Note that this will modify the store multiple times so it should be wrapped in a transaction\n       *\n       * @param action Error action to handle\n       * @param rootQuery The root playlist query\n       * @param rootService The root playlist service\n       * @param mediaOptionType The media option type that the error originates from. Required for penalty box\n       * @param mediaOptionId The media option id that the error originates from. Required for penalty box\n       * @returns true if error was handled (we did something in reaction to it)\n       */\n      function handleErrorAction(action, error, rootQuery, rootService, mediaOptionType, mediaOptionId, isTimeOut) {\n          const { errorAction, errorActionFlags } = action;\n          let errorHandled = true;\n          switch (errorAction) {\n              case NetworkErrorAction.RemoveAlternatePermanently:\n              case NetworkErrorAction.SendAlternateToPenaltyBox: {\n                  if (mediaOptionType == null || mediaOptionId == null) {\n                      error.handled = false;\n                      return false;\n                  }\n                  const itemId = rootQuery.itemId;\n                  let failedMediaOptionId = mediaOptionId;\n                  let failedMediaOption = rootQuery.mediaOptionListQueries[mediaOptionType].mediaOptionFromId(mediaOptionId);\n                  if (failedMediaOption.backingMediaOptionId) {\n                      failedMediaOptionId = failedMediaOption.backingMediaOptionId;\n                      failedMediaOption = rootQuery.mediaOptionListQueries[mediaOptionType].mediaOptionFromId(failedMediaOptionId);\n                  }\n                  const shouldSwitchHosts = (errorActionFlags & ErrorActionFlags.MoveAllAlternatesMatchingHost) != 0;\n                  const shouldMoveMatchingHDCP = (errorActionFlags & ErrorActionFlags.MoveAllAlternatesMatchingHDCP) != 0;\n                  const shouldSwitchToSDR = (errorActionFlags & ErrorActionFlags.SwitchToSDR) != 0;\n                  const shouldRemove = errorAction === NetworkErrorAction.RemoveAlternatePermanently;\n                  rootService.logger.debug(`[handleErrorAction] mediaOptionId ${mediaOptionId} shouldSwitchHosts ${shouldSwitchHosts} shouldMoveMatchingHDCP ${shouldMoveMatchingHDCP} shouldSwitchToSDR ${shouldSwitchToSDR} shouldRemove ${shouldRemove} fatal ${error.fatal}`);\n                  if (shouldMoveMatchingHDCP && 'hdcpLevel' in failedMediaOption) {\n                      const maxHdcpLevel = failedMediaOption.hdcpLevel;\n                      rootService.setMaxHdcpLevel(itemId, maxHdcpLevel);\n                  }\n                  if (shouldSwitchToSDR) {\n                      rootService.switchToSDROnly(itemId);\n                  }\n                  if (shouldSwitchHosts) {\n                      const hostName = getHostName(failedMediaOption.url);\n                      rootService.moveAllWithMatchingHosts(itemId, mediaOptionType, hostName, shouldRemove);\n                  }\n                  else {\n                      if (shouldRemove) {\n                          rootService.removePermanently(itemId, mediaOptionType, failedMediaOptionId);\n                      }\n                      else {\n                          rootService.addToPenaltyBox(itemId, mediaOptionType, failedMediaOptionId);\n                      }\n                  }\n                  // Switch enabled option only if we're the enabled option\n                  const currentMediaOptionId = rootQuery.enabledMediaOptionIdByType(mediaOptionType);\n                  if (currentMediaOptionId === mediaOptionId) {\n                      let newOptions = [NoMediaOption, NoMediaOption, NoMediaOption];\n                      newOptions = rootService.getFallbackMediaOptionTupleFromMediaOptionId(rootQuery, mediaOptionType, mediaOptionId, null, false, shouldSwitchHosts, isTimeOut);\n                      if (rootQuery.isValidMediaOptionTuple(newOptions)) {\n                          rootService.setPreferredHost(itemId, getHostName(newOptions[MediaOptionType.Variant].url));\n                      }\n                      else {\n                          error.fatal = true; // Couldn't find matching variant\n                      }\n                      rootService.logger.debug(`[handleErrorAction] ${error.fatal ? 'rejected' : 'picked'} ${JSON.stringify(newOptions)}`);\n                      if (error.fatal) {\n                          newOptions = [NoMediaOption, NoMediaOption, NoMediaOption];\n                      }\n                      rootService.setNextMediaOptions(rootQuery.itemId, newOptions);\n                  }\n                  break;\n              }\n              case NetworkErrorAction.SendEndCallback:\n                  error.fatal = true;\n                  break;\n              case NetworkErrorAction.RetryRequest: // Retry should be handled outside of this using retryWhen\n              case NetworkErrorAction.DoNothing:\n              default:\n                  errorHandled = false;\n                  break;\n          }\n          error.handled = errorHandled;\n          return errorHandled;\n      }\n      function logError(logger, error, action, retryCount, nextRetry) {\n          var _a, _b;\n          let requestID;\n          if (error instanceof ManifestNetworkError) {\n              requestID = 'manifest';\n          }\n          else if (error instanceof PlaylistNetworkError || error instanceof FragmentNetworkError) {\n              requestID = `${MediaOptionNames[error.mediaOptionType]}:${error.mediaOptionId}`;\n          }\n          else if (error instanceof KeyRequestError || error instanceof KeyRequestTimeoutError) {\n              requestID = `key:${redactUrl(error.keyuri)}`;\n          }\n          const data = {\n              requestID,\n              type: error.type,\n              details: error.details,\n              fatal: error.fatal,\n              code: (_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.code) !== null && _b !== void 0 ? _b : NaN,\n              errorAction: action === null || action === void 0 ? void 0 : action.errorAction,\n              errorActionFlags: action === null || action === void 0 ? void 0 : action.errorActionFlags,\n              retryCount,\n              nextRetry,\n          };\n          logger.qe({\n              critical: true,\n              name: 'internalError',\n              data,\n          });\n      }\n    \n      /**\n       * Common helpers / operators for handling errors\n       */\n      function handleRetryAction(error, retryCount, retryConfig, logger) {\n          error.handled = true;\n          if (retryConfig && retryCount < retryConfig.maxNumRetry && isFiniteNumber(retryConfig.retryDelayMs)) {\n              let timeoutMs;\n              switch (retryConfig.backoff) {\n                  case 'linear':\n                      timeoutMs = (retryCount + 1) * retryConfig.retryDelayMs;\n                      break;\n                  default:\n                      // exponential\n                      timeoutMs = Math.pow(2, retryCount) * retryConfig.retryDelayMs;\n                      break;\n              }\n              timeoutMs = Math.min(retryConfig.maxRetryDelayMs, timeoutMs);\n              logError(logger, error, { errorAction: NetworkErrorAction.RetryRequest, errorActionFlags: 0 }, retryCount, timeoutMs);\n              return timer(timeoutMs);\n          }\n          error.fatal = true;\n          logError(logger, error, { errorAction: NetworkErrorAction.SendEndCallback, errorActionFlags: 0 }, retryCount);\n          return throwError(error);\n      }\n      /**\n       * For use in retryWhen. This is a generic helper just in case we don't want to go\n       * through getActionAndHandleError.\n       *\n       * @returns timer() if we should retry, else throws if we should stop / abort the request\n       */\n      function handleErrorWithRetry(error, retryCount, retryConfig, action, rootQuery, rootService, mediaOptionType, mediaOptionId, isTimeOut = false) {\n          if ((action === null || action === void 0 ? void 0 : action.errorAction) === NetworkErrorAction.RetryRequest) {\n              return handleRetryAction(error, retryCount, retryConfig, rootService.logger);\n          }\n          return handleErrorActionCommon(error, retryCount, action, rootQuery, rootService, mediaOptionType, mediaOptionId, isTimeOut);\n      }\n      function handleErrorActionCommon(error, retryCount, action, rootQuery, rootService, mediaOptionType, mediaOptionId, isTimeOut = false) {\n          const async$ = new AsyncSubject();\n          // Wrap handleErrorAction in transaction because it will update the store a few times\n          applyTransaction(() => {\n              if (action) {\n                  logError(rootService.logger, error, action, retryCount);\n                  handleErrorAction(action, error, rootQuery, rootService, mediaOptionType, mediaOptionId, isTimeOut);\n              }\n              async$.error(error);\n          });\n          return async$;\n      }\n    \n      /**\n       * Handle errors coming from demuxers\n       */\n      /**\n       * An operator for handling demux errors\n       */\n      function addDemuxErrorHandlingPolicy(rootService, rootQuery, mediaOptionType, mediaOptionId) {\n          return (source$) => source$.pipe(catchError((error) => {\n              rootService.logger.error(`Got demux error ${error.message}`);\n              if (error instanceof FragParsingError || error instanceof RemuxAllocError) {\n                  let errorAction = NetworkErrorAction.SendAlternateToPenaltyBox;\n                  if (error.fatal) {\n                      errorAction = NetworkErrorAction.SendEndCallback;\n                  }\n                  else if (error instanceof RemuxAllocError) {\n                      errorAction = NetworkErrorAction.SendAlternateToPenaltyBox;\n                  }\n                  else {\n                      errorAction = NetworkErrorAction.RemoveAlternatePermanently;\n                  }\n                  const action = {\n                      errorAction,\n                      errorActionFlags: 0,\n                  };\n                  // No retry allowed\n                  return handleErrorActionCommon(error, 0, action, rootQuery, rootService, mediaOptionType, mediaOptionId);\n              }\n              throw error;\n          }));\n      }\n    \n      /**\n       * Handle errors that occur while fetching keys or from keysystem\n       */\n      function updateKeyTimeouts(keyUri, increment, rootQuery, rootService, ksQuery) {\n          var _a, _b;\n          const mediaOptionIds = (_b = (_a = ksQuery.getKeyInfo(keyUri)) === null || _a === void 0 ? void 0 : _a.mediaOptionIds) !== null && _b !== void 0 ? _b : [];\n          for (const mediaOptionId of mediaOptionIds) {\n              for (const query of rootQuery.mediaOptionListQueries) {\n                  if (query.mediaOptionFromId(mediaOptionId) != null) {\n                      rootService.updateConsecutiveTimeouts(rootQuery.itemId, query.mediaOptionType, increment, 'key');\n                  }\n              }\n          }\n      }\n      function addKeyErrorHandlingPolicy(keyUri, loadConfig, rootQuery, rootService, ksQuery) {\n          return (source) => source.pipe(withTransaction(() => {\n              updateKeyTimeouts(keyUri, false, rootQuery, rootService, ksQuery);\n          }), retryWhen((errors) => errors.pipe(mergeMap((err, retryCount) => {\n              if (err instanceof KeyRequestTimeoutError || err instanceof KeyRequestError) {\n                  return handleKeyError(err, retryCount, getRetryConfig(err, loadConfig), rootService, rootQuery, ksQuery);\n              }\n              throw err;\n          }))));\n      }\n      function handleKeyError(error, retryCount, retryConfig, rootService, rootQuery, ksQuery) {\n          const logger = rootService.logger;\n          const enabledOptions = rootQuery.enabledMediaOptionKeys;\n          const mediaOptions = [];\n          for (const mediaOptionId of error.mediaOptionIds) {\n              const isEnabled = enabledOptions.some((key) => key.mediaOptionId === mediaOptionId);\n              const query = rootQuery.mediaOptionListQueries.find((query) => query.mediaOptionFromId(mediaOptionId) != null);\n              if (!query) {\n                  logger.warn(`Couldn't find query for ${mediaOptionId}`);\n                  continue;\n              }\n              const mediaOptionType = query.mediaOptionType;\n              const obj = { mediaOptionId, mediaOptionType };\n              if (isEnabled) {\n                  mediaOptions.push(obj); // Handle after all other options because of fallback handling\n              }\n              else {\n                  mediaOptions.unshift(obj);\n              }\n          }\n          const async$ = new AsyncSubject();\n          applyTransaction(() => {\n              const isTimeout = error instanceof KeyRequestTimeoutError;\n              updateKeyTimeouts(error.keyuri, isTimeout, rootQuery, rootService, ksQuery);\n              let shouldRetry = false;\n              let action;\n              for (const { mediaOptionId, mediaOptionType } of mediaOptions) {\n                  action = getActionForCryptKeyNetworkError(error, mediaOptionId, mediaOptionType, rootQuery, rootService);\n                  logger.error(`[Keys] handleNetworkError uri=${redactUrl(error.keyuri)} mediaOptionId=${mediaOptionId} mediaOptionType=${mediaOptionType} action=${JSON.stringify(action)}`);\n                  if (action.errorAction === NetworkErrorAction.RetryRequest) {\n                      // This means there's no fallback!\n                      shouldRetry = true;\n                  }\n                  handleErrorAction(action, error, rootQuery, rootService, mediaOptionType, mediaOptionId);\n              }\n              if (shouldRetry) {\n                  async$.next();\n                  async$.complete();\n              }\n              else {\n                  logError(logger, error, action, retryCount); // Log final action\n                  async$.error(error);\n              }\n          });\n          return async$.pipe(switchMap(() => {\n              return handleRetryAction(error, retryCount, retryConfig, rootService.logger);\n          }));\n      }\n    \n      /**\n       * Handle root playlist, media playlist and fragment load errors\n       */\n      /**\n       * An operator for handling Playlist and Fragment load errors. It will either retry or abort the observable by throwing error\n       * Additional error handling may happen by putting something into penalty box\n       */\n      function addLoadErrorHandlingPolicy(itemId, mediaOptionType, loadConfig, maxTimeouts, isPrefetch, rootQuery, rootPlaylistService, statsService) {\n          maxTimeouts = Math.max(0, maxTimeouts);\n          return (source) => source.pipe(\n          // Expected that the source will throw appropriate HlsError.\n          tap(() => {\n              if (mediaOptionType != null) {\n                  rootPlaylistService.updateConsecutiveTimeouts(itemId, mediaOptionType, false, 'load');\n              }\n          }), retryWhen((errors) => errors.pipe(mergeMap((error, retryCount) => {\n              return getActionAndHandleError(error, retryCount, getRetryConfig(error, loadConfig), isPrefetch, maxTimeouts, rootQuery, rootPlaylistService, statsService);\n          }))));\n      }\n      /**\n       * Meant to be used within retryWhen for an Observable\n       * @param retryCount How many times we have retried this observable. 0 means this was the original request\n       * @param retryConfig Retry config to use\n       * @param isPrefetch true if this is a prefetch (not needed for playback)\n       * @param maxTimeouts Maximum number of consecutive timeouts allowed before failing\n       * @param rootQuery The root playlist query\n       * @param rootService The root playlist service\n       * @returns Retry timer if retrying, else throws error\n       */\n      function getActionAndHandleError(error, retryCount, retryConfig, isPrefetch, maxTimeouts, rootQuery, rootService, statsService) {\n          var _a;\n          if (!(error instanceof HlsError)) {\n              return throwError(error);\n          }\n          let mediaOptionId;\n          let mediaOptionType;\n          let action;\n          let isTimeout = false;\n          if (error instanceof ManifestNetworkError) {\n              action = getActionForManifestError(error);\n          }\n          else if (error instanceof PlaylistNetworkError || error instanceof FragmentNetworkError) {\n              ({ mediaOptionType, mediaOptionId, isTimeout } = error);\n              const mediaOption = (_a = rootQuery.mediaOptionListQueries[mediaOptionType]) === null || _a === void 0 ? void 0 : _a.mediaOptionFromId(mediaOptionId);\n              if (!isPrefetch && error.isTimeout && mediaOption != null && !('iframes' in mediaOption && mediaOption.iframes === true)) {\n                  rootService.updateConsecutiveTimeouts(rootQuery.itemId, error.mediaOptionType, true, 'load');\n                  // record only for fragments\n                  if (error instanceof FragmentNetworkError && error.stats) {\n                      const now = performance.now();\n                      statsService.setBandwidthSample(Object.assign(Object.assign({}, error.stats), { tfirst: error.stats.tfirst || now, tload: error.stats.tload || now, complete: true, mediaOptionType: mediaOptionType }));\n                  }\n              }\n              action = getActionForPlaylistOrFragError(error, isPrefetch, maxTimeouts, rootQuery, rootService);\n          }\n          // TODO: add more error types\n          return handleErrorWithRetry(error, retryCount, retryConfig, action, rootQuery, rootService, mediaOptionType, mediaOptionId, isTimeout);\n      }\n    \n      class HlsQuery extends QueryEntity {\n          constructor(store) {\n              super(store);\n          }\n          get currentConfig() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.config;\n          }\n          get extendMaxTTFB() {\n              var _a;\n              return (_a = this.getActive()) === null || _a === void 0 ? void 0 : _a.extendMaxTTFB;\n          }\n          get config$() {\n              return this.selectActive((entity) => entity === null || entity === void 0 ? void 0 : entity.config);\n          }\n          get userSeek$() {\n              return this.selectActive((entity) => entity === null || entity === void 0 ? void 0 : entity.userSeek);\n          }\n      }\n    \n      // rdar://84941644 ([HLS JS 2.1a beta] [DoW] The plugin for 'MapSet' has not been loaded into Immer)\n      // hls.js uses Set and/or Map in highestVideoCodecs and various entities.\n      // dev-app occasionally throws \"The plugin for 'MapSet' has not been loaded into Immer.\" error during error handling (e.g., switchToSDROnly).\n      // need to call enableMapSet() after and including immer 6.\n      // reference: https://immerjs.github.io/immer/map-set/\n      enableMapSet_1();\n      /**\n       * @brief Store for keeping track of things that are associated with Hls lifetime\n       */\n      class HlsStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'hls-store', producerFn: produce_1 });\n          }\n      }\n    \n      /**\n       * @brief Service for HlsStore\n       */\n      class HlsService {\n          constructor(store) {\n              this.store = store;\n          }\n          getQuery() {\n              return new HlsQuery(this.store);\n          }\n          /**\n           * Add and set active HlsEntity\n           */\n          setHlsEntity(entity) {\n              const id = entity.id;\n              logAction(`hls.set.entity ${id}`);\n              applyTransaction(() => {\n                  this.store.add(deepCpy(entity));\n                  this.store.setActive(id);\n              });\n          }\n          removeEntity(id) {\n              logAction(`hls.remove ${id}`);\n              this.store.remove(id);\n          }\n          // legacy hack to get airplay to work\n          setStartTime(startTimeSec) {\n              this.store.updateActive((active) => {\n                  active.config.startPosition = startTimeSec;\n              });\n          }\n          // If we got a user seek\n          setUserSeek(position) {\n              this.store.updateActive((active) => {\n                  active.userSeek = position;\n              });\n          }\n          setExtendMaxTTFB(value) {\n              this.store.updateActive((active) => {\n                  active.extendMaxTTFB = value;\n              });\n          }\n      }\n      let service;\n      function globalHlsService() {\n          if (!service) {\n              service = new HlsService(new HlsStore());\n          }\n          return service;\n      }\n      function createHlsQuery() {\n          return globalHlsService().getQuery();\n      }\n      /**\n       * Config for active hls entity\n       */\n      function getCurrentConfig() {\n          return globalHlsService().getQuery().currentConfig;\n      }\n    \n      const detailFields = ['mediaOptionId', 'startSN', 'endSN', 'ptsKnown'];\n      /**\n       * Used for live, merge the two playlists together\n       * @param oldDetails\n       * @param newDetails  Newly parsed variant info from PlaylistParser. Assumption is that fragments[0].start === 0\n       */\n      function mergeDetails(oldDetails, newDetails, logger) {\n          var _a;\n          // no merging required in VOD or if not matching in iframe mode\n          if (oldDetails.type === 'VOD' || newDetails.type === 'VOD' || oldDetails.iframesOnly !== newDetails.iframesOnly) {\n              return;\n          }\n          logger.info(`[live] merging ${JSON.stringify(oldDetails, detailFields)}+${JSON.stringify(newDetails, detailFields)}`);\n          const matchingMediaOption = oldDetails.mediaOptionId === newDetails.mediaOptionId;\n          const startIdx = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN; // start of overlap inside newfragments\n          const endIdx = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN; // end of overlap inside newfragments\n          const idxDelta = newDetails.startSN - oldDetails.startSN;\n          const oldfragments = oldDetails.fragments;\n          const newfragments = newDetails.fragments;\n          let discoSeqNumOffset = 0; // oldCC - newCC\n          for (let i = startIdx; i <= endIdx; ++i) {\n              // Expect this to only be O(1) usually...\n              if (oldfragments[idxDelta + i] && newfragments[i]) {\n                  discoSeqNumOffset = oldfragments[idxDelta + i].discoSeqNum - newfragments[i].discoSeqNum;\n                  // non zero value means the content is in violation of authoring guidelines\n                  logger.debug(`[live] merging details for mediaOptionId: ${newDetails.mediaOptionId} using discoSeqNumOffset: ${discoSeqNumOffset}`);\n                  break;\n              }\n          }\n          // loop through overlapping SN and update startPTS , cc, and duration if any found\n          const mergedInitSegments = {};\n          let lastPtsFrag = null;\n          for (let i = 0; i < newfragments.length; i++) {\n              // logger.info(`[live] merging details for media sequence number: ${newfragments[i].mediaSeqNum}`);\n              const oldFrag = oldfragments[idxDelta + i];\n              const newFrag = newfragments[i];\n              if (discoSeqNumOffset) {\n                  // This block is to handle publisher side issue, where the\n                  // authoring guideline below is not handled: 8.17. If\n                  // live/linear content will ever contain an EXT-X-DISCONTINUITY\n                  // tag, the EXT-X-DISCONTINUITY-SEQUENCE tag MUST always be\n                  // present.\n                  const discoSeqNum = newFrag.discoSeqNum + discoSeqNumOffset;\n                  if (newDetails.initSegments[newFrag.discoSeqNum]) {\n                      // logger.info(`[live] merging details offseting discoSeqNum from ${newFrag.discoSeqNum} to ${discoSeqNum}`);\n                      newDetails.initSegments[newFrag.discoSeqNum].discoSeqNum = discoSeqNum; // update the frag details\n                      mergedInitSegments[discoSeqNum] = newDetails.initSegments[newFrag.discoSeqNum]; // update the record\n                      delete newDetails.initSegments[newFrag.discoSeqNum]; // delete from the old record.\n                  }\n                  newFrag.discoSeqNum = discoSeqNum;\n              }\n              if (matchingMediaOption && newFrag.mediaSeqNum === (oldFrag === null || oldFrag === void 0 ? void 0 : oldFrag.mediaSeqNum) && oldFrag.startPts != null) {\n                  // logger.info(`[live] merging timestamps for media sequence number: ${newFrag.mediaSeqNum} using start PTS: ${oldFrag.startPTS}`);\n                  newFrag.start = oldFrag.start;\n                  newFrag.duration = oldFrag.duration;\n                  newFrag.startDtsTs = oldFrag.startDtsTs;\n                  newFrag.endDtsTs = oldFrag.endDtsTs;\n                  newFrag.startPts = oldFrag.startPts;\n                  newFrag.endPts = oldFrag.endPts;\n                  lastPtsFrag = newFrag;\n              }\n          }\n          if (Object.keys(mergedInitSegments).length) {\n              newDetails.initSegments = mergedInitSegments;\n          }\n          if (lastPtsFrag) {\n              // Force update entire list to ensure correct sliding window\n              updateFragPTSDTS(newDetails, lastPtsFrag, lastPtsFrag.start, undefined, false, true);\n          }\n          else {\n              // ensure that delta is within oldfragments range\n              // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n              // in that case we also need to adjust start offset of all fragments\n              if (idxDelta >= 0 && idxDelta < oldfragments.length) {\n                  // adjust start by sliding offset\n                  const sliding = oldfragments[idxDelta].start;\n                  logger.info(`[live] merging details using sliding ${sliding}`);\n                  const mergedFragments = newDetails.fragments;\n                  for (let i = 0; i < newfragments.length; i++) {\n                      mergedFragments[i].start += sliding;\n                  }\n              }\n          }\n          // If overlapping use oldDetails.PTSKnown\n          newDetails.ptsKnown = newDetails.ptsKnown || (matchingMediaOption && oldDetails.ptsKnown === true && oldDetails.endSN >= newDetails.startSN);\n          updateDateToMediaTimeMap(newDetails);\n          const startPos = (_a = newDetails.fragments[0]) === null || _a === void 0 ? void 0 : _a.start;\n          const endPos = startPos + newDetails.totalduration;\n          logger.info(`[live] merged ${JSON.stringify(oldDetails, detailFields)}+${JSON.stringify(newDetails, detailFields)}=[${startPos === null || startPos === void 0 ? void 0 : startPos.toFixed(3)},${endPos === null || endPos === void 0 ? void 0 : endPos.toFixed(3)}]`);\n      }\n    \n      function computeLivePosition(sliding, mediaOptionDetails, config, logger) {\n          let targetLatency = mediaOptionDetails.targetduration;\n          if (isFiniteNumber(config.liveSyncDuration)) {\n              targetLatency = config.liveSyncDuration;\n          }\n          else if (isFiniteNumber(config.liveSyncDurationCount)) {\n              targetLatency = config.liveSyncDurationCount * mediaOptionDetails.targetduration;\n          }\n          const result = sliding + Math.max(0, mediaOptionDetails.totalduration - targetLatency);\n          logger.info(`[live] computeLivePosition: ${toFixed(result, 3)}`);\n          return result;\n      }\n      function sanitizeLiveSeek(seekTo, details, config, logger) {\n          let santizedSeek = seekTo;\n          const liveWindowStart = details.fragments[0].start;\n          const liveWindowEnd = details.fragments[details.fragments.length - 1].start + details.fragments[details.fragments.length - 1].duration;\n          if (seekTo < liveWindowStart) {\n              santizedSeek = liveWindowStart;\n          }\n          else if (seekTo > liveWindowEnd) {\n              santizedSeek = computeLivePosition(0, details, config, logger);\n          }\n          if (seekTo < liveWindowStart || seekTo > liveWindowEnd) {\n              logger.warn(`[live] sanitizeLiveSeek seekTo:${toFixed(seekTo, 3)}, sanitizedSeek:${toFixed(santizedSeek, 3)}, liveWindowStart:${toFixed(liveWindowStart, 3)}, liveWindowEnd:${toFixed(liveWindowEnd, 3)}`);\n          }\n          return santizedSeek;\n      }\n      function getMinPlayablePosition(pos, details, lastUpdateMillis, maxBufferHole, mediaQuery) {\n          if (!details.ptsKnown) {\n              return 0;\n          }\n          const targetDuration = details.targetduration;\n          const liveWindowStart = details.fragments[0].start;\n          const playlistEstimate = { avgPlaylistLoadTimeMs: 0, avgPlaylistParseTimeMs: 0 };\n          const canPlayThrough = mediaQuery.canContinuePlaybackWithoutGap(details, lastUpdateMillis, playlistEstimate, maxBufferHole);\n          let minPosition = Math.max(0, pos - targetDuration);\n          if (pos < liveWindowStart && !canPlayThrough) {\n              minPosition = liveWindowStart;\n          }\n          return minPosition;\n      }\n      /**\n       * @returns An observable that will ensure playback stays within the live window on playlist refresh\n       * emits the seek position\n       */\n      function ensurePlaybackWithinWindow(context) {\n          const { config, mediaSink, rootPlaylistQuery, mediaLibraryService } = context;\n          const logger = context.logger.child({ name: 'live' });\n          const mediaQuery = mediaSink.mediaQuery;\n          return rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(filter(isEnabledMediaOption), switchMap((option) => {\n              const libQuery = mediaLibraryService.getQueryForOption(option);\n              return libQuery.mediaOptionDetailsEntity$.pipe(filter((entity) => { var _a; return ((_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionDetails) === null || _a === void 0 ? void 0 : _a.ptsKnown) && entity.mediaOptionDetails.liveOrEvent; }), distinctUntilChanged((a, b) => (a === null || a === void 0 ? void 0 : a.lastUpdateMillis) === (b === null || b === void 0 ? void 0 : b.lastUpdateMillis)));\n          }), map((entity) => {\n              const details = entity.mediaOptionDetails;\n              const pos = mediaQuery.currentTime;\n              const duration = mediaQuery.msDuration;\n              if (duration < entity.playlistDuration) {\n                  logger.info(`msDuration < playlistDuration, updating ${duration}->${entity.playlistDuration}`);\n                  mediaSink.msDuration = entity.playlistDuration;\n              }\n              else if (isFiniteNumber(mediaSink.msDuration)) {\n                  // audio could have been behind video and stagnated, and missed out on last opportunity\n                  // and video playlist could stagnate subsequently\n                  // doing this will trigger the needData, giving a chance to survive low buffer stall\n                  mediaSink.msDuration = mediaSink.msDuration + config.livePlaylistDurationNudge;\n              }\n              const minPosition = getMinPlayablePosition(pos, details, entity.lastUpdateMillis, config.maxBufferHole, mediaQuery);\n              let seekTo = NaN;\n              if (pos < minPosition) {\n                  seekTo = computeLivePosition(details.fragments[0].start, details, config, logger);\n                  logger.info(`${pos.toFixed(3)} too far behind window start:${minPosition} seek to live=${seekTo}`);\n                  mediaSink.seekTo = seekTo;\n              }\n              return seekTo;\n          }));\n      }\n    \n      /*\n       * deals with live/event refresh related aspects\n       *\n       *\n       * \n       */\n      // in milliseconds\n      function getLiveRefreshInterval(mediaOptionDetails) {\n          return 1000 * (mediaOptionDetails.averagetargetduration ? mediaOptionDetails.averagetargetduration : mediaOptionDetails.targetduration);\n      }\n      function needToRefreshLevel(mediaOptionDetails, lastUpdateMillis) {\n          const refreshInterval = getLiveRefreshInterval(mediaOptionDetails);\n          const timeSinceLastLevelRequest = performance.now() - lastUpdateMillis;\n          return mediaOptionDetails.liveOrEvent && timeSinceLastLevelRequest >= refreshInterval;\n      }\n      /**\n       *\n       * @param curDetails\n       * @param newDetails\n       * @param logger\n       * @returns Whether there has been a change between curDetails && newDetails\n       */\n      function mediaOptionDetailsHasChanged(curDetails, newDetails) {\n          return curDetails == null || newDetails.endSN !== curDetails.endSN || newDetails.liveOrEvent !== curDetails.liveOrEvent;\n      }\n      function getReloadTimer(mediaOptionDetailsEntity, slowDownTimeInMillis, logger) {\n          // In gapless mode it is possible the mediaOptionDetailsEntity is null right after an item eviction\n          if (!mediaOptionDetailsEntity) {\n              logger.info('mediaOptionDetailsEntity is null');\n              return EMPTY;\n          }\n          const { mediaOptionDetails, lastUpdateMillis, unchangedCount } = mediaOptionDetailsEntity;\n          if (!(mediaOptionDetails === null || mediaOptionDetails === void 0 ? void 0 : mediaOptionDetails.liveOrEvent)) {\n              logger.info(`End of event refresh for mediaOptionId: ${mediaOptionDetails.mediaOptionId}`);\n              return EMPTY;\n          }\n          if (needToRefreshLevel(mediaOptionDetails, lastUpdateMillis)) {\n              return timer(0).pipe(tap(() => logger.info(`[live] immediate live refresh for mediaOptionId: ${mediaOptionDetails.mediaOptionId}`)));\n          }\n          let reloadInterval = getLiveRefreshInterval(mediaOptionDetails);\n          if (unchangedCount > 0) {\n              reloadInterval /= 2;\n              reloadInterval = Math.max(reloadInterval, 5000); // Have a minumum 5 seconds gap\n          }\n          // decrement reloadInterval with level loading delay\n          const now = performance.now();\n          const sinceLastUpdate = now - lastUpdateMillis;\n          reloadInterval -= sinceLastUpdate;\n          reloadInterval += slowDownTimeInMillis;\n          // in any case, don't reload more than every second\n          reloadInterval = Math.max(1000, Math.round(reloadInterval));\n          return timer(reloadInterval).pipe(tap(() => logger.info(`[live] live refresh after ${reloadInterval} for mediaOptionId: ${mediaOptionDetails.mediaOptionId}`)));\n      }\n      /**\n       * @returns whether the live playlist is too far in the past. This means the sliding window end is too\n       * far behind the minimum playback position\n       */\n      function livePlaylistExpired(details, lastUpdateMillis, maxBufferHole, mediaQuery) {\n          const minPosition = getMinPlayablePosition(mediaQuery.currentTime, details, lastUpdateMillis, maxBufferHole, mediaQuery);\n          const lastFrag = details.fragments[details.fragments.length - 1];\n          const windowEnd = (lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.start) + (lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.duration);\n          const expired = lastFrag != null && details.liveOrEvent && details.ptsKnown && windowEnd < minPosition;\n          return { expired, windowEnd, minPosition };\n      }\n    \n      function findFragForCriteria(details, fn, startSN = NaN) {\n          const fragList = details.fragments;\n          const startIdx = startSN > details.startSN ? startSN - details.startSN : 0;\n          for (let idx = startIdx; idx < fragList.length; ++idx) {\n              const mediaFragment = fragList[idx];\n              const { start: timelineOffset } = mediaFragment;\n              if (fn(mediaFragment)) {\n                  return { timelineOffset, mediaFragment };\n              }\n          }\n          return null;\n      }\n      function discoSeqNumForTime(details, position) {\n          var _a;\n          const foundFrag = (_a = findFragForCriteria(details, (f) => {\n              const positiveDuration = f.duration > 0;\n              const fragEnd = f.start + f.duration;\n              const validPosition = fragEnd > position || (position - fragEnd < 1 && f.isLastFragment);\n              return positiveDuration && validPosition;\n          })) !== null && _a !== void 0 ? _a : null;\n          return foundFrag === null || foundFrag === void 0 ? void 0 : foundFrag.mediaFragment.discoSeqNum;\n      }\n      function validUnbufferedFragment(bufferedSeg, position, f) {\n          const positiveDuration = f.duration > 0;\n          const fragEnd = f.start + f.duration;\n          // edge case : <rdar://82696656> position is after last segment, but its very close, use the last fragment.\n          const validPosition = position == null || fragEnd > position || (position - fragEnd < 1 && f.isLastFragment);\n          const fragNotAlreadyBuffered = bufferedSeg.every((seg) => !fragEqual(seg.frag, f));\n          return positiveDuration && fragNotAlreadyBuffered && validPosition;\n      }\n      function findFragment(position, activeDiscoSeqNum, anchorMSN, details, bufferedSeg) {\n          var _a, _b, _c;\n          const firstUnbufferedFrag = (_a = findFragForCriteria(details, validUnbufferedFragment.bind(null, bufferedSeg, undefined), anchorMSN)) !== null && _a !== void 0 ? _a : null;\n          let foundFrag = null;\n          if (firstUnbufferedFrag) {\n              // Try to find fragment with valid position using previous result as hint\n              foundFrag = (_b = findFragForCriteria(details, validUnbufferedFragment.bind(null, bufferedSeg, position), firstUnbufferedFrag.mediaFragment.mediaSeqNum)) !== null && _b !== void 0 ? _b : null;\n              if (!foundFrag && details.liveOrEvent && !details.ptsKnown) {\n                  // this is fall back for fairly rare case\n                  foundFrag = firstUnbufferedFrag;\n              }\n          }\n          let nextDisco = NaN;\n          if (foundFrag != null && isFiniteNumber(activeDiscoSeqNum) && foundFrag.mediaFragment.discoSeqNum !== activeDiscoSeqNum) {\n              nextDisco = foundFrag.mediaFragment.discoSeqNum;\n              foundFrag = null;\n          }\n          // When switching variants and segments have the potential to drop frames, return mediaSeqNum -1\n          //  to retieve the start of the GOP needed to buffer the start of the segment time range.\n          const canDropFrames = bufferedSeg.some((seg) => seg.frag.framesWithoutIDR > 0);\n          if (foundFrag && canDropFrames) {\n              const levelSwitch = bufferedSeg[bufferedSeg.length - 1].frag.mediaOptionId !== details.mediaOptionId;\n              if (levelSwitch) {\n                  foundFrag = (_c = findFragForCriteria(details, (f) => f.mediaSeqNum === foundFrag.mediaFragment.mediaSeqNum - 1)) !== null && _c !== void 0 ? _c : foundFrag;\n              }\n          }\n          return { foundFrag, nextDisco };\n      }\n      function findIframeFragmentForPosition(position, details, audioDetails, rate, iframeMachine) {\n          const nextFragResult = iframeMachine.nextFragment(details.fragments, (audioDetails === null || audioDetails === void 0 ? void 0 : audioDetails.fragments) || [], rate, position);\n          if (!nextFragResult) {\n              return null;\n          }\n          const { frag, newMediaRootTime } = nextFragResult;\n          const foundFrag = { timelineOffset: frag.iframeMediaStart, mediaFragment: frag };\n          return { foundFrag, nextDisco: NaN, newMediaRootTime };\n      }\n      function calculatePlaylistEnd(details) {\n          const fragEnd = details.fragments[details.fragments.length - 1];\n          return fragEnd ? fragEnd.start + fragEnd.duration : 0;\n      }\n    \n      /**\n       * @brief Query interface to the media library.  Holds the details and init segments\n       */\n      class MediaLibraryQuery extends QueryEntity {\n          constructor(mediaLibraryStore, mediaOption) {\n              super(mediaLibraryStore);\n              this.mediaOption = mediaOption;\n          }\n          get itemId() {\n              return this.mediaOption.itemId;\n          }\n          get mediaOptionId() {\n              return this.mediaOption.mediaOptionId;\n          }\n          get initSegmentEntities() {\n              var _a;\n              return (_a = this.mediaOptionDetailsEntity) === null || _a === void 0 ? void 0 : _a.initSegmentCacheEntities;\n          }\n          get mediaLibraryEntity() {\n              return this.getEntity(this.itemId);\n          }\n          get mediaOptionDetailsEntityRecord() {\n              var _a;\n              return (_a = this.mediaLibraryEntity) === null || _a === void 0 ? void 0 : _a.mediaOptionDetailsEntityRecord;\n          }\n          get mediaOptionDetailsEntity() {\n              if (!this.mediaOptionDetailsEntityRecord)\n                  return null;\n              return this.mediaOptionDetailsEntityRecord[this.mediaOptionId];\n          }\n          get mediaOptionDetails() {\n              var _a;\n              return (_a = this.mediaOptionDetailsEntity) === null || _a === void 0 ? void 0 : _a.mediaOptionDetails;\n          }\n          get playlistDuration() {\n              var _a;\n              return (_a = this.mediaOptionDetailsEntity) === null || _a === void 0 ? void 0 : _a.playlistDuration;\n          }\n          get mediaOptionDetailsEntity$() {\n              const { itemId, mediaOptionId } = this;\n              return this.selectEntity(itemId, (libraryEntity) => {\n                  if (libraryEntity === null || libraryEntity === void 0 ? void 0 : libraryEntity.mediaOptionDetailsEntityRecord) {\n                      return libraryEntity === null || libraryEntity === void 0 ? void 0 : libraryEntity.mediaOptionDetailsEntityRecord[mediaOptionId];\n                  }\n              });\n          }\n          get mediaOptionDetails$() {\n              return this.selectEntity(this.itemId, (entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionDetailsEntityRecord[this.mediaOptionId]) === null || _a === void 0 ? void 0 : _a.mediaOptionDetails; }).pipe(filterNullOrUndefined());\n          }\n          get playlistDuration$() {\n              return this.mediaOptionDetailsEntity$.pipe(map((mediaOptionDetailsEntity) => mediaOptionDetailsEntity === null || mediaOptionDetailsEntity === void 0 ? void 0 : mediaOptionDetailsEntity.playlistDuration), filterNullOrUndefined(), distinctUntilChanged());\n          }\n          get live$() {\n              return this.mediaOptionDetails$.pipe(map((mediaOptionDetails) => mediaOptionDetails === null || mediaOptionDetails === void 0 ? void 0 : mediaOptionDetails.liveOrEvent), distinctUntilChanged());\n          }\n      }\n    \n      class MediaLibraryStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'media-library-store', idKey: 'itemId', producerFn: produce_1 });\n          }\n      }\n    \n      /**\n       * @brief Service interface to the media library.  Will fetch and catch media options details and init segments, and find\n       * the right fragments to load.\n       *\n       * The retrieve functions are rxjs pipeable operators:\n       * https://rxjs.dev/guide/v6/pipeable-operators\n       */\n      class MediaLibraryService {\n          constructor(store) {\n              this.store = store;\n          }\n          getQuery() {\n              return new QueryEntity(this.store);\n          }\n          getQueryForOption(mediaOption) {\n              return new MediaLibraryQuery(this.store, mediaOption);\n          }\n          createMediaLibraryEntity(itemId) {\n              const libraryEntity = { itemId, mediaOptionDetailsEntityRecord: {} };\n              logAction(`library.entity.create: ${itemId}`);\n              this.store.add(libraryEntity);\n          }\n          setDetailsLoading(mediaOption) {\n              const { itemId, mediaOptionId } = mediaOption;\n              logAction(`library.details.loading: ${mediaOptionId}`);\n              this.store.update(itemId, ({ mediaOptionDetailsEntityRecord }) => {\n                  if (!mediaOptionDetailsEntityRecord[mediaOptionId]) {\n                      mediaOptionDetailsEntityRecord[mediaOptionId] = { initSegmentCacheEntities: {}, unchangedCount: 0 };\n                  }\n                  mediaOptionDetailsEntityRecord[mediaOptionId].detailsLoading = true;\n              });\n          }\n          archiveMediaOptionDetails(mediaOptionDetails, stats, changed) {\n              const { itemId, mediaOptionId } = mediaOptionDetails;\n              const lastUpdateMillis = performance.now();\n              const playlistDuration = calculatePlaylistEnd(mediaOptionDetails);\n              logAction(`library.details.loaded: ${mediaOptionId}`);\n              this.store.update(itemId, (libraryEntity) => {\n                  const detailsEntity = libraryEntity.mediaOptionDetailsEntityRecord[mediaOptionId];\n                  detailsEntity.detailsLoading = false;\n                  detailsEntity.mediaOptionDetails = mediaOptionDetails;\n                  detailsEntity.lastUpdateMillis = lastUpdateMillis;\n                  if (changed) {\n                      detailsEntity.unchangedCount = 0;\n                  }\n                  else {\n                      ++detailsEntity.unchangedCount;\n                  }\n                  detailsEntity.playlistDuration = playlistDuration;\n                  detailsEntity.stats = stats;\n                  libraryEntity.liveOrEvent = mediaOptionDetails.liveOrEvent;\n              });\n          }\n          setInitSegmentLoading(initSegment) {\n              const { itemId, mediaOptionId, discoSeqNum } = initSegment;\n              logAction(`library.initsegs.loading: ${mediaOptionId}/${discoSeqNum}`);\n              this.store.update(itemId, (libraryEntity) => {\n                  libraryEntity.mediaOptionDetailsEntityRecord[mediaOptionId].initSegLoading = discoSeqNum;\n              });\n          }\n          archiveInitSegmentEntity(original, generated) {\n              const { itemId, mediaOptionId, discoSeqNum } = original;\n              logAction(`library.initseg.loaded: ${mediaOptionId}/${discoSeqNum}`);\n              this.store.update(itemId, ({ mediaOptionDetailsEntityRecord }) => {\n                  const detailsEntity = mediaOptionDetailsEntityRecord[mediaOptionId];\n                  detailsEntity.initSegmentCacheEntities[discoSeqNum] = [original, generated];\n                  detailsEntity.initSegLoading = null;\n              });\n          }\n          updatePTSDTS(itemId, mediaOptionId, initPTSInfo, parsedFrag) {\n              var _a;\n              const origDetails = (_a = this.getQueryForOption({ itemId, mediaOptionId })) === null || _a === void 0 ? void 0 : _a.mediaOptionDetails;\n              if (!origDetails || !fragIsInDetails(origDetails, parsedFrag)) {\n                  return;\n              }\n              // <rdar://90651041> immer read/write is slow, modify details cpy outside of store update\n              const { startDtsTs } = parsedFrag;\n              const { variantDTS, timelineOffset, iframeMode } = initPTSInfo;\n              const startOffset = diffSeconds(startDtsTs, variantDTS) + timelineOffset;\n              const newDetails = Object.assign({}, origDetails); // shallow copy\n              updateFragPTSDTS(newDetails, parsedFrag, startOffset, iframeMode, true);\n              updateDateToMediaTimeMap(newDetails);\n              const newPlaylistDuration = calculatePlaylistEnd(newDetails);\n              this.store.update(itemId, ({ mediaOptionDetailsEntityRecord }) => {\n                  const entity = mediaOptionDetailsEntityRecord[mediaOptionId];\n                  if (!(entity === null || entity === void 0 ? void 0 : entity.mediaOptionDetails)) {\n                      return;\n                  }\n                  entity.mediaOptionDetails = newDetails;\n                  entity.playlistDuration = newPlaylistDuration;\n              });\n          }\n          remove(ids) {\n              this.store.remove(ids);\n          }\n          clear() {\n              this.store.remove();\n          }\n      }\n      /**\n       * Global state store for the service\n       */\n      let libraryService;\n      function mediaLibraryService() {\n          if (!libraryService) {\n              libraryService = new MediaLibraryService(new MediaLibraryStore());\n          }\n          return libraryService;\n      }\n      /**\n       * Creates a new media library query from any media option info (MediaOption, MediaOptionDetails, etc)\n       * Uses the global store for read only query, but protects the store access\n       *\n       * @param {MediaOptionDetails} mediaOptionDetails The details to store\n       */\n      const createMediaLibraryQuery = (mediaOption) => {\n          return mediaLibraryService().getQueryForOption(mediaOption);\n      };\n      /**\n       * Upserts a MediaOptionDetails to the store\n       *\n       * @param {MediaOptionDetails} mediaOptionDetails The details to store\n       */\n      const archiveMediaOptionDetails = (mediaOptionDetails, stats, changed) => {\n          mediaLibraryService().archiveMediaOptionDetails(mediaOptionDetails, stats, changed);\n      };\n      /**\n       * Retrieve the details (a mediaplaylist.m3u8) for a media option (variant or alternate)\n       * Uses the global store for read only query, but protects the store access\n       *\n       * @param {MediaOption} mediaOption media option to load the details for\n       * @param {LoadPolicy} loadPolicy the policy determining how to load the details\n       * @param {number} maxTimeouts Maximum number of consecutive timeouts allowed\n       * @returns {Observable<MediaOptionDetails>} retrieved (cached or loaded) details for the source media option\n       */\n      const retrieveMediaOptionDetails = (libContext, mediaOption, isPrefetch = false, force = false) => {\n          if (mediaOption == null || !isEnabledMediaOption(mediaOption)) {\n              return of(null);\n          }\n          const { itemId } = mediaOption;\n          const { mediaLibraryService: libraryService } = libContext;\n          const libraryQuery = libraryService.getQueryForOption(mediaOption);\n          if (!libraryQuery.hasEntity(itemId)) {\n              libraryService.createMediaLibraryEntity(itemId);\n          }\n          const entity = libraryQuery.mediaOptionDetailsEntity;\n          const details = libraryQuery.mediaOptionDetails;\n          if (details != null && !force && (details.type === 'VOD' || (details.liveOrEvent && !needToRefreshLevel(details, entity.lastUpdateMillis)))) {\n              return of(details).pipe(tag('retrieveMediaOptionDetails.emit.cached')).pipe(take(1));\n          }\n          libraryService.setDetailsLoading(mediaOption);\n          return getMediaOptionDetailsCommon(libContext, mediaOption, isPrefetch);\n      };\n      /**\n       * Schedules playlist refresh if needed\n       */\n      function refreshMediaOptionDetails(libContext, mediaOption) {\n          const { mediaLibraryService, logger } = libContext;\n          const mediaLibraryQuery = mediaLibraryService.getQueryForOption(mediaOption);\n          // getReloadTimer returns EMPTY if non-live so it shouldn't emit\n          return getReloadTimer(mediaLibraryQuery.mediaOptionDetailsEntity, 0, logger).pipe(switchMap(() => retrieveMediaOptionDetails(libContext, mediaOption, false, true)), switchMap(() => refreshMediaOptionDetails(libContext, mediaOption)));\n      }\n      // Load media option details with error handling\n      function getMediaOptionDetailsCommon(libContext, mediaOption, isPrefetch) {\n          var _a, _b;\n          const { logger, config, rootPlaylistQuery: rootQuery, rootPlaylistService: rootService, statsService, mediaLibraryService, mediaSink } = libContext;\n          const mediaQuery = mediaSink.mediaQuery;\n          const loadPolicy = config.playlistLoadPolicy;\n          const keySystemPreference = config.keySystemPreference;\n          const masterVariableList = rootQuery.masterVariableList;\n          const extendMaxTTFB = (_b = (_a = globalHlsService()) === null || _a === void 0 ? void 0 : _a.getQuery()) === null || _b === void 0 ? void 0 : _b.extendMaxTTFB;\n          return loadMediaOptionDetails(mediaOption, rootQuery.itemStartOffset, config, loadPolicy, logger, keySystemPreference, statsService, masterVariableList, extendMaxTTFB)\n              .pipe(map((loadMediaOptionDetailsResult) => {\n              var _a;\n              // Handle merging with previous level for live/event\n              const curLibraryQuery = mediaLibraryService.getQueryForOption(mediaOption);\n              const thisMediaOptionDetails = curLibraryQuery.mediaOptionDetails;\n              const { mediaOptionDetails: newMediaOptionDetails } = loadMediaOptionDetailsResult;\n              const { stats } = loadMediaOptionDetailsResult;\n              let changed = true;\n              if (newMediaOptionDetails.liveOrEvent) {\n                  const { mediaOptionType } = newMediaOptionDetails;\n                  changed = mediaOptionDetailsHasChanged(thisMediaOptionDetails, newMediaOptionDetails);\n                  // Try merging with self first, then last loaded\n                  if (thisMediaOptionDetails) {\n                      mergeDetails(thisMediaOptionDetails, newMediaOptionDetails, logger);\n                  }\n                  const lastLoadedOption = rootQuery.lastLoadedMediaOptionByType(mediaOptionType);\n                  const lastMediaOptionDetails = lastLoadedOption ? (_a = mediaLibraryService.getQueryForOption(lastLoadedOption)) === null || _a === void 0 ? void 0 : _a.mediaOptionDetails : null;\n                  if (!newMediaOptionDetails.ptsKnown && lastMediaOptionDetails && lastMediaOptionDetails.mediaOptionId !== (thisMediaOptionDetails === null || thisMediaOptionDetails === void 0 ? void 0 : thisMediaOptionDetails.mediaOptionId)) {\n                      mergeDetails(lastMediaOptionDetails, newMediaOptionDetails, logger);\n                  }\n              }\n              if (newMediaOptionDetails) {\n                  applyTransaction(() => {\n                      mediaLibraryService.archiveMediaOptionDetails(newMediaOptionDetails, stats, changed);\n                      rootService.setLastLoadedMediaOptionByType(rootQuery.itemId, mediaOption.mediaOptionType, mediaOption);\n                  });\n              }\n              const hitUnchangedMaxCount = !changed && curLibraryQuery.mediaOptionDetailsEntity.unchangedCount >= config.liveMaxUnchangedPlaylistRefresh;\n              const isExpiredInfo = livePlaylistExpired(newMediaOptionDetails, stats.tload, config.maxBufferHole, mediaQuery);\n              if (hitUnchangedMaxCount || isExpiredInfo.expired) {\n                  let response;\n                  if (hitUnchangedMaxCount) {\n                      response = ErrorResponses.LivePlaylistUpdateError;\n                  }\n                  else {\n                      response = {\n                          text: `Live window too far in the past end:${isExpiredInfo.windowEnd.toFixed(3)} minPosition:${isExpiredInfo.minPosition}`,\n                          code: 0,\n                      };\n                  }\n                  throw new PlaylistNetworkError(false, response.text, response.code, response, false, mediaOption.mediaOptionType, mediaOption.mediaOptionId, mediaOption.url);\n              }\n              return newMediaOptionDetails;\n          }), tag('getMediaOptionDetailsCommon.emit.loaded'), addLoadErrorHandlingPolicy(mediaOption.itemId, mediaOption.mediaOptionType, getLoadConfig(mediaOption, loadPolicy), config.maxNumAddLevelToPenaltyBox, isPrefetch, rootQuery, rootService, statsService))\n              .pipe(take(1));\n      }\n      /**\n       * Retrieve the corresponding init segment (#EXT-X-MAP) for a media fragment\n       *\n       * @param {MediaFragment} mediaFragment get init segment for this media fragment\n       * @returns {Observable<InitSegmentCacheEntity>} retrieved (cached or loaded) init segment\n       */\n      const retrieveInitSegmentCacheEntity = (libContext, mediaFragment) => {\n          if (!mediaFragment)\n              return of(null);\n          const { logger } = libContext;\n          const { mediaLibraryService, mediaParser } = libContext;\n          const mediaLibraryQuery = mediaLibraryService.getQueryForOption(mediaFragment);\n          const { mediaOption, mediaOptionDetailsEntityRecord, mediaOptionDetails } = mediaLibraryQuery;\n          const { mediaOptionId } = mediaOption;\n          if (!(mediaOptionDetailsEntityRecord === null || mediaOptionDetailsEntityRecord === void 0 ? void 0 : mediaOptionDetailsEntityRecord[mediaOptionId]))\n              throw new Error('retrieveInitSegmentCacheEntity no details entity');\n          if (!mediaOptionDetails)\n              throw new Error('retrieveInitSegmentCacheEntity no details');\n          const { initSegmentCacheEntities } = mediaOptionDetailsEntityRecord[mediaOptionId];\n          const { initSegments } = mediaOptionDetails;\n          const { mediaSeqNum, discoSeqNum } = mediaFragment;\n          if (initSegmentCacheEntities[discoSeqNum]) {\n              logger.debug({ mediaOptionId, mediaSeqNum, discoSeqNum }, 'found cached init segment');\n              const [original, generated] = initSegmentCacheEntities[discoSeqNum];\n              let entity = original;\n              if (generated) {\n                  const trackSwitch = mediaParser.willBeTrackSwitch(mediaFragment);\n                  entity = trackSwitch ? original : generated;\n              }\n              return of(entity);\n          }\n          const initFrag = initSegments[discoSeqNum];\n          if (!initFrag) {\n              logger.debug({ mediaOptionId, mediaSeqNum, discoSeqNum }, 'no init segment entry');\n              return of(null);\n          }\n          mediaLibraryService.setInitSegmentLoading(initFrag);\n          logger.info({ mediaSeqNum, discoSeqNum }, 'loading init segment');\n          const timingObj = {\n              mediaOptionId,\n              mediaSeqNum: 'initSegment',\n              discoSeqNum,\n              name: MediaOptionNames[mediaFragment.mediaOptionType],\n              state: 'loading',\n          };\n          const tlog = logger.child({ name: 'timing' });\n          tlog.info(`${JSON.stringify(timingObj)}`);\n          return getMediaFragmentCommon(libContext, initFrag, false, false).pipe(tap(() => {\n              tlog.info(`${JSON.stringify(Object.assign(Object.assign({}, timingObj), { state: 'loaded' }))}`);\n          }), observeOn(asyncScheduler), switchMap((data) => {\n              tlog.info(`${JSON.stringify(Object.assign(Object.assign({}, timingObj), { state: 'parsing' }))}`);\n              return parseInitSegment(data, initFrag, libContext);\n          }), tap(() => {\n              tlog.info(`${JSON.stringify(Object.assign(Object.assign({}, timingObj), { state: 'parsed' }))}`);\n          }));\n      };\n      function parseInitSegment(data, frag, libContext) {\n          var _a;\n          const { logger, mediaSink, rootPlaylistService, rootPlaylistQuery, mediaParser, mediaLibraryService, gaplessInstance } = libContext;\n          const { mediaQuery } = mediaSink;\n          const mediaLibraryQuery = mediaLibraryService.getQueryForOption(frag);\n          const { mediaOption, mediaOptionDetails } = mediaLibraryQuery;\n          const { itemId, mediaOptionId } = mediaOption;\n          const { keyTagInfo, discoSeqNum, mediaSeqNum, mediaOptionType } = frag;\n          const seeking = mediaQuery.seeking;\n          const live = mediaOptionDetails.liveOrEvent;\n          const ptsKnown = mediaOptionType === MediaOptionType.Variant ? mediaOptionDetails.ptsKnown : false;\n          let segment;\n          let initSegment;\n          if (frag.isInitSegment) {\n              initSegment = new Uint8Array(data);\n          }\n          else {\n              segment = new Uint8Array(data);\n          }\n          const parserContext = {\n              segment,\n              initSegment,\n              frag,\n              ptsKnown,\n              seeking,\n              live,\n              totalDuration: mediaOptionDetails.totalduration,\n          };\n          return mediaParser.parseInitSegment(parserContext, (_a = navigator === null || navigator === void 0 ? void 0 : navigator.vendor) !== null && _a !== void 0 ? _a : '').pipe(map((parsedInitSegment) => {\n              const { track, moovData, mimeType } = parsedInitSegment;\n              const { initSegment } = track;\n              if (gaplessInstance.inGaplessMode && MediaUtil.isVideoCodec(track.codec)) {\n                  logger.warn(`Video codec discovered in gapless mode codec:${track.codec}`);\n                  gaplessInstance.dequeueSource('InvalidFormat');\n              }\n              const initSegmentCacheEntity = { itemId, mediaOptionId, discoSeqNum, initParsedData: moovData, data: initSegment, mimeType, keyTagInfo, fragment: frag };\n              mediaLibraryService.archiveInitSegmentEntity(initSegmentCacheEntity);\n              logger.info({ mediaOptionId, mediaSeqNum, discoSeqNum }, 'loaded init segment');\n              return initSegmentCacheEntity;\n          }), addDemuxErrorHandlingPolicy(rootPlaylistService, rootPlaylistQuery, mediaOptionType, mediaOptionId));\n      }\n      function parseSegment(data, defaultInitPTS, initSegmentCacheEntity, frag, timelineOffset, libContext) {\n          var _a, _b;\n          const segment = new Uint8Array(data);\n          const { legibleSystemAdapter, rootPlaylistService, mediaSink, mediaParser, rootPlaylistQuery, mediaLibraryService } = libContext;\n          const { mediaQuery } = mediaSink;\n          const mediaLibraryQuery = mediaLibraryService.getQueryForOption(frag);\n          const { mediaOption, mediaOptionDetails } = mediaLibraryQuery;\n          const { initSegments } = mediaOptionDetails;\n          const { itemId, mediaOptionId } = mediaOption;\n          const { discoSeqNum, mediaSeqNum, mediaOptionType, isLastFragment } = frag;\n          const seeking = mediaQuery.seeking;\n          const live = mediaOptionDetails.liveOrEvent;\n          const initSeg = initSegments[discoSeqNum];\n          const ptsKnown = mediaOptionType === MediaOptionType.Variant ? mediaOptionDetails.ptsKnown : false;\n          const parserContext = {\n              segment,\n              frag,\n              seeking,\n              live,\n              ptsKnown,\n              totalDuration: mediaOptionDetails.totalduration,\n              defaultInitPTS,\n              iframeMediaStart: isIframeMediaFragment(frag) ? frag.iframeMediaStart : undefined,\n              iframeDuration: isIframeMediaFragment(frag) ? frag.iframeMediaDuration : undefined,\n              iframeOriginalStart: isIframeMediaFragment(frag) ? frag.iframeOriginalStart : undefined,\n          };\n          let source;\n          if (initSegmentCacheEntity != null && ((_a = frag.keyTagInfo) === null || _a === void 0 ? void 0 : _a.uri) === ((_b = initSegmentCacheEntity.keyTagInfo) === null || _b === void 0 ? void 0 : _b.uri)) {\n              source = of(initSegmentCacheEntity);\n          }\n          else if (initSegmentCacheEntity != null) {\n              // key rotated, update cached init segment with current frag keyTagInfo, pass to demuxer for parsing\n              const updatedFrag = Object.assign(Object.assign({}, initSegmentCacheEntity.fragment), { keyTagInfo: frag.keyTagInfo });\n              const initData = initSeg ? initSegmentCacheEntity.data : data;\n              source = parseInitSegment(initData, updatedFrag, libContext);\n          }\n          else {\n              source = parseInitSegment(data, frag, libContext);\n          }\n          return source.pipe(switchMap((initSegmentCacheEntity) => {\n              const parseStartTime = performance.now();\n              if (initSegmentCacheEntity != null) {\n                  const { data: is } = initSegmentCacheEntity;\n                  const initSegment = new Uint8Array(is);\n                  parserContext.initSegment = initSegment;\n              }\n              if (frag.mediaOptionType === MediaOptionType.Variant) {\n                  legibleSystemAdapter === null || legibleSystemAdapter === void 0 ? void 0 : legibleSystemAdapter.setupForFrag(frag);\n              }\n              return mediaParser.parseSegment(parserContext, '').pipe(map((parsedSegment) => {\n                  var _a;\n                  const parseEndTime = performance.now();\n                  const { startPTS, startDTS: startDtsTs, endPTS, endDTS: endDtsTs, firstKeyframePts, framesWithoutIDR, dropped, data1, data2, captionData, id3Samples, parsedInitSegment } = parsedSegment;\n                  const fragSample = {\n                      durationSec: endPTS.baseTime / endPTS.timescale - startPTS.baseTime / startPTS.timescale,\n                      parseTimeMs: parseEndTime - parseStartTime,\n                  };\n                  libContext.statsService.setFragSample(fragSample);\n                  // parser updated initSegment, possibly due to silent audio insertion\n                  let generatedInitSegmentCacheEntity = Object.assign({}, initSegmentCacheEntity);\n                  if (parsedInitSegment) {\n                      const { track, moovData, mimeType } = parsedInitSegment;\n                      const { initSegment } = track;\n                      generatedInitSegmentCacheEntity = { itemId, mediaOptionId, discoSeqNum, initParsedData: moovData, data: initSegment, mimeType, keyTagInfo: frag.keyTagInfo, fragment: frag };\n                      mediaLibraryService.archiveInitSegmentEntity(initSegmentCacheEntity, generatedInitSegmentCacheEntity);\n                  }\n                  const keyTagInfo = frag.keyTagInfo;\n                  const mediaFragmentCacheEntity = {\n                      itemId,\n                      mediaOptionId,\n                      mediaSeqNum,\n                      discoSeqNum,\n                      startDtsTs,\n                      endDtsTs,\n                      timelineOffset,\n                      firstKeyframePts,\n                      framesWithoutIDR,\n                      dropped,\n                      data1,\n                      data2,\n                      startPts: startPTS,\n                      endPts: endPTS,\n                      keyTagInfo,\n                      isLastFragment,\n                      iframe: (_a = frag.iframe) !== null && _a !== void 0 ? _a : false,\n                      duration: frag.duration,\n                      iframeMediaDuration: isIframeMediaFragment(frag) ? frag.iframeMediaDuration : undefined,\n                      iframeOriginalStart: isIframeMediaFragment(frag) ? frag.iframeOriginalStart : undefined,\n                      captionData,\n                      id3Samples,\n                  };\n                  const appendDataTuple = [generatedInitSegmentCacheEntity, mediaFragmentCacheEntity];\n                  return appendDataTuple;\n              }));\n          }), addDemuxErrorHandlingPolicy(rootPlaylistService, rootPlaylistQuery, mediaOptionType, mediaOptionId));\n      }\n      // Fragment loading with error handling\n      function getMediaFragmentCommon(libContext, frag, updateStats, updateRtc) {\n          var _a, _b, _c;\n          const { rootPlaylistQuery: rootQuery, rootPlaylistService: rootService, config, rtcService, statsService } = libContext;\n          const { itemId, mediaOptionType } = frag;\n          const loadPolicy = config.fragLoadPolicy;\n          const isMediaFragment = isFiniteNumber(frag.mediaSeqNum);\n          let onProgress;\n          if (isMediaFragment) {\n              const updateSample = (_url, _status, stats, _data) => {\n                  rootService.updateInflightFrag(itemId, frag.mediaOptionType, frag, 'loading', stats);\n                  return false;\n              };\n              onProgress = { getData: false, cb: updateSample };\n          }\n          let requestServerInfo = false;\n          if (updateRtc) {\n              if (rtcService.serverInfoInstance === null) {\n                  requestServerInfo = true;\n              }\n          }\n          const fetchSegment$ = loadMediaFragment(frag, config, loadPolicy, onProgress, requestServerInfo, (_b = (_a = globalHlsService()) === null || _a === void 0 ? void 0 : _a.getQuery()) === null || _b === void 0 ? void 0 : _b.extendMaxTTFB).pipe(tap(([, , stats, serverInfo]) => {\n              libContext.logger.qe({\n                  critical: true,\n                  name: 'resourceTimingMonitor',\n                  data: {\n                      type: MediaOptionNames[frag.mediaOptionType],\n                      trequest: stats.trequest,\n                      tfirst: stats.tfirst,\n                      tload: stats.tload,\n                      bitsDownloaded: stats.total,\n                      mediaSeqNum: frag.mediaSeqNum,\n                      mediaOpitonId: frag.mediaOptionId,\n                  },\n              });\n              if (updateStats) {\n                  statsService.setBandwidthSample(Object.assign(Object.assign({}, stats), { mediaOptionType: frag.mediaOptionType }));\n              }\n              if (updateRtc && requestServerInfo) {\n                  rtcService.serverInfoInstance = serverInfo;\n              }\n              if (isMediaFragment) {\n                  rootService.updateInflightFrag(itemId, frag.mediaOptionType, frag, 'loaded', stats);\n              }\n          }), tap(([mediaFragment, , stats]) => {\n              if (updateRtc) {\n                  const { logger } = rootService;\n                  logger.qe({\n                      critical: true,\n                      name: 'fragLoaded',\n                      data: { mediaOptionType: frag.mediaOptionType, fragLoadingProcessingMs: stats.tload - stats.tfirst, loaded: stats.loaded, duration: frag.duration, fragLoadMs: stats.tload - stats.trequest },\n                  });\n                  rtcService.handleFragLoaded(mediaFragment, stats);\n              }\n          }), addLoadErrorHandlingPolicy(itemId, mediaOptionType, getLoadConfig(frag, loadPolicy), config.maxNumAddLevelToPenaltyBox, false, rootQuery, rootService, statsService));\n          // <rdar://89444975> Don't need to wait for key if segment is not encrypted!\n          const shouldWaitForKey = ((_c = frag.keyTagInfo) === null || _c === void 0 ? void 0 : _c.method) === 'AES-128';\n          if (shouldWaitForKey) {\n              return forkJoin([loadKey(libContext, frag.keyTagInfo, { itemId: frag.itemId, mediaOptionId: frag.mediaOptionId }), fetchSegment$]).pipe(switchMap(([keyTagInfo, fragInfo]) => {\n                  const [mediaFragment, fragDataBuf] = fragInfo;\n                  mediaFragment.keyTagInfo.key = keyTagInfo.key;\n                  return decryptMediaFragment(mediaFragment, fragDataBuf, config, libContext.logger, libContext.rpcClients.crypto);\n              }));\n          }\n          return fetchSegment$.pipe(map((fragInfo) => fragInfo[1]));\n      }\n      /**\n       * Retrieve the data for a media fragment\n       *\n       * @param {MediaFragment} retrieveFragAction the media fragment to retrieve data for\n       * @returns {Observable<SbDataTuple>} the init segment data and fragment data\n       */\n      const retrieveSubtitleFragmentCacheEntity = (libContext, initPTS, mediaFragment) => {\n          const { logger } = libContext;\n          const { mediaOptionType, mediaOptionId, discoSeqNum, mediaSeqNum } = mediaFragment;\n          logger.info(`[${MediaOptionNames[mediaOptionType]}] loading media fragment ${JSON.stringify({ mediaOptionId, discoSeqNum, mediaSeqNum })}`);\n          return getMediaFragmentCommon(libContext, mediaFragment, false, false).pipe(map((data) => {\n              logger.info(`[${MediaOptionNames[mediaOptionType]}] loaded media fragment ${JSON.stringify({ mediaOptionId, discoSeqNum, mediaSeqNum })}`);\n              return { initPTS, data, mediaFragment };\n          }), tag('retrieveSubtitleFragmentCacheEntity.emit'));\n      };\n      /**\n       * Retrieve the data for a media fragment\n       *\n       * @param {MediaFragment} retrieveFragAction the media fragment to retrieve data for\n       * @returns {Observable<SbDataTuple>} the init segment data and fragment data\n       */\n      const retrieveMediaFragmentCacheEntity = (libContext, mediaOptionType, retrieveFragAction) => {\n          const { rootPlaylistService: rootService, rootPlaylistQuery: rootQuery } = libContext;\n          const { logger } = rootService;\n          const { timelineOffset, mediaFragment } = retrieveFragAction.foundFrag;\n          const { itemId, mediaOptionId, discoSeqNum, mediaSeqNum } = mediaFragment;\n          logger.info(`[${MediaOptionNames[mediaOptionType]}] loading media fragment ${JSON.stringify({ mediaOptionId, discoSeqNum, mediaSeqNum })}`);\n          return retrieveInitSegmentCacheEntity(libContext, mediaFragment).pipe(switchMap((initSegmentCacheEntity) => {\n              rootService.updateInflightFrag(itemId, mediaFragment.mediaOptionType, mediaFragment, 'loading', null);\n              return getMediaFragmentCommon(libContext, mediaFragment, true, true).pipe(switchMap((data) => {\n                  var _a;\n                  rootService.updateInflightFrag(itemId, mediaOptionType, mediaFragment, 'parsing', null);\n                  return parseSegment(data, (_a = rootQuery.getInitPTS(discoSeqNum)) === null || _a === void 0 ? void 0 : _a.offsetTimestamp, initSegmentCacheEntity, mediaFragment, timelineOffset, libContext);\n              }), tap((parsedData) => {\n                  rootService.updateInflightFrag(itemId, mediaOptionType, mediaFragment, 'parsed', null);\n                  const { startPts, endPts, startDtsTs, endDtsTs } = parsedData[1];\n                  logger.info(`[${MediaOptionNames[mediaOptionType]}] ${JSON.stringify({ mediaOptionId, discoSeqNum, mediaSeqNum })} parsed: ${JSON.stringify({ startPts, endPts, startDtsTs, endDtsTs })}`);\n              }), tag(`retrieveMediaFragmentCacheEntity.${mediaOptionType}.emit`));\n          }), take(1));\n      };\n      function loadKey(context, keyTagInfo, mediaOptionKey) {\n          const { keySystemAdapter, rootPlaylistQuery, rootPlaylistService, config } = context;\n          return keySystemAdapter\n              .getKeyFromDecryptData(keyTagInfo, mediaOptionKey)\n              .pipe(addKeyErrorHandlingPolicy(keyTagInfo.uri, getLoadConfig({ url: keyTagInfo.uri }, config.keyLoadPolicy), rootPlaylistQuery, rootPlaylistService, keySystemAdapter.ksQuery));\n      }\n      function mediaLibraryRemove(ids) {\n          mediaLibraryService().remove(ids);\n      }\n      function mediaLibraryClear() {\n          mediaLibraryService().clear();\n      }\n    \n      /*\n       * HLS Player Events\n       *\n       * \n       */\n      /*\n       * @brief subscribes to hls public queries and sends out events.\n       */\n      class HlsPlayerEvents {\n          constructor(hls, logger, rtcService) {\n              this.hls = hls;\n              this.destroy$ = new Subject();\n              this.iframeSwitchStart = 0;\n              this.logger = logger.child({ name: 'hls-player-events' });\n              this.rtc = rtcService;\n              this.subscribeAndEmit();\n          }\n          destroy() {\n              this.destroy$.next();\n          }\n          subscribeAndEmit() {\n              const loaderQuery$ = this.loaderQueryListener(createLoaderQuery());\n              const publicQueries$ = this.hls.publicQueries$.pipe(switchMap(([rootPlaylistQuery, mediaElementQuery]) => {\n                  return merge(this.rootPlaylistQueryListener(rootPlaylistQuery, mediaElementQuery), this.mediaElementQueryListener(mediaElementQuery, rootPlaylistQuery));\n              }));\n              const activeItemQuery$ = this.activeItemListener(this.hls.itemQueue);\n              merge(loaderQuery$, publicQueries$, activeItemQuery$)\n                  .pipe(catchError((err) => {\n                  let errMessage = err.message;\n                  {\n                      errMessage = err.stack;\n                  }\n                  this.logger.error(`Got error in HlsPlayerEvents ${errMessage}`, err);\n                  return EMPTY;\n              }), takeUntil(this.destroy$), finalize$1(() => {\n                  this.logger.info('HlsPlayerEvents finalized');\n              }))\n                  .subscribe();\n          }\n          activeItemListener(itemQueue) {\n              const manifestLoadSource$ = itemQueue.activeItemById$.pipe(filterNullOrUndefined(), switchMap((item) => {\n                  var _a;\n                  const url = item.url;\n                  this.logger.debug(`Manifest loading: ${(_a = this.hls.itemQueue.activeItem) === null || _a === void 0 ? void 0 : _a.url}`);\n                  this.hls.trigger(HlsEvent.MANIFEST_LOADING, { url });\n                  return EMPTY;\n              }));\n              return manifestLoadSource$;\n          }\n          rootPlaylistQueryListener(rootPlaylistQuery, mediaElementQuery) {\n              const variantSource$ = rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(filter((mediaOption) => !!mediaOption), switchMap((mediaOption) => {\n                  var _a;\n                  this.logger.debug(`Switching to level: ${mediaOption.mediaOptionId}`);\n                  this.hls.trigger(HlsEvent.LEVEL_SWITCHING, mediaOption);\n                  (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleLevelSwitching(mediaOption.url);\n                  return EMPTY;\n              }));\n              const levelLoading$ = rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(switchMap((mediaOption) => {\n                  const mediaLibQuery = createMediaLibraryQuery(mediaOption);\n                  return mediaLibQuery.mediaOptionDetailsEntity$.pipe(filter((entity) => (entity === null || entity === void 0 ? void 0 : entity.detailsLoading) === true), tap((_) => {\n                      const levelLoading = {\n                          url: redactUrl(mediaOption === null || mediaOption === void 0 ? void 0 : mediaOption.url),\n                          level: mediaOption.mediaOptionId,\n                          type: MediaOptionNames[mediaOption.mediaOptionType],\n                      };\n                      this.logger.qe({ critical: true, name: 'levelLoading', data: levelLoading });\n                      this.hls.trigger(HlsEvent.LEVEL_LOADING, levelLoading);\n                      return EMPTY;\n                  }));\n              }));\n              const levelLoaded$ = rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(switchMap((mediaOption) => {\n                  const query = createMediaLibraryQuery(mediaOption);\n                  let lastUpdate = 0;\n                  // filter on entities that have loading set to false and have stats filled and have been updated\n                  return query.mediaOptionDetailsEntity$.pipe(filterNullOrUndefined(), filter((entity) => {\n                      var _a;\n                      const retValue = entity.stats !== null && entity.detailsLoading === false && entity.lastUpdateMillis > lastUpdate;\n                      lastUpdate = (_a = entity.lastUpdateMillis) !== null && _a !== void 0 ? _a : 0;\n                      return retValue;\n                  }));\n              }), switchMap((mediaDetailsEntity) => {\n                  var _a;\n                  const mediaOptionDetails = mediaDetailsEntity.mediaOptionDetails;\n                  const stats = mediaDetailsEntity.stats;\n                  const levelLoadedData = {\n                      mediaOptionId: mediaOptionDetails.mediaOptionId,\n                      details: mediaOptionDetails,\n                      playlistType: mediaOptionDetails.type,\n                      stats: stats,\n                  };\n                  // this.logger.debug('Level loaded %o', levelLoadedData);\n                  this.logger.qe({\n                      critical: true,\n                      name: 'levelLoaded',\n                      data: { url: redactUrl(mediaOptionDetails === null || mediaOptionDetails === void 0 ? void 0 : mediaOptionDetails.url), level: mediaOptionDetails.mediaOptionId, type: MediaOptionNames[mediaOptionDetails.mediaOptionType], adt: stats.tload - stats.trequest },\n                  });\n                  (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleLevelLoaded(mediaOptionDetails, levelLoadedData.stats);\n                  this.hls.trigger(HlsEvent.LEVEL_LOADED, levelLoadedData);\n                  if (mediaDetailsEntity.unchangedCount === 0) {\n                      const levelUpdatedData = {\n                          level: 0,\n                          details: mediaOptionDetails,\n                      };\n                      // This is critical for gapless. Muze uses this to set media duration\n                      this.hls.trigger(HlsEvent.LEVEL_UPDATED, levelUpdatedData);\n                  }\n                  if (mediaOptionDetails === null || mediaOptionDetails === void 0 ? void 0 : mediaOptionDetails.daterangeTags) {\n                      const dateRangeTags = { daterangeTags: mediaOptionDetails.daterangeTags };\n                      // this.logger.debug('Date range tags parsed: %o', dateRangeTags);\n                      this.logger.qe({ critical: true, name: 'dateRangeTags', data: { dateRangeTags } });\n                      this.hls.trigger(HlsEvent.DATERANGE_UPDATED, dateRangeTags);\n                  }\n                  return EMPTY;\n              }));\n              const audioSource$ = rootPlaylistQuery.enableMediaOptionSwitchedForType$(MediaOptionType.AltAudio).pipe(switchMap((mediaOption) => {\n                  const altOption = rootPlaylistQuery.alternateMediaOptionById(MediaOptionType.AltAudio, mediaOption.mediaOptionId);\n                  if (altOption) {\n                      this.triggerAudioSwitch(altOption);\n                  }\n                  return EMPTY;\n              }));\n              // The first audio switch occurs before the rootPlaylistQuery is ready. As a result, we'll monitor the\n              // rootPlaylistEntity to trigger the first audio switch\n              const firstAudioSwitch$ = rootPlaylistQuery.rootPlaylistEntity$.pipe(filter((rootEntity) => rootEntity.enabledMediaOptionKeys[MediaOptionType.AltAudio].mediaOptionId !== null), take(1), switchMap((rootEntity) => {\n                  const mediaOptionId = rootEntity.enabledMediaOptionKeys[MediaOptionType.AltAudio].mediaOptionId;\n                  if (mediaOptionId) {\n                      const altOption = rootEntity.mediaOptionListTuple[MediaOptionType.AltAudio].mediaOptions.find((option) => option.mediaOptionId === mediaOptionId);\n                      this.triggerAudioSwitch(Object.assign(Object.assign({}, altOption), { url: redactUrl(altOption === null || altOption === void 0 ? void 0 : altOption.url) }));\n                  }\n                  return EMPTY;\n              }));\n              // Trigger SUBTITLE_TRACK_SWITCH only when the HTML5 texttracks have been created.\n              // MatchPoint will call addCueChange on the enabled texttrack.\n              const subtitleSource$ = waitFor(mediaElementQuery.textTracksCreated$, (created) => created).pipe(switchMap(() => {\n                  return rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Subtitle).pipe(switchMap((mediaOption) => {\n                      const altOption = rootPlaylistQuery.alternateMediaOptionById(MediaOptionType.Subtitle, mediaOption.mediaOptionId);\n                      if (altOption) {\n                          const data = {\n                              trackId: altOption.id,\n                              mediaOptionId: altOption.mediaOptionId,\n                              groupId: altOption.groupId,\n                              persistentId: altOption.persistentID,\n                              name: altOption.name,\n                          };\n                          this.logger.qe({ critical: true, name: 'textTrackSwitch', data });\n                          this.logger.debug(`Subtitle track switch track: ${altOption.id}`);\n                          this.hls.trigger(HlsEvent.SUBTITLE_TRACK_SWITCH, {\n                              track: Object.assign({}, altOption),\n                              hidden: false,\n                          });\n                      }\n                      else {\n                          this.hls.trigger(HlsEvent.SUBTITLE_TRACK_SWITCH, {\n                              track: undefined,\n                              hidden: false,\n                          });\n                          this.logger.qe({ critical: true, name: 'textTrackSwitch', data: { unselected: true } });\n                      }\n                      return EMPTY;\n                  }));\n              }));\n              const sessionData$ = rootPlaylistQuery.sessionData$.pipe(filter((d) => d.complete != undefined), take(1), tap((sd) => this.logger.debug('Session Data Complete: %o', sd)), map((sd) => {\n                  this.hls.trigger(HlsEvent.SESSION_DATA_COMPLETE, sd);\n              }));\n              const prefferedLevels$ = rootPlaylistQuery.getPreferredMediaOptionsByType$(MediaOptionType.Variant).pipe(skip(1), map((prefLevels) => {\n                  var _a;\n                  const variantList = prefLevels;\n                  this.logger.debug('Levels changed %o', variantList);\n                  (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleLevelsChanged(variantList);\n                  this.logger.qe({ critical: true, name: 'levelsChanged', data: { numLevels: variantList.length } });\n                  variantList.forEach((level) => {\n                      const { mediaOptionId, bandwidth, bitrate, videoCodec, audioCodec, height, width, videoRange, iframes } = level;\n                      this.logger.qe({ critical: true, name: 'manifestLevel', data: { mediaOptionId, bandwidth, bitrate, videoCodec, audioCodec, height, width, videoRange, iframes } });\n                  });\n                  this.hls.trigger(HlsEvent.LEVELS_CHANGED, { requiresReset: false, levels: variantList });\n                  //TODO fix require reset\n              }));\n              const altPrefferedLevels$ = rootPlaylistQuery.getPreferredMediaOptionsByType$(MediaOptionType.AltAudio).pipe(map((prefLevels) => {\n                  const altList = prefLevels;\n                  this.logger.debug('Audio tracks updated %o', altList);\n                  this.hls.trigger(HlsEvent.AUDIO_TRACKS_UPDATED, { audioTracks: altList });\n                  //TODO fix require reset\n              }));\n              // Trigger SUBTITLE_TRACKS_UPDATED only when the HTML5 texttracks have been created.\n              // MatchPoint may query the available media option list and relate them to the HTML5 texttracks\n              const subPrefferedLevels$ = waitFor(mediaElementQuery.textTracksCreated$, (created) => created).pipe(switchMap(() => {\n                  return rootPlaylistQuery.getPreferredMediaOptionsByType$(MediaOptionType.Subtitle).pipe(take(1), map((prefLevels) => {\n                      const altList = prefLevels;\n                      // Potentially large object log\n                      // this.logger.info('Subtitle tracks updated %o', altList);\n                      this.hls.trigger(HlsEvent.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: altList });\n                      this.logger.info('Subtitle tracks created');\n                      this.hls.trigger(HlsEvent.SUBTITLE_TRACKS_CREATED);\n                      //TODO fix require reset\n                  }));\n              }));\n              return merge(variantSource$, audioSource$, subtitleSource$, sessionData$, prefferedLevels$, altPrefferedLevels$, subPrefferedLevels$, levelLoaded$, levelLoading$, firstAudioSwitch$);\n          }\n          mediaElementQueryListener(mediaElementQuery, rootPlaylistQuery) {\n              const seekSource$ = mediaElementQuery.seekTo$.pipe(map((seekTo) => {\n                  var _a, _b;\n                  if (seekTo && isFiniteNumber(seekTo.pos)) {\n                      this.logger.debug(`Seeking pos:${seekTo.pos}`);\n                      (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleSeek('SEEKING');\n                      this.hls.trigger(HlsEvent.SEEKING, { seekToPos: seekTo.pos });\n                  }\n                  else if (seekTo === null) {\n                      (_b = this.rtc) === null || _b === void 0 ? void 0 : _b.handleSeek('SEEKED');\n                      this.logger.debug('Seeked');\n                      this.hls.trigger(HlsEvent.SEEKED);\n                  }\n              }));\n              const desiredRateSource$ = mediaElementQuery.desiredRate$.pipe(startWith(0), pairwise(), map((pair) => {\n                  var _a;\n                  const oldRate = pair[0];\n                  const newRate = pair[1];\n                  if (isIframeRate(newRate)) {\n                      if (this.iframeSwitchStart == 0) {\n                          this.iframeSwitchStart = performance.now();\n                      }\n                  }\n                  else {\n                      this.iframeSwitchStart = 0;\n                  }\n                  this.logger.debug(`Rate changed oldRate: ${oldRate}, newRate: ${newRate}`);\n                  this.hls.trigger(HlsEvent.DESIRED_RATE_CHANGED, { oldRate, newRate });\n                  (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleDesiredRateChanged(oldRate, newRate);\n              }));\n              const audioBufferSource$ = mediaElementQuery.sourceBufferEntityByType$(SourceBufferType.AltAudio).pipe(filter((buffer) => !!buffer), distinctUntilChanged((prev, cur) => prev.totalBytes === cur.totalBytes), map((buffer) => {\n                  this.logger.trace('Audio Buffer Appended. Buffer= %o', buffer);\n                  this.hls.trigger(HlsEvent.BUFFER_APPENDED);\n              }));\n              const variantBufferSource$ = mediaElementQuery.sourceBufferEntityByType$(SourceBufferType.Variant).pipe(filter((buffer) => !!buffer), distinctUntilChanged((prev, cur) => prev.totalBytes === cur.totalBytes), map((buffer) => {\n                  var _a;\n                  this.logger.trace('Variant Buffer Appended. Buffer= %o', buffer);\n                  (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleVariantBufferAppended(buffer.timestampOffset, buffer.totalBytes);\n                  this.hls.trigger(HlsEvent.BUFFER_APPENDED);\n              }));\n              const stallInfo$ = mediaElementQuery.stallInfo$.pipe(filterNullOrUndefined(), withLatestFrom(mediaElementQuery.combinedBuffer$), map(([stallInfo, buffered]) => {\n                  var _a;\n                  this.logger.qe({ critical: true, name: 'stall', data: Object.assign(Object.assign({}, stallInfo), { buffered }) });\n                  (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleStalled(stallInfo, mediaElementQuery.getCombinedBufferInfo(stallInfo.currentTime, 0).len);\n                  this.hls.trigger(HlsEvent.STALLED, stallInfo);\n              }));\n              const fragChangeMonitor$ = combineLatest([\n                  of(rootPlaylistQuery),\n                  combineQueries([mediaElementQuery.timeupdate$, mediaElementQuery.bufferedSegmentsByType$(SourceBufferType.Variant)]).pipe(throttleTime(1000), map(([currentTime, bufferedSegments]) => {\n                      const playingFrag = bufferedSegments === null || bufferedSegments === void 0 ? void 0 : bufferedSegments.find((seg) => seg.startPTS <= currentTime && seg.endPTS > currentTime);\n                      return playingFrag;\n                  }), filter((playingFrag) => !!playingFrag), startWith(null), pairwise()),\n              ]).pipe(switchMap(([rootPlaylistQuery, [a, b]]) => {\n                  var _a;\n                  const playingFrag = b === null || b === void 0 ? void 0 : b.frag;\n                  const previousFrag = a === null || a === void 0 ? void 0 : a.frag;\n                  if (playingFrag && !fragEqual(previousFrag, playingFrag)) {\n                      this.hls.trigger(HlsEvent.FRAG_CHANGED, b);\n                      if (this.hls.inGaplessMode) {\n                          this.checkAndTriggerReadyForNext(mediaElementQuery, b);\n                      }\n                      if (!previousFrag || playingFrag.mediaOptionId !== previousFrag.mediaOptionId) {\n                          const variantOption = rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.Variant].mediaOptionFromId(playingFrag.mediaOptionId);\n                          if (!variantOption) {\n                              // TODO investigate this.. sometimes happens in gapless mode\n                              this.logger.warn('variantInfo is undefined in fragChangeMonitor');\n                              return EMPTY;\n                          }\n                          const oldVariant = previousFrag ? previousFrag.mediaOptionId : '';\n                          const newVariant = playingFrag.mediaOptionId;\n                          const data = {\n                              oldVariant,\n                              newVariant,\n                              bitrate: variantOption.bitrate,\n                              bandwidth: variantOption.bandwidth,\n                              avgBandwidth: variantOption.avgBandwidth,\n                              width: variantOption.width,\n                              height: variantOption.height,\n                              levelCodec: variantOption.levelCodec,\n                              frameRate: variantOption.frameRate,\n                          };\n                          if (variantOption.iframes) {\n                              const rate = mediaElementQuery.desiredRate;\n                              const state = mediaElementQuery.isIframeRate;\n                              const startupTime = performance.now() - this.iframeSwitchStart;\n                              this.logger.qe({ critical: true, name: 'iframes', data: { state, rate, oldVariant, newVariant, startupTime } });\n                          }\n                          this.logger.qe({ critical: true, name: 'variantSwitched', data });\n                          (_a = this.rtc) === null || _a === void 0 ? void 0 : _a.handleLevelSwitched({ url: variantOption.url, mediaOptionId: variantOption.mediaOptionId, oldVariant: oldVariant !== '' ? oldVariant : undefined, newVariant: newVariant });\n                          this.hls.trigger(HlsEvent.LEVEL_SWITCHED, variantOption);\n                      }\n                  }\n                  return EMPTY;\n              }));\n              const fullyBuffered$ = mediaElementQuery.isBufferedToEnd$(this.hls.config.maxBufferHole, false).pipe(filter((isBuffered) => isBuffered === true), \n              // Use asyncScheduler as the READY_FOR_NEXT_ITEM event could cause an item queue change\n              observeOn(asyncScheduler), map((isBuffered) => {\n                  if (isBuffered && !this.hls.itemQueue.isPreloading() && this.hls.inGaplessMode) {\n                      const combinedBuffer = mediaElementQuery.getCombinedBufferInfo(mediaElementQuery.currentTime, 0);\n                      let duration = 0;\n                      if (combinedBuffer) {\n                          duration = combinedBuffer.end;\n                      }\n                      else {\n                          this.logger.info('Combined Buffer is not ready, do not trigger READY_FOR_NEXT_ITEM');\n                          return;\n                      }\n                      const mediaDuration = mediaElementQuery.mediaElementDuration;\n                      // Only trigger READY_FOR_NEXT with less than 10 seconds to play. This is a Muze hack so that\n                      // short songs are not skipped\n                      if (duration > 0 && mediaDuration - mediaElementQuery.currentTime < 10) {\n                          this.logger.info(`Trigger READY_FOR_NEXT_ITEM BufferDuration=${duration}, mediaDuration=${mediaDuration}`);\n                          this.hls.trigger(HlsEvent.READY_FOR_NEXT_ITEM, { duration });\n                      }\n                  }\n              }));\n              return merge(seekSource$, desiredRateSource$, audioBufferSource$, variantBufferSource$, stallInfo$, fragChangeMonitor$, fullyBuffered$);\n          }\n          checkAndTriggerReadyForNext(mediaElementQuery, currentFrag) {\n              if (!currentFrag || !currentFrag.frag) {\n                  return;\n              }\n              this.logger.trace('currentFrag %o', currentFrag);\n              const pos = mediaElementQuery.currentTime;\n              const combinedBuffer = mediaElementQuery.getCombinedBufferInfo(pos, 0);\n              if (!combinedBuffer) {\n                  this.logger.info('Combined Buffer is not ready, do not trigger READY_FOR_NEXT_ITEM');\n                  return;\n              }\n              const duration = combinedBuffer.end;\n              const mediaDuration = mediaElementQuery.mediaElementDuration;\n              const bufInfoMonitor = mediaElementQuery.bufferMonitorInfo;\n              // The closeToEndThreashold is typically half of the target duration. This differs from 2.0 that uses the full target duration.\n              // This leaves short time to buffer the next item. Good for audio but will not work for video.\n              // If we ever want to do gapless video we'll need to re-visit the using the fullyBuffered$ method above\n              const closeToEndThreshold = Math.max(bufInfoMonitor.almostDryWaterLevelSeconds, bufInfoMonitor.lowWaterLevelSeconds / 2);\n              if (mediaDuration - currentFrag.endPTS <= closeToEndThreshold || currentFrag.frag.isLastFragment) {\n                  if (this.hls.inGaplessMode && !this.hls.isPreloading) {\n                      this.logger.info(`Trigger READY_FOR_NEXT_ITEM BufferDuration=${duration}, mediaDuration=${mediaDuration}`);\n                      this.hls.trigger(HlsEvent.READY_FOR_NEXT_ITEM, { duration });\n                  }\n              }\n          }\n          loaderQueryListener(loaderQuery) {\n              const unresolvedUriLoadingSource$ = loaderQuery.unresolvedUriLoading$.pipe(map((entities) => {\n                  return entities.map((entity) => {\n                      this.logger.debug('Unresolved Uri Loading, data= %o', entity);\n                      const data = { uri: entity.uri, responseType: entity.responseType, userAgent: entity.userAgent };\n                      this.hls.trigger(HlsEvent.UNRESOLVED_URI_LOADING, data);\n                  });\n              }));\n              return merge(unresolvedUriLoadingSource$);\n          }\n          triggerAudioSwitch(altOption) {\n              if (altOption) {\n                  this.logger.info(`Audio track switched id: ${altOption.id} ${altOption.mediaOptionId}`);\n                  this.logger.qe({ critical: true, name: 'audioTrackSwitched', data: { altOption } });\n                  this.hls.trigger(HlsEvent.AUDIO_TRACK_SWITCHED, { id: altOption.id });\n              }\n          }\n          triggerManifestLoaded(loadRootMediaOptionsResult) {\n              var _a;\n              const payload = {\n                  levels: loadRootMediaOptionsResult.rootMediaOptionsTuple[MediaOptionType.Variant],\n                  audioTracks: loadRootMediaOptionsResult.rootMediaOptionsTuple[MediaOptionType.AltAudio],\n                  subtitleTracks: loadRootMediaOptionsResult.rootMediaOptionsTuple[MediaOptionType.Subtitle],\n                  url: loadRootMediaOptionsResult.baseUrl,\n                  audioMediaSelectionGroup: loadRootMediaOptionsResult.audioMediaSelectionGroup,\n                  subtitleMediaSelectionGroup: loadRootMediaOptionsResult.subtitleMediaSelectionGroup,\n                  stats: loadRootMediaOptionsResult.stats,\n                  isMediaPlaylist: loadRootMediaOptionsResult.isMediaPlaylist,\n              };\n              this.logger.debug('Manifest loaded');\n              this.logger.qe({ critical: true, name: 'manifestLoaded', data: { numLevels: (_a = payload.levels) === null || _a === void 0 ? void 0 : _a.length } });\n              this.hls.trigger(HlsEvent.MANIFEST_LOADED, payload);\n          }\n          triggerManifestParsed(rootQuery) {\n              var _a, _b;\n              // TODO Fix firstlevel, audio, video and altAudio\n              const manifestParsedData = {\n                  levels: rootQuery.mediaOptionListQueries[MediaOptionType.Variant].filteredMediaOptionList,\n                  firstLevel: 0,\n                  audio: false,\n                  video: true,\n                  altAudio: false,\n                  audioTracks: rootQuery.mediaOptionListQueries[MediaOptionType.AltAudio].filteredMediaOptionList,\n                  audioMediaSelectionGroup: rootQuery.audioMediaSelectionGroup,\n                  subtitleMediaSelectionGroup: rootQuery.subtitleMediaSelectionGroup,\n                  stats: rootQuery.loadStats,\n              };\n              this.logger.debug('Manifest parsed %o', manifestParsedData);\n              this.logger.qe({ critical: true, name: 'manifestParsed', data: { numLevels: (_a = manifestParsedData.levels) === null || _a === void 0 ? void 0 : _a.length } });\n              (_b = this.rtc) === null || _b === void 0 ? void 0 : _b.handleManifestParsed(manifestParsedData);\n              this.hls.trigger(HlsEvent.MANIFEST_PARSED, manifestParsedData);\n          }\n          urlRedactedManifestLoaded(indata) {\n              const outdata = Object.assign({}, indata);\n              outdata.url = redactUrl(outdata.url);\n              outdata.levels = urlRedactedLevelInfo(outdata.levels);\n              outdata.audioTracks = urlRedactedAltMediaOption(outdata.audioTracks);\n              outdata.subtitleTracks = urlRedactedAltMediaOption(outdata.subtitleTracks);\n              return outdata;\n          }\n          urlRedactedManifestParsed(indata) {\n              const outdata = Object.assign({}, indata);\n              outdata.levels = urlRedactedLevelInfo(outdata.levels);\n              outdata.audioTracks = urlRedactedAltMediaOption(outdata.audioTracks);\n              return outdata;\n          }\n      }\n    \n      var SwitchReason;\n      (function (SwitchReason) {\n          SwitchReason[\"LowBandwidth\"] = \"LowBandwidth\";\n          SwitchReason[\"HighBandwidth\"] = \"HighBandwidth\";\n          SwitchReason[\"PreferredListChanged\"] = \"PreferredListChanged\";\n          SwitchReason[\"IframeModeChange\"] = \"IframeModeChange\";\n          SwitchReason[\"None\"] = \"\";\n      })(SwitchReason || (SwitchReason = {}));\n    \n      const firstMediaOptionSelectionMetrics = {\n          minValidBitrate: 2000000,\n          maxValidBitrate: 5000000,\n          maxPreferredBitrate: 3000000,\n          minValidHeight: 480,\n          maxValidHeight: 720,\n      };\n      // Filter media options that are not compatible with the starting tier\n      // Currently we hit an issue when switching between audio codecs: ac-3 / ec-3 / mp4a.40.*\n      // and video codecs: dolby, hevc, avc\n      const isCompatible = (mediaOption1, mediaOption2) => {\n          let isVideoCompatible = true;\n          if (mediaOption1.videoCodec && mediaOption2.videoCodec) {\n              isVideoCompatible = MediaUtil.isCompatibleVideoCodec(mediaOption1.videoCodec, mediaOption2.videoCodec);\n          }\n          let isVideoRangeSame = false;\n          if (mediaOption1.videoRange && mediaOption2.videoRange) {\n              isVideoRangeSame = mediaOption1.videoRange == mediaOption2.videoRange;\n          }\n          else if (!mediaOption1.videoRange && !mediaOption2.videoRange) {\n              isVideoRangeSame = true;\n          }\n          let isAudioCompatible = true;\n          if (mediaOption1.audioCodec && mediaOption2.audioCodec) {\n              // Both have valid audio codecs, check with MediaUtil.isAudioCompatible\n              isAudioCompatible = MediaUtil.isCompatibleAudioCodec(mediaOption1.audioCodec, mediaOption2.audioCodec);\n          }\n          return isVideoCompatible && isVideoRangeSame && isAudioCompatible;\n      };\n      function filterMediaOptionsBasedOnFirstMediaOptions(mediaOptions, firstMediaOptionInfo) {\n          // Filter out again according to starting level, and save audioGroups of filtered levels if present\n          return mediaOptions.reduce((prev, cur) => {\n              const validMediaOption = isCompatible(firstMediaOptionInfo, cur);\n              if (validMediaOption) {\n                  const audioGroup = cur.audioGroupId;\n                  if (audioGroup) {\n                      prev.audioGroups.add(audioGroup);\n                  }\n                  prev.mediaOptions.add(cur);\n              }\n              const subtitleGroup = cur.subtitleGroupId;\n              if (subtitleGroup) {\n                  prev.subtitleGroups.add(subtitleGroup);\n              }\n              const closedCaptionGroup = cur.closedcaption;\n              if (closedCaptionGroup) {\n                  prev.closedCaptionGroups.add(closedCaptionGroup);\n              }\n              return prev;\n          }, { mediaOptions: new Set(), audioGroups: new Set(), subtitleGroups: new Set(), closedCaptionGroups: new Set() });\n      }\n      function chooseFirstMediaOptionBasedOnScore(mediaOptions, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          const ranking = mediaOptions.reduce((prev, cur) => {\n              if (cur.iframes) {\n                  return prev;\n              }\n              let result = prev;\n              const rank = getScoreRank(cur, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n              if (!prev || rank.isGreaterThan(prev.bestRank) || (rank.isEqualTo(prev.bestRank) && cur.bandwidth < prev.selected.bandwidth)) {\n                  result = { selected: cur, bestRank: rank };\n              }\n              return result;\n          }, null);\n          return ranking.selected;\n      }\n      // Determine the highest ranking MediaOption to be used as first MediaOption (breaking ties by prioritizing the higher bitrate if two MediaOptions have the same rank)\n      function chooseFirstMediaOptionBasedOnRanking(mediaOptions, metrics, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          const ranking = mediaOptions.reduce((prev, cur) => {\n              if (cur.iframes) {\n                  return prev;\n              }\n              let result = prev;\n              const rank = getMediaOptionRank(cur, metrics, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n              if (!prev || rank.isGreaterThan(prev.bestRank) || (rank.isEqualTo(prev.bestRank) && cur.bitrate > prev.selected.bitrate)) {\n                  result = { selected: cur, bestRank: rank };\n              }\n              return result;\n          }, null);\n          return ranking.selected;\n      }\n      // A MediaOption SCORE ranking is determined by a multisort comparison of 2 properties in order of importance:\n      // (1) within bandwidth cap\n      // (2) SCORE (determined by the playlist)\n      function getScoreRank(mediaInfo, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          const score = mediaInfo.score;\n          const isWithinCap = bandwidthHistory &&\n              adaptiveStartupConfig &&\n              playlistEstimate &&\n              fragEstimate &&\n              !isWithinBandwidthCap(mediaInfo, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate)\n              ? MatchRanking.INVALID\n              : MatchRanking.VALID; // If no bandwidthHistory or adaptiveStartupConfig specified, then don't mark the media option as INVALID;\n          return new MediaOptionRank(isWithinCap, score);\n      }\n      // A MediaOption's ranking is determined by a multisort comparison on 8 properties in order of importance:\n      // (1) validMetrics (between 2-5 mbps, height between 480-720p)\n      // (2) videoRangeRank (PQ/HLG/SDR)\n      // (3) videoRank (video codec rank)\n      // (4) audioChannelRank (if available and supported, then a 5.1 ac-3 tier takes precedence over stereo ec-3 tier)\n      // (5) audioCodecRank (audio codec rank)\n      // (6) within bandwidth cap\n      // (7) preferred max bitrate (less than 3 mbps)\n      // (8) MediaOption's height\n      function getMediaOptionRank(mediaInfo, firstMediaOptionSelectionMetrics, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          const validMetrics = hasValidMetrics(mediaInfo.bitrate, mediaInfo.height, firstMediaOptionSelectionMetrics) ? MatchRanking.VALID : MatchRanking.INVALID;\n          const videoRangeRank = getVideoRangeRanking(mediaInfo.videoRange);\n          const { videoCodecRank, audioCodecRank } = getAudioVideoCodecRanks(mediaInfo);\n          const lessThanMaxPreferredBitrate = mediaInfo.bitrate < firstMediaOptionSelectionMetrics.maxPreferredBitrate ? MatchRanking.VALID : MatchRanking.INVALID;\n          const DEFAULT_AUDIO_CHANNEL_COUNT = 1;\n          const audioChannelCount = mediaInfo.audioChannelCount || DEFAULT_AUDIO_CHANNEL_COUNT; // use the channel count for ranking;\n          const isWithinCap = bandwidthHistory &&\n              adaptiveStartupConfig &&\n              playlistEstimate &&\n              fragEstimate &&\n              !isWithinBandwidthCap(mediaInfo, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate)\n              ? MatchRanking.INVALID\n              : MatchRanking.VALID; // If no bandwidthHistory or adaptiveStartupConfig specified, then don't mark the MediaOption as INVALID\n          return new MediaOptionRank(validMetrics, videoRangeRank, videoCodecRank, audioChannelCount, audioCodecRank, isWithinCap, lessThanMaxPreferredBitrate, mediaInfo.height);\n      }\n      function isWithinBandwidthCap(mediaInfo, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          const { targetDuration, targetStartupMs } = adaptiveStartupConfig;\n          const { avgPlaylistLoadTimeMs } = playlistEstimate;\n          const { avgParseTimeMs } = fragEstimate;\n          const { avgBufferCreateMs, avgInitFragAppendMs, avgDataFragAppendMs } = bufferEstimate;\n          const avgBufferTimeMs = avgInitFragAppendMs + avgDataFragAppendMs;\n          const { avgBandwidth, avgLatencyMs } = bandwidthHistory;\n          const fragCount = 1; // Math.ceil(targetDuration / maxDuration);\n          return (mediaInfo.bandwidth <= avgBandwidth && // has sufficient bandwidth\n              (((mediaInfo.avgBandwidth || mediaInfo.bandwidth) * targetDuration) / avgBandwidth) * 1000 +\n                  avgPlaylistLoadTimeMs +\n                  avgBufferCreateMs +\n                  (avgLatencyMs + avgParseTimeMs + avgBufferTimeMs) * fragCount <=\n                  targetStartupMs); // can be loaded within targetStartupMs\n      }\n      function onlyIFrames(mediaOptions) {\n          return mediaOptions.every((opt) => opt.iframes);\n      }\n      function hasValidMetrics(bitrate, height, metrics) {\n          const inRange = (input, minVal, maxVal) => (input - minVal) * (input - maxVal) <= 0;\n          return inRange(bitrate, metrics.minValidBitrate, metrics.maxValidBitrate) && inRange(height, metrics.minValidHeight, metrics.maxValidHeight);\n      }\n      /**\n       * Choose first MediaOption from MediaOption array\n       *\n       * @param mediaOptions Set of MediaOptions to choose from\n       * @param hasScoreAvailable If SCORE metric is available\n       * @param metrics Metrics to use for selection\n       * @param bandwidthHistory Bandwidth history\n       * @param adaptiveStartupConfig Override configs\n       */\n      function chooseFirstMediaOption(mediaOptions, metrics, hasScoreAvailable, logger, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          let firstMediaOption;\n          if (!mediaOptions || mediaOptions.length < 1 || onlyIFrames(mediaOptions)) {\n              logger.warn('no non-iframe media option found');\n              return;\n          }\n          if (hasScoreAvailable) {\n              firstMediaOption = chooseFirstMediaOptionBasedOnScore(mediaOptions, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n          }\n          else {\n              firstMediaOption = chooseFirstMediaOptionBasedOnRanking(mediaOptions, metrics, bandwidthHistory, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n          }\n          if (!firstMediaOption) {\n              logger.warn('no valid first media option found');\n          }\n          return firstMediaOption;\n      }\n      function filterRegularLevelsBasedOnCapOn1080p(levels) {\n          // standard 1080p resolution with a slight tolerance of 1.2\n          const PIXELS_CAP = 2488320;\n          const capedLevels = levels.filter((levelInfo) => !levelInfo.iframes && (!levelInfo.width || !levelInfo.height || levelInfo.width * levelInfo.height <= PIXELS_CAP));\n          return capedLevels;\n      }\n    \n      /*\n       * simple ABR level switcher\n       *  - compute next level based on last fragment bw heuristics\n       *  - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n       *\n       * 2018 Apple Inc. All rights reserved.\n       */\n      const abrLogName = { name: 'abr' };\n      function getMaxStarvationDelaySec(fragDuration, maxBufStarvationSec) {\n          return isFiniteNumber(fragDuration) ? Math.min(fragDuration, maxBufStarvationSec) : maxBufStarvationSec;\n      }\n      function instantBwTooSlow(avgBw, abrStatus, bwStatus) {\n          const instantBw = bwStatus.instantBw;\n          return abrStatus.fragDownloadSlow || abrStatus.fragDownloadTooSlow || (isFiniteNumber(instantBw) && instantBw < avgBw);\n      }\n      function gotSlowMedia(abrStatus) {\n          return abrStatus.fragDownloadSlow || abrStatus.fragDownloadTooSlow;\n      }\n      function hasReliableBandwidthEstimate(bandwidthEstimate) {\n          return isFiniteNumber(bandwidthEstimate === null || bandwidthEstimate === void 0 ? void 0 : bandwidthEstimate.avgBandwidth);\n      }\n      function nextAutoMediaOption(abrConfig, rootPlaylistQuery, rootPlaylistService, mediaLibraryQuery, mediaElementQuery, statsQuery, logger) {\n          let defaultAutoVariantOption = rootPlaylistQuery.nextMaxAutoOptionId;\n          // In 2.0 arch, There was check to see if the nextMaxAutoOptionId was\n          // in penalty box. Don't see a possibility of that, here in 2.1 as\n          // the nexMaxAutoOptionId is set from the preferrdList.\n          if (defaultAutoVariantOption !== NoMediaOption.mediaOptionId && !hasReliableBandwidthEstimate(statsQuery.getBandwidthEstimate())) {\n              if (mediaElementQuery.isIframeRate) {\n                  // no group matching for iframe mode\n                  return { variantMediaOption: defaultAutoVariantOption, holdOffDuration: 0, lowestCandidate: null };\n              }\n              else {\n                  // defaultAutoVariantOption (rootPlaylistQuery.nextMaxAutoOptionId) gets set in likelyToStall.\n                  // Even though it has matching altAudio and subtitle mediaOptions at that time.\n                  // It might not at this moment due to penalized alternates.\n                  // getBestMediaOptionTupleFromVariantAndPersistentId will look for a\n                  // fallback variant that has matching alternates.\n                  // If it comes up short, then continue to use the current variant and alternates.\n                  const variantMediaOption = rootPlaylistQuery.variantMediaOptionById(defaultAutoVariantOption);\n                  const subtitleAltOption = rootPlaylistQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle);\n                  const audioAltOption = rootPlaylistQuery.enabledAlternateMediaOptionByType(MediaOptionType.AltAudio);\n                  const audioPersistentId = audioAltOption === null || audioAltOption === void 0 ? void 0 : audioAltOption.persistentID;\n                  const subtitlePersistentId = subtitleAltOption === null || subtitleAltOption === void 0 ? void 0 : subtitleAltOption.persistentID;\n                  const sdrOnly = !rootPlaylistQuery.preferHDR;\n                  const mediaOptionTuple = rootPlaylistService.getBestMediaOptionTupleFromVariantAndPersistentId(rootPlaylistQuery, variantMediaOption, audioPersistentId, subtitlePersistentId, undefined, [], sdrOnly, false, false);\n                  logger.info(`capped at sdrOnly ${sdrOnly} ${JSON.stringify(defaultAutoVariantOption)} with matching alternates: ${JSON.stringify(mediaOptionTuple)}`);\n                  if (rootPlaylistQuery.isValidMediaOptionTuple(mediaOptionTuple)) {\n                      defaultAutoVariantOption = mediaOptionTuple[MediaOptionType.Variant].mediaOptionId;\n                      const alternates = {\n                          altAudio: mediaOptionTuple[MediaOptionType.AltAudio],\n                          subtitle: mediaOptionTuple[MediaOptionType.Subtitle],\n                      };\n                      return { variantMediaOption: defaultAutoVariantOption, holdOffDuration: 0, alternates, lowestCandidate: null };\n                  }\n                  else {\n                      logger.info(`No fallback variant with matching alternates for (capped) level ${defaultAutoVariantOption}: use currentVariant instead.`);\n                  }\n                  const currentVariant = rootPlaylistQuery.enabledMediaOptionKeys[MediaOptionType.Variant];\n                  return { variantMediaOption: currentVariant.mediaOptionId, holdOffDuration: 0, lowestCandidate: null }; // by using currentVariant, switch will be skipped.\n              }\n          }\n          return nextABRAutoMediaOption(abrConfig, rootPlaylistQuery, mediaLibraryQuery, mediaElementQuery, statsQuery, logger);\n      }\n      function nextABRAutoMediaOption(abrConfig, rootPlaylistQuery, mediaLibraryQuery, mediaElementQuery, statsQuery, logger) {\n          const loggerChild = logger.child({ name: 'abr' });\n          const iframeMode = mediaElementQuery.isIframeRate;\n          const enabledVariantOptionId = rootPlaylistQuery.enabledMediaOptionIdByType(MediaOptionType.Variant);\n          const autoVariantOption = findNextABRAutoVariantOptionInMode(iframeMode, abrConfig, rootPlaylistQuery, mediaLibraryQuery, mediaElementQuery, statsQuery, loggerChild);\n          loggerChild.info(`nextABRAutoMediaOption ${enabledVariantOptionId}->${autoVariantOption.variantMediaOption}`);\n          return autoVariantOption;\n      }\n      function getABRPlaybackRate(mediaElementQuery) {\n          // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as\n          // if we're playing back at the normal rate.\n          return mediaElementQuery.playbackRate !== 0 ? Math.abs(mediaElementQuery.playbackRate) : 1;\n      }\n      // Scaled buffer ahead in seconds for video buffer\n      function getBufferAheadSec(mediaElementQuery, maxBufferHole) {\n          return mediaElementQuery.getCurrentWaterLevelByType(SourceBufferType.Variant, maxBufferHole) / getABRPlaybackRate(mediaElementQuery);\n      }\n      function findLowestValidVariantIndex(minAutoVariantIndex, availableVariantOptions, iframeMode, rootPlaylistQuery) {\n          if (iframeMode) {\n              return minAutoVariantIndex;\n          }\n          let lowestValidVariantId = -1;\n          if (minAutoVariantIndex < 0) {\n              return lowestValidVariantId;\n          }\n          for (let i = minAutoVariantIndex; i < availableVariantOptions.length; ++i) {\n              const variantMediaOption = availableVariantOptions[i];\n              const alternates = getMatchingAlternates(variantMediaOption, rootPlaylistQuery);\n              if (alternates.altAudio && alternates.subtitle) {\n                  lowestValidVariantId = i;\n                  break;\n              }\n          }\n          return lowestValidVariantId;\n      }\n      function findNextABRAutoVariantOptionInMode(iframeMode, abrConfig, rootPlaylistQuery, curOptionQuery, mediaElementQuery, statsQuery, logger) {\n          const variantOptions = rootPlaylistQuery.preferredMediaOptions[MediaOptionType.Variant].filter((variantOption) => variantOption.iframes === iframeMode);\n          if (!variantOptions.length) {\n              return { variantMediaOption: NoMediaOption.mediaOptionId, holdOffDuration: 0, lowestCandidate: null };\n          }\n          // Find minAutoVariant if it was set because of highBWTrigger\n          let minAutoVariantOption = 0;\n          const minAutoVariantOptionId = rootPlaylistQuery.nextMinAutoOptionId;\n          if (minAutoVariantOptionId !== NoMediaOption.mediaOptionId) {\n              const found = variantOptions.findIndex((variantOption) => variantOption.mediaOptionId === minAutoVariantOptionId);\n              if (found >= 0) {\n                  minAutoVariantOption = found;\n                  logger.info(`minAutoVariantOptionId set=${minAutoVariantOptionId}, minAutoVariantOption=${minAutoVariantOption}/${variantOptions.length}`);\n              }\n          }\n          // Ensure the minAutoVariant is valid\n          minAutoVariantOption = findLowestValidVariantIndex(minAutoVariantOption, variantOptions, iframeMode, rootPlaylistQuery);\n          if (minAutoVariantOption < 0) {\n              return { variantMediaOption: NoMediaOption.mediaOptionId, holdOffDuration: 0, lowestCandidate: null };\n          }\n          let maxAutoVariantOption = variantOptions.length - 1;\n          // if forced auto level has been defined, use it to cap ABR computed quality level\n          const maxAutoVariantOptionId = rootPlaylistQuery.nextMaxAutoOptionId;\n          if (maxAutoVariantOptionId !== NoMediaOption.mediaOptionId) {\n              const found = variantOptions.findIndex((variantOption) => variantOption.mediaOptionId === maxAutoVariantOptionId);\n              if (found >= 0) {\n                  maxAutoVariantOption = found;\n                  logger.info(`maxAutoVariantOptionId set=${maxAutoVariantOptionId}, maxAutoVariantOption=${maxAutoVariantOption}/${variantOptions.length}`);\n              }\n          }\n          const currentVariant = rootPlaylistQuery.variantMediaOptionById(curOptionQuery.mediaOptionId);\n          const currentVariantOptionDetails = curOptionQuery.mediaOptionDetails; // Get info even if in penalty box TODO check here\n          const bufferedDuration = (currentVariant === null || currentVariant === void 0 ? void 0 : currentVariant.iframes) !== iframeMode ? 0 : getBufferAheadSec(mediaElementQuery, abrConfig.maxBufferHole);\n          let bestLevelHeuristics, currentFragDuration;\n          if (!iframeMode) {\n              currentFragDuration = currentVariantOptionDetails ? currentVariantOptionDetails.targetduration : 0;\n              // TODO where is the current Frag and get duration, be careful not to use init segment\n          }\n          else {\n              const desiredIframeFPS = abrConfig.desiredIframeFPS;\n              currentFragDuration = currentVariantOptionDetails ? currentVariantOptionDetails.targetduration / desiredIframeFPS : 0;\n              // lower limit on iframe duration - dense tracks likely have a target duration that would achieve more than 8 fps if we displayed everything\n              currentFragDuration = Math.max(1 / desiredIframeFPS, currentFragDuration);\n          }\n          const bwUpFactor = abrConfig.abrBandWidthUpFactor;\n          const bwFactor = abrConfig.abrBandWidthFactor;\n          // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n          bestLevelHeuristics = findBestVariantOption(variantOptions, currentFragDuration, minAutoVariantOption, maxAutoVariantOption, bufferedDuration, iframeMode, statsQuery.getCombinedEstimate(), statsQuery.bandwidthStatus, bwFactor, bwUpFactor, abrConfig, rootPlaylistQuery, curOptionQuery, mediaElementQuery, logger, true);\n          if (bestLevelHeuristics.variantMediaOption === NoMediaOption.mediaOptionId) {\n              logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');\n              // not possible to get rid of rebuffering ... let's try to find\n              // level that will guarantee less than maxStarvationDelay of\n              // rebuffering if no matching level found, logic will return 0\n              const maxStarvationDelay = getMaxStarvationDelaySec(currentFragDuration, abrConfig.maxStarvationDelay);\n              bestLevelHeuristics = findBestVariantOption(variantOptions, currentFragDuration, minAutoVariantOption, maxAutoVariantOption, bufferedDuration + maxStarvationDelay, iframeMode, statsQuery.getCombinedEstimate(), statsQuery.bandwidthStatus, bwFactor, bwUpFactor, abrConfig, rootPlaylistQuery, curOptionQuery, mediaElementQuery, logger, true);\n              if (bestLevelHeuristics.variantMediaOption === NoMediaOption.mediaOptionId && minAutoVariantOption >= 0) {\n                  bestLevelHeuristics.variantMediaOption = variantOptions[minAutoVariantOption].mediaOptionId;\n                  bestLevelHeuristics.alternates = iframeMode ? null : getMatchingAlternates(variantOptions[minAutoVariantOption], rootPlaylistQuery);\n              }\n          }\n          logger.debug(`[ findNextABRAutoVariantOptionInMode] Returning ${JSON.stringify(bestLevelHeuristics)}`);\n          return bestLevelHeuristics;\n      }\n      function getMatchingAlternates(variant, rootPlaylistQuery) {\n          const enabledMediaOptions = rootPlaylistQuery.enabledMediaOptionKeys;\n          const altAudioKey = enabledMediaOptions[MediaOptionType.AltAudio];\n          const altAudio = isEnabledMediaOption(altAudioKey) ? rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.AltAudio].getMatchingAlternate(altAudioKey.mediaOptionId, variant) : NoMediaOption;\n          const subtitleKey = enabledMediaOptions[MediaOptionType.Subtitle];\n          const subtitle = isEnabledMediaOption(subtitleKey) ? rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.Subtitle].getMatchingAlternate(subtitleKey.mediaOptionId, variant) : NoMediaOption;\n          return { altAudio, subtitle };\n      }\n      const minItemsInBandwidthAverage = 4;\n      const shortTermBandwidthFactor = 1.8;\n      /**\n       * @param variantOptionList The filtered list of candidate variants\n       */\n      function findBestVariantOption(variantOptionList, currentFragDuration, minAutoVariant, maxAutoVariant, maxFetchDuration, iframeMode, estimate, bwStatus, bwFactor, bwUpFactor, abrConfig, rootPlaylistQuery, mediaLibraryQuery, mediaElementQuery, logger, dumpParams = false) {\n          if (abrConfig.abrBandwidthEstimator !== 'bandwidth-history-controller') {\n              logger.warn(`Unsupported configuration: ${abrConfig.abrBandwidthEstimator} for ABR bandwidth estimator`);\n          }\n          const bandwidthSamples = bwStatus.bandwidthSampleCount;\n          const abrStatus = rootPlaylistQuery.abrStatus;\n          const maxBufferSize = mediaElementQuery.maxBufferSize;\n          const minTargetDurations = abrConfig.minTargetDurations || 1;\n          const mediaOptionListInfo = rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.Variant].mediaOptionListInfo;\n          const hasScore = mediaOptionListInfo.hasScore;\n          if (!variantOptionList.length) {\n              return { variantMediaOption: NoMediaOption.mediaOptionId, holdOffDuration: -1, lowestCandidate: null };\n          }\n          const enabledVariantOptionId = rootPlaylistQuery.enabledMediaOptionIdByType(MediaOptionType.Variant);\n          const enabledVariantOption = rootPlaylistQuery.variantMediaOptionById(enabledVariantOptionId);\n          const enabledVariantOptionIsValid = variantOptionList.find((variantOption) => variantOption.mediaOptionId === enabledVariantOptionId) != null;\n          const isSameMode = enabledVariantOption && enabledVariantOption.iframes === iframeMode;\n          const currentScore = enabledVariantOption && isSameMode ? enabledVariantOption.score : undefined;\n          const currentFrameRate = enabledVariantOption && isSameMode ? enabledVariantOption.frameRate : undefined;\n          const currentHeight = enabledVariantOption && isSameMode ? enabledVariantOption.height : undefined;\n          const bufferedDuration = isSameMode ? getBufferAheadSec(mediaElementQuery, abrConfig.maxBufferHole) : 0;\n          // Sanity capping\n          maxAutoVariant = Math.max(0, Math.min(variantOptionList.length - 1, maxAutoVariant));\n          minAutoVariant = Math.max(0, Math.min(variantOptionList.length - 1, minAutoVariant));\n          if (dumpParams) {\n              logger.debug(`[abr] findBestLevel params=${stringifyWithPrecision({\n                enabledVariantOptionId,\n                currentFragDuration,\n                estimate,\n                minAutoVariant,\n                maxAutoVariant,\n                bwFactor,\n                bwUpFactor,\n                maxFetchDuration,\n                iframeMode,\n                maxBufferSize,\n                bufferedDuration,\n                currentScore,\n                currentFrameRate,\n                currentHeight,\n            })}`);\n          }\n          const mediaOptionDetailsEntityRecord = mediaLibraryQuery.mediaOptionDetailsEntityRecord;\n          const adjustedBwObj = getAdjustedBW(estimate.avgBandwidth, bwUpFactor, bwFactor, bandwidthSamples, logger);\n          let lowestCandidate;\n          for (let i = maxAutoVariant; i >= minAutoVariant; i--) {\n              const variantOption = variantOptionList[i];\n              let variantOptionId = variantOption.mediaOptionId;\n              const variantOptionScore = variantOption.score;\n              const variantOptionDetails = mediaOptionDetailsEntityRecord && mediaOptionDetailsEntityRecord[variantOptionId] ? mediaOptionDetailsEntityRecord[variantOptionId].mediaOptionDetails : undefined;\n              const lastUpdateMs = mediaOptionDetailsEntityRecord && mediaOptionDetailsEntityRecord[variantOptionId] ? mediaOptionDetailsEntityRecord[variantOptionId].lastUpdateMillis : null;\n              const avgDuration = variantOptionDetails ? variantOptionDetails.totalduration / variantOptionDetails.fragments.length : currentFragDuration;\n              const isUpSwitch = enabledVariantOption != null && variantOption.bitrate > enabledVariantOption.bitrate;\n              const isDownSwitch = enabledVariantOption != null && variantOption.bitrate < enabledVariantOption.bitrate;\n              // don't switch up to a lower frame rate or switch down to a higher frame rate\n              const validFrameRate = !(currentFrameRate != null && ((isUpSwitch && variantOption.frameRate < currentFrameRate) || (isDownSwitch && variantOption.frameRate > currentFrameRate)));\n              // pick only ascending levels that have greater than/equal height than the current level\n              const validHeight = !(isUpSwitch && currentHeight != null && currentHeight > variantOption.height);\n              /*\n                Note: AMP playlists are set up in such a way that\n                  - fragments are served from a primary host (e.g. Apple CDN, vod-ap1-aoc.tv.apple.com) and alternate host (e.g. Akamai, vod-ak-aoc.tv.apple.com)\n                  - for both of these, the playlists are served from a single host (e.g. play.itunes.apple.com)\n                  - the primary and alternate hosts are identified by a bitrate difference of 1 bit (primary bitrate > alternate bitrate by 1)\n              */\n              // Don't use same bitrate on alternate CDN for downswitch.\n              const validCDN = !(isDownSwitch && (variantOption.bitrate === enabledVariantOption.bitrate - 1 || variantOption.bitrate === enabledVariantOption.bitrate + 1));\n              // if SCORE attribute is available, pick ascending levels that have greater/equal SCORE than the current level\n              // if SCORE attributes are the same, ignore levels that have higher bitrate than current selected level\n              const validScore = !(hasScore &&\n                  isUpSwitch &&\n                  currentScore != null &&\n                  (variantOptionScore < currentScore || (variantOptionScore === currentScore && enabledVariantOption && variantOption.bitrate >= enabledVariantOption.bitrate)));\n              const validMode = variantOption.iframes === iframeMode;\n              if (!isFiniteNumber(avgDuration) || !validMode || !validFrameRate || !validHeight || !validCDN || !validScore) {\n                  logger.debug(`variant ${variantOptionId} ineligible ${stringifyWithPrecision({ avgDuration, validMode, validFrameRate, validHeight, validCDN, validScore })}`);\n                  continue;\n              }\n              const { adjustedbw, bitrate, fetchDuration, rejectLevelDueToPeakBW, canFitMultipleSegments, requireAlternates, alternates } = getVariantOptionMetrics(variantOption, variantOptionDetails, bufferedDuration, minTargetDurations, isUpSwitch, estimate, adjustedBwObj, currentFragDuration, maxBufferSize, lastUpdateMs, iframeMode, rootPlaylistQuery, logger);\n              if (dumpParams) {\n                  logger.debug(`getVariantOptionMetrics in=${stringifyWithPrecision({\n                    bufferedDuration,\n                    minTargetDurations,\n                    isUpSwitch,\n                    estimate,\n                    bwUpFactor,\n                    bwFactor,\n                    currentFragDuration,\n                    maxBufferSize,\n                    bandwidthSamples,\n                    lastUpdateMs,\n                    iframeMode,\n                })} out=${stringifyWithPrecision({ adjustedbw, bitrate, fetchDuration, rejectLevelDueToPeakBW, canFitMultipleSegments, requireAlternates })} alternates=${JSON.stringify(alternates)}`);\n              }\n              // lowestCandidate is also guaranteed to be delivering fragments from same host.\n              if (requireAlternates && Boolean(alternates)) {\n                  lowestCandidate = variantOptionId;\n              }\n              // if adjusted bw is greater than level bitrate AND\n              if (adjustedbw > bitrate &&\n                  canFitMultipleSegments &&\n                  !rejectLevelDueToPeakBW &&\n                  (!requireAlternates || Boolean(alternates)) &&\n                  // fragment fetchDuration unknown OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n                  (iframeMode || !fetchDuration || fetchDuration < maxFetchDuration)) {\n                  // as we are looping from highest to lowest, this will return the best achievable quality level\n                  if (instantBwTooSlow(adjustedbw, abrStatus, bwStatus) && enabledVariantOptionIsValid && isSameMode) {\n                      // low inst bw and a switchdown imminent, only switch up if we have enough buffer\n                      if (bufferedDuration <= 2 * avgDuration && isUpSwitch) {\n                          // do not switch up\n                          logger.info(`Last fragment too slow, not switching up instantBw=${bwStatus.instantBw}, ${enabledVariantOptionId}->${variantOptionId}, ${stringifyWithPrecision({\n                            bufferedDuration,\n                            avgDuration,\n                            isUpSwitch,\n                        })}`);\n                          variantOptionId = enabledVariantOptionId;\n                      }\n                      else if (isUpSwitch && bwUpFactor * bwStatus.instantBw < bitrate) {\n                          // instantBw might be too slow for this level, but we could upswitch to a lower level\n                          continue;\n                      }\n                  }\n                  return { variantMediaOption: variantOptionId, holdOffDuration: fetchDuration, alternates: alternates, lowestCandidate: lowestCandidate };\n              }\n          }\n          // not enough time budget even with quality level 0 ... rebuffering might happen\n          return { variantMediaOption: NoMediaOption.mediaOptionId, holdOffDuration: -1, lowestCandidate: lowestCandidate };\n      }\n      // Get metrics used for switching\n      function getVariantOptionMetrics(variantOption, variantOptionDetails, bufferedDuration, minTargetDurations, isUpSwitch, estimate, adjustedBwObj, defaultFragDuration, maxBufferSize, lastUpdateMs, iframeMode, rootPlaylistQuery, logger) {\n          const adjustedbw = isUpSwitch ? adjustedBwObj.bwUp : adjustedBwObj.bwDown;\n          const bitrate = variantOption.bitrate;\n          // const live = levelDetails != null && levelDetails.live;\n          const avgDuration = variantOptionDetails ? variantOptionDetails.totalduration / variantOptionDetails.fragments.length : defaultFragDuration;\n          const playlistFetchMs = isFiniteNumber(estimate.avgPlaylistLoadTimeMs) ? estimate.avgPlaylistLoadTimeMs : estimate.avgLatencyMs;\n          const fetchDuration = calcFetchDuration(variantOption, variantOptionDetails, defaultFragDuration, adjustedbw, playlistFetchMs, lastUpdateMs, logger);\n          const peakBandwidth = variantOption.bandwidth;\n          // have atleast 2 target-durations buffered to switch if peak exceeds measured bandwidth\n          const rejectLevelDueToPeakBW = adjustedbw > bitrate && adjustedbw < peakBandwidth && bufferedDuration <= 2 * avgDuration;\n          const peakSegSizeBits = (peakBandwidth || bitrate || 0) * ((variantOptionDetails === null || variantOptionDetails === void 0 ? void 0 : variantOptionDetails.targetduration) || avgDuration);\n          // can fit at least this.minTargetDurations * targetDuration seconds into the buffer\n          const canFitMultipleSegments = (minTargetDurations * peakSegSizeBits) / 8 <= maxBufferSize;\n          // must have matching alternates\n          let alternates = null;\n          const requireAlternates = !iframeMode;\n          if (requireAlternates) {\n              alternates = getMatchingAlternates(variantOption, rootPlaylistQuery);\n              logger.debug(`${variantOption.mediaOptionId} matched alternate audio ${JSON.stringify(alternates.altAudio)} subtitle ${JSON.stringify(alternates.subtitle)}`);\n              if (!alternates.altAudio || !alternates.subtitle) {\n                  logger.info(`no matching alternates ${alternates.altAudio} or ${alternates.subtitle}, skipping ${variantOption.mediaOptionId}`);\n                  alternates = null;\n              }\n          }\n          return {\n              adjustedbw,\n              bitrate,\n              fetchDuration,\n              rejectLevelDueToPeakBW,\n              canFitMultipleSegments,\n              requireAlternates,\n              alternates,\n          };\n      }\n      function getAdjustedBW(bw, switchUpFactor, switchDownFactor, numBandwidthSamples, logger) {\n          let bwUp;\n          let bwDown;\n          if (numBandwidthSamples >= minItemsInBandwidthAverage) {\n              bwUp = bw * switchUpFactor;\n              bwDown = bw * switchDownFactor;\n          }\n          else {\n              bwUp = bwDown = bw / shortTermBandwidthFactor;\n          }\n          logger.trace(`[getAdjustedBW] numSamples: ${numBandwidthSamples}, minSamples: ${minItemsInBandwidthAverage} - returning up: ${bwUp}, down: ${bwDown}`);\n          return { bwUp, bwDown };\n      }\n      function calcFetchDuration(variantOption, variantOptionDetails, defaultFragDuration, bw, playlistFetchMs, lastUpdateMs, logger) {\n          const bitrate = variantOption.bitrate;\n          const avgDuration = variantOptionDetails ? variantOptionDetails.totalduration / variantOptionDetails.fragments.length : defaultFragDuration;\n          const avgSegSizeBits = bitrate * avgDuration;\n          let fetchDuration = avgSegSizeBits / bw;\n          // if live and !ptsKnown or outOfDate\n          if ((variantOptionDetails === null || variantOptionDetails === void 0 ? void 0 : variantOptionDetails.liveOrEvent) && (!variantOptionDetails.ptsKnown || likelyOutOfDate(variantOptionDetails.totalduration, playlistFetchMs, lastUpdateMs))) {\n              // live fetch duration could be up to two segments if it doesn't have time info\n              // First segment could be the wrong segment if we don't have PTS since we choose the middle frag\n              logger.debug(`PTS unknown / expired, using 2x fetchDuration for ${variantOption.mediaOptionId}`);\n              fetchDuration *= 2;\n          }\n          // if this is first update for this option or if live\n          if (isFiniteNumber(playlistFetchMs) && (!isFiniteNumber(lastUpdateMs) || (variantOptionDetails === null || variantOptionDetails === void 0 ? void 0 : variantOptionDetails.liveOrEvent))) {\n              fetchDuration += playlistFetchMs / 1000;\n          }\n          return fetchDuration;\n      }\n      function minSwitchBufferAheadSec(from, to, toDetails, currentFragDuration, abrStatus, statsQuery, abrConfig, lastUpdateMs, logger) {\n          const forcedAutoOptionId = abrStatus.nextMaxAutoOptionId;\n          // in case next auto level has been forced, and bw not available or not reliable, return false\n          if (forcedAutoOptionId !== NoMediaOption.mediaOptionId && !hasReliableBandwidthEstimate(statsQuery.getBandwidthEstimate())) {\n              return Number.POSITIVE_INFINITY;\n          }\n          const bw = getAdjustedBW(statsQuery.getBandwidthEstimate().avgBandwidth, abrConfig.abrBandWidthUpFactor, abrConfig.abrBandWidthFactor, statsQuery.bandwidthStatus.bandwidthSampleCount, logger);\n          const playlistFetchMs = isFiniteNumber(statsQuery.getPlaylistEstimate().avgPlaylistLoadTimeMs)\n              ? statsQuery.getPlaylistEstimate().avgPlaylistLoadTimeMs\n              : statsQuery.getBandwidthEstimate().avgLatencyMs;\n          // How much buffer ahead required to switch\n          // duration from playhead pos that is necessary to stay at this level\n          const isUpSwitch = to.bitrate > from.bitrate;\n          const bwValue = isUpSwitch ? bw.bwUp : bw.bwDown;\n          if ((toDetails === null || toDetails === void 0 ? void 0 : toDetails.liveOrEvent) && (!toDetails.ptsKnown || likelyOutOfDate(toDetails.totalduration, playlistFetchMs, lastUpdateMs))) {\n              // Don't allow flush if we won't have overlapping window\n              return Number.POSITIVE_INFINITY;\n          }\n          return calcFetchDuration(to, toDetails, currentFragDuration, bwValue, playlistFetchMs, lastUpdateMs, logger);\n      }\n      function getLowestSuperiorBW(mediaOptionId, variantOptions) {\n          let lowestSuperiorBW = Infinity;\n          if (mediaOptionId === NoMediaOption.mediaOptionId) {\n              return lowestSuperiorBW;\n          }\n          const givenMediaOption = variantOptions.find((mediaOption) => mediaOption.mediaOptionId === mediaOptionId);\n          if (!givenMediaOption) {\n              return Infinity;\n          }\n          const iframeMode = givenMediaOption.iframes;\n          const bitrate = givenMediaOption.bitrate;\n          const frameRate = givenMediaOption.frameRate;\n          const nextMediaOption = variantOptions.find((mediaOption) => mediaOption.iframes === iframeMode && (frameRate === undefined || mediaOption.frameRate >= frameRate) && mediaOption.bitrate > bitrate);\n          if (nextMediaOption) {\n              lowestSuperiorBW = nextMediaOption.bitrate;\n          }\n          return lowestSuperiorBW;\n      }\n      /**\n       * Returns whether it's likely that the refreshed level will end up with a non-overlapping playlist (causing ptsKnown == false)\n       * @param totalDurationSecs Details about the level\n       * @param playlistFetchMs time in MS to get playlist refresh\n       * @param lastUpdateMillis timeStamp of the last update\n       */\n      function likelyOutOfDate(totalDurationSecs, playlistFetchMs, lastUpdateMillis) {\n          playlistFetchMs = isFiniteNumber(playlistFetchMs) ? playlistFetchMs : 0;\n          return !isFiniteNumber(lastUpdateMillis) || performance.now() - lastUpdateMillis + playlistFetchMs > totalDurationSecs * 1000;\n      }\n      /**\n       * Choose option to resume at when coming out of trickplay\n       */\n      function getTrickPlayMaxResumeOption(preIframeOptionId, config, logger, rootPlaylistQuery, statsQuery) {\n          const vQuery = rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.Variant];\n          const vOptions = vQuery.preferredMediaOptionList;\n          const targetStartupMs = config.targetStartupMs;\n          const playlistEstimate = {\n              // statsQuery.playlistEstimate\n              avgPlaylistParseTimeMs: 0,\n              avgPlaylistLoadTimeMs: 0,\n          }; // <rdar://75273462> Do not use max values for this estimate\n          const fragEstimate = statsQuery.getFragEstimate();\n          const bufferEstimate = {\n              avgBufferCreateMs: 0,\n              avgInitFragAppendMs: 0,\n              avgDataFragAppendMs: 0,\n          };\n          const fragDuration = fragEstimate.maxDurationSec;\n          // <rdar://75273462> Use 0 latency since it is already wrapped into bw estimate(See BandwidthHistoryController.record). Change back if we use tload - tfirst instead\n          const bw = {\n              avgLatencyMs: 0,\n              avgBandwidth: statsQuery.getBandwidthEstimate().avgBandwidth,\n          };\n          const startConfig = {\n              targetDuration: fragDuration,\n              targetStartupMs: targetStartupMs,\n              metricsOverride: {\n                  maxValidHeight: 0,\n                  maxValidBitrate: 0,\n                  maxPreferredBitrate: 0,\n              },\n          };\n          logger.info(`trickplay resume selection params=${stringifyWithPrecision({ startConfig, bw, playlistEstimate, fragEstimate, bufferEstimate })}`);\n          const regOptions = filterRegularLevelsBasedOnCapOn1080p(vOptions);\n          let resumeId = preIframeOptionId;\n          if (regOptions.length > 0) {\n              resumeId = regOptions[0].mediaOptionId;\n          }\n          const candidates = regOptions.filter((option) => isWithinBandwidthCap(option, bw, startConfig, playlistEstimate, fragEstimate, bufferEstimate));\n          logger.debug(`Picking resume level from validLevels/regLevels/resumeLevels ${vOptions.length}/${regOptions.length}/${candidates.length}`);\n          if (candidates.length > 0) {\n              resumeId = candidates[candidates.length - 1].mediaOptionId;\n          }\n          logger.info(`trickplay start/max resume:${preIframeOptionId}/${resumeId}`);\n          return resumeId;\n      }\n      function fragAbrStatusDidChange(a, b) {\n          return (a === null || a === void 0 ? void 0 : a.fragDownloadSlow) === (b === null || b === void 0 ? void 0 : b.fragDownloadSlow) && a.fragDownloadTooSlow === (b === null || b === void 0 ? void 0 : b.fragDownloadTooSlow);\n      }\n      /**\n       * @returns Returns whether we should abort the fragment and also updates AbrStatus\n       */\n      function shouldAbortFrag(context) {\n          // Slow fragment download:\n          const { mediaSink, rootPlaylistQuery, rootPlaylistService } = context;\n          const mediaQuery = mediaSink.mediaQuery;\n          const logger = context.logger.child(abrLogName);\n          return merge(slowFragmentCheck(rootPlaylistQuery, mediaQuery, logger), likelyToStallCheck(context)).pipe(startWith({ fragDownloadSlow: false, fragDownloadTooSlow: false }), scan((curState, newState) => {\n              return {\n                  fragDownloadSlow: curState.fragDownloadSlow || newState.fragDownloadSlow,\n                  fragDownloadTooSlow: curState.fragDownloadTooSlow || newState.fragDownloadTooSlow,\n              };\n          }), distinctUntilChanged(fragAbrStatusDidChange), map((status) => {\n              logger.debug(`abrStatus update=${JSON.stringify(status)}`);\n              rootPlaylistService.setFragLoadSlow(rootPlaylistQuery.itemId, status);\n              return false;\n          }), catchError((err) => {\n              if (err instanceof FragmentAbortError) {\n                  const wayTooSlow = { fragDownloadSlow: true, fragDownloadTooSlow: true };\n                  rootPlaylistService.setFragLoadSlow(rootPlaylistQuery.itemId, wayTooSlow);\n                  return of(true);\n              }\n              return throwError(err);\n          }));\n      }\n      function slowFragmentCheck(rootPlaylistQuery, mediaQuery, logger) {\n          return combineQueries([mediaQuery.fellBelowLowWater$, rootPlaylistQuery.getInFlightFragByType$(MediaOptionType.Variant)]).pipe(switchMap((value) => {\n              const [, inFlight] = value;\n              if (!hasValidSample(inFlight)) {\n                  return EMPTY;\n              }\n              const elapsedMs = performance.now() - inFlight.bwSample.trequest;\n              const flowDeadline = kFlowMeasurementPeriodMS - elapsedMs;\n              const durationDeadline = inFlight.duration * 1000 - elapsedMs;\n              const timers$ = [VOID];\n              if (flowDeadline > 0) {\n                  timers$.push(timer(flowDeadline));\n              }\n              if (durationDeadline > 0) {\n                  timers$.push(timer(durationDeadline));\n              }\n              return merge(...timers$).pipe(mapTo(value));\n          }), scan((curState, [fellBelowLowWater, inFlight]) => {\n              const newState = Object.assign({}, curState);\n              if (fellBelowLowWater) {\n                  newState.fragDownloadSlow = true;\n              }\n              return gotSlowFlow(inFlight, newState, rootPlaylistQuery, logger);\n          }, { fragDownloadSlow: false, fragDownloadTooSlow: false }), startWith({ fragDownloadSlow: false, fragDownloadTooSlow: false }), distinctUntilChanged(fragAbrStatusDidChange));\n      }\n      function hasValidSample(inFlight) {\n          var _a;\n          return (inFlight === null || inFlight === void 0 ? void 0 : inFlight.state) === 'loading' && isFiniteNumber((_a = inFlight.bwSample) === null || _a === void 0 ? void 0 : _a.trequest);\n      }\n      const kFlowMeasurementPeriodMS = 2000;\n      const kUnderflowAllowanceMS = 1000;\n      function gotSlowFlow(inFlight, curStatus, rootQuery, logger) {\n          let { fragDownloadSlow, fragDownloadTooSlow } = curStatus;\n          const variant = rootQuery.variantMediaOptionById(inFlight.mediaOptionId);\n          const bitrate = variant.bitrate;\n          const stats = inFlight.bwSample;\n          logger = logger.child(abrLogName);\n          const totalBytes = stats.total ? stats.total : Math.max(stats.loaded, Math.round((inFlight.duration * bitrate) / 8)), timeSpentMS = performance.now() - stats.tfirst, // time spent downloading the fragment\n          durationDownloadedMS = (stats.loaded * inFlight.duration * 1000) / totalBytes;\n          if (timeSpentMS >= kFlowMeasurementPeriodMS && timeSpentMS - durationDownloadedMS >= kUnderflowAllowanceMS) {\n              if (!fragDownloadSlow) {\n                  logger.warn(`flow indicates low bandwidth, after time/duration behind real time: ${timeSpentMS}/${timeSpentMS - durationDownloadedMS}`);\n              }\n              fragDownloadSlow = true;\n          }\n          if (timeSpentMS >= inFlight.duration * 1000) {\n              if (!fragDownloadTooSlow) {\n                  logger.warn(`too much time spent downloading fragment, likely to switch down ${timeSpentMS} > ${inFlight.duration * 1000}`);\n              }\n              fragDownloadTooSlow = true;\n          }\n          return { fragDownloadSlow, fragDownloadTooSlow };\n      }\n      function likelyToStallCheck(context) {\n          const mediaQuery = context.mediaSink.mediaQuery;\n          const { rootPlaylistQuery: rootQuery, config } = context;\n          return mediaQuery.desiredRate$\n              .pipe(switchMap((desiredRate) => {\n              // Don't emit if about to pause or if we are currently paused\n              if (desiredRate === 0) {\n                  return EMPTY;\n              }\n              return combineQueries([\n                  rootQuery.getInFlightFragByType$(MediaOptionType.Variant),\n                  rootQuery.mediaOptionListQueries[MediaOptionType.Variant].preferredMediaOptionList$.pipe(map((list) => list.filter(isMatchingIframeLevel.bind(null, isIframeRate(desiredRate))))),\n              ]);\n          }), throttleTime(100), switchMap((value) => {\n              const [inFlight, preferredList] = value;\n              // Make sure inFlight fragment in correct mode && not the lowest bitrate variant\n              if (!hasValidSample(inFlight) || preferredList.findIndex((o) => o.mediaOptionId === inFlight.mediaOptionId) <= 0) {\n                  return EMPTY;\n              }\n              // Wait some min threshold for stable bitrate calculation then check every 100ms\n              const now = performance.now();\n              const elapsedMs = now - inFlight.bwSample.trequest;\n              const maxStarvationDelaySec = getMaxStarvationDelaySec(inFlight.duration, config.maxStarvationDelay);\n              const minThresholdMs = Math.min(maxStarvationDelaySec * 1000, (inFlight.duration * 500) / mediaQuery.playbackRate);\n              const delayMs = Math.max(0, minThresholdMs - elapsedMs);\n              return timer(delayMs, 100).pipe(mapTo(value));\n          }))\n              .pipe(scan((curStatus, [inFlight, preferredList]) => {\n              return likelyToStall(curStatus, inFlight, preferredList, context);\n          }, { fragDownloadSlow: false, fragDownloadTooSlow: false }), startWith({ fragDownloadSlow: false, fragDownloadTooSlow: false }), distinctUntilChanged(fragAbrStatusDidChange));\n      }\n      /**\n       * Determine whether we are going to stall based on the remaining time to download the inflight fragment and buffer then switch fragments if needed.\n       * Can initiate abort of inflight fragment and switch down through limiting the nexMaxAutoOptiondId to either a level that can download in time or the lowest option.\n       * Alternatively, can just initiate a switch down without abort by limiting nextMaxAutoOptionId to one level down if the current fragment can download quickly enough.\n       */\n      function likelyToStall(curStatus, inFlight, preferredList, // filtered list in the correct mode\n      context) {\n          var _a, _b;\n          let { fragDownloadSlow, fragDownloadTooSlow } = curStatus;\n          const { config, rootPlaylistService, rootPlaylistQuery: rootQuery, mediaSink, statsService, mediaLibraryService } = context;\n          const logger = context.logger.child(abrLogName);\n          const mediaQuery = mediaSink.mediaQuery;\n          // Prevent switch down if we are not in play state\n          if (mediaQuery.paused) {\n              return curStatus;\n          }\n          const stats = inFlight.bwSample;\n          // likelyToStall not required to check until download has started\n          if (!isFiniteNumber(stats.tfirst)) {\n              return curStatus;\n          }\n          const now = performance.now();\n          const elapsedMs = now - stats.trequest;\n          const maxStarvationDelaySec = getMaxStarvationDelaySec(inFlight.duration, config.maxStarvationDelay);\n          const mediaOptionType = MediaOptionType.Variant;\n          const mediaOptionId = inFlight.mediaOptionId;\n          const curVariant = rootQuery.variantMediaOptionById(mediaOptionId);\n          const curLibQuery = mediaLibraryService.getQueryForOption(curVariant);\n          const variantBitrate = curVariant.bitrate;\n          const instantBw = Math.max(1, (stats.loaded * 8000) / elapsedMs); // instant load rate in bits per second\n          const totalBytes = isFiniteNumber(stats.total) ? stats.total : Math.max(stats.loaded, Math.round((inFlight.duration * variantBitrate) / 8)); // fragment size in bytes\n          const remainingTimeSec = ((totalBytes - stats.loaded) * 8) / instantBw; // how much longer until this fragment will be loaded in seconds\n          const bufferAheadSec = getBufferAheadSec(mediaQuery, config.maxBufferHole);\n          let maxTimeToLoadSec; // Max time to load the next fragment\n          if (isFiniteNumber(bufferAheadSec) && bufferAheadSec > 0 && !isFiniteNumber((_a = mediaQuery.seekTo) === null || _a === void 0 ? void 0 : _a.pos)) {\n              maxTimeToLoadSec = bufferAheadSec;\n          }\n          else {\n              // bufferAheadSec === 0 or NaN or seeking\n              const elapsedSec = elapsedMs / 1000;\n              if (elapsedSec < maxStarvationDelaySec) {\n                  // Already starving. Try to complete load by maxStarvationDelaySec relative to current load\n                  maxTimeToLoadSec = maxStarvationDelaySec - elapsedSec;\n              }\n              else {\n                  // Could happen if we have high target duration. Start over with maxStarvationDelay\n                  maxTimeToLoadSec = maxStarvationDelaySec;\n              }\n          }\n          const wasSlow = fragDownloadSlow; // To make logs less chatty\n          ({ fragDownloadSlow, fragDownloadTooSlow } = gotSlowFlow(inFlight, curStatus, rootQuery, logger));\n          // consider emergency switch down only if we have less than 2 frag buffered AND\n          // time to finish loading current fragment is bigger than buffer starvation delay\n          // ie if we risk buffer starvation if bw does not increase quickly.\n          const minSwitchDuration = 2 * (((_b = curLibQuery.mediaOptionDetails) === null || _b === void 0 ? void 0 : _b.targetduration) || inFlight.duration);\n          const likelyToStall = bufferAheadSec <= minSwitchDuration && (remainingTimeSec >= maxTimeToLoadSec || fragDownloadSlow);\n          if (!likelyToStall) {\n              if (globalHlsService().getQuery().extendMaxTTFB) {\n                  logger.info('[abr] re-enabling TTFB');\n                  globalHlsService().setExtendMaxTTFB(0);\n              }\n              return { fragDownloadSlow, fragDownloadTooSlow };\n          }\n          if (!wasSlow) {\n              logger.warn(`likely to stall ${stringifyWithPrecision({\n                maxTimeToLoadSec,\n                minSwitchDuration,\n                stats,\n                elapsedMs,\n                remainingTimeSec,\n                instantBw,\n                bufferAheadSec,\n                fragDownloadSlow,\n            })}`);\n          }\n          fragDownloadSlow = true;\n          if (!globalHlsService().getQuery().extendMaxTTFB) {\n              logger.info('[abr] temporarily disabling TTFB');\n              globalHlsService().setExtendMaxTTFB(600000); // set to 10mins\n          }\n          // TODO: in native stack we only downswitch if our predictedBitrate < levelBitrate. However\n          // seems like we need to investigate if bandwidth estimate is reacting fast enough to bandwidth changes\n          let nextOptionId = undefined;\n          // Find something that will take less than bufferStarvationDelay (avoids rebuffering)\n          const itemId = inFlight.itemId;\n          const statsQuery = statsService.getQueryForItem(itemId);\n          const avgEstimate = statsQuery.getCombinedEstimate();\n          const instantEstimate = Object.assign(Object.assign({}, avgEstimate), { avgBandwidth: instantBw });\n          const bwStatus = statsQuery.bandwidthStatus;\n          const bwFactor = 1;\n          const bwUpFactor = 1;\n          const iframeMode = curVariant.iframes;\n          // We should probably switch down either way after this fragment, but whether we abort depends on whether we can avoid rebuffering\n          // <rdar://87250808> Never abort in iframe mode. It kills the av-pipe when handleVariantSwitch does not switch\n          const shouldAbort = remainingTimeSec >= maxTimeToLoadSec && !iframeMode;\n          // Find lowest index with matching group or 0 if none\n          const minLevelIdx = findLowestValidVariantIndex(0, preferredList, iframeMode, rootQuery);\n          // There is no variant with audio/subtitle group matching, so there is nothing to switch to\n          if (minLevelIdx < 0) {\n              logger.info('findLowestValidVariantIndex could not find a valid level');\n              return { fragDownloadSlow, fragDownloadTooSlow };\n          }\n          // Set max level to current level or the lowest valid level, whichever is greater\n          const maxLevelIdx = Math.max(minLevelIdx, preferredList.findIndex((v) => v && v.mediaOptionId === curVariant.mediaOptionId));\n          if (shouldAbort) {\n              // We will stall if we do not abort and switch down\n              // Check if we can find a variant that will load within maxTimeToLoadSec\n              let res = findBestVariantOption(preferredList, inFlight.duration, minLevelIdx, maxLevelIdx, maxTimeToLoadSec, iframeMode, instantEstimate, bwStatus, bwFactor, bwUpFactor, config, rootQuery, curLibQuery, mediaQuery, logger);\n              const badOptionId = NoMediaOption.mediaOptionId;\n              if (res.variantMediaOption !== badOptionId) {\n                  logger.info(`buffered: ${bufferAheadSec} got option ${res.variantMediaOption} that will load in conditions ${stringifyWithPrecision({ maxTimeToLoadSec, instantBw })}`);\n                  nextOptionId = res.variantMediaOption;\n              }\n              else if ((res = findBestVariantOption(preferredList, inFlight.duration, minLevelIdx, maxLevelIdx, remainingTimeSec, iframeMode, instantEstimate, bwStatus, bwFactor, bwUpFactor, config, rootQuery, curLibQuery, mediaQuery, logger)).variantMediaOption !== badOptionId) {\n                  // Found variant that will load before current frag is done\n                  nextOptionId = res.variantMediaOption;\n                  logger.info(`buffered: ${bufferAheadSec} got option ${nextOptionId} that will load in conditions ${stringifyWithPrecision({ remainingTimeSec, instantBw })}`);\n              }\n              else {\n                  // Waiting for current frag to finish will result in rebuffering, fall back to minimum option and abort\n                  nextOptionId = res.lowestCandidate;\n                  logger.info(`buffered: ${bufferAheadSec} got fallback option ${nextOptionId}, could not find variant that will load in conditions ${stringifyWithPrecision({ remainingTimeSec, instantBw })}`);\n              }\n          }\n          else {\n              // Can finish current frag download and then switch down by one level, matching alternates.\n              // Reverse preferredList in range [minLevelIdx, maxLevelIdx-1] inclusive then look for the lowest idx with valid variant audio/subtitle matching.\n              // This will return -1 on failure, maxLevelIdx-1 if iframeMode, or the offset from the tail of the highest idx below maxLevelIdx with matching\n              const offsetFromTail = findLowestValidVariantIndex(0, preferredList.slice(minLevelIdx, maxLevelIdx).reverse(), iframeMode, rootQuery);\n              const nextMatchingGroupIdx = maxLevelIdx - 1 - offsetFromTail; // maxLevelIdx-1 since slice(start, end) excludes the end idx\n              // Cap to next highest level with audio/subtitle group matching. If there is no lower group, stay at the currently enabled option and log it.\n              if (offsetFromTail >= 0 || maxLevelIdx === minLevelIdx) {\n                  logger.info('cap to next highest level with audio/subtitle matching');\n                  nextOptionId = preferredList[nextMatchingGroupIdx].mediaOptionId;\n              }\n              else {\n                  logger.info(`no lower level with matching audio/subtitle to switch to level=${curVariant.mediaOptionId}`);\n              }\n          }\n          if (nextOptionId != null && nextOptionId !== rootQuery.abrStatus.nextMaxAutoOptionId) {\n              logger.info(`capping level to ${nextOptionId} because likelyToStall`);\n              rootPlaylistService.setNextMaxAutoOptionId(itemId, nextOptionId);\n          }\n          // only emergency switch down if it takes less time to load new fragment at lowest level instead\n          // of finishing loading current one ...\n          if (shouldAbort) {\n              logger.warn(`loading too slow, abort fragment loading and switch to level ${nextOptionId}`);\n              logger.debug(`abort stats=${stringifyWithPrecision({\n                instantBw,\n                loadedBytes: stats.loaded,\n                totalBytes,\n                elapsedMs,\n                remainingTimeSec,\n                maxTimeToLoadSec,\n                fragDownloadSlow,\n            })}`);\n              // force next load level in auto mode\n              // update bw estimate for this fragment before cancelling load (this will help reducing the bw)\n              logger.info(`[${MediaOptionNames[mediaOptionType]}] fragLoadingProcessingMs/stats.loaded: ${elapsedMs}/${stats.loaded}`); // also log when too slow\n              statsService.setBandwidthSample(Object.assign(Object.assign({}, stats), { tfirst: stats.tfirst || now, tload: stats.tload || now, complete: true, mediaOptionType: mediaOptionType }));\n              fragDownloadTooSlow = true;\n              // Abort current sequence\n              throw new FragmentAbortError({ mediaOptionType, mediaOptionId }, nextOptionId, ErrorResponses.FragmentAbortError);\n          }\n          return { fragDownloadSlow, fragDownloadTooSlow };\n      }\n      function initializeAbrStatus(mediaOptionId, variantOptions) {\n          const highBWTrigger = getLowestSuperiorBW(mediaOptionId, variantOptions);\n          return {\n              fragDownloadSlow: false,\n              fragDownloadTooSlow: false,\n              nextMinAutoOptionId: NoMediaOption.mediaOptionId,\n              nextMaxAutoOptionId: NoMediaOption.mediaOptionId,\n              highBWTrigger: highBWTrigger,\n          };\n      }\n      /**\n       * @brief Use ABR logic to switch VariantMediaOption if needed\n       *\n       * We should not switch levels unless we hit certain triggers:\n       * 1. Bandwidth High / Low change\n       * 2. Crossing low water level threshold\n       * 3. Hitting end of buffer\n       * 4. Slow fragment or level loading\n       * 5. iframe mode change\n       * 6. gapless item transition\n       * Exceptions are when we are at a discontinuity or seeking, when we should only switch if we have\n       * slow media (timeout) current level was sent to penalty box.\n       * When switching variant, handleVariantSwitch will ensure altAudio and subtitle mediaOptions follow\n       * the same groups specified by the chosen variant.\n       */\n      function handleVariantSwitch(originalReason, config, rootQuery, mediaElementQuery, rootService) {\n          var _a, _b;\n          const logger = rootService.logger.child(abrLogName);\n          const iframeMode = mediaElementQuery.isIframeRate;\n          const optionListQuery = rootQuery.mediaOptionListQueries[MediaOptionType.Variant];\n          const preferredList = optionListQuery.preferredMediaOptionList;\n          const curVariant = rootQuery.enabledMediaOptionKeys[MediaOptionType.Variant];\n          let switchReason = originalReason;\n          if (switchReason === SwitchReason.None && !preferredList.some((option) => option.mediaOptionId === curVariant.mediaOptionId)) {\n              switchReason = SwitchReason.PreferredListChanged;\n              logger.info(`overriding switchReason: ${originalReason}->${switchReason}`);\n          }\n          const shouldSwitchVariant = switchReason !== SwitchReason.None;\n          if (!shouldSwitchVariant) {\n              logger.info(`Skipping variant switch as switchReason: ${switchReason}`);\n              return false;\n          }\n          if (iframeMode && switchReason !== SwitchReason.IframeModeChange) {\n              const bufferedIframes = mediaElementQuery.getBufferedSegmentsByType(SourceBufferType.Variant).filter((seg) => seg.frag.iframe);\n              if (bufferedIframes.length < config.minFramesBeforeSwitchingLevel) {\n                  logger.info(`[iframes] only ${bufferedIframes.length} iframes, stay at current mediaOption ${curVariant.mediaOptionId}`);\n                  // TODO: <rdar://87250808> Force needData$. If fragment was aborted and water level is almost/dry, av-pipe will die. <@robert-walch 3/8/2022>\n                  return false;\n              }\n          }\n          if (iframeMode && switchReason === SwitchReason.IframeModeChange) {\n              rootService.setEnabledVariantMediaOptionIdBeforeTrickplaySwitch(rootQuery.itemId, curVariant.mediaOptionId);\n          }\n          const statsQuery = createStatsQuery(rootQuery.itemId);\n          const mediaLibraryQuery = createMediaLibraryQuery(curVariant);\n          const newOptions = [NoMediaOption, NoMediaOption, NoMediaOption];\n          // rdar://85517745 (Resume from trickplay level calculation needs functional parity with 2.15)\n          // On leaving trickplay, set the nextMaxAutioOptionId, this will in turn be used in nextAutoMediaOption\n          if (!iframeMode && originalReason === SwitchReason.IframeModeChange) {\n              const maxResumeOption = getTrickPlayMaxResumeOption(rootQuery.enabledVariantMediaOptionIdBeforeTrickplaySwitch, config, logger, rootQuery, statsQuery);\n              logger.info(`Capping variant selection to ${maxResumeOption} because switchReason: ${originalReason}`);\n              rootService.setNextMaxAutoOptionId(rootQuery.itemId, maxResumeOption);\n              rootService.setEnabledVariantMediaOptionIdBeforeTrickplaySwitch(rootQuery.itemId, undefined);\n          }\n          const nextVariant = nextAutoMediaOption(config, rootQuery, rootService, mediaLibraryQuery, mediaElementQuery, statsQuery, logger);\n          if (!iframeMode && originalReason === SwitchReason.IframeModeChange) {\n              // reset nextMaxAutioOptionId that was set above\n              rootService.setNextMaxAutoOptionId(rootQuery.itemId, NoMediaOption.mediaOptionId);\n          }\n          if (nextVariant.variantMediaOption === curVariant.mediaOptionId) {\n              logger.info(`Skipping variant switch as no better candidate than ${curVariant.mediaOptionId}`);\n              // TODO: <rdar://87250808> Force needData$. If fragment was aborted and water level is almost/dry, av-pipe will die. <@robert-walch 3/8/2022>\n              return false;\n          }\n          logger.qe({ critical: true, name: 'shouldSwitchVariant', data: { value: shouldSwitchVariant, reason: switchReason } });\n          newOptions[MediaOptionType.Variant] = { itemId: rootQuery.itemId, mediaOptionId: nextVariant.variantMediaOption };\n          for (const i of [MediaOptionType.AltAudio, MediaOptionType.Subtitle]) {\n              const curOptionId = rootQuery.enabledMediaOptionIdByType(i);\n              if (curOptionId !== NoMediaOption.mediaOptionId) {\n                  // newAlternate may be null for iframe, NoMediaOption, or reuse existing variant (no switch): reuse existing alternates\n                  const newAlternate = i === MediaOptionType.AltAudio ? (_a = nextVariant.alternates) === null || _a === void 0 ? void 0 : _a.altAudio : (_b = nextVariant.alternates) === null || _b === void 0 ? void 0 : _b.subtitle;\n                  newOptions[i] = newAlternate ? newAlternate : { itemId: rootQuery.itemId, mediaOptionId: curOptionId };\n              }\n          }\n          rootService.setEnabledMediaOptions(rootQuery.itemId, newOptions);\n          logger.info(`Switching variant ${switchReason}: ${curVariant.mediaOptionId} variant/audio/subtitle ${newOptions[0].mediaOptionId}/${newOptions[1].mediaOptionId}/${newOptions[2].mediaOptionId}`);\n          return true;\n      }\n      /**\n       * @returns whether we should check for downswitch\n       */\n      function gotLowBw(rootQuery, mediaElementQuery, rootService) {\n          var _a;\n          const logger = rootService.logger.child(abrLogName);\n          const abrStatus = rootQuery.abrStatus;\n          const slowMedia = gotSlowMedia(abrStatus);\n          const seeking = isFiniteNumber((_a = mediaElementQuery.seekTo) === null || _a === void 0 ? void 0 : _a.pos);\n          if (slowMedia && !abrStatus.fragDownloadTooSlow && seeking) {\n              logger.warn('could be ignoring low bandwidth due to seek');\n              return false;\n          }\n          return slowMedia;\n      }\n      /**\n       * @returns whether we should check for upswitch\n       */\n      function gotHighBw(config, rootQuery, rootService) {\n          var _a;\n          const logger = rootService.logger;\n          const statsQuery = createStatsQuery(rootQuery.itemId);\n          const bwe = statsQuery.getBandwidthEstimate();\n          const abrStatus = rootQuery.abrStatus;\n          if (!hasReliableBandwidthEstimate(bwe)) {\n              return false;\n          }\n          const bandwidthSampleCount = ((_a = statsQuery.bandwidthStatus) === null || _a === void 0 ? void 0 : _a.bandwidthSampleCount) || 0;\n          const { bwUp } = getAdjustedBW(bwe.avgBandwidth, config.abrBandWidthUpFactor, config.abrBandWidthFactor, bandwidthSampleCount, logger);\n          if (bwUp > abrStatus.highBWTrigger) {\n              logger.info(`[abr] bandwidth high ${Math.round(bwe.avgBandwidth / 1000)}kbps trigger=${abrStatus.highBWTrigger / 1000}kbps factor=${config.abrBandWidthUpFactor}`);\n              return true;\n          }\n          return false;\n      }\n    \n      const loggerName$2 = { name: 'iframes' };\n      var PrefetchResult;\n      (function (PrefetchResult) {\n          PrefetchResult[PrefetchResult[\"DISABLED\"] = 0] = \"DISABLED\";\n          PrefetchResult[PrefetchResult[\"ERRORED\"] = 1] = \"ERRORED\";\n          PrefetchResult[PrefetchResult[\"SUCCESS\"] = 2] = \"SUCCESS\";\n      })(PrefetchResult || (PrefetchResult = {}));\n      const checkForIframePrefetch = (context) => {\n          const { config, logger } = context;\n          if (!config.enableIFramePreloading) {\n              logger.info(loggerName$2, 'Iframe prefetch disabled');\n              return of(PrefetchResult.DISABLED);\n          }\n          return waitTillAllowedPrefetch(context);\n      };\n      function waitTillAllowedPrefetch(context) {\n          const { mediaSink, rootPlaylistQuery, mediaLibraryService, logger } = context;\n          const { mediaQuery } = mediaSink;\n          return combineQueries([mediaQuery.desiredRate$, mediaQuery.waterLevelChangedForType$(SourceBufferType.Variant)]).pipe(\n          // startup: don't subscribe to root playlist query until needed\n          switchMap(([desiredRate, waterLevel]) => {\n              if (isIframeRate(desiredRate) || waterLevel !== BufferWaterLevel.AboveHighWater) {\n                  return EMPTY;\n              }\n              return rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(map((enabledVariantMediaOption) => {\n                  var _a, _b;\n                  const variantQuery = rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.Variant];\n                  const hasIframes = variantQuery.hasIframes;\n                  const libQuery = mediaLibraryService.getQuery();\n                  const isLiveOrEvent = (_b = (_a = libQuery.getEntity(rootPlaylistQuery.itemId)) === null || _a === void 0 ? void 0 : _a.liveOrEvent) !== null && _b !== void 0 ? _b : false;\n                  if (!hasIframes || isLiveOrEvent) {\n                      logger.info(loggerName$2, `Skipping iframe prefetch hasIframes=${hasIframes}, liveOrEvent=${isLiveOrEvent}`);\n                      return PrefetchResult.DISABLED;\n                  }\n                  return enabledVariantMediaOption;\n              }));\n          }), take(1), exhaustMap((variantOption) => beginPrefetch(variantOption, context)), finalize$1(() => {\n              logger.trace(loggerName$2, 'finalizing iframe prefetch');\n          }));\n      }\n      function beginPrefetch(variantOption, context) {\n          const { logger } = context;\n          if (variantOption === PrefetchResult.DISABLED) {\n              return of(variantOption);\n          }\n          return prefetchPlaylist(variantOption, context).pipe(exhaustMap((mediaOptionDetails) => prefetchInitSegmentAndKey(mediaOptionDetails, context)), mapTo(PrefetchResult.SUCCESS), catchError((err) => {\n              logger.error(loggerName$2, `got error ${err.message} in prefetch`);\n              return of(PrefetchResult.ERRORED);\n          }));\n      }\n      function prefetchPlaylist(variantOption, context) {\n          const { rootPlaylistQuery, logger, config, mediaSink, statsService } = context;\n          const { mediaQuery } = mediaSink;\n          const statsQuery = statsService.getQueryForItem(rootPlaylistQuery.itemId);\n          const mediaLibraryQuery = createMediaLibraryQuery(variantOption);\n          const iframeMediaChoice = findNextABRAutoVariantOptionInMode(true, config, rootPlaylistQuery, mediaLibraryQuery, mediaQuery, statsQuery, logger);\n          const iframeMediaOption = rootPlaylistQuery.variantMediaOptionById(iframeMediaChoice.variantMediaOption);\n          logger.info(loggerName$2, `prefetching variant ${iframeMediaChoice.variantMediaOption}`);\n          return retrieveMediaOptionDetails(context, iframeMediaOption, true);\n      }\n      function prefetchInitSegmentAndKey(mediaOptionDetails, context) {\n          var _a;\n          const { logger, mediaSink, rootPlaylistQuery } = context;\n          const { mediaQuery } = mediaSink;\n          const fragResult = findFragment(mediaQuery.currentTime, rootPlaylistQuery.discoSeqNum, 0, mediaOptionDetails, []);\n          if (!((_a = fragResult === null || fragResult === void 0 ? void 0 : fragResult.foundFrag) === null || _a === void 0 ? void 0 : _a.mediaFragment)) {\n              return throwError('Unable to find fragment for iframe prefetch');\n          }\n          const mediaFragment = fragResult.foundFrag.mediaFragment;\n          const prefetchKey$ = loadKey(context, mediaFragment.keyTagInfo, { itemId: mediaFragment.itemId, mediaOptionId: mediaFragment.mediaOptionId });\n          const prefetchInitSeg$ = retrieveInitSegmentCacheEntity(context, mediaFragment);\n          return forkJoin([prefetchKey$, prefetchInitSeg$]).pipe(tap(() => logger.info(loggerName$2, `prefetched variant ${mediaOptionDetails.mediaOptionId}`)), mapTo(PrefetchResult.SUCCESS));\n      }\n      function checkForIframeAutoPause(context) {\n          const { config, logger, iframeMachine, mediaSink } = context;\n          const { mediaQuery } = mediaSink;\n          return mediaQuery.desiredRate$.pipe(switchMap((rate) => {\n              if (!isIframeRate(rate)) {\n                  return EMPTY;\n              }\n              const period = Math.abs(1000 / rate);\n              return timer(0, period).pipe(map(() => {\n                  let result = null;\n                  const seekable = mediaQuery.seekable;\n                  if (!iframeMachine.isStarted || seekable.length < 1) {\n                      return result;\n                  }\n                  const iframeReferenceClockTime = iframeMachine.iframeClockTimeSeconds;\n                  const { leftMediaTimeToAutoPause } = config;\n                  const minTime = seekable.start(0);\n                  const maxTime = seekable.end(seekable.length - 1);\n                  if (rate > 1 && maxTime - iframeReferenceClockTime < leftMediaTimeToAutoPause) {\n                      logger.info({ name: 'iframes' }, `near the end of media, pausing normal playback, maxTime ${maxTime}, ifrct ${iframeReferenceClockTime}`);\n                      result = { newRate: 0, postFlushSeek: maxTime - leftMediaTimeToAutoPause };\n                      iframeMachine.pause();\n                  }\n                  else if (rate < 0 && iframeReferenceClockTime - minTime < rate / -2) {\n                      logger.info({ name: 'iframes' }, `near the start of media, resuming playback, minTime ${minTime}, ifrct: ${iframeReferenceClockTime}`);\n                      result = { newRate: 1, postFlushSeek: minTime };\n                  }\n                  return result;\n              }), filterNullOrUndefined(), tap(({ newRate, postFlushSeek }) => {\n                  mediaSink.postFlushSeek = postFlushSeek;\n                  mediaSink.desiredRate = newRate;\n              }), switchMapTo(EMPTY));\n          }));\n      }\n      function desiredRateChange(context) {\n          const mediaQuery = context.mediaSink.mediaQuery;\n          return combineLatest([of(context), mediaQuery.desiredRate$.pipe(pairwise())]).pipe(switchMap(([context, [oldRate, newRate]]) => {\n              const { rootPlaylistQuery, rootPlaylistService, config, logger, mediaSink, mediaLibraryService, statsService } = context;\n              const mediaQuery = mediaSink.mediaQuery;\n              const wasIframeRate = isIframeRate(oldRate);\n              const iframeRate = isIframeRate(newRate);\n              if (wasIframeRate !== iframeRate) {\n                  logger.qe({ critical: true, name: 'iframes', data: { state: iframeRate, prevRate: oldRate, newRate } });\n                  handleVariantSwitch(SwitchReason.IframeModeChange, config, rootPlaylistQuery, mediaQuery, rootPlaylistService);\n              }\n              else if (oldRate === 0 && newRate === 1) {\n                  const canPlayWithoutGap = AVMediaOptionTypes.every((type) => {\n                      var _a;\n                      const enabledOption = rootPlaylistQuery.enabledMediaOptionKeys[type];\n                      const libQuery = mediaLibraryService.getQueryForOption(enabledOption);\n                      const statsQuery = statsService.getQueryForItem(rootPlaylistQuery.itemId);\n                      const entity = libQuery.mediaOptionDetailsEntity;\n                      return (!((_a = entity === null || entity === void 0 ? void 0 : entity.mediaOptionDetails) === null || _a === void 0 ? void 0 : _a.ptsKnown) ||\n                          mediaQuery.canContinuePlaybackWithoutGap(entity.mediaOptionDetails, entity.lastUpdateMillis, statsQuery.getPlaylistEstimate(), config.maxBufferHole));\n                  });\n                  if (!canPlayWithoutGap) {\n                      logger.info('flush due to live gap [0, Infinity]');\n                      mediaSink.pause();\n                      return mediaSink.flushAll(0, Infinity, true);\n                  }\n              }\n              return EMPTY;\n          }), switchMapTo(EMPTY));\n      }\n      function capToEnabledIframeOption(context) {\n          const rootQuery = context.rootPlaylistQuery;\n          const mediaQuery = context.mediaSink.mediaQuery;\n          const enabledOption$ = rootQuery.enabledMediaOptionByType$(MediaOptionType.Variant);\n          return combineLatest([of(context), mediaQuery.desiredRate$.pipe(pairwise())]).pipe(\n          // distinct until desiredRate changed\n          distinctUntilChanged((prev, cur) => prev[1] === cur[1]), withLatestFrom(enabledOption$), // Startup: don't subscribe to root playlist query until needed\n          switchMap(([[context, [oldRate, newRate]], enabledMediaOption]) => {\n              const wasIframeRate = isIframeRate(oldRate);\n              const iframeRate = isIframeRate(newRate);\n              // Early return if trickplay was not toggled\n              if (wasIframeRate === iframeRate) {\n                  return EMPTY;\n              }\n              const { rootPlaylistService, logger } = context;\n              if (iframeRate) {\n                  // Check if level uncapped\n                  if (context.rootPlaylistQuery.nextMaxAutoOptionId === NoMediaOption.mediaOptionId) {\n                      // Attach to rootPlaylistQuery so it lasts throughout trickplay\n                      rootPlaylistService.setNextMaxAutoOptionId(context.rootPlaylistQuery.itemId, enabledMediaOption.mediaOptionId);\n                      logger.info(`Capped level to ${enabledMediaOption.mediaOptionId} on entering trickplay`);\n                  }\n              }\n              return EMPTY;\n          }));\n      }\n    \n      class QueueItemQuery extends QueryEntity {\n      }\n      const queueItemStore = new EntityStore({}, { name: 'item-queue', producerFn: produce_1, idKey: 'itemId', resettable: true });\n      const queueItemQuery = new QueueItemQuery(queueItemStore);\n      /**\n       * @brief The playback queue\n       */\n      class ItemQueue {\n          constructor() {\n              this.firstItem = true;\n              this.playingEntity = null;\n              this.loadingEntity = null;\n          }\n          static createItem(name, url, initialSeekTime = NaN, platformInfo, serviceName) {\n              const today = new Date();\n              const createTime = `${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}`;\n              // The MediaFragment URI start time we get from URL will take precedence over:\n              // hls.config.startPosition > TIME-OFFSET in playlist > initialSeekTime parameter in this function.\n              const logger = getLogger();\n              const timeOffset = getTimeOffsetParameter(url);\n              logger.info(`timeOffset parsed from URL ${timeOffset}`);\n              if (isFiniteNumber(timeOffset)) {\n                  initialSeekTime = timeOffset;\n              }\n              else {\n                  const hlsConfig = getCurrentConfig();\n                  if (isFiniteNumber(hlsConfig === null || hlsConfig === void 0 ? void 0 : hlsConfig.startPosition)) {\n                      // override only if finite value\n                      initialSeekTime = hlsConfig.startPosition;\n                      logger.info(`override initialSeekTime with startPosition ${initialSeekTime}`);\n                  }\n              }\n              const queueItem = {\n                  itemId: `${name}_${createTime}`,\n                  name,\n                  url,\n                  serviceName,\n                  createTime,\n                  initialSeekTime,\n                  itemStartOffset: 0,\n                  platformInfo,\n                  config: {},\n              };\n              return queueItem;\n          }\n          /**\n           * @returns obervable for whenever active item changes\n           */\n          get activeItemById$() {\n              return queueItemQuery.selectActiveId().pipe(map((_) => queueItemQuery.getActive()));\n          }\n          get removedItems$() {\n              return queueItemQuery.selectEntityAction(EntityActions.Remove).pipe(map((ids) => ids));\n          }\n          /**\n           * @returns the active item. The active item is the currently downloading item\n           * which could be different from the playing item.\n           */\n          get activeItem() {\n              return queueItemQuery.getActive();\n          }\n          /**\n           * @returns the entire play queue\n           */\n          get queueItems$() {\n              return queueItemQuery.selectAll().pipe(map((queueItems) => queueItems !== null && queueItems !== void 0 ? queueItems : []));\n          }\n          /*\n           * @returns whether this is the first item\n           */\n          get isFirstItem() {\n              return this.firstItem;\n          }\n          get playingItem() {\n              return this.playingEntity;\n          }\n          get loadingItem() {\n              return this.loadingEntity;\n          }\n          /**\n           * Add item to the queue and makes it active but keeps the former active item.\n           *\n           * @param name Identifier for the item\n           * @param url  URL for the root playlist\n           */\n          addQueueItem(name, url, initialSeekTime, platformInfo, itemStartOffset, serviceName) {\n              // TODO: Kola to investigate not exposing itemStartOffset in the public API of addQueueItem\n              queueItemQuery.getCount();\n              const queueItem = ItemQueue.createItem(name, url, initialSeekTime, platformInfo, serviceName);\n              if (this.playingEntity != null) {\n                  // clear initialSeekTime if it's not the playing item\n                  queueItem.initialSeekTime = undefined;\n              }\n              if (itemStartOffset) {\n                  queueItem.itemStartOffset = itemStartOffset;\n                  getLogger().debug(`itemStartOffset=${queueItem.itemStartOffset}`);\n                  this.firstItem = false;\n                  // set playing and loading item ids\n                  this.playingEntity = this.activeItem;\n                  this.loadingEntity = queueItem;\n              }\n              logAction(`queue.add.item: ${name}`);\n              applyTransaction(() => {\n                  queueItemStore.add(queueItem);\n                  queueItemStore.setActive(queueItem.itemId);\n              });\n          }\n          /**\n           * Update the playing item id from loading item id and clear loading item id\n           */\n          updatePlayingItemId() {\n              this.playingEntity = this.loadingEntity;\n              this.loadingEntity = null;\n              this.clearAllButActive();\n          }\n          /**\n           * Reset loading item\n           */\n          resetLoadingItem() {\n              this.removeQueueItem(this.loadingEntity.itemId);\n              this.loadingEntity = null;\n              applyTransaction(() => {\n                  queueItemStore.setActive(this.playingEntity.itemId);\n              });\n          }\n          /**\n           * Returns whether a track is currently preloading but not yet playing\n           */\n          isPreloading() {\n              // If both loading and playing items are not undefined then a track is currently loading\n              return this.playingEntity !== null && this.loadingEntity !== null;\n          }\n          setQueueItem(name, url, initialSeekTime, platformInfo, serviceName) {\n              logAction('queue.set.item');\n              this.loadingEntity = null;\n              applyTransaction(() => {\n                  queueItemStore.reset();\n                  const queueItem = ItemQueue.createItem(name, url, initialSeekTime, platformInfo, serviceName);\n                  queueItemStore.add(queueItem);\n                  queueItemStore.setActive(queueItem.itemId);\n              });\n              this.playingEntity = this.activeItem;\n          }\n          /**\n           * Remove an item from the queue\n           */\n          removeQueueItem(itemId) {\n              queueItemStore.remove(itemId);\n          }\n          /**\n           * Clear the queue\n           */\n          clearQueue() {\n              queueItemStore.reset();\n          }\n          /**\n           * Clear all items but the active item\n           */\n          clearAllButActive() {\n              var _a;\n              const activeId = (_a = this.activeItem) === null || _a === void 0 ? void 0 : _a.itemId;\n              applyTransaction(() => {\n                  const items = queueItemQuery.getAll();\n                  items.forEach((item) => {\n                      if (item.itemId !== activeId) {\n                          queueItemStore.remove(item.itemId);\n                      }\n                  });\n              });\n          }\n          set earlyAudioSelection(audioPersistentId) {\n              queueItemStore.updateActive((activeItem) => {\n                  if (!activeItem.earlySelection) {\n                      activeItem.earlySelection = {};\n                  }\n                  activeItem.earlySelection.audioPersistentId = audioPersistentId;\n              });\n          }\n          get earlyAudioSelection() {\n              var _a;\n              return (_a = this.activeItem.earlySelection) === null || _a === void 0 ? void 0 : _a.audioPersistentId;\n          }\n          set earlySubtitleSelection(subtitlePersistentId) {\n              queueItemStore.updateActive((activeItem) => {\n                  if (!activeItem.earlySelection) {\n                      activeItem.earlySelection = {};\n                  }\n                  activeItem.earlySelection.subtitlePersistentId = subtitlePersistentId;\n              });\n          }\n          get earlySubtitleSelection() {\n              var _a;\n              return (_a = this.activeItem.earlySelection) === null || _a === void 0 ? void 0 : _a.subtitlePersistentId;\n          }\n      }\n    \n      /**\n       * Handle MSE related errors: sourcebuffer creation, appending, etc.\n       */\n      // Append error handling\n      function addAppendErrorHandlingPolicy(mediaSink, sbAdapter, mediaOptionType, mediaOptionId, targetDuration, config, rootQuery, rootService, meQuery) {\n          return (source) => source.pipe(tap(() => {\n              rootService.updateConsecutiveTimeouts(rootQuery.itemId, mediaOptionType, false, 'append');\n          }), retryWhen((errors) => errors.pipe(mergeMap((err, retryCount) => {\n              const isTimeout = err instanceof AppendBufferError && err.isTimeout;\n              rootService.updateConsecutiveTimeouts(rootQuery.itemId, mediaOptionType, isTimeout, 'append');\n              if (isTimeout) {\n                  return handleAppendTimeout(err, retryCount, config, mediaOptionType, mediaOptionId, meQuery, rootQuery, rootService);\n              }\n              if (err instanceof BufferFullError) {\n                  return handleBufferFullError(err, sbAdapter, retryCount, targetDuration, config, mediaOptionType, mediaOptionId, meQuery, rootQuery, rootService);\n              }\n              if (err instanceof MediaDecodeError) {\n                  const { mediaOptionType, mediaOptionId } = err;\n                  return handleFormatError(err, mediaOptionType, mediaOptionId, mediaSink, rootService, rootQuery);\n              }\n              throw err;\n          }))));\n      }\n      function handleBufferFullError(error, sb, retryCount, targetDuration, config, mediaOptionType, mediaOptionId, meQuery, rootQuery, rootService) {\n          const sbType = sb.type;\n          const currentWaterLevel = meQuery.getCurrentWaterLevelByType(sbType, config.maxBufferHole); // Always use real position for buffer full errors\n          const mediaBuffered = currentWaterLevel >= config.almostDryBufferSec;\n          // <rdar://87250808> Ejecting media from the buffer in iframe-mode will allow trick-play to recover when the forward audio buffer is full\n          // TODO: This should be considered for normal playback. Retries buy time, but they don't help reduce buffer usage.\n          //   Flushing back and forward buffer is a better long-term solution for reclaiming memory.\n          if (mediaBuffered && !meQuery.isIframeRate) {\n              // this.logger.debug(`${self} bufferFullError waterLevel:${currentWaterLevel} targetDur:${this.targetDuration}`);\n              const retryDelayMs = targetDuration * 1000;\n              const action = {\n                  errorAction: NetworkErrorAction.RetryRequest,\n                  errorActionFlags: 0,\n              };\n              if (currentWaterLevel * 1000 < retryDelayMs) {\n                  if (rootService.hasFallbackMediaOptionTuple(rootQuery, mediaOptionType, mediaOptionId, false)) {\n                      // Put into penalty box if we might run out of buffer before we can append again\n                      action.errorAction = NetworkErrorAction.SendAlternateToPenaltyBox;\n                  }\n                  else {\n                      // can only fit 1 target duration so likely to stall. Probably pointless to keep going\n                      // this.logger.warn(`${self} buffer too small to sustain playback @${pos.toFixed(3)} buffered:${TimeRangesExt.toString(this.buffered)}`);\n                      action.errorAction = NetworkErrorAction.SendEndCallback;\n                  }\n              }\n              // this.logger.info(`${self} handleBufferFullError errorAction:${errorAction} ${retryDelayMs}ms`);\n              const retryConfig = {\n                  retryDelayMs,\n                  maxNumRetry: Infinity,\n                  maxRetryDelayMs: retryDelayMs,\n              };\n              return handleErrorWithRetry(error, retryCount, retryConfig, action, rootQuery, rootService, mediaOptionType, mediaOptionId);\n          }\n          else if (retryCount < config.appendErrorMaxRetry) {\n              // current position is not buffered, but browser is still complaining about buffer full error\n              // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n              // in that case flush the whole buffer to recover and retry\n              // this.logger.warn(`${self} buffer full and not buffered. flush everything and retry`);\n              return sb.remove(0, Number.POSITIVE_INFINITY);\n          }\n          else {\n              error.fatal = true;\n          }\n          return throwError(error); // Rethrow\n      }\n      function handleAppendTimeout(err, retryCount, config, mediaOptionType, mediaOptionId, meQuery, rootQuery, rootService) {\n          // Should be rare. If append timeout occurs possibly there is some platform or media issue so safer to\n          // reset and switch\n          let errorAction = {\n              errorAction: NetworkErrorAction.SendAlternateToPenaltyBox,\n              errorActionFlags: 0,\n          };\n          const waterLevel = meQuery.getCurrentWaterLevel(config.maxBufferHole);\n          const bufferEmpty = waterLevel < config.almostDryBufferSec;\n          let retryDelayMs = NaN;\n          const maxAppendFails = config.appendErrorMaxRetry;\n          const appendTimeouts = rootQuery.rootPlaylistEntity.errorsByType[mediaOptionType].timeouts.append;\n          if ((bufferEmpty && appendTimeouts >= maxAppendFails) || retryCount >= maxAppendFails) {\n              errorAction.errorAction = NetworkErrorAction.SendEndCallback;\n          }\n          else {\n              retryDelayMs = waterLevel * 1000; // should only trigger on last variant\n          }\n          const retryConfig = {\n              retryDelayMs,\n              maxNumRetry: maxAppendFails,\n              maxRetryDelayMs: retryDelayMs,\n          };\n          errorAction = modifyErrorActionIfCurrentLevelIsLastValidLevel(errorAction, false, err.response.code, mediaOptionId, mediaOptionType, rootQuery, rootService);\n          return handleErrorWithRetry(err, retryCount, retryConfig, errorAction, rootQuery, rootService, mediaOptionType, mediaOptionId)\n              .pipe();\n      }\n      function handleFormatError(err, mediaOptionType, mediaOptionId, mediaSink, rootService, rootQuery) {\n          let action = {\n              errorAction: NetworkErrorAction.RemoveAlternatePermanently,\n              errorActionFlags: 0,\n          };\n          action = modifyErrorActionIfCurrentLevelIsLastValidLevel(action, false, err.response.code, mediaOptionId, mediaOptionType, rootQuery, rootService);\n          // No retry\n          return handleErrorActionCommon(err, 0, action, rootQuery, rootService, mediaOptionType, mediaOptionId).pipe(catchError((err) => {\n              if (err.fatal === false) {\n                  mediaSink.resetMediaSource();\n              }\n              throw err;\n          }));\n      }\n      // Handle CreateSourceBufferError. For combined audio video append, handle the error here so that\n      // reset does not destroy the other SourceBuffer too early\n      function addCreateSourceBufferErrorHandlingPolicy(mediaSink, rootService, rootQuery) {\n          return (source$) => source$.pipe(catchError((err) => {\n              if (err instanceof CreateSourceBufferError) {\n                  const { mediaOptionType, mediaOptionId } = err;\n                  return handleFormatError(err, mediaOptionType, mediaOptionId, mediaSink, rootService, rootQuery);\n              }\n              throw err;\n          }));\n      }\n    \n      class FragmentPicker {\n          constructor(logger, _rootPlaylistService, _rootQuery, _mediaQuery, _iframeMachine, config) {\n              this.logger = logger;\n              this._rootPlaylistService = _rootPlaylistService;\n              this._rootQuery = _rootQuery;\n              this._mediaQuery = _mediaQuery;\n              this._iframeMachine = _iframeMachine;\n              this._anchorMSNs = [NaN, NaN]; // First fragment in current discontinuity\n              this._avDetails = [null, null]; // enabled AV options latest details (just the relevant info)\n              this.logger = logger.child({ name: 'fpicker' });\n              this._discoSeqNum = NaN;\n              this.lookUpTolerance = Math.max(config.maxBufferHole, config.maxFragLookUpTolerance);\n              this.firstAudioMustOverlapVideoStart = config.firstAudioMustOverlapVideoStart;\n              this.lookUpToleranceAlt = config.firstAudioMustOverlapVideoStart ? 0 : config.maxFragLookUpTolerance;\n              this.logger.info(`new item ${this._rootQuery.itemId}`);\n          }\n          destroy() {\n              this._anchorMSNs = [NaN, NaN];\n              this._avDetails = [null, null];\n              this._rootQuery = null;\n              this._mediaQuery = null;\n              this._rootPlaylistService = null;\n              this._iframeMachine = null;\n          }\n          get discoSeqNum() {\n              return this._discoSeqNum;\n          }\n          get _discoSeqNum() {\n              return this._rootQuery.discoSeqNum;\n          }\n          set _discoSeqNum(cc) {\n              // Should we just have a separate store for fragment selection?\n              this._rootPlaylistService.setDiscoSeqNum(this._rootQuery.itemId, cc);\n          }\n          get anchorMSNs() {\n              return this._anchorMSNs;\n          }\n          _resolvePosition(position, type, newDetails) {\n              var _a;\n              let resolvedPosition = position;\n              const curDetails = this._avDetails[type];\n              // LIVE:\n              // 1. try choosing position based on program date time @ the switch position\n              // 2. if ptsknown, we can reasonably choose @ switch position\n              // 3. else, choose at live offset from end\n              // Has END-TAG:\n              // Simple case. just use position.\n              if ((curDetails === null || curDetails === void 0 ? void 0 : curDetails.mediaOptionId) !== (newDetails === null || newDetails === void 0 ? void 0 : newDetails.mediaOptionId) &&\n                  newDetails.liveOrEvent &&\n                  newDetails.ptsKnown === false &&\n                  (!curDetails || Math.max(curDetails.startSN, newDetails.startSN) > Math.min(curDetails.endSN, newDetails.endSN)) // no overlap\n              ) {\n                  // Commenting out PDT based revisal as it needs new position as opposed to old position, before rebasing to newDetails.\n                  // if (curDetails?.dateMediaTimePairs != null && newDetails.dateMediaTimePairs) {\n                  //   const date = resolvePTSToDate(curDetails.dateMediaTimePairs, position);\n                  //   resolvedPosition = resolveDateToPTS(newDetails.dateMediaTimePairs, date);\n                  //   this.logger.info(`Use program date time ${date.toISOString()} ${position.toFixed(3)}->${resolvedPosition.toFixed(3)}`);\n                  // } else {\n                  const liveOffsetSec = 3 * newDetails.targetduration; // HLS native chooses 3 * targetDuration, or HOLD-BACK property\n                  const liveEdge = ((_a = newDetails.fragments[0]) === null || _a === void 0 ? void 0 : _a.start) + newDetails.totalduration;\n                  resolvedPosition = Math.max(0, liveEdge - liveOffsetSec);\n                  this.logger.info(`Use live offset ${liveOffsetSec.toFixed(3)} ${position.toFixed(3)}->${resolvedPosition.toFixed(3)}`);\n                  // }\n              }\n              return resolvedPosition;\n          }\n          getDiscoSeqNumForTime(details, position) {\n              if (this._mediaQuery.isIframeRate && details.iframesOnly) {\n                  return DiscoHelper$1.discoSeqNumForTime(details.fragments, position); // from iframeMachine startClocksAndGetFirstFragment\n              }\n              else {\n                  return discoSeqNumForTime(details, position);\n              }\n          }\n          /**\n           * After a seek, need to re-anchor using latest details\n           * @param position Position for re-anchor\n           * @param detailsTuple details\n           */\n          _updateAnchorByPosition(position, detailsTuple) {\n              let newCC = NaN;\n              const vDetails = detailsTuple[SourceBufferType.Variant];\n              let resolvedPosition = position;\n              if (vDetails) {\n                  const fragments = vDetails.fragments;\n                  resolvedPosition = this._resolvePosition(position, SourceBufferType.Variant, vDetails);\n                  newCC = this.getDiscoSeqNumForTime(vDetails, resolvedPosition); // used resolved position to get CC\n                  if (!isFiniteNumber(newCC)) {\n                      const firstFrag = fragments[0];\n                      const lastFrag = fragments[fragments.length - 1];\n                      const startPTSSec = firstFrag === null || firstFrag === void 0 ? void 0 : firstFrag.start;\n                      const endPTSSec = (lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.start) + (lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.duration);\n                      this.logger.warn(`${position.toFixed(3)} out of range [${startPTSSec === null || startPTSSec === void 0 ? void 0 : startPTSSec.toFixed(3)},${endPTSSec === null || endPTSSec === void 0 ? void 0 : endPTSSec.toFixed(3)}]`);\n                      if (resolvedPosition <= startPTSSec) {\n                          // Gapless preloading\n                          newCC = firstFrag.discoSeqNum;\n                      }\n                      else if (resolvedPosition >= endPTSSec) {\n                          newCC = lastFrag.discoSeqNum;\n                      }\n                      else {\n                          this.logger.warn(`Unable to determine newCC. fragFirst: ${JSON.stringify(firstFrag)} fragLast: ${JSON.stringify(lastFrag)}`);\n                      }\n                      if (!isFiniteNumber(newCC)) {\n                          this.logger.warn(`Unable to determine newCC. fragFirst: ${JSON.stringify(firstFrag)} fragLast: ${JSON.stringify(lastFrag)}`);\n                      }\n                  }\n              }\n              else {\n                  this.logger.warn('No variant details for anchoring');\n              }\n              if (newCC !== this._discoSeqNum) {\n                  this.logger.info(`Update anchor by position:${resolvedPosition.toFixed(3)} cc:${this._discoSeqNum}->${newCC}`);\n              }\n              this._updateAnchor(newCC, detailsTuple);\n              return resolvedPosition;\n          }\n          _updateAnchor(newCC, detailsTuple) {\n              const ccDidChange = newCC !== this._discoSeqNum;\n              if (ccDidChange) {\n                  this.logger.info(`Update anchor cc:${this._discoSeqNum}->${newCC}`);\n                  this._discoSeqNum = newCC;\n              }\n              AVMediaOptionTypes.forEach((type) => {\n                  const curDetails = this._avDetails[type];\n                  const newDetails = detailsTuple[type];\n                  const detailsChanged = (curDetails === null || curDetails === void 0 ? void 0 : curDetails.mediaOptionId) !== (newDetails === null || newDetails === void 0 ? void 0 : newDetails.mediaOptionId);\n                  if (ccDidChange || detailsChanged) {\n                      this._updateAnchorForType(mediaOptionTypeToSourceBufferType(type), newDetails);\n                  }\n                  else if (newDetails) {\n                      const { mediaOptionId, ptsKnown, dateMediaTimePairs, startSN, endSN } = newDetails;\n                      this._avDetails[type] = { mediaOptionId, ptsKnown, dateMediaTimePairs, startSN, endSN };\n                  }\n              });\n          }\n          /**\n           * Get next set of fragments to choose.\n           * @param pos The playback position (media.currentTime)\n           * @param detailsTuple The latest details for variant and alt audio\n           * @param usePosition if true, use position for selection. else, use buffer end\n           */\n          getNextFragments(action, detailsTuple, logger) {\n              const { position, bufferInfoTuple, switchContexts } = action;\n              const searchPositions = bufferInfoTuple.map((bufferInfo, type) => {\n                  return getSearchPosition(position, detailsTuple[type], switchContexts[type], bufferInfo === null || bufferInfo === void 0 ? void 0 : bufferInfo.buffered, type === MediaOptionType.AltAudio ? this.lookUpToleranceAlt : this.lookUpTolerance);\n              });\n              let anchorPosition = searchPositions.reduce((lastMin, position) => Math.min(position, lastMin), Number.POSITIVE_INFINITY);\n              if (isFiniteNumber(action.discoSeqNum)) {\n                  // if anchorTime specifies a discontinuity sequence number, find only fragments in the specified cc.\n                  // happens right after resetting mediaSource when crossing an incompat. discontinuity\n                  const combinedRange = detailsTuple.reduce((finalRange, details) => {\n                      if (!details) {\n                          return finalRange;\n                      }\n                      const thisRange = DiscoHelper$1.getTimeRangeForCC(details.fragments, action.discoSeqNum, logger); // adjust anchorPosition in case the anchor cc is a bit off\n                      return [Math.max(finalRange[0], thisRange[0]), Math.min(finalRange[1], thisRange[1])];\n                  }, [Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY]);\n                  anchorPosition = Math.min(Math.max(anchorPosition, combinedRange[0]), combinedRange[1]);\n                  this.logger.info(`adjusted anchorPosition ${anchorPosition} to fit in cc ${action.discoSeqNum} [${combinedRange[0]}-${combinedRange[1]}]`);\n              }\n              action.position = this._updateAnchorByPosition(anchorPosition, detailsTuple);\n              return this._getNextFragmentsInternal(action, detailsTuple);\n          }\n          _getNextFragmentsInternal(action, detailsTuple) {\n              var _a, _b;\n              const chosenFrags = [null, null];\n              let origPosition;\n              detailsTuple.forEach((_, type) => {\n                  var _a;\n                  if (this.firstAudioMustOverlapVideoStart && type === MediaOptionType.AltAudio && this._mediaQuery.seeking) {\n                      // this ensures the audio is not ahead of the video;\n                      // especially, decode from iframes could further pull back the\n                      // seek position, and we should ensure that the corresponding audio is\n                      // also available\n                      if ((_a = chosenFrags[MediaOptionType.Variant]) === null || _a === void 0 ? void 0 : _a.foundFrag) {\n                          // retain original position in case of next discontinuity\n                          origPosition = action.position;\n                          action.position = chosenFrags[MediaOptionType.Variant].foundFrag.mediaFragment.start;\n                          this.logger.info(`revised altAudio frag search position to ${action.position} based on variant frag start`);\n                      }\n                  }\n                  chosenFrags[type] = this._getNextFragmentForType(action, detailsTuple, type);\n              });\n              const vResult = chosenFrags[SourceBufferType.Variant];\n              const aResult = chosenFrags[SourceBufferType.AltAudio];\n              // One buffer is too far ahead of the other one\n              // 1. Could happen in i-frame mode where audio fragments are much longer\n              // 2. Audio switch that causes complete flush\n              const vFrag = (_a = vResult === null || vResult === void 0 ? void 0 : vResult.foundFrag) === null || _a === void 0 ? void 0 : _a.mediaFragment;\n              const aFrag = (_b = aResult === null || aResult === void 0 ? void 0 : aResult.foundFrag) === null || _b === void 0 ? void 0 : _b.mediaFragment;\n              if (vFrag && aFrag) {\n                  if (aFrag.start > vFrag.start + vFrag.duration) {\n                      // must not load audio too far ahead in iframe mode, cause unrecoverable bufferFull error in AirPlay\n                      this.logger.warn('Audio too far ahead');\n                      chosenFrags[SourceBufferType.AltAudio] = FragmentPicker.noopResult;\n                  }\n                  else if (vFrag.start > aFrag.start + aFrag.duration && !this._mediaQuery.isIframeRate) {\n                      this.logger.warn('Video too far ahead');\n                      chosenFrags[SourceBufferType.Variant] = FragmentPicker.noopResult;\n                  }\n              }\n              // All fragments in next discontinuity. Advance and try selecting again\n              if (isFinite(vResult === null || vResult === void 0 ? void 0 : vResult.nextDisco) && (aResult == null || isFiniteNumber(aResult.nextDisco))) {\n                  const newDisco = chosenFrags[SourceBufferType.Variant].nextDisco;\n                  this.logger.info(`Advance anchor cc: ${this._discoSeqNum}->${newDisco}`);\n                  this._updateAnchor(newDisco, detailsTuple);\n                  if (isFiniteNumber(origPosition)) {\n                      // reinstate the original position due to previous firstAudioMustOverlapVideoStart override\n                      action.position = origPosition;\n                      origPosition = NaN;\n                  }\n                  return this._getNextFragmentsInternal(action, detailsTuple);\n              }\n              return chosenFrags;\n          }\n          /**\n           * Get fragment for position for particular buffer\n           * @param pos position that fragment should overlap\n           * @param usePos if true, choose fragment overlapping pos (e.g. immediate switch w/o flush). else, use bufferEnd (default)\n           */\n          _getNextFragmentForType(action, detailsTuple, type) {\n              var _a, _b, _c, _d, _e, _f, _g, _h;\n              const { position: pos, bufferInfoTuple, switchContexts } = action;\n              const newDetails = detailsTuple[type];\n              const bufferInfo = (_b = (_a = bufferInfoTuple[type]) === null || _a === void 0 ? void 0 : _a.buffered) !== null && _b !== void 0 ? _b : { start: pos, end: pos, len: 0 };\n              const bufferedSeg = this._mediaQuery.getBufferedSegmentsByType(type);\n              const willFlush = (_d = (_c = switchContexts[type]) === null || _c === void 0 ? void 0 : _c.userInitiated) !== null && _d !== void 0 ? _d : false; // Full flush of this buffer will happen\n              const searchPos = getSearchPosition(pos, newDetails, switchContexts[type], bufferInfo, this.lookUpTolerance);\n              if (!newDetails) {\n                  return null;\n              }\n              const { highWaterLevelSeconds, lowWaterLevelSeconds } = this._mediaQuery.bufferMonitorInfo;\n              const bufferAhead = bufferInfo.len; // Future bufferAhead\n              if (!willFlush && bufferAhead >= highWaterLevelSeconds) {\n                  this.logger.info(`[${MediaOptionNames[type]}] got high buffer @${pos.toFixed(3)} ${bufferInfo.len.toFixed(3)} > ${highWaterLevelSeconds}`);\n                  return FragmentPicker.noopResult;\n              }\n              // Special case where audio is starving but variant is ok\n              const otherType = type === SourceBufferType.Variant ? SourceBufferType.AltAudio : SourceBufferType.Variant;\n              const otherBuffer = (_e = bufferInfoTuple[otherType]) === null || _e === void 0 ? void 0 : _e.buffered;\n              const otherWillFlush = (_g = (_f = switchContexts[otherType]) === null || _f === void 0 ? void 0 : _f.userInitiated) !== null && _g !== void 0 ? _g : false;\n              let wantToDelayVariant = false;\n              if (type === SourceBufferType.Variant &&\n                  bufferAhead >= lowWaterLevelSeconds &&\n                  // Yield to altaudio (but ensure audio load-n-append does not punt back to variant, causing an infinite loop):\n                  // A) Audio buffer ends earlier than video buffer.\n                  //    If buffered audio ends later than video, audio append may abort & wait for video append to catch up in mediaSink.getMatchingInfo\n                  this._mediaQuery.expectedSbCount > 1 &&\n                  otherBuffer != null &&\n                  otherBuffer.end < bufferInfo.end &&\n                  // B) Audio was starting from an empty buffer (true starvation after audio track switch): _total_ audio buffer < 1 target duration\n                  //    Use (otherBuffer.end - otherBuffer.start) instead of otherBuffer.len (which begins from currentTime, not start of buffer)\n                  (otherWillFlush || otherBuffer.end - otherBuffer.start < lowWaterLevelSeconds)) {\n                  this.logger.info(`[${MediaOptionNames[type]}] want to delay variant due to audio starvation @${pos.toFixed(3)} ${bufferInfo.len.toFixed(3)} > ${lowWaterLevelSeconds}`);\n                  wantToDelayVariant = true;\n              }\n              let foundFrag = null;\n              let nextDisco = NaN;\n              let newMediaRootTime = undefined;\n              if (this._mediaQuery.isIframeRate && type === SourceBufferType.Variant && newDetails.iframesOnly) {\n                  const result = findIframeFragmentForPosition(searchPos, newDetails, detailsTuple[SourceBufferType.AltAudio], this._mediaQuery.desiredRate, this._iframeMachine);\n                  if (result) {\n                      ({ foundFrag, nextDisco, newMediaRootTime } = result);\n                      const frag = foundFrag.mediaFragment;\n                      if (frag.discoSeqNum !== this._discoSeqNum) {\n                          this.logger.info(`[iframes] overrride cc:${frag.discoSeqNum}`);\n                          // OK to advance here since Variant will run before AltAudio.\n                          this._updateAnchor(frag.discoSeqNum, detailsTuple);\n                      }\n                  }\n              }\n              else {\n                  // Find eligible segment in the specified discontinuity\n                  const anchorMSN = this._anchorMSNs[type];\n                  ({ foundFrag, nextDisco, newMediaRootTime } = findFragment(searchPos, this._discoSeqNum, anchorMSN, newDetails, bufferedSeg));\n              }\n              if (wantToDelayVariant && this._rootQuery.getInitPTS(foundFrag === null || foundFrag === void 0 ? void 0 : foundFrag.mediaFragment.discoSeqNum)) {\n                  this.logger.info(`[${MediaOptionNames[type]}] delay variant since initPTS[${foundFrag === null || foundFrag === void 0 ? void 0 : foundFrag.mediaFragment.discoSeqNum}] is available`);\n                  return FragmentPicker.noopResult;\n              }\n              this.logger.info(`[${MediaOptionNames[type]}] getNextFragmentForType searchPos:${searchPos.toFixed(3)} pos:${pos.toFixed(3)} bufferEnd:${bufferInfo === null || bufferInfo === void 0 ? void 0 : bufferInfo.end.toFixed(3)} willFlush: ${willFlush} cc:${this._discoSeqNum} foundFrag:${fragPrint(foundFrag === null || foundFrag === void 0 ? void 0 : foundFrag.mediaFragment)} timelineOffset:${(_h = foundFrag === null || foundFrag === void 0 ? void 0 : foundFrag.timelineOffset) === null || _h === void 0 ? void 0 : _h.toFixed(3)} nextDisco:${nextDisco} newMediaRootTime:${newMediaRootTime}`);\n              return { foundFrag, nextDisco, newMediaRootTime };\n          }\n          _updateAnchorForType(type, newDetails) {\n              var _a;\n              if (!newDetails) {\n                  this._anchorMSNs[type] = NaN;\n                  this._avDetails[type] = null;\n                  return;\n              }\n              if (!isFiniteNumber(this._discoSeqNum)) {\n                  this.logger.warn('Trying to anchor with non-finite discoSeqNum');\n                  return;\n              }\n              const cc = this._discoSeqNum;\n              const anchorFrag = getAnchorFrag(newDetails.fragments, cc);\n              const mediaSeqNum = (_a = anchorFrag === null || anchorFrag === void 0 ? void 0 : anchorFrag.mediaSeqNum) !== null && _a !== void 0 ? _a : newDetails.startSN; // No anchor, use first fragment as fallback\n              this._anchorMSNs[type] = mediaSeqNum;\n              const { mediaOptionId, ptsKnown, dateMediaTimePairs, startSN, endSN } = newDetails;\n              this._avDetails[type] = { mediaOptionId, ptsKnown, dateMediaTimePairs, startSN, endSN };\n              this.logger.info(`[${MediaOptionNames[type]}] Anchor update id:${mediaOptionId} sn:${this._anchorMSNs[type]}->${mediaSeqNum} discoSeqNum:${this._discoSeqNum}`);\n          }\n      }\n      FragmentPicker.noopResult = { foundFrag: null, nextDisco: NaN }; // prevents us from skipping ahead in disco\n      /**\n       * Get first fragment in discontinuity cc\n       */\n      function getAnchorFrag(fragments, cc) {\n          return fragments.find((f) => f.discoSeqNum === cc);\n      }\n      function getSearchPosition(pos, details, switchContext, bufferInfo, defaultTolerance) {\n          var _a;\n          bufferInfo = bufferInfo !== null && bufferInfo !== void 0 ? bufferInfo : { start: pos, end: pos, len: 0 };\n          const willFlush = (_a = switchContext === null || switchContext === void 0 ? void 0 : switchContext.userInitiated) !== null && _a !== void 0 ? _a : false; // Full flush of this buffer will happen\n          const tolerance = (details === null || details === void 0 ? void 0 : details.iframesOnly) ? 0 : defaultTolerance;\n          return willFlush || bufferInfo.len === 0 ? pos : bufferInfo.end + tolerance;\n      }\n    \n      const avPipeLogName = { name: 'avpipe' };\n      // AVPipe\n      function makeAVPipe(context) {\n          const { config, rootPlaylistService, rootPlaylistQuery, mediaSink, gaplessInstance } = context;\n          const mediaQuery = mediaSink.mediaQuery;\n          const mediaOptionSwitching$ = combineQueries(AVMediaOptionTypes.map((type) => {\n              return rootPlaylistQuery.enabledMediaOptionSwitchForType$(type).pipe(tap((switchInfo) => logger.info(`${MediaOptionNames[type]} mediaOptionSwitch: ${JSON.stringify(switchInfo)}`)));\n          })).pipe(switchMap((switchInfo) => {\n              // Teardown if no enabled option for at least main\n              if (!isEnabledMediaOption({ itemId: rootPlaylistQuery.itemId, mediaOptionId: switchInfo[MediaOptionType.Variant].toId })) {\n                  throw new ExceptionError(true, `No valid variant enabled id:${switchInfo[MediaOptionType.Variant].toId}`, ErrorResponses.NoValidAlternates);\n              }\n              // Handle switch\n              const switchActions$ = switchInfo.map(({ fromId, toId }, mediaOptionType) => {\n                  return pipelineHandleOptionSwitch(context, statsQuery, mediaOptionType, fromId, toId);\n              });\n              return concat(of(true), // Emit on switch start\n              forkJoin(switchActions$).pipe(mapTo(false)) // Emit when we're ready to select fragments\n              );\n          }), tag('mediaOptionSwitch.audiovideo.out'));\n          const statsQuery = createStatsQuery(rootPlaylistQuery.itemId);\n          const logger = context.logger.child(avPipeLogName);\n          const fragmentPicker = new FragmentPicker(logger, rootPlaylistService, rootPlaylistQuery, mediaQuery, context.iframeMachine, config);\n          const anchorTimeChange$ = rootPlaylistQuery.anchorTime$.pipe(tag('anchorTime.audiovideo.in'));\n          // Switch subscriptions when:\n          // 1. anchor time change\n          // 2. enabled option change\n          // Exhaust / wait for pipeline to finalize when:\n          // 1. Need data changes\n          return combineQueries([anchorTimeChange$, mediaOptionSwitching$]).pipe(switchMap(([anchorTime, handlingSwitch]) => {\n              logger.info(`anchorTime=${anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos.toFixed(3)} cc=${anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.discoSeqNum} handlingSwitch=${handlingSwitch}`);\n              if (handlingSwitch) {\n                  return EMPTY; // Just cancel any loads in progress. This is to stop stuff from loading while we're flushing\n              }\n              return mediaQuery.needData$(config.maxBufferHole, gaplessInstance.inGaplessMode).pipe(map((needData) => {\n                  const switchContexts = [\n                      rootPlaylistQuery.enabledMediaOptionSwitchContexts[MediaOptionType.Variant],\n                      rootPlaylistQuery.enabledMediaOptionSwitchContexts[MediaOptionType.AltAudio],\n                  ];\n                  return mediaQuery.getSourceBufferInfoAction(needData, anchorTime, switchContexts, config.maxBufferHole);\n              }), exhaustMap((sbAction) => {\n                  if (!sbAction) {\n                      return EMPTY; // Don't emit if we didn't do anything\n                  }\n                  logger.debug(`start hoses ${JSON.stringify(sbAction)}`);\n                  const producerConsumer$ = of(sbAction).pipe(mediaProducerEpic(context, fragmentPicker), mediaConsumerEpic(context));\n                  return race(producerConsumer$, waitFor(shouldAbortFrag(context), (abort) => abort) // If this emits, we'll abort the whole chain\n                  ).pipe(take(1), finalize$1(() => {\n                      AVMediaOptionTypes.forEach((type) => {\n                          rootPlaylistService.updateInflightFrag(rootPlaylistQuery.itemId, type, null, null, null);\n                      });\n                  }));\n              }));\n          }), map(() => {\n              if (rootPlaylistQuery.getEntity(rootPlaylistQuery.itemId).manualMode) {\n                  return;\n              }\n              // Check for automatic / lazy switch\n              let switchReason = SwitchReason.None;\n              if (checkAndUpdateViewportInfo(platformService(), mediaQuery, config, logger)) {\n                  switchReason = SwitchReason.PreferredListChanged;\n              }\n              let cappedForLowBandwidth = false;\n              const enabledOption = rootPlaylistQuery.enabledVariantMediaOption;\n              if (gotLowBw(rootPlaylistQuery, mediaQuery, rootPlaylistService)) {\n                  switchReason = SwitchReason.LowBandwidth;\n                  // Only add a cap if there is not already one in place\n                  if (rootPlaylistQuery.nextMaxAutoOptionId === NoMediaOption.mediaOptionId) {\n                      // Should uncap automatically if we select a different variant, ensure this is released after handling switch\n                      rootPlaylistService.setNextMaxAutoOptionId(enabledOption.itemId, enabledOption.mediaOptionId);\n                      logger.info(`Capping variant selection to ${enabledOption.mediaOptionId} because switchReason: ${switchReason}`);\n                      cappedForLowBandwidth = true;\n                  }\n              }\n              else if (mediaQuery.playbackStarted && gotHighBw(config, rootPlaylistQuery, rootPlaylistService)) {\n                  switchReason = SwitchReason.HighBandwidth;\n                  rootPlaylistService.setNextMinAutoOptionId(enabledOption.itemId, enabledOption.mediaOptionId);\n                  logger.info(`Capping variant selection to above ${enabledOption.mediaOptionId} because switchReason: ${switchReason}`);\n              }\n              handleVariantSwitch(switchReason, config, rootPlaylistQuery, mediaQuery, rootPlaylistService);\n              // Remove any max/min level caps we placed before level selection\n              if (cappedForLowBandwidth) {\n                  rootPlaylistService.setNextMaxAutoOptionId(enabledOption.itemId, NoMediaOption.mediaOptionId);\n              }\n              else if (switchReason === SwitchReason.HighBandwidth) {\n                  rootPlaylistService.setNextMinAutoOptionId(enabledOption.itemId, NoMediaOption.mediaOptionId);\n              }\n          }), finalize$1(() => {\n              // on (i) active item change, or (ii) after handleErrorActionCommon which will reuse fragmentPicker.\n              // let fragmentPicker garbage collect automatically.\n              logger.debug('teardown');\n          }));\n      }\n      function audioMediaOptionRemoved(rootPlaylistQuery, fromId, toId) {\n          const fromAlternate = fromId === 'Nah' ? null : rootPlaylistQuery.alternateMediaOptionById(MediaOptionType.AltAudio, fromId);\n          const fromIdHasAudio = Boolean(fromAlternate && fromAlternate.url);\n          const toAlternate = fromId === 'Nah' ? null : rootPlaylistQuery.alternateMediaOptionById(MediaOptionType.AltAudio, toId);\n          const toIdHasAudio = Boolean(toAlternate && toAlternate.url);\n          // rename function to audioMediaOptionRemovedOrAdded if uncommenting following line.\n          // return fromIdHasAudio !== toIdHasAudio;\n          return fromIdHasAudio && !toIdHasAudio;\n      }\n      /**\n       * @brief Handle option switch at start of pipeline\n       * Called within pipeline as an action before fetch, as part of switching the enabled option\n       * May be called before or after destination option has actually fully loaded\n       */\n      function pipelineHandleOptionSwitch(libContext, statsQuery, mediaOptionType, fromId, toId) {\n          var _a, _b;\n          const { rootPlaylistQuery, rootPlaylistService, mediaSink, mediaParser, logger, config, iframeMachine } = libContext;\n          const meQuery = mediaSink.mediaQuery;\n          if (!fromId || !toId || (fromId === toId && (mediaOptionType === MediaOptionType.AltAudio || !iframeMachine.isStarted))) {\n              // <rdar://88230974> if iframeMachine.isStarted, must check for trickplay exit condition\n              return VOID;\n          }\n          switch (mediaOptionType) {\n              case MediaOptionType.Variant:\n                  {\n                      if (fromId !== toId) {\n                          mediaParser.reset(MediaOptionType.Variant);\n                      }\n                      const sbType = mediaOptionTypeToSourceBufferType(mediaOptionType);\n                      const fromVariant = rootPlaylistQuery.variantMediaOptionById(fromId);\n                      const toVariant = rootPlaylistQuery.variantMediaOptionById(toId);\n                      const itemId = rootPlaylistQuery.itemId;\n                      if (toVariant == null || fromVariant == null) {\n                          return VOID;\n                      }\n                      const resumingFromTrickPlay = !toVariant.iframes && iframeMachine.isStarted;\n                      if (fromVariant.iframes !== toVariant.iframes || resumingFromTrickPlay) {\n                          mediaSink.toggleTrickPlaybackMode(toVariant.iframes);\n                          if (resumingFromTrickPlay) {\n                              if (!isFiniteNumber(mediaSink.mediaQuery.postFlushSeek)) {\n                                  mediaSink.postFlushSeek = iframeMachine.iframeClockTimeSeconds;\n                              }\n                              iframeMachine.stop();\n                          }\n                          logger.info(`pause & flush for iframeMode transition [0, Infinity] postFlushSeek=${mediaSink.mediaQuery.postFlushSeek} resumingFromTrickPlay=${resumingFromTrickPlay}`);\n                          mediaSink.pause();\n                          // <rdar://88320795> (2.1a) Flush audio and video when resuming from trickplay to avoid fpicker getting stuck with audio gaps after rewind\n                          const postTrickPlayFlush$ = resumingFromTrickPlay ? mediaSink.flushAll(0, Infinity, true) : mediaSink.flushData(sbType, 0, Infinity, true);\n                          return postTrickPlayFlush$.pipe(tap(() => {\n                              const postFlushSeek = mediaSink.mediaQuery.postFlushSeek;\n                              if (isFiniteNumber(postFlushSeek)) {\n                                  rootPlaylistService.setPendingSeek(itemId, postFlushSeek);\n                              }\n                          }));\n                      }\n                      // From stream-controller.ts attemptSafeNextLevelSwitch\n                      if (!config.allowFastSwitchUp || toVariant.iframes) {\n                          return VOID;\n                      }\n                      const fromQuery = createMediaLibraryQuery(fromVariant);\n                      const fromDetails = fromQuery.mediaOptionDetails;\n                      if (fromDetails != null && toVariant != null && fromVariant.bitrate < toVariant.bitrate) {\n                          const fromTargetDuration = fromDetails.targetduration;\n                          const mediaLibraryQuery = createMediaLibraryQuery(toVariant);\n                          const toDetails = mediaLibraryQuery.mediaOptionDetails;\n                          const lastUpdateMs = mediaLibraryQuery.mediaOptionDetailsEntity.lastUpdateMillis;\n                          const currentWaterLevel = meQuery.getCurrentWaterLevelByType(sbType, config.maxBufferHole);\n                          const minBufferAhead = minSwitchBufferAheadSec(fromVariant, toVariant, toDetails, fromTargetDuration, rootPlaylistQuery.abrStatus, statsQuery, config, lastUpdateMs, logger) + config.maxStarvationDelay; // add a safety delay of maxStarvationDelay\n                          logger.info(`fastSwitchUp: currentWaterLevel:${currentWaterLevel} minBufferAhead:${minBufferAhead}`);\n                          // Flush from somewhere past midpoint of first segment after minFlushStart position\n                          const minFlushStart = meQuery.currentTime + minBufferAhead;\n                          const segment = (_b = (_a = meQuery.sourceBufferEntityByType(sbType)) === null || _a === void 0 ? void 0 : _a.bufferedSegments) === null || _b === void 0 ? void 0 : _b.find((seg) => seg.startPTS >= minFlushStart);\n                          // Flush position will remove half to a quarter (at least maxFragLookUpTolerance) of the buffered segment\n                          //  to avoid gaps left by appening new segments with dropped samples up to the first IDR frame\n                          let flushStart;\n                          if (segment) {\n                              const duration = segment.endPTS - segment.startPTS;\n                              flushStart = segment.startPTS + Math.min(Math.max(duration - config.maxFragLookUpTolerance, duration * 0.5), duration * 0.75);\n                          }\n                          if (isFiniteNumber(flushStart) && currentWaterLevel >= minBufferAhead) {\n                              // Note: old code had special handling for live to preserve fragPrevious\n                              logger.info(`flush for fast switchup [${flushStart.toFixed(3)}, Infinity]`);\n                              return mediaSink.flushData(sbType, flushStart, Infinity);\n                          }\n                      }\n                  }\n                  break;\n              case MediaOptionType.AltAudio:\n                  if (audioMediaOptionRemoved(rootPlaylistQuery, fromId, toId)) {\n                      // altAudio -> muxed handling is tricky because:\n                      // when hls switches audio, the new altAudio mediaOption (toId) has no url; audio is muxed with video.\n                      // During switching, getDetailsAndSwitchContext(altAudio) will ignore toId because it has no mediaOptionDetails too.\n                      // As a result, chooseAndFetchFragment will never sees toId's switchContext to trigger any audio switching logic.\n                      // Cleaner to shortcircuit the process: reset the mediaSource now, reload and seek with only the muxed mediaOption.\n                      logger.info(`alt audio removed/added while switching fromId ${fromId} to toId ${toId} @ ${meQuery.currentTime}`);\n                      rootPlaylistService.setEnabledMediaOptionSwitchContextByType(rootPlaylistQuery.itemId, MediaOptionType.AltAudio, toId, undefined);\n                      mediaSink.resetMediaSource(meQuery.currentTime);\n                  }\n                  mediaParser.reset(MediaOptionType.AltAudio);\n                  break;\n          }\n          return VOID;\n      }\n      function checkAndUpdateViewportInfo(platformService, mediaQuery, config, logger) {\n          var _a;\n          const clientWidth = mediaQuery === null || mediaQuery === void 0 ? void 0 : mediaQuery.clientWidth;\n          const clientHeight = mediaQuery === null || mediaQuery === void 0 ? void 0 : mediaQuery.clientHeight;\n          const devicePixelRatio = typeof window === 'object' && window.devicePixelRatio ? window.devicePixelRatio : 1;\n          const newViewportInfo = clientWidth && clientHeight ? { width: clientWidth * devicePixelRatio, height: clientHeight * devicePixelRatio } : undefined;\n          const curViewportInfo = ((_a = platformService.getQuery()) === null || _a === void 0 ? void 0 : _a.viewportInfo) || {};\n          const isViewportSizeChanged = curViewportInfo && newViewportInfo && (curViewportInfo.width !== newViewportInfo.width || curViewportInfo.height !== newViewportInfo.height);\n          if (config.useViewportSizeForLevelCap && isViewportSizeChanged) {\n              platformService.updateViewportInfo(newViewportInfo);\n              logger.info(`ViewportSize changed, old: ${JSON.stringify(curViewportInfo)}, new: ${JSON.stringify(newViewportInfo)}`);\n              return true;\n          }\n          return false;\n      }\n      // AV Producer should work as follows:\n      // 1. wait for details for enabled variant & alt audio\n      // 2. choose fragment(s) for the position if < highWaterLevelSeconds\n      // 3. fetch & parse candidate fragments(s)\n      // 4. on parse, check if we need to re-select any fragment (ptsKnown changed)\n      // 5. advance discontinuity if needed\n      // 6. fetch & parse any new candidate fragment(s)\n      const mediaProducerEpic = (pipelineContext, fragmentPicker) => (bufferInfoAction$) => {\n          const { rootPlaylistQuery: rootQuery, mediaSink } = pipelineContext;\n          const logger = pipelineContext.logger.child(avPipeLogName);\n          return bufferInfoAction$.pipe(observeOn(asyncScheduler), withLatestFrom(rootQuery.enabledMediaOptionKeys$), \n          // Wait for details and switch context\n          switchMap(([action, enabledOptionKeys]) => {\n              return zip(getDetailsAndSwitchContext(action, MediaOptionType.Variant, pipelineContext, enabledOptionKeys).pipe(tap((detailsAndContext) => {\n                  var _a, _b;\n                  const varEntity = detailsAndContext.detailsEntity;\n                  if (!varEntity.mediaOptionDetails.liveOrEvent || varEntity.mediaOptionDetails.ptsKnown) {\n                      const newDuration = varEntity.playlistDuration;\n                      // When AltAudio buffer is ahead of Variant and AltAudio buffer end is slightly greater than playlistDuration\n                      // then setting mediaSink.msDuration based on variant alone will lead to mediaSource buffer trucation to set duration.\n                      // This behavior is seen on Chrome browser, Roku & LG\n                      const variantBufferEnd = ((_a = action.bufferInfoTuple[0]) === null || _a === void 0 ? void 0 : _a.buffered.end) || 0;\n                      const altAudioBufferEnd = ((_b = action.bufferInfoTuple[1]) === null || _b === void 0 ? void 0 : _b.buffered.end) || 0;\n                      const maxBufferEnd = Math.max(variantBufferEnd, altAudioBufferEnd);\n                      mediaSink.msDuration = isFiniteNumber(mediaSink.msDuration) ? Math.max(mediaSink.msDuration, newDuration, maxBufferEnd) : newDuration;\n                  }\n              })), getDetailsAndSwitchContext(action, MediaOptionType.AltAudio, pipelineContext, enabledOptionKeys)).pipe(map((detailsAndContext) => ({ action, detailsAndContext })));\n          }), \n          // Choose, fetch, & parse fragments:\n          switchMap(({ action, detailsAndContext }) => chooseAndFetchFragments(logger, fragmentPicker, pipelineContext, action, detailsAndContext)), tag('mediaProducerEpic.emit'));\n      };\n      function playlistIsValid(mediaOptionDetails, lastUpdateMillis) {\n          return !mediaOptionDetails.liveOrEvent || !mediaOptionDetails.ptsKnown || !likelyOutOfDate(mediaOptionDetails === null || mediaOptionDetails === void 0 ? void 0 : mediaOptionDetails.totalduration, 0, lastUpdateMillis);\n      }\n      function getDetailsAndSwitchContext(bufferInfoAction, type, pipelineContext, enabledMediaOptionKeys) {\n          const { rootPlaylistQuery, mediaLibraryService, gaplessInstance, config } = pipelineContext;\n          // Note we don't expect enabled option to change while we're in this hose because of makeAVPipe.\n          const option = enabledMediaOptionKeys[type];\n          const logger = pipelineContext.logger.child({ name: MediaOptionNames[type] });\n          if (!option || option.mediaOptionId === 'Nah') {\n              return of({ detailsEntity: null, switchContext: null });\n          }\n          const playlistQuery = mediaLibraryService.getQueryForOption(option);\n          return combineLatest([\n              of(bufferInfoAction),\n              playlistQuery.mediaOptionDetailsEntity$.pipe(distinctUntilChanged((a, b) => (a === null || a === void 0 ? void 0 : a.lastUpdateMillis) === (b === null || b === void 0 ? void 0 : b.lastUpdateMillis)), filter((mediaOptionDetailsEntity) => {\n                  const mediaOptionDetails = mediaOptionDetailsEntity === null || mediaOptionDetailsEntity === void 0 ? void 0 : mediaOptionDetailsEntity.mediaOptionDetails;\n                  if (!mediaOptionDetails) {\n                      return true; // audio/muxed content\n                  }\n                  const now = performance.now();\n                  const lastUpdateMillis = mediaOptionDetailsEntity.lastUpdateMillis || now;\n                  const liveOrEvent = mediaOptionDetails.liveOrEvent;\n                  const targetDuration = mediaOptionDetails.targetduration;\n                  // logger.info(`playlist updated at ${lastUpdateMillis}, current time is ${now}, delta is ${(now - lastUpdateMillis) / 1000} gt/lt ${2 * targetDuration}`);\n                  // Ensure live mediaOptionDetails is not stale from a previous use of this level.\n                  return !liveOrEvent || now - lastUpdateMillis < config.livePlaylistUpdateStaleness * targetDuration * 1000;\n              })),\n          ]).pipe(filter(([bufferInfoAction, detailsEntity]) => {\n              var _a, _b;\n              logger.info(`details entity ${(_a = detailsEntity === null || detailsEntity === void 0 ? void 0 : detailsEntity.mediaOptionDetails) === null || _a === void 0 ? void 0 : _a.mediaOptionId} updated`);\n              if (type === MediaOptionType.AltAudio && !rootPlaylistQuery.altMediaOptionHasValidUrl(type, option.mediaOptionId)) {\n                  logger.info('manifest may have unused alternate audio options');\n                  return true;\n              }\n              const mediaOptionDetails = detailsEntity === null || detailsEntity === void 0 ? void 0 : detailsEntity.mediaOptionDetails;\n              // Old code tries to save effort by blocking variant if it has already loaded the last segment.\n              // but altAudio may backtrack to media.currentTime when user switches audio.\n              // In which case, hls needs both variant and altaudio to emit getDetailsAndSwitchContext @ media.currentTime\n              // const bufferedSegments = bufferInfoAction.bufferInfoTuple[type]?.bufferedSegments ?? [];\n              return (mediaOptionDetails != null && playlistIsValid(mediaOptionDetails, (_b = detailsEntity.lastUpdateMillis) !== null && _b !== void 0 ? _b : 0)\n              // && (!lastFragmentBuffered(mediaOptionDetails, bufferedSegments, rootPlaylistQuery.itemStartOffset, gaplessInstance.inGaplessMode))\n              );\n          }), take(1), withLatestFrom(rootPlaylistQuery.enabledMediaOptionSwitchContextsByType$(type)), map(([[, detailsEntity], switchContext]) => {\n              var _a, _b, _c;\n              const details = detailsEntity === null || detailsEntity === void 0 ? void 0 : detailsEntity.mediaOptionDetails;\n              if (details) {\n                  const lastFrag = details.fragments[details.fragments.length - 1];\n                  logger.info(`${details.mediaOptionId} got details MSNs:[${details.startSN},${details.endSN}] range=[${(_b = (_a = details.fragments[0]) === null || _a === void 0 ? void 0 : _a.start) === null || _b === void 0 ? void 0 : _b.toFixed(3)},${(_c = ((lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.start) + (lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.duration))) === null || _c === void 0 ? void 0 : _c.toFixed(3)}]`);\n              }\n              return { detailsEntity, switchContext };\n          }));\n      }\n      function chooseAndFetchFragments(logger, fragmentPicker, pipelineContext, action, detailsAndContext) {\n          var _a, _b;\n          const { mediaSink, iframeMachine, rootPlaylistQuery } = pipelineContext;\n          const detailsTuple = [detailsAndContext[MediaOptionType.Variant].detailsEntity.mediaOptionDetails, (_b = (_a = detailsAndContext[MediaOptionType.AltAudio]) === null || _a === void 0 ? void 0 : _a.detailsEntity) === null || _b === void 0 ? void 0 : _b.mediaOptionDetails];\n          let chosenFrags = fragmentPicker.getNextFragments(action, detailsTuple, logger);\n          logger.info(`chosen frags=${JSON.stringify(chosenFrags.map((x) => {\n            var _a;\n            return ({\n                foundFrag: fragPrint((_a = x === null || x === void 0 ? void 0 : x.foundFrag) === null || _a === void 0 ? void 0 : _a.mediaFragment),\n                nextDisco: x === null || x === void 0 ? void 0 : x.nextDisco,\n                newMediaRootTime: x === null || x === void 0 ? void 0 : x.newMediaRootTime,\n            });\n        }))}`);\n          const newMediaRootTime = chosenFrags.reduce((prev, cur) => {\n              return Math.max(prev, isFiniteNumber(cur === null || cur === void 0 ? void 0 : cur.newMediaRootTime) ? cur.newMediaRootTime : -Infinity);\n          }, -Infinity);\n          if (isFiniteNumber(newMediaRootTime)) {\n              logger.info(`seek to newMediaRootTime ${newMediaRootTime}`);\n              mediaSink.seekTo = newMediaRootTime;\n              chosenFrags = [null, null];\n          }\n          if (chosenFrags.every((f) => (f === null || f === void 0 ? void 0 : f.foundFrag) == null)) {\n              return of(null); // no more to produce\n          }\n          return zip(...chosenFrags.map((f, type) => {\n              if (!f || f.foundFrag == null) {\n                  return of(null);\n              }\n              else {\n                  const { mediaFragment } = f.foundFrag;\n                  const prefetchKey$ = loadKey(pipelineContext, mediaFragment.keyTagInfo, { itemId: mediaFragment.itemId, mediaOptionId: mediaFragment.mediaOptionId });\n                  let fetchAndParse$ = retrieveMediaFragmentCacheEntity(pipelineContext, type, f).pipe(tap((sbDataTuple) => {\n                      var _a;\n                      const mediaFragmentCacheEntity = sbDataTuple[1];\n                      const switchContext = detailsAndContext[type].switchContext;\n                      mediaFragmentCacheEntity.switchPosition = switchContext === null || switchContext === void 0 ? void 0 : switchContext.switchPosition;\n                      // if user initiated or rewind rate change\n                      const userInitiated = (_a = switchContext === null || switchContext === void 0 ? void 0 : switchContext.userInitiated) !== null && _a !== void 0 ? _a : false;\n                      const { mediaQuery } = mediaSink;\n                      const { desiredRate, isIframeRate } = mediaQuery;\n                      const rewindRateChange = isIframeRate && iframeMachine.isStarted && desiredRate && desiredRate < 0 && desiredRate !== iframeMachine.iframeRate;\n                      if (userInitiated || rewindRateChange) {\n                          logger.info(`creating flushBeforeAppend > userInitiated=${userInitiated}, rewindRateChange=${rewindRateChange} :: iframeMachine.isStarted=${iframeMachine.isStarted}, iframeMachine.iframeRate=${iframeMachine.iframeRate}, desiredRate=${desiredRate}`);\n                          mediaFragmentCacheEntity.flushBeforeAppend = { start: 0, end: Number.POSITIVE_INFINITY };\n                      }\n                  }));\n                  // UpdatePTSDTS is expensive on startup\n                  // try to parallelize with key request and/or fragment request\n                  if (type === MediaOptionType.Variant) {\n                      fetchAndParse$ = fetchAndParse$.pipe(tap((sbData) => {\n                          const initPTSInfo = updateInitPTS(logger, pipelineContext, sbData, fragmentPicker.discoSeqNum);\n                          updatePTSDTS(logger, pipelineContext, sbData, initPTSInfo);\n                      }));\n                  }\n                  else {\n                      const initPTSInfo$ = waitFor(rootPlaylistQuery.initPTS$(fragmentPicker.discoSeqNum), (initPTSInfo) => {\n                          const iframeMode = mediaSink.mediaQuery.isIframeRate;\n                          return initPTSInfo != null && (iframeMode || !initPTSInfo.iframeMode);\n                      });\n                      fetchAndParse$ = forkJoin([fetchAndParse$, initPTSInfo$]).pipe(map(([sbData, initPTSInfo]) => {\n                          updatePTSDTS(logger, pipelineContext, sbData, initPTSInfo);\n                          return sbData;\n                      }));\n                  }\n                  return forkJoin([prefetchKey$, fetchAndParse$]).pipe(map((res) => res[1]));\n              }\n          })).pipe(map((sbDataTuple) => getConsumerInput(logger, pipelineContext, fragmentPicker.discoSeqNum, sbDataTuple)), switchMap((consumerInput) => {\n              if (!consumerInput) {\n                  // Potentially dangerous (unbounded loop) if we keep selecting the same fragment\n                  logger.info('Attempting fragment reselection because of complete overlap with updated details');\n                  const updatedDetailsAndContext = getUpdatedDetailsAndContext(rootPlaylistQuery, detailsAndContext, logger);\n                  return chooseAndFetchFragments(logger, fragmentPicker, pipelineContext, action, updatedDetailsAndContext);\n              }\n              return of(consumerInput);\n          }));\n      }\n      function getUpdatedDetailsAndContext(rootPlaylistQuery, detailsAndContext, logger) {\n          const enabledMediaKeys = rootPlaylistQuery.enabledMediaOptionKeys;\n          const updatedDetailsAndContext = [null, null];\n          const detailsInfo = [null, null];\n          AVMediaOptionTypes.map((type) => {\n              var _a, _b;\n              if (isEnabledMediaOption(enabledMediaKeys[type])) {\n                  const libraryQuery = createMediaLibraryQuery(enabledMediaKeys[type]);\n                  const detailsEntity = libraryQuery.mediaOptionDetailsEntity;\n                  detailsInfo[type] = (_a = detailsEntity.mediaOptionDetails) === null || _a === void 0 ? void 0 : _a.ptsKnown;\n                  updatedDetailsAndContext[type] = { detailsEntity, switchContext: (_b = detailsAndContext[type]) === null || _b === void 0 ? void 0 : _b.switchContext };\n              }\n          });\n          logger.info(`retrieve updated details entity ${JSON.stringify(detailsInfo)}`);\n          return updatedDetailsAndContext;\n      }\n      /**\n       * Update initPTS info\n       * @param vTuple the parsed fragment information for the variant\n       */\n      function updateInitPTS(logger, pipelineContext, vTuple, activeDiscoSeqNum) {\n          var _a, _b, _c;\n          if (!vTuple) {\n              return null;\n          }\n          const { rootPlaylistService: rootService, rootPlaylistQuery: rootQuery } = pipelineContext;\n          const itemId = rootQuery.itemId;\n          const variantData = vTuple[1];\n          const fragIsIframe = variantData.iframe;\n          // Favor non-iframe initPTS if available\n          let initPTSInfo = rootQuery.getInitPTS(activeDiscoSeqNum);\n          if (initPTSInfo == null || (!fragIsIframe && initPTSInfo.iframeMode)) {\n              const variantDTS = (_a = variantData.startDtsTs) !== null && _a !== void 0 ? _a : null;\n              if (variantDTS == null) {\n                  logger.warn('updateInitPTS: Variant data missing.');\n                  return null;\n              }\n              let timelineOffset = (_b = variantData.timelineOffset) !== null && _b !== void 0 ? _b : 0;\n              if (fragIsIframe) {\n                  logger.info(`updateInitPTS: initPTS timelineOffset is appendData iframeOriginalStart ${vTuple[1].iframeOriginalStart}`);\n                  timelineOffset = (_c = variantData.iframeOriginalStart) !== null && _c !== void 0 ? _c : 0;\n              }\n              else {\n                  logger.info(`updateInitPTS: initPTS timelineOffset is appendData timelineOffset ${vTuple[1].timelineOffset}`);\n              }\n              if (variantDTS.timescale < 1000) {\n                  // this scaleup is especially useful when traversing 23.976/24 fps discos\n                  variantDTS.timescale = variantDTS.timescale * 1000;\n                  variantDTS.baseTime = variantDTS.baseTime * 1000;\n              }\n              const playlistTS = convertSecondsToTimestamp(timelineOffset, variantDTS.timescale);\n              const offsetTimestamp = { baseTime: variantDTS.baseTime - playlistTS.baseTime, timescale: variantDTS.timescale };\n              logger.info(`initPTS[${activeDiscoSeqNum}] ${JSON.stringify({ variantDTS, timelineOffset, offsetTimestamp, fragIsIframe })}`);\n              rootService.setInitPTS(itemId, activeDiscoSeqNum, variantDTS, timelineOffset, offsetTimestamp, fragIsIframe);\n              initPTSInfo = { variantDTS, timelineOffset, offsetTimestamp, iframeMode: fragIsIframe };\n          }\n          return initPTSInfo;\n      }\n      function updatePTSDTS(logger, pipelineContext, sbData, initPTSInfo) {\n          const { mediaLibraryService, rootPlaylistQuery, mediaSink } = pipelineContext;\n          const itemId = rootPlaylistQuery.itemId;\n          if (initPTSInfo == null) {\n              return;\n          }\n          // Don't update if we're in normal playback and we have an i-frame initPTS\n          const curIframeMode = mediaSink.mediaQuery.isIframeRate;\n          if (!curIframeMode && initPTSInfo.iframeMode) {\n              logger.warn('updatePTSDTS iframeMode mismatch');\n              return;\n          }\n          // Update playlist offsets. Never update for main in i-frame mode\n          if (sbData && !isFiniteNumber(sbData[1].iframeMediaDuration)) {\n              const tstart = performance.now();\n              mediaLibraryService.updatePTSDTS(itemId, sbData[1].mediaOptionId, initPTSInfo, sbData[1]);\n              logger.info(`updatePTSDTS took ${Math.round(performance.now() - tstart)}ms`);\n          }\n      }\n      function getConsumerInput(logger, pipelineContext, activeDiscoSeqNum, sbDataTuple) {\n          const { rootPlaylistQuery: rootQuery, mediaSink, config } = pipelineContext;\n          const mediaQuery = mediaSink.mediaQuery;\n          const iframeMode = mediaQuery.isIframeRate;\n          const initPTSInfo = rootQuery.getInitPTS(activeDiscoSeqNum);\n          if (initPTSInfo == null) {\n              logger.warn('No initPTS info found');\n              return null;\n          }\n          const variantData = sbDataTuple[MediaOptionType.Variant];\n          const variantFragData = variantData === null || variantData === void 0 ? void 0 : variantData[1];\n          if (variantFragData && variantFragData.iframe !== iframeMode) {\n              logger.warn(`frag mediaSeqNum ${variantFragData.mediaSeqNum} discoSeqNum ${variantFragData.discoSeqNum} mediaOptionId ${variantFragData.mediaOptionId} doesn't match mediaSink's iframeMode ${iframeMode}; discard`);\n              return null; // repick frag since the parsed one doesn't match mediaSink's iframe mode\n          }\n          // Build output\n          const appendDataTuple = [null, null];\n          if (variantData) {\n              const [initSeg, dataSeg] = variantData;\n              let offsetTimestamp = initPTSInfo.offsetTimestamp;\n              if (iframeMode) {\n                  // Always offset video\n                  const dts = dataSeg.startDtsTs;\n                  const timelineOffset = dataSeg.timelineOffset;\n                  const playlistTS = convertSecondsToTimestamp(timelineOffset, dts.timescale);\n                  offsetTimestamp = { baseTime: dts.baseTime - playlistTS.baseTime, timescale: dts.timescale };\n              }\n              appendDataTuple[SourceBufferType.Variant] = { initSeg, dataSeg, offsetTimestamp };\n          }\n          const audioData = sbDataTuple[MediaOptionType.AltAudio];\n          if (audioData != null) {\n              const [initSeg, dataSeg] = audioData;\n              appendDataTuple[SourceBufferType.AltAudio] = { initSeg, dataSeg, offsetTimestamp: initPTSInfo.offsetTimestamp };\n          }\n          // Update in flight fragments\n          const inFlightFrags = appendDataTuple.map((data, type) => {\n              var _a, _b;\n              const dataSeg = data === null || data === void 0 ? void 0 : data.dataSeg;\n              if (dataSeg) {\n                  const { itemId, mediaOptionId, mediaSeqNum, discoSeqNum, startPts, endPts, duration, iframe } = dataSeg;\n                  const { offsetTimestamp } = data;\n                  const startPTSSec = diffSeconds(startPts, offsetTimestamp);\n                  const endPTSSec = diffSeconds(endPts, offsetTimestamp);\n                  const libraryQuery = createMediaLibraryQuery(dataSeg);\n                  logger.info(`${MediaOptionNames[type]} aboutToAppend iframe:${dataSeg.iframeMediaDuration != null} ${stringifyWithPrecision({\n                    mediaOptionId,\n                    mediaSeqNum,\n                    discoSeqNum,\n                    offsetTimestamp,\n                    startPTSSec,\n                    endPTSSec,\n                    startPts,\n                    endPts,\n                })} buffered:${stringifyWithPrecision(mediaQuery.getBufferedRangeByType(type))}`);\n                  const videoSegment = appendDataTuple[0];\n                  const noDroppedFrames = !videoSegment || !videoSegment.dataSeg.dropped;\n                  if (noDroppedFrames && !dataSeg.flushBeforeAppend && ((_b = (_a = mediaQuery.getBufferInfo(startPTSSec, config.maxBufferHole)[type]) === null || _a === void 0 ? void 0 : _a.buffered) === null || _b === void 0 ? void 0 : _b.len) >= endPTSSec - startPTSSec) {\n                      logger.warn(`${MediaOptionNames[type]} Discarding append due to complete overlap with existing buffer`);\n                      appendDataTuple[type] = null;\n                      return null;\n                  }\n                  return {\n                      start: startPTSSec,\n                      duration: iframe ? duration : endPTSSec - startPTSSec,\n                      itemId,\n                      mediaOptionId,\n                      mediaSeqNum,\n                      discoSeqNum,\n                      targetDuration: libraryQuery.mediaOptionDetails.targetduration,\n                  };\n              }\n              return null;\n          });\n          if (inFlightFrags.every((f) => !f)) {\n              return null;\n          }\n          return { appendDataTuple, inFlightFrags, initPTSInfo };\n      }\n      /**\n       * @brief The media consumer side\n       * transform consumerInput to boolean indicating whether we actually appended anything\n       */\n      const mediaConsumerEpic = (context) => (consumerInput) => {\n          const { rootPlaylistQuery: rootQuery, rootPlaylistService: rootService, mediaSink, legibleSystemAdapter, statsService, rtcService } = context;\n          return consumerInput.pipe(tag('mediaConsumerEpic.in'), \n          // Do Append\n          switchMap((appendData) => {\n              if (!appendData) {\n                  return of(false);\n              }\n              const { appendDataTuple, inFlightFrags, initPTSInfo } = appendData;\n              const { offsetTimestamp } = initPTSInfo;\n              inFlightFrags.forEach((frag, type) => {\n                  if (frag) {\n                      rootService.updateInflightFrag(frag.itemId, type, frag, 'appending', null);\n                  }\n              });\n              // Pass rootQuery.itemStartOffset into appendData.\n              // add samples based on captiondata\n              appendDataTuple.forEach((sbAppendData) => {\n                  if (sbAppendData) {\n                      const dataSeg = sbAppendData.dataSeg;\n                      legibleSystemAdapter.addLegibleSamples(offsetTimestamp, dataSeg.captionData, dataSeg.id3Samples, dataSeg.endPts);\n                  }\n              });\n              return mediaSink\n                  .appendData(appendDataTuple, (sbAdapter, mediaOptionType, mediaOptionId, config, meQuery) => {\n                  var _a;\n                  const targetDuration = (_a = inFlightFrags[mediaOptionType].targetDuration) !== null && _a !== void 0 ? _a : 10;\n                  return addAppendErrorHandlingPolicy(mediaSink, sbAdapter, mediaOptionType, mediaOptionId, targetDuration, config, rootQuery, rootService, meQuery);\n              }, rootQuery.highestVideoCodec)\n                  .pipe(map((metrics) => {\n                  var _a, _b;\n                  inFlightFrags.forEach((frag, type) => {\n                      if (frag) {\n                          rootService.updateInflightFrag(frag.itemId, type, frag, 'appended', null);\n                      }\n                  });\n                  const metric = metrics.filter((metric) => (metric === null || metric === void 0 ? void 0 : metric.fragmentType) === MediaOptionType.Variant);\n                  if (metric.length) {\n                      statsService.setBufferMetric(metric[0]);\n                      rtcService === null || rtcService === void 0 ? void 0 : rtcService.handleFragBuffered(metric[0]);\n                  }\n                  const audioAppendData = appendDataTuple[SourceBufferType.AltAudio];\n                  if (((_a = audioAppendData === null || audioAppendData === void 0 ? void 0 : audioAppendData.dataSeg) === null || _a === void 0 ? void 0 : _a.flushBeforeAppend) || isFiniteNumber((_b = audioAppendData === null || audioAppendData === void 0 ? void 0 : audioAppendData.dataSeg) === null || _b === void 0 ? void 0 : _b.switchPosition)) {\n                      const { itemId, mediaOptionId } = audioAppendData.dataSeg;\n                      rootService.setEnabledMediaOptionSwitchContextByType(itemId, MediaOptionType.AltAudio, mediaOptionId, undefined);\n                  }\n                  return true;\n              }), addCreateSourceBufferErrorHandlingPolicy(mediaSink, rootService, rootQuery));\n          }));\n      };\n    \n      /**\n       * Convert seek to date values into media position seeks\n       */\n      /**\n       * @brief Get the media time for a given date\n       * @param dateMediaTimeTuple  DateTimeMs, mediaTimeSec pairs sorted in ascending order\n       * @param searchDate date to resolve\n       * @returns media position. 0 if earlier than beginning of playlist\n       */\n      function resolveDateToPTS(dateMediaTimeTuple, searchDate) {\n          var _a;\n          if (!dateMediaTimeTuple || dateMediaTimeTuple.length === 0) {\n              return 0;\n          }\n          // Scan for the max startDateTime that is smaller than the searchDate\n          const descendingTuple = [...dateMediaTimeTuple].sort((a, b) => b[0] - a[0]);\n          const searchDt = searchDate.getTime();\n          const closest = (_a = descendingTuple.find(([dt]) => searchDt >= dt)) !== null && _a !== void 0 ? _a : descendingTuple[descendingTuple.length - 1];\n          const [closestDt, startPTSSec] = closest;\n          const resolvedTime = startPTSSec + (searchDt - closestDt) / 1000;\n          return Math.max(0, resolvedTime);\n      }\n      /**\n       * @brief Get the date for a given position in media\n       * @param dateMediaTimeTuple  DateTimeMs, mediaTimeSec pairs sorted in ascending order\n       * @param ptsSeconds time in media seconds\n       * @returns Date associated with this time. undefined if no date available\n       */\n      function resolvePTSToDate(dateMediaTimeTuple, ptsSeconds) {\n          var _a;\n          if (!dateMediaTimeTuple || dateMediaTimeTuple.length === 0) {\n              return undefined;\n          }\n          const descendingTuple = [...dateMediaTimeTuple].sort((a, b) => b[1] - a[1]);\n          const closest = (_a = descendingTuple.find(([_, mediaTime]) => ptsSeconds >= mediaTime)) !== null && _a !== void 0 ? _a : descendingTuple[descendingTuple.length - 1];\n          const [closestDt, startPTSSec] = closest;\n          const resolvedDate = new Date(closestDt + (ptsSeconds - startPTSSec) * 1000);\n          return resolvedDate;\n      }\n      function resolveSeekToDateAsync(seekTo, rootQuery, libService) {\n          return rootQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(switchMap((option) => {\n              return libService.getQueryForOption(option).mediaOptionDetails$;\n          }), map((details) => resolveDateToPTS(details.dateMediaTimePairs, seekTo)), take(1));\n      }\n      /**\n       * Return seek position within media\n       * @param seekTo\n       * @param rootPlaylistQuery\n       * @returns\n       */\n      function resolveSeekToAsync(seekTo, isFirstSeek, config, rootPlaylistQuery, libService, logger) {\n          // seekTo value meanings:\n          // non-finite = auto seek position. LIVE: live edge, VOD: startTimeOffset if available or start of item\n          // 0 = if (LIVE && liveEdgeForZeroStartPositon), live edge, else 0\n          // positive = position in media timeline\n          // negative = LIVE: live edge, VOD: position relative to end of playlist\n          let resolvedSeekTo$ = rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(switchMap((variant) => libService.getQueryForOption(variant).mediaOptionDetails$), filter((details) => isFiniteNumber(details === null || details === void 0 ? void 0 : details.totalduration)), take(1), map((details) => {\n              const hasEndTag = !details.liveOrEvent;\n              const totalDuration = details.totalduration;\n              const itemStartOffset = rootPlaylistQuery.itemStartOffset;\n              if (hasEndTag) {\n                  if (!isFiniteNumber(seekTo)) {\n                      const offset = isFiniteNumber(details.startTimeOffset) ? details.startTimeOffset : 0;\n                      return itemStartOffset + offset;\n                  }\n                  else if (seekTo >= 0) {\n                      // seekTo positive values are never pending\n                      // seekTo 0 is pending only when liveEdgeForZeroStartPositon is opted in\n                      return seekTo;\n                  }\n                  else {\n                      // seekTo negative values\n                      const offset = totalDuration + seekTo;\n                      return itemStartOffset + offset;\n                  }\n              }\n              else {\n                  // live and event (no EXT-X-END tag)\n                  if (!isFiniteNumber(seekTo) || seekTo < 0 || (seekTo === 0 && config.liveEdgeForZeroStartPositon)) {\n                      // catch up to live edge\n                      return computeLivePosition(0, details, config, logger);\n                  }\n                  else {\n                      // isFinite(seekTo) && seekTo >= 0 && (seekTo !== 0 || !liveEdgeForZeroStartPosition)\n                      // sanitize seek value\n                      return sanitizeLiveSeek(seekTo, details, config, logger);\n                  }\n              }\n          }));\n          if (isFirstSeek) {\n              resolvedSeekTo$ = resolvedSeekTo$.pipe(tap((seekTo) => {\n                  logger.qe({ critical: true, name: 'initialSeekSet', data: { seekTo, source: 'rootPlaylistQuery.pendingSeek' } });\n              }));\n          }\n          return resolvedSeekTo$;\n      }\n      /**\n       * Epic that just updates pending seek in active item from hls service.\n       * @param rootQuery\n       * @param libService\n       * @returns\n       */\n      function userSeekEpic(itemQueue, rootService) {\n          return (userSeek$) => userSeek$.pipe(filterNullOrUndefined(), switchMap((seekTo) => forkJoin([\n              of(seekTo),\n              itemQueue.activeItemById$.pipe(filterNullOrUndefined(), switchMap((entity) => {\n                  return rootService.getQueryForId(entity.itemId).rootPlaylistEntity$;\n              }), take(1)),\n          ])), map(([seekTo, activeItem]) => {\n              rootService.setPendingSeek(activeItem.itemId, seekTo);\n              return seekTo;\n          }));\n      }\n      /**\n       * Epic that handles requested seeks made to the current active item and\n       * then updates mediaSink position. Expected to be subscribed on active item change\n       *\n       * @param config      configuration for seek resolution\n       * @param logger      logger object\n       * @param mediaSink   MediaSink object\n       * @param rootQuery   Query for the active item\n       * @param libService  Media library service\n       * @returns\n       */\n      function pendingSeekEpic(config, logger, mediaSink, rootService, rootQuery, libService) {\n          logger = logger.child({ name: 'seek' });\n          return (pendingSeek$) => pendingSeek$.pipe(switchMap((pendingSeek, index) => {\n              if (pendingSeek == null) {\n                  return EMPTY;\n              }\n              logger.info(`got pendingSeek=${pendingSeek}`);\n              const gotNewerSeek$ = mediaSink.mediaQuery.seekTo$.pipe(skip(1), // seekTo$ always emits the active seekTo value to new subscribers (which is populated while seeking, null otherwise)\n              filterNullOrUndefined());\n              return resolveSeek(pendingSeek, index === 0, config, logger, rootQuery, libService).pipe(finalize$1(() => {\n                  rootService.setPendingSeek(rootQuery.itemId, undefined);\n              }), takeUntil(gotNewerSeek$));\n          }), tap((pendingSeek) => {\n              logger.info(`resolved pendingSeek=${pendingSeek}`);\n              if (isFiniteNumber(pendingSeek)) {\n                  mediaSink.seekTo = pendingSeek;\n              }\n          }));\n      }\n      function resolveSeek(seekTo, isFirst, config, logger, rootQuery, libService) {\n          if (seekTo == null) {\n              return EMPTY;\n          }\n          if (seekTo instanceof Date) {\n              return resolveSeekToDateAsync(seekTo, rootQuery, libService);\n          }\n          else {\n              return resolveSeekToAsync(seekTo, isFirst, config, rootQuery, libService, logger);\n          }\n      }\n    \n      function updateEnabledMediaOptionsAsync(rootPlaylistService, itemId) {\n          return timer(0).pipe(map(() => {\n              rootPlaylistService.logger.debug(`[updateEnabledMediaOptions] itemId ${itemId}`);\n              rootPlaylistService.updateEnabledMediaOptions(itemId);\n          }));\n      }\n      /**\n       * Handle end of the pipeline error. Update the media options as needed based\n       * on nextMediaOptionsKeys (updated by ErrorHandlingPolicies)\n       *\n       * Should always be the last operator.\n       */\n      function mediaPipelineHandleError(pipelineContext) {\n          const { logger, rootPlaylistService, rootPlaylistQuery } = pipelineContext;\n          const itemId = rootPlaylistQuery.itemId;\n          return (source) => source.pipe(retryWhen((errors) => errors.pipe(mergeMap((err) => {\n              logger.error(`Got error in pipeline ${err.message} fatal:${err === null || err === void 0 ? void 0 : err.fatal} handled:${err === null || err === void 0 ? void 0 : err.handled}`);\n              if (!(err instanceof HlsError) || err.fatal) {\n                  throw err;\n              }\n              if (!err.handled) {\n                  return EMPTY; // Do nothing, wait for next emit\n              }\n              // Not fatal, we can re-subscribe to source after updating media options\n              return updateEnabledMediaOptionsAsync(rootPlaylistService, itemId);\n          }))));\n      }\n      /**\n       * Core fetch and append epic.  Listens to what details are available from the playlist service,\n       * and the playback and buffering state from the mediaPlaybackService.  It can respond to either\n       * by changing downloading fragments or initiating track switching.\n       *\n       * store with these selections\n       * @param mediaPlaybackService\n       * @param config Configuration needed load and playback\n       */\n      const mediaFragmentPipelineEpic = () => (pipelineActionSource$) => {\n          return pipelineActionSource$.pipe(tag('mediaFragmentPipelineEpic.in'), switchMap((pipelineContext) => {\n              if (!pipelineContext) {\n                  return EMPTY;\n              }\n              const { logger, config, platformService, rootPlaylistService, rootPlaylistQuery, keySystemAdapter, mediaSink, mediaParser, gaplessInstance, mediaLibraryService } = pipelineContext;\n              const { itemId } = rootPlaylistQuery;\n              const { mediaQuery } = mediaSink;\n              logger.info(`mediaFragmentPipelineEpic start ${itemId}`);\n              const keyStatusChange$ = keySystemAdapter.keyStatusChange$.pipe(keyStatusChangeEpic(pipelineContext));\n              const platformQuery = platformService.getQuery();\n              const displayChange$ = platformQuery.displaySupportsHdr$.pipe(distinctUntilChanged(), switchMap((capable) => {\n                  logger.info(`hdr display change=${capable}`);\n                  rootPlaylistService.setHDRPreference(itemId, capable, true);\n                  return EMPTY;\n              }));\n              const viewPortChange$ = platformQuery.viewportInfo$.pipe(distinctUntilChanged((a, b) => a && b && a.width === b.width && a.height === b.height), tap((viewportInfo) => {\n                  logger.info(`viewport change=${JSON.stringify(viewportInfo)}, useViewportSizeForLevelCap: ${config.useViewportSizeForLevelCap}`);\n                  if (config.useViewportSizeForLevelCap) {\n                      rootPlaylistService.setViewportInfo(itemId, viewportInfo);\n                  }\n              }), switchMapTo(EMPTY));\n              const needsMediaReset$ = combineQueries([rootPlaylistQuery.hdrMode$.pipe(distinctUntilChanged()), rootPlaylistQuery.maxHdcpLevel$.pipe(distinctUntilChanged())]).pipe(switchMap(([hdrMode, maxHdcpLevel]) => {\n                  logger.info(`hdrMode=${hdrMode} maxHdcpLevel=${maxHdcpLevel}`);\n                  // if not in gapless mode and the current item is not offset on the timeline, reset the media source\n                  if (!gaplessInstance.inGaplessMode && rootPlaylistQuery.itemStartOffset === 0) {\n                      mediaSink.resetMediaSource();\n                      mediaParser.reset();\n                  }\n                  return EMPTY;\n              }));\n              // Register this separately so errors here that may be recovered don't cause us to re-subscribe to the platform updates\n              const mediaPipes$ = merge(\n              // prettier-ignore\n              handleEnabledMediaOptions(pipelineContext), makeAVPipe(pipelineContext), makeSubtitlePipe(pipelineContext), keyStatusChange$).pipe(\n              // This updates enabled media options whenever an emit happens\n              mapTo(undefined), mediaPipelineHandleError(pipelineContext));\n              const anchor$ = mediaQuery.seekTo$.pipe(filter((seekTo) => isFiniteNumber(seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos)), distinctUntilChanged((a, b) => Math.abs(a.pos - b.pos) < Number.EPSILON), // Can choose different threshold\n              switchMap((anchorTime) => {\n                  rootPlaylistService.setAnchorTime(itemId, anchorTime);\n                  return EMPTY;\n              }));\n              // Non-functional, Logs compatible levels after playback starts\n              const logCompatibleLevels$ = mediaQuery.gotPlaying$.pipe(filter((playing) => playing), tap((_) => {\n                  const mediaOptionQuery = rootPlaylistQuery.mediaOptionListQueries[MediaOptionType.Variant];\n                  const compatibleMediaLevels = mediaOptionQuery.filteredMediaOptionList;\n                  logger.qe({ critical: true, name: 'compatibleLevels', data: { numLevels: compatibleMediaLevels.length } });\n                  compatibleMediaLevels.forEach((level) => {\n                      const { mediaOptionId, bandwidth, bitrate, videoCodec, audioCodec, height, width, videoRange, iframes } = level;\n                      logger.qe({ critical: true, name: 'manifestLevel', data: { mediaOptionId, bandwidth, bitrate, videoCodec, audioCodec, height, width, videoRange, iframes } });\n                  });\n              }), take(1), switchMapTo(EMPTY));\n              return merge(\n              // Seeking / position adjustments\n              rootPlaylistQuery.pendingSeek$.pipe(pendingSeekEpic(config, logger, mediaSink, rootPlaylistService, rootPlaylistQuery, mediaLibraryService)), ensurePlaybackWithinWindow(pipelineContext), // Adjust position within live window\n              anchor$, \n              // Download pipe\n              mediaPipes$, \n              // Following observables monitor state changes that may modify enabled media options\n              displayChange$, viewPortChange$, needsMediaReset$, desiredRateChange(pipelineContext), capToEnabledIframeOption(pipelineContext), logCompatibleLevels$).pipe(tag('mediaFragmentPiplineEpic.emit'), mapTo(undefined));\n          }));\n      };\n      /**\n       * update expected SbCount and load all media playlists\n       */\n      function handleEnabledMediaOptions(pipelineContext) {\n          const { logger, rootPlaylistQuery, mediaSink } = pipelineContext;\n          const updateExpectedSbCount$ = rootPlaylistQuery.enabledMediaOptions$.pipe(filterNullOrUndefined(), tap((enabledOptions) => {\n              const altAudio = enabledOptions[MediaOptionType.AltAudio];\n              const expectedSbCount = isEnabledMediaOption(altAudio) && (altAudio === null || altAudio === void 0 ? void 0 : altAudio.url) != null ? 2 : 1;\n              mediaSink.setExpectedSbCount(expectedSbCount);\n          }));\n          const setBufferTargetDuration$ = forkJoin([\n              rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(filter((option) => isEnabledMediaOption(option)), switchMap((option) => {\n                  const query = createMediaLibraryQuery(option);\n                  return query.mediaOptionDetails$;\n              }), take(1) // Just update on first load. Target duration should be consistent across variants\n              ),\n              waitFor(mediaSink.mediaQuery.updating$, (x) => x), // On startup don't need to do this immediately\n          ]).pipe(observeOn(asyncScheduler), tap(([details]) => {\n              mediaSink.bufferMonitorTargetDuration = details.targetduration;\n          }));\n          const loadMediaOptions = MediaOptionTypes.map((mediaOptionType) => {\n              return rootPlaylistQuery.enabledMediaOptionByType$(mediaOptionType).pipe(tag('mediaOptionRetrieve.switch'), switchMap((option) => {\n                  if (!option || !option.url || !isEnabledMediaOption(option)) {\n                      return EMPTY;\n                  }\n                  const allowRefresh$ = mediaSink.mediaQuery.desiredRate$.pipe(map((rate) => rate !== 0), distinctUntilChanged());\n                  // always request first copy. this will either return cached value or request from server\n                  return retrieveMediaOptionDetails(pipelineContext, option).pipe(tag('mediaOptionRetrieve.first'), switchMapTo(allowRefresh$), switchMap((allowRefresh) => {\n                      if (!allowRefresh) {\n                          return EMPTY; // Don't refresh while in pause\n                      }\n                      // refresh\n                      return refreshMediaOptionDetails(pipelineContext, option);\n                  }));\n              }));\n          });\n          return merge(updateExpectedSbCount$, setBufferTargetDuration$, merge(...loadMediaOptions)).pipe(switchMapTo(EMPTY));\n      }\n      function makeSubtitlePipe(pipelineContext) {\n          const { rootPlaylistQuery, mediaSink } = pipelineContext;\n          const mediaQuery = mediaSink.mediaQuery;\n          return waitFor(mediaQuery.mediaElementEntity$, (entity) => entity).pipe(switchMap((_) => {\n              return rootPlaylistQuery.anchorTime$.pipe(tag('anchorTime.subtitle.in'), filter((anchorTime) => isFiniteNumber(anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos)), subtitleSelectionEpic(pipelineContext), subtitleLoadAndProcessEpic(pipelineContext));\n          }));\n      }\n      function keyStatusChangeEpic(keyLoadContext) {\n          return (source) => source.pipe(switchMap((event) => {\n              const { decryptdata, status, error } = event;\n              const { rootPlaylistQuery } = keyLoadContext;\n              if (status === 'needs-renewal') {\n                  return loadKey(keyLoadContext, decryptdata, null);\n              }\n              else if (status === 'error' && (error instanceof KeyRequestError || error instanceof KeyRequestTimeoutError) && !error.handled) {\n                  // Don't actually retry, we're just doing penalty box stuff and updating enabled options\n                  const { rootPlaylistService, keySystemAdapter } = keyLoadContext;\n                  return handleKeyError(error, 0, null, rootPlaylistService, rootPlaylistQuery, keySystemAdapter.ksQuery);\n              }\n              return EMPTY;\n          }), switchMap(() => EMPTY));\n      }\n      /**\n       * @brief subtitle selection\n       */\n      const subtitleSelectionEpic = (pipelineContext) => (anchorTimeSource$) => {\n          const { rootPlaylistQuery, rootPlaylistService, legibleSystemAdapter } = pipelineContext;\n          // setup HTML5 texttracks\n          const enabledMediaOption = rootPlaylistQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle);\n          if (!legibleSystemAdapter.gotTracks) {\n              const availableAlternateMediaOptions = rootPlaylistQuery.preferredMediaOptions[MediaOptionType.Subtitle];\n              legibleSystemAdapter.setTracks(availableAlternateMediaOptions, enabledMediaOption, rootPlaylistQuery.getDisabledMediaOption(MediaOptionType.Subtitle));\n          }\n          else {\n              legibleSystemAdapter.selectedTrack = enabledMediaOption;\n          }\n          return anchorTimeSource$.pipe(tag('subtitleEpic.select.in'), switchMap(() => {\n              return merge(legibleSystemAdapter.nativeSubtitleTrackChange$.pipe(\n              // mediaOption selected via native media element video controller UI\n              switchMap((mediaOption) => {\n                  if (mediaOption.mediaOptionId !== legibleSystemAdapter.selectedMediaOption.mediaOptionId) {\n                      rootPlaylistService.setEnabledMediaOptionByType(mediaOption.itemId, MediaOptionType.Subtitle, mediaOption);\n                  }\n                  return EMPTY;\n              })), rootPlaylistQuery\n                  .enabledMediaOptionByType$(MediaOptionType.Subtitle)\n                  .pipe(\n              // mediaOption selected via hls.js API\n              map((option) => {\n                  // option may be null initially\n                  const altMediaOption = isEnabledMediaOption(option) ? rootPlaylistQuery.alternateMediaOptionById(MediaOptionType.Subtitle, option.mediaOptionId) : option;\n                  legibleSystemAdapter.selectedMediaOption = altMediaOption;\n                  return altMediaOption;\n              }))\n                  .pipe(distinctUntilChanged((a, b) => {\n                  return (a === null || a === void 0 ? void 0 : a.mediaOptionId) === (b === null || b === void 0 ? void 0 : b.mediaOptionId);\n              })));\n          }), tag('subtitleEpic.select.emit'));\n      };\n      const loadOneSubtitleFrag = (pipelineContext, initPTS, loadingFrag) => {\n          const { rootPlaylistQuery, legibleSystemAdapter } = pipelineContext;\n          return defer(() => {\n              return retrieveSubtitleFragmentCacheEntity(pipelineContext, initPTS, loadingFrag).pipe(map(({ initPTS, data, mediaFragment }) => {\n                  const enabledAltMediaOption = rootPlaylistQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle);\n                  const parsedCueRecord = processSubtitlePayload(enabledAltMediaOption, mediaFragment, initPTS, data, legibleSystemAdapter);\n                  return { frag: mediaFragment, cueRange: parsedCueRecord };\n              }));\n          });\n      };\n      const loadSubtitleBatch = (pipelineContext, initPTS, findFragsResult, details) => {\n          const legibleServiceAdapter = pipelineContext.legibleSystemAdapter;\n          const nextFrags = findFragsResult.foundFrags;\n          return from(nextFrags).pipe(\n          // emit next frags to load in a sequence\n          map((frag) => {\n              return loadOneSubtitleFrag(pipelineContext, initPTS, frag).pipe(delayWhen((parsedFragResult) => {\n                  return legibleServiceAdapter.checkReadyToLoadNextSubtitleFragment$(frag, nextFrags).pipe(filter((x) => x));\n              }));\n          }), mergeAll(pipelineContext.config.vttConcurrentLoadCount), tap((parsedFragResult) => {\n              if (legibleServiceAdapter.reviewParsedFrag(parsedFragResult, findFragsResult, details) !== ParsedFragQuality.CloseEnough) {\n                  // may be too far from target frag. find another frag based on newly parsed cues\n                  pipelineContext.legibleSystemAdapter.tryAgain$.next(true);\n              }\n          }));\n      };\n      const loadSubtitleInDiscontinuity = (pipelineContext, details, activeSeqNum) => {\n          const { legibleSystemAdapter, rootPlaylistQuery } = pipelineContext;\n          return rootPlaylistQuery.initPTS$(activeSeqNum).pipe(switchMap((initPTS) => {\n              if (!initPTS || initPTS.iframeMode) {\n                  return NEVER;\n              }\n              return legibleSystemAdapter.findFrags$(details, activeSeqNum).pipe(switchMap((findFragsResult) => {\n                  if (!details || !(findFragsResult === null || findFragsResult === void 0 ? void 0 : findFragsResult.foundFrags))\n                      return VOID;\n                  return loadSubtitleBatch(pipelineContext, initPTS.offsetTimestamp, findFragsResult, details);\n              }));\n          }));\n      };\n      /**\n       * @brief subtitle loading & processing\n       */\n      const subtitleLoadAndProcessEpic = (pipelineContext) => (bufferInfoSource$) => {\n          const { mediaSink, rootPlaylistQuery, legibleSystemAdapter, logger } = pipelineContext;\n          return bufferInfoSource$.pipe(tag('subtitleEpic.process.in'), switchMap((option) => {\n              if (!option || !option.url || !isEnabledMediaOption(option)) {\n                  return of([null, null, null]);\n              }\n              const mediaLibraryQuery = createMediaLibraryQuery(option);\n              const details$ = mediaLibraryQuery.mediaOptionDetails$;\n              const activeDiscoSeqNum$ = rootPlaylistQuery.discoSeqNum$.pipe(filter((sn) => isFiniteNumber(sn)));\n              return combineQueries([details$, activeDiscoSeqNum$]).pipe(switchMap(([details, activeSeqNum]) => {\n                  return loadSubtitleInDiscontinuity(pipelineContext, details, activeSeqNum);\n              }));\n          }), tag('subtitleEpic.process.emit'));\n      };\n      function processSubtitlePayload(enabledMediaOption, mediaFragment, initPTS, data, legibleSystemAdapter) {\n          if (enabledMediaOption) {\n              return legibleSystemAdapter.processSubtitleFrag(enabledMediaOption, mediaFragment, initPTS, data);\n          }\n          return;\n      }\n    \n      const getMimeInfo = (initParsedData, container) => {\n          var _a;\n          let mimeType = '';\n          let codec = '';\n          let type;\n          if (initParsedData.videoCodec && initParsedData.audioCodec) {\n              codec = `${initParsedData.videoCodec}, ${initParsedData.audioCodec}`;\n              container = container !== null && container !== void 0 ? container : 'video/mp4';\n              type = 'audiovideo';\n          }\n          else if (initParsedData.videoCodec) {\n              codec = `${initParsedData.videoCodec}`;\n              container = container !== null && container !== void 0 ? container : 'video/mp4';\n              type = 'video';\n          }\n          else {\n              codec = `${(_a = initParsedData.audioCodec) !== null && _a !== void 0 ? _a : ''}`;\n              container = container !== null && container !== void 0 ? container : 'audio/mp4';\n              type = 'audio';\n          }\n          mimeType = `${container};codecs=${codec}`;\n          return { mimeType, codec, container, type };\n      };\n    \n      class MediaParser {\n          constructor(config, logger, demuxClient) {\n              this.config = config;\n              this.logger = logger;\n              this.demuxClient = demuxClient;\n              this.typeSupported = {\n                  mp4: MediaSource.isTypeSupported('video/mp4'),\n                  mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n                  mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n                  ac3: MediaSource.isTypeSupported('audio/mp4; codecs=\"ac-3\"'),\n                  ec3: MediaSource.isTypeSupported('audio/mp4; codecs=\"ec-3\"'),\n              };\n              this.demuxers = [];\n              this.lastInitFrags = [];\n              this.lastFrags = [];\n          }\n          parseInitSegment(context, vendor) {\n              return this.getDemuxerInfo(context, this.lastInitFrags, vendor, this.demuxClient).pipe(switchMap(({ demuxer, contiguous, trackSwitch, discontinuity, accurateTimeOffset }) => {\n                  const { frag } = context;\n                  const { keyTagInfo, start: timeOffset, mediaOptionType } = frag;\n                  this.lastInitFrags[mediaOptionType] = frag;\n                  if (context.initSegment) {\n                      const remuxedInitSegment = MP4EncryptionRemuxer.remuxInitSegment(new Uint8Array(context.initSegment), this.logger, keyTagInfo);\n                      const initParsedData = MP4Demuxer.parseInitSegment(remuxedInitSegment);\n                      const { mimeType, type, codec, container } = getMimeInfo(initParsedData);\n                      return of({ moovData: initParsedData, mimeType, track: { type, codec, initSegment: remuxedInitSegment, container } });\n                  }\n                  const segmentData = context.segment ? context.segment : context.initSegment;\n                  const initSegmentData = segmentData ? context.initSegment : undefined;\n                  const demuxerTarget = fromEventTarget(demuxer.observer);\n                  return of(demuxerTarget.event(DemuxerEvent.FRAG_PARSING_INIT_SEGMENT).pipe(map(this.handleInitSegmentData)), demuxerTarget.event(HlsEvent$1.INTERNAL_ERROR).pipe(switchMap(this.handleError)), \n                  // Because we're sending the same data to demuxers multiple times, we cannot transfer to worker here.\n                  demuxer\n                      .pushWithoutTransfer(segmentData, keyTagInfo, initSegmentData, timeOffset, discontinuity, trackSwitch, contiguous, context.totalDuration, accurateTimeOffset, undefined, // context.defaultInitPTS,\n                  context.iframeMediaStart, context.iframeDuration)\n                      .pipe(switchMapTo(EMPTY))).pipe(mergeAll(), take(1));\n              }));\n          }\n          parseSegment(context, vendor) {\n              return this.getDemuxerInfo(context, this.lastFrags, vendor, this.demuxClient).pipe(switchMap(({ demuxer, contiguous, trackSwitch, discontinuity, accurateTimeOffset }) => {\n                  const { frag, defaultInitPTS } = context;\n                  const { keyTagInfo, start: timeOffset, duration, mediaOptionType } = frag;\n                  this.lastFrags[mediaOptionType] = frag;\n                  let parsedInitSegment;\n                  const demuxerTarget = fromEventTarget(demuxer.observer);\n                  return of(demuxerTarget.event(DemuxerEvent.FRAG_PARSING_INIT_SEGMENT).pipe(switchMap((data) => {\n                      var _a;\n                      if (data.track.initSegment.byteLength !== ((_a = context.initSegment) === null || _a === void 0 ? void 0 : _a.byteLength)) {\n                          parsedInitSegment = this.handleInitSegmentData(data);\n                      }\n                      return EMPTY;\n                  })), demuxerTarget.event(DemuxerEvent.FRAG_PARSING_DATA).pipe(map((parsedData) => {\n                      const { startPTS, startDTS, firstKeyframePts, framesWithoutIDR, dropped, data1, data2, captionData, id3Samples } = parsedData;\n                      let { endPTS, endDTS } = parsedData;\n                      if (endPTS == null) {\n                          this.logger.warn(`${MediaOptionNames[mediaOptionType]} ${fragPrint(frag)}: null endPTS parsed, using duration ${duration}`);\n                          endPTS = Object.assign(Object.assign({}, startPTS), { baseTime: startPTS.baseTime + convertSecondsToTimestamp(duration, startPTS.timescale).baseTime });\n                      }\n                      if (endDTS == null) {\n                          this.logger.warn(`${MediaOptionNames[mediaOptionType]} ${fragPrint(frag)}: null endDTS parsed, using duration ${duration}`);\n                          endDTS = Object.assign(Object.assign({}, startDTS), { baseTime: startDTS.baseTime + convertSecondsToTimestamp(duration, startDTS.timescale).baseTime });\n                      }\n                      // <rdar://problem/54533536> Don't post sanity check error event for trickplay until we fix the rounding problem (due to small timescale)\n                      if (!isFiniteNumber(context.iframeMediaStart)) {\n                          // Just do duration check for now (accurateTimeOffset == false)\n                          checkIfValidFragParsingData(frag, parsedData, defaultInitPTS, false, context.iframeMediaStart, this.config.audioPrimingDelay);\n                      }\n                      return { startPTS, endPTS, startDTS, endDTS, firstKeyframePts, framesWithoutIDR, dropped, data1, data2, captionData, id3Samples, parsedInitSegment };\n                  })), demuxerTarget.event(HlsEvent$1.INTERNAL_ERROR).pipe(switchMap(this.handleError)), demuxer\n                      .push(context.segment, keyTagInfo, context.initSegment, timeOffset, discontinuity, trackSwitch, contiguous, context.totalDuration, accurateTimeOffset, defaultInitPTS, context.iframeMediaStart, context.iframeDuration)\n                      .pipe(switchMapTo(EMPTY))).pipe(mergeAll(), take(1));\n              }));\n          }\n          reset(mediaOptionType = undefined) {\n              if (mediaOptionType == undefined) {\n                  this.demuxers.forEach((demuxer) => {\n                      if (demuxer)\n                          demuxer.destroy();\n                  });\n                  this.demuxers = [];\n                  return;\n              }\n              const demuxer = this.demuxers[mediaOptionType];\n              demuxer === null || demuxer === void 0 ? void 0 : demuxer.destroy();\n              this.demuxers[mediaOptionType] = null;\n          }\n          destroy(mediaOptionType = undefined) {\n              if (mediaOptionType == undefined) {\n                  this.reset();\n                  return;\n              }\n              this.reset(mediaOptionType);\n          }\n          willBeTrackSwitch(mediaFragment, frags) {\n              const { mediaOptionType, mediaOptionId } = mediaFragment;\n              const lastFrag = frags ? frags[mediaOptionType] : this.lastFrags[mediaOptionType];\n              return !(lastFrag && lastFrag.mediaOptionId === mediaOptionId);\n          }\n          getDemuxerInfo(context, frags, vendor, demuxClient) {\n              const { frag, ptsKnown, seeking, live } = context;\n              const { discoSeqNum, mediaSeqNum, mediaOptionType } = frag;\n              return defer(() => {\n                  const demuxer = this.demuxers[mediaOptionType];\n                  if (demuxer) {\n                      return of(demuxer);\n                  }\n                  return demuxClient.init(this.typeSupported, this.config, vendor).pipe(tap((demuxer) => (this.demuxers[mediaOptionType] = demuxer)));\n              }).pipe(map((demuxer) => {\n                  const lastFrag = frags[mediaOptionType];\n                  const trackSwitch = this.willBeTrackSwitch(frag, frags);\n                  const discontinuity = !(lastFrag && discoSeqNum === lastFrag.discoSeqNum);\n                  const contiguous = (lastFrag || false) && !trackSwitch && lastFrag.mediaSeqNum + 1 === mediaSeqNum;\n                  const accurateTimeOffset = !seeking && (ptsKnown || !live);\n                  return { demuxer, trackSwitch, discontinuity, contiguous, accurateTimeOffset };\n              }));\n          }\n          handleInitSegmentData(data) {\n              const { track } = data;\n              const { initSegment } = track;\n              const moovData = MP4Demuxer.parseInitSegment(initSegment);\n              const { mimeType, type, codec, container } = getMimeInfo(moovData, track.container);\n              return { moovData, mimeType, track: Object.assign(Object.assign({}, track), { type, codec, initSegment, container }) };\n          }\n          handleError(err) {\n              return throwError(err);\n          }\n      }\n      // Basic sanity check. Returns true if this is valid data, false if PTS/DTS values seem wrong\n      function checkIfValidFragParsingData(frag, data, initPTS, accurateTimeOffset, iframeMediaStart, audioPrimingDelay) {\n          let fudge = NaN; // max diff in seconds between parsed startDTS & expectedStartDTS\n          let expectedStartDTS = NaN; // expected value of parsed startDTS in seconds\n          if (isFiniteNumber(iframeMediaStart)) {\n              expectedStartDTS = iframeMediaStart;\n              // Most we should be off is one tick of the timescale due to rounding.  iframe tracks can have small timescales, so allow up to 10 ms\n              fudge = 0.01;\n              if (isFinite(expectedStartDTS) && isFinite(audioPrimingDelay)) {\n                  expectedStartDTS += audioPrimingDelay;\n              }\n          }\n          else if (accurateTimeOffset && initPTS) {\n              const timestampOffset = convertTimestampToSeconds(initPTS);\n              expectedStartDTS = frag.start + timestampOffset;\n              fudge = frag.duration;\n          }\n          const { startPTS, startDTS, endPTS, endDTS } = data;\n          // Technically we could have negative numbers if value > Number.MAX_SAFE_INTEGER\n          // but right now we would barf in LevelHelper adjustment\n          const success = startPTS.baseTime >= 0 &&\n              startDTS.baseTime >= 0 &&\n              frag.duration > 0 &&\n              (endPTS == null || diffSeconds(endPTS, startPTS) > 0) &&\n              (endDTS == null || diffSeconds(endDTS, startDTS) > 0) &&\n              (!isFiniteNumber(fudge) || !isFiniteNumber(expectedStartDTS) || Math.abs(convertTimestampToSeconds(startDTS) - expectedStartDTS) <= fudge);\n          if (!success) {\n              throw new FragParsingError(false, `Failed demuxer sanity check frag=${fragPrint(frag)} parsed=${JSON.stringify({ startPTS, endPTS, startDTS, endDTS })} ${stringifyWithPrecision({ expectedStartDTS, fudge })}`, ErrorResponses.FailedDemuxerSanityCheck);\n          }\n          return success;\n      }\n      function createMediaParser(config, logger, demuxClient) {\n          return new Observable((subscriber) => {\n              const parser = new MediaParser(config, logger, demuxClient);\n              subscriber.next(parser);\n              return () => {\n                  parser.destroy();\n              };\n          });\n      }\n    \n      function getMinBufferAhead(config, details, bufferInfo) {\n          var _a, _b;\n          // Allow if we have a whole segment ahead\n          let playingFragDuration = Infinity;\n          if (bufferInfo.playingFrag) {\n              playingFragDuration = (_b = (_a = details.fragments[bufferInfo.playingFrag.mediaSeqNum - details.startSN]) === null || _a === void 0 ? void 0 : _a.duration) !== null && _b !== void 0 ? _b : Infinity;\n          }\n          const { minRequiredStartDuration, maxRequiredStartDuration, startTargetDurationFactor } = config;\n          const { targetduration, averagetargetduration } = details;\n          const requiredStartDuration = startTargetDurationFactor * Math.min(playingFragDuration, averagetargetduration, targetduration, maxRequiredStartDuration);\n          return Math.max(minRequiredStartDuration, requiredStartDuration);\n      }\n      /**\n       * @returns whether we probably have enough\n       */\n      function probablyHaveEnough(config, fragInfo, playlistInfo, bufferInfo, desiredRate, bwEstimate, fragEstimate, bufferEstimate, logger) {\n          const { combined } = bufferInfo;\n          const minBufferAhead = getMinBufferAhead(config, playlistInfo.details, bufferInfo);\n          let haveEnough = haveEnoughBuffer(fragInfo, playlistInfo, bufferInfo, desiredRate, minBufferAhead);\n          if (!haveEnough && combined.len > 0 && (fragInfo === null || fragInfo === void 0 ? void 0 : fragInfo.state)) {\n              const estTimeToHaveEnough = getEstTimeToHaveEnough(fragInfo, playlistInfo.variant.bitrate, minBufferAhead, bufferInfo, bwEstimate, fragEstimate, bufferEstimate, config.maxBufferHole);\n              haveEnough = estTimeToHaveEnough <= combined.len;\n              logger === null || logger === void 0 ? void 0 : logger.info(`haveEnough (probably): ${haveEnough}, ${stringifyWithPrecision({\n                bufferLen: combined.len,\n                pos: bufferInfo.pos,\n                estTimeToHaveEnough,\n                minBufferAhead,\n                state: fragInfo.state,\n                tstart: fragInfo.tstart,\n                avgParseMs: fragEstimate.avgParseTimeMs,\n                avgAppendMs: bufferEstimate.avgDataFragAppendMs,\n            })}`);\n          }\n          else if (!haveEnough && fragInfo == null) {\n              logger === null || logger === void 0 ? void 0 : logger.info(`haveEnough: ${haveEnough}, bufferLen: ${combined.len.toFixed(3)}`);\n          }\n          return haveEnough;\n      }\n      /**\n       * @returns whether we have enough buffer without using any estimation\n       */\n      function haveEnoughBuffer(fragInfo, playlistInfo, bufferInfo, desiredRate, requiredStartDuration) {\n          const { pos, combined, playingFrag } = bufferInfo;\n          if (combined.len === 0) {\n              return false;\n          }\n          const iframeMode = desiredRate != 0 && desiredRate != 1;\n          const details = playlistInfo.details;\n          const fragments = details.fragments;\n          let haveEnough = iframeMode || combined.len >= requiredStartDuration;\n          const lastFrag = fragments[details.fragments.length - 1];\n          const playlistStart = fragments[0].start;\n          const playlistEnd = playlistStart + details.totalduration;\n          let gotDiscontinuity = false;\n          if (playingFrag) {\n              const lastFragForCC = BinarySearch$1.search(fragments, (frag) => playingFrag.discoSeqNum - frag.discoSeqNum);\n              gotDiscontinuity =\n                  (fragInfo && playingFrag.discoSeqNum !== fragInfo.discoSeqNum) ||\n                      lastFragForCC == null || // buffered cc does not appear in the refreshed playlist anymore\n                      fragEqual(lastFragForCC, playingFrag); // buffered cc appears to end in refreshed playlist\n          }\n          // Also ensure that live is behind furthest live position\n          if (haveEnough && details.liveOrEvent) {\n              const behindLivePosition = playlistEnd - lastFrag.duration;\n              haveEnough = pos <= behindLivePosition;\n          }\n          else if (!details.liveOrEvent) {\n              // Allow play through if we're close to the end\n              haveEnough = haveEnough || pos >= playlistEnd - requiredStartDuration;\n          }\n          haveEnough = haveEnough || gotDiscontinuity;\n          return haveEnough;\n      }\n      /**\n       * @returns the duration relative to now when we think that the fragment will be\n       * buffered / complete\n       */\n      function getEstTimeToHaveEnough(fragInfo, bitrate, minBufferAhead, bufferInfo, bwEstimate, fragEstimate, bufferEstimate, maxBufferHole) {\n          var _a, _b;\n          const mainBufferInfo = (_a = bufferInfo.sbTuple[MediaOptionType.Variant]) === null || _a === void 0 ? void 0 : _a.buffered;\n          const audioBufferInfo = (_b = bufferInfo.sbTuple[MediaOptionType.AltAudio]) === null || _b === void 0 ? void 0 : _b.buffered;\n          if ((mainBufferInfo === null || mainBufferInfo === void 0 ? void 0 : mainBufferInfo.len) >= minBufferAhead && (!audioBufferInfo || audioBufferInfo.len >= minBufferAhead)) {\n              // Already have enough buffered in main/audio sb. Its\n              // already assumed that if main suffices, audio will as well - but\n              // still checking for sanity\n              return 0;\n          }\n          else if (!mainBufferInfo || !fragInfo || !fragOverlapsEndAndSufficient(fragInfo, mainBufferInfo, maxBufferHole, minBufferAhead, bufferInfo.pos)) {\n              // Not enough fragment info\n              return Infinity;\n          }\n          const state = fragInfo.state;\n          let tStartOfState = fragInfo.tstart;\n          let timeToComplete = 0;\n          switch (state) {\n              case 'loading':\n                  timeToComplete += getTimeToLoad(fragInfo, bitrate, bwEstimate);\n                  tStartOfState = fragInfo.tstart + timeToComplete * 1000;\n              // fallthrough\n              case 'loaded':\n              case 'parsing':\n                  timeToComplete += getTimeToParse(tStartOfState, fragEstimate);\n                  tStartOfState = fragInfo.tstart + timeToComplete * 1000;\n              // fallthrough\n              case 'parsed':\n              case 'appending':\n                  timeToComplete += getTimeToAppendBuffer(tStartOfState, bufferEstimate);\n                  break;\n              case 'appended':\n                  // 0 triggers a false positive for haveEnough; If appended, it\n                  // should be factored in combined.len.\n                  timeToComplete = Infinity;\n                  break;\n              default:\n                  timeToComplete = Infinity;\n                  break;\n          }\n          return timeToComplete;\n      }\n      /**\n       * @returns the estimated remaining amount of time to load the fragment\n       */\n      function getTimeToLoad(fragInfo, bitrate, bwEstimate) {\n          const { bwSample: fragStats, duration } = fragInfo;\n          if (!fragStats) {\n              return Infinity;\n          }\n          // Calculate based on current bw when we think the next frag will be finished\n          // Assume audio will take less time\n          const totalBits = isFiniteNumber(fragStats.total) ? fragStats.total * 8 : Math.ceil(duration * bitrate); // est bytes using bitrate & duration\n          const loadedBits = fragStats.loaded * 8;\n          const remainingBits = totalBits - loadedBits;\n          const instantBW = (loadedBits / (performance.now() - fragStats.tfirst)) * 1000; // bps\n          if (!isFiniteNumber(instantBW)) {\n              return Infinity;\n          }\n          const avgBW = bwEstimate.avgBandwidth; // bps\n          const bandwidth = Math.min(avgBW, instantBW);\n          return remainingBits / bandwidth;\n      }\n      /**\n       * @returns the estimated remaining amount of time to parse the fragment\n       */\n      function getTimeToParse(tParseStart, fragEstimate) {\n          const avgParseTimeMs = isFiniteNumber(fragEstimate.avgParseTimeMs) ? fragEstimate.avgParseTimeMs : 0;\n          if (performance.now() < tParseStart) {\n              return avgParseTimeMs / 1000;\n          }\n          return Math.max(0, avgParseTimeMs - (performance.now() - tParseStart)) / 1000;\n      }\n      /**\n       * @returns the estimated remaining amount of time to append the fragment\n       */\n      function getTimeToAppendBuffer(tAppendStart, bufferEstimate) {\n          const avgDataFragAppendMs = isFiniteNumber(bufferEstimate.avgDataFragAppendMs) ? bufferEstimate.avgDataFragAppendMs : 0;\n          if (performance.now() < tAppendStart) {\n              return avgDataFragAppendMs / 1000;\n          }\n          return Math.max(0, avgDataFragAppendMs - (performance.now() - tAppendStart)) / 1000;\n      }\n      /**\n       *@returns true if to frag overlaps end\n       */\n      function fragOverlapsEndAndSufficient(fragInfo, bufferInfo, maxBufferHole, minBufferAhead, currentPosition) {\n          const fragend = fragInfo.start + fragInfo.duration;\n          return fragend > bufferInfo.end && (fragInfo.start - bufferInfo.end <= maxBufferHole || fragInfo.start <= bufferInfo.end) && fragend - currentPosition >= minBufferAhead;\n      }\n    \n      /**\n       * Observables that keep track of pipeline and media state to update playback state\n       */\n      function checkForHaveEnough(config, logger, rootQuery, mediaSink, mediaLibraryService, statsQuery) {\n          const mediaQuery = mediaSink.mediaQuery;\n          // Startup perf: avoid subscribing to stuff on startup if we don't /need/ it\n          // Have enough won't ever be true until something gets buffered so don't listen to any observables until then.\n          return waitFor(mediaQuery.combinedBuffer$, (combinedBuffer) => (combinedBuffer === null || combinedBuffer === void 0 ? void 0 : combinedBuffer.length) > 0).pipe(switchMap(() => {\n              const mediaBufferInfo$ = combineQueries([mediaQuery.seekTo$, mediaQuery.bufferedSegmentsByType$(SourceBufferType.Variant)]).pipe(map(([seekTo, bufferedSeg]) => {\n                  var _a;\n                  const pos = isFiniteNumber(seekTo === null || seekTo === void 0 ? void 0 : seekTo.pos) ? seekTo.pos : mediaQuery.currentTime;\n                  const playingSeg = bufferedSeg.find((seg) => seg.startPTS <= pos && seg.endPTS > pos);\n                  const sbTuple = mediaQuery.getBufferInfo(pos, config.maxBufferHole);\n                  const combined = mediaQuery.getCombinedBufferInfo(pos, config.maxBufferHole);\n                  return {\n                      pos,\n                      sbTuple,\n                      combined,\n                      playingFrag: (_a = playingSeg === null || playingSeg === void 0 ? void 0 : playingSeg.frag) !== null && _a !== void 0 ? _a : null,\n                  };\n              }));\n              const inFlightInfo$ = combineQueries([\n                  rootQuery.getInFlightFragByType$(MediaOptionType.Variant),\n                  rootQuery.enabledMediaOptionByType$(MediaOptionType.Variant),\n              ]).pipe(switchMap(([inFlightFrag, mediaOption]) => {\n                  const playlistQuery = mediaLibraryService.getQueryForOption(mediaOption);\n                  return zip(of(inFlightFrag), of(mediaOption), playlistQuery.mediaOptionDetails$);\n              }), map(([currentFrag, variant, details]) => {\n                  return [currentFrag, { variant, details }];\n              }));\n              const bwEstimates$ = combineQueries([statsQuery.bandwidthEstimate$, statsQuery.fragEstimate$, statsQuery.bufferEstimate$]);\n              return combineQueries([mediaQuery.readyState$, inFlightInfo$, mediaBufferInfo$, mediaQuery.desiredRate$, bwEstimates$]);\n          }), throttleTime(100, asyncScheduler, { leading: true, trailing: true }), map(([_readyState, inFlightInfo, bufferInfo, desiredRate, bwEstimates]) => {\n              const [fragInfo, playlistInfo] = inFlightInfo;\n              const [bwEstimate, fragEstimate, bufferEstimate] = bwEstimates;\n              let overrideFragEstimate = fragEstimate;\n              let overrideBufferEsimate = bufferEstimate;\n              if (fragEstimate) {\n                  const maxDurationSec = isFiniteNumber(fragEstimate.maxDurationSec) ? fragEstimate.maxDurationSec : config.defaultTargetDuration;\n                  const avgParseTimeMs = isFiniteNumber(fragEstimate.avgParseTimeMs) ? fragEstimate.avgParseTimeMs : config.statDefaults.fragParseTimeMs;\n                  overrideFragEstimate = { maxDurationSec, avgParseTimeMs };\n              }\n              if (bufferEstimate) {\n                  const avgBufferCreateMs = isFiniteNumber(bufferEstimate.avgBufferCreateMs) ? bufferEstimate.avgBufferCreateMs : config.statDefaults.fragBufferCreationDelayMs;\n                  const avgInitFragAppendMs = isFiniteNumber(bufferEstimate.avgInitFragAppendMs) ? bufferEstimate.avgInitFragAppendMs : config.statDefaults.initFragAppendMs;\n                  const avgDataFragAppendMs = isFiniteNumber(bufferEstimate.avgDataFragAppendMs) ? bufferEstimate.avgDataFragAppendMs : config.statDefaults.dataFragAppendMs;\n                  overrideBufferEsimate = { avgBufferCreateMs, avgInitFragAppendMs, avgDataFragAppendMs };\n              }\n              const haveEnough = probablyHaveEnough(config, fragInfo, playlistInfo, bufferInfo, desiredRate, bwEstimate, overrideFragEstimate, overrideBufferEsimate, logger);\n              mediaSink.haveEnough = haveEnough;\n              return haveEnough;\n          }), distinctUntilChanged(), tap((haveEnough) => {\n              logger.info(`[seek] haveEnough=${haveEnough}`);\n          }), switchMapTo(EMPTY));\n      }\n      function checkForEndOfStream(context) {\n          const { config, logger, mediaSink, rootPlaylistQuery: rootQuery, mediaLibraryService, gaplessInstance } = context;\n          const { mediaQuery } = mediaSink;\n          const currentEnabledDetails$ = rootQuery.enabledAVOptions$.pipe(switchMap((options) => zip(...options.map((option) => {\n              if (!isEnabledMediaOption(option)) {\n                  return of(null);\n              }\n              return mediaLibraryService.getQueryForOption(option).mediaOptionDetails$;\n          }))));\n          // Startup: wait for something to be buffered before subscribe to enabledAVOptions & details\n          return waitFor(mediaQuery.combinedBuffer$, (combined) => {\n              return (combined === null || combined === void 0 ? void 0 : combined.length) > 0;\n          }).pipe(switchMapTo(combineQueries([\n              currentEnabledDetails$,\n              mediaQuery.msReadyState$,\n              mediaQuery.updating$,\n              mediaQuery.isIframeRate$,\n              mediaQuery.isBufferedToEnd$(config.maxBufferHole, !gaplessInstance.inGaplessMode),\n          ])), tag('checkForEndOfStream'), filter(([_, readyState, updating, isIframeRate, bufferedToEnd]) => {\n              return readyState === 'open' && updating === false && !isIframeRate && bufferedToEnd;\n          }), tap(([details]) => {\n              logger.info('Reached end of stream');\n              const isVOD = details[0] != null && details.every((x) => x == null || (x.liveOrEvent === false && x.iframesOnly === false));\n              if (isVOD && !gaplessInstance.inGaplessMode) {\n                  logger.info('Calling MediaSink endStream');\n                  mediaSink.endStream(); // May only be called when updating == false\n              }\n          }), switchMapTo(EMPTY));\n      }\n    \n      function loadRootMediaOptions(item, loadPolicy, logger, config, statsService, extendMaxTTFB) {\n          const { itemId, url, itemStartOffset } = item;\n          const loadConfig = getLoadConfig(item, loadPolicy);\n          return fromUrlText({\n              url,\n              onProgress: { getData: true, cb: loadProgress },\n              xhrSetup: config.xhrSetup,\n          }, loadConfig, extendMaxTTFB).pipe(map(({ responseText: rawPlaylist, responseURL: rURL, stats }) => {\n              const { keySystemPreference } = config;\n              logger.debug(`root playlist url: ${url}, baseUrl: ${rURL}`);\n              if (!rURL) {\n                  logger.warn('Missing response url. Reusing request url as base url');\n                  rURL = url;\n              }\n              if (PlaylistParser$1.isMediaPlaylist(rawPlaylist)) {\n                  const mediaOptionId = 'media-pl-' + guid();\n                  const parsed = PlaylistParser$1.parseMediaOptionPlaylist(rawPlaylist, rURL, true, keySystemPreference, {}, itemId, mediaOptionId, MediaOptionType.Variant, logger, itemStartOffset);\n                  updatePlaylistAttributes(parsed.mediaOptionDetails);\n                  const variantOption = {\n                      itemId,\n                      mediaOptionId,\n                      mediaOptionType: MediaOptionType.Variant,\n                      url,\n                      bandwidth: 0,\n                      bitrate: 0,\n                      iframes: parsed.mediaOptionDetails.iframesOnly,\n                      pathwayID: '.',\n                  };\n                  const rootMediaOptionsTuple = [[variantOption], [], []];\n                  const loadResult = {\n                      itemId,\n                      itemStartOffset,\n                      rootMediaOptionsTuple,\n                      stats,\n                      baseUrl: rURL,\n                      initialDetails: parsed.mediaOptionDetails,\n                      isMediaPlaylist: true,\n                  };\n                  return loadResult;\n              }\n              else {\n                  const sessionData = PlaylistParser$1.parseSessionData(rawPlaylist, rURL);\n                  const sessionKeys = PlaylistParser$1.parseSessionKeys(rawPlaylist, rURL, keySystemPreference);\n                  const parsed = PlaylistParser$1.parseRootPlaylist(itemId, rawPlaylist, rURL, true);\n                  if (parsed.playlistParsingError) {\n                      throw parsed.playlistParsingError;\n                  }\n                  const { variantMediaOptions, contentSteeringOption, masterVariableList } = parsed;\n                  const parsingResult = PlaylistParser$1.parseRootPlaylistAlternateMediaOptions(itemId, rawPlaylist, rURL, parsed.variantMediaOptions, true, masterVariableList);\n                  if (parsingResult.playlistParsingError) {\n                      throw parsingResult.playlistParsingError;\n                  }\n                  const { audioAlternateOptions, subtitleAlternateOptions, audioMediaSelectionGroup, subtitleMediaSelectionGroup } = parsingResult.alternateMediaInfo;\n                  const rootMediaOptionsTuple = [variantMediaOptions, audioAlternateOptions, subtitleAlternateOptions];\n                  const loadResult = {\n                      itemId,\n                      itemStartOffset,\n                      rootMediaOptionsTuple,\n                      stats,\n                      baseUrl: rURL,\n                      audioMediaSelectionGroup,\n                      subtitleMediaSelectionGroup,\n                      contentSteeringOption,\n                      sessionData,\n                      sessionKeys,\n                      masterVariableList,\n                  };\n                  return loadResult;\n              }\n          }), convertToManifestNetworkError(false));\n      }\n      function loadProgress(url, status, _stats, data) {\n          if (status === 200 && data && data.length > 10) {\n              // only look at responses which have status 200 and is at least 10 chars long\n              if (!PlaylistParser$1.isValidPlaylist(data)) {\n                  const playlistParsingError = new PlaylistParsingError(ErrorTypes.NETWORK_ERROR, ErrorDetails.MANIFEST_PARSING_ERROR, true, 'response doesnt have #EXTM3U tag', ErrorResponses.PlaylistErrorMissingEXTM3U);\n                  playlistParsingError.url = url;\n                  throw playlistParsingError;\n              }\n              return true;\n          }\n          return false;\n      }\n    \n      const loggerName$1 = { name: 'pltfrm' };\n      var HdrMetadataType;\n      (function (HdrMetadataType) {\n          HdrMetadataType[\"HDR10\"] = \"smpteSt2086\";\n          HdrMetadataType[\"DoVi\"] = \"smpteSt2094-10\";\n          HdrMetadataType[\"HDR10Plus\"] = \"smpteSt2094-40\";\n      })(HdrMetadataType || (HdrMetadataType = {}));\n      function isValidSecurityLevel(securityLevel, keySystemId) {\n          const securityLevels = KeySystemFactory$1.getKeySystemSecurityLevel(keySystemId);\n          return securityLevel != null && securityLevels[securityLevel] !== undefined;\n      }\n      function onlyIframes(mediaOptionList) {\n          return mediaOptionList.every((mediaOption) => mediaOption.iframes);\n      }\n      function isWithinCap(val, cap) {\n          // If there is no value or if there is no cap, then the value is vacuously within the cap\n          return !isFiniteNumber(val) || !isFiniteNumber(cap) || val <= cap; // TODO revert or fix <- <jgainfort> this is not my todo, inherited from 2.0\n      }\n      function makeVideoConfiguration(codec, mediaOption) {\n          const vConfig = {\n              contentType: `video/mp4;codecs=${codec}`,\n              width: mediaOption.width,\n              height: mediaOption.height,\n              bitrate: mediaOption.bandwidth || mediaOption.avgBandwidth,\n              framerate: mediaOption.iframes ? 8 : mediaOption.frameRate,\n          };\n          if (mediaOption.videoRange) {\n              switch (mediaOption.videoRange) {\n                  case 'PQ':\n                      if (MediaUtil.isDolby(codec)) {\n                          vConfig.hdrMetadataType = HdrMetadataType.DoVi;\n                          vConfig.colorGamut = 'rec2020';\n                      }\n                      else if (MediaUtil.isHEVC(codec) || MediaUtil.isVP09(codec)) {\n                          // Assuming HDR10\n                          vConfig.hdrMetadataType = HdrMetadataType.HDR10;\n                          vConfig.colorGamut = 'rec2020';\n                      }\n                      vConfig.transferFunction = 'pq';\n                      break;\n                  case 'HLG':\n                      // no metadata\n                      vConfig.colorGamut = 'rec2020';\n                      vConfig.transferFunction = 'hlg';\n                      break;\n              }\n          }\n          return vConfig;\n      }\n      function makeAudioConfiguration(codec, mediaOption, audioMediaOptions) {\n          const aConfig = {\n              contentType: `audio/mp4;codecs=${codec}`,\n          };\n          // Optional fields\n          const channels = RichestMedia.getRichestChannelLayoutForGroupId(mediaOption.audioGroupId, audioMediaOptions);\n          if (channels) {\n              aConfig.channels = MediaUtil.getChannelCount(channels).toString();\n              aConfig.spatialRendering = MediaUtil.isDolbyAtmos(codec, channels);\n          }\n          return aConfig;\n      }\n      function createHandleCodec(logger) {\n          // can reduce the number of calls by caching the results\n          const cachedDecodingInfo = new Map();\n          const mediaCapabilities = navigator && navigator.mediaCapabilities;\n          return (mediaOption, audioMediaOptions, codec, isVideo, isTypeSupportedObservables) => {\n              const config = {\n                  type: 'media-source',\n              };\n              if (isVideo) {\n                  config.video = makeVideoConfiguration(codec, mediaOption);\n              }\n              else {\n                  config.audio = makeAudioConfiguration(codec, mediaOption, audioMediaOptions);\n              }\n              const configStr = JSON.stringify(config);\n              let decodingInfoObservable;\n              if (cachedDecodingInfo.has(configStr)) {\n                  decodingInfoObservable = cachedDecodingInfo.get(configStr);\n              }\n              else {\n                  decodingInfoObservable = from(mediaCapabilities.decodingInfo(config)).pipe(map((decodingInfo) => {\n                      const supportedConfig = decodingInfo.configuration || decodingInfo.supportedConfiguration;\n                      const hasRequestedFields = supportedConfig instanceof Object &&\n                          (!config.video || Object.keys(config.video).find((k) => !(k in supportedConfig.video)) == undefined) &&\n                          (!config.audio || Object.keys(config.audio).find((k) => !(k in supportedConfig.audio)) == undefined);\n                      const isTypeSupported = decodingInfo.supported && (!isVideo || decodingInfo.powerEfficient) && hasRequestedFields;\n                      if (!isTypeSupported) {\n                          logger.warn(loggerName$1, `Unsupported config ${decodingInfo.supported}/${decodingInfo.powerEfficient}/${hasRequestedFields} ${JSON.stringify(config)} supportedConfig=${JSON.stringify(supportedConfig)}`);\n                      }\n                      return isTypeSupported;\n                  }));\n                  cachedDecodingInfo.set(configStr, decodingInfoObservable);\n              }\n              return [...isTypeSupportedObservables, decodingInfoObservable];\n          };\n      }\n      function createIsSupportedInternal() {\n          const supportedCodecs = new Set();\n          const unsupportedCodecs = new Set();\n          return (mediaOption) => {\n              const checkSupported = (type, codec) => {\n                  let isSupported = MediaSource.isTypeSupported(`${type}/mp4;codecs=${codec}`);\n                  if (codec === 'mp4a.40.34' && !isSupported) {\n                      isSupported = MediaSource.isTypeSupported(`${type}/mpeg`);\n                  }\n                  return isSupported;\n              };\n              const updateCachedCodecsSetsIfNecessary = (codec, isAudioCodec) => {\n                  const type = isAudioCodec ? 'audio' : 'video';\n                  // Minimizes calls to chromium by caching supported/unsupported audio video codecs\n                  if (!supportedCodecs.has(codec) && !unsupportedCodecs.has(codec)) {\n                      if (checkSupported(type, codec)) {\n                          supportedCodecs.add(codec);\n                      }\n                      else {\n                          unsupportedCodecs.add(codec);\n                      }\n                  }\n              };\n              // Update the codec support/notSupport cache based on MediaSource support.\n              // After that verify if that codec falls into unsupported category.\n              const checkUnsupportedCodec = (codec, isAudioCodec) => {\n                  updateCachedCodecsSetsIfNecessary(codec, isAudioCodec);\n                  return unsupportedCodecs.has(codec);\n              };\n              let foundUnsupportedCodec = false;\n              if (mediaOption.audioCodecList) {\n                  foundUnsupportedCodec = mediaOption.audioCodecList.some((codec) => checkUnsupportedCodec(codec, true));\n              }\n              if (!foundUnsupportedCodec && mediaOption.videoCodecList) {\n                  foundUnsupportedCodec = mediaOption.videoCodecList.some((codec) => checkUnsupportedCodec(codec, false));\n              }\n              return !foundUnsupportedCodec;\n          };\n      }\n      function useFallbackCapsIfMissing(result, fallback) {\n          const keys = Object.keys(fallback);\n          keys.forEach((key) => {\n              if (!result[key]) {\n                  result[key] = fallback[key];\n              }\n          });\n          return result;\n      }\n      /**\n       * @param cappingInfoList Usually platformInfo.videoCodecs or platformInfo.videoDynamicRangeFormats\n       * @param type to use for lookup\n       * @returns Capping info with matching type\n       */\n      function getCappingInfoFromType(cappingInfoList, type) {\n          for (const id in cappingInfoList) {\n              if (cappingInfoList[id].type === type) {\n                  return cappingInfoList[id];\n              }\n          }\n          return {};\n      }\n      /**\n       * @param format  DynamicRangeFormat\n       * @param compressionType CompressionType\n       * @param videoCodecs List of capping info [ { type: DynamicRangeFormat } ]\n       * @param videoDynamicRangeFormats  List of capping info [ {type, CompressionType } ]\n       * @returns The capping information to use\n       */\n      function getCappingInfo(vdrType, compressionType, videoCodecs, videoDynamicRangeFormats) {\n          if (!videoDynamicRangeFormats && !videoCodecs) {\n              return {};\n          }\n          const cappingFromCompressionInfo = videoCodecs ? getCappingInfoFromType(videoCodecs, compressionType) : {};\n          const cappingFromFormat = videoDynamicRangeFormats ? getCappingInfoFromType(videoDynamicRangeFormats, vdrType) : {};\n          let preferredCaps;\n          let fallbackCaps;\n          switch (vdrType) {\n              case VideoDynamicRangeType.SDR:\n                  // Prioritize using compressionType > dynamic range\n                  preferredCaps = cappingFromCompressionInfo;\n                  fallbackCaps = cappingFromFormat;\n                  break;\n              default:\n                  // Prioritize using dynamic range > compressionType\n                  preferredCaps = cappingFromFormat;\n                  fallbackCaps = cappingFromCompressionInfo;\n          }\n          const result = Object.assign({}, preferredCaps);\n          return useFallbackCapsIfMissing(result, fallbackCaps);\n      }\n      function getSupportedVideoFormats(videoDynamicRangeFormats) {\n          return videoDynamicRangeFormats.reduce((prev, cur) => {\n              switch (cur.type) {\n                  case VideoDynamicRangeType.DolbyVision:\n                      prev.doViSupported = true;\n                      break;\n                  case VideoDynamicRangeType.HDR10:\n                      prev.hdr10Supported = true;\n                      break;\n                  case VideoDynamicRangeType.HLG:\n                      prev.hlgSupported = true;\n                      break;\n              }\n              return prev;\n          }, { doViSupported: false, hdr10Supported: false, hlgSupported: false });\n      }\n      function filterMediaOptionInfoPrint(filterName, unfilteredMediaOptionInfo, filteredMediaOptionInfo, logger) {\n          const unfilteredMediaOptionCount = unfilteredMediaOptionInfo.length;\n          const filteredMediaOptionCount = filteredMediaOptionInfo.length;\n          const unchanged = unfilteredMediaOptionCount === filteredMediaOptionCount;\n          const removedMediaOptionIds = unfilteredMediaOptionInfo.filter((mediaOption) => !filteredMediaOptionInfo.includes(mediaOption)).map((mediaOption) => mediaOption.mediaOptionId);\n          logger.qe({ critical: true, name: 'mediaFiltering', data: { filterName, unchanged, remaining: filteredMediaOptionCount, filteredIds: removedMediaOptionIds } });\n      }\n      function printMediaOptionInfo(mediaOptionInfo, logger) {\n          logger.info(loggerName$1, `Unsupported level ${JSON.stringify(mediaOptionInfo, ['avgBandwidth', 'audioCodecList', 'videoCodecList', 'videoRange', 'frameRate', 'width', 'height', 'iframes'])}`);\n      }\n      function filterMediaOptionsBasedOnHlsConfig(mediaOptions, disableVideoCodecList, disableAudioCodecList, logger) {\n          let filteredMediaOptions = mediaOptions.filter((mediaOption) => {\n              if (mediaOption.videoCodec) {\n                  return mediaOption.videoCodecList.every((codec) => {\n                      const videoCodecRank = getVideoCodecRanking(codec);\n                      return !disableVideoCodecList.has(videoCodecRank);\n                  });\n              }\n              return true;\n          });\n          filteredMediaOptions = filteredMediaOptions.filter((mediaOption) => {\n              if (!mediaOption.iframes && mediaOption.audioCodec) {\n                  return mediaOption.audioCodecList.every((codec) => {\n                      const audioCodecRank = getAudioCodecRanking(codec);\n                      return !disableAudioCodecList.has(audioCodecRank);\n                  });\n              }\n              return true;\n          });\n          filterMediaOptionInfoPrint('Disable Codec config', mediaOptions, filteredMediaOptions, logger);\n          return filteredMediaOptions;\n      }\n      function filterMediaOptionsBasedOnMaxAllowedHdcpLevel(mediaOptions, maxHdcpLevel, logger) {\n          const maxHdcpRanking = hdcpLevelToInt(maxHdcpLevel);\n          const filteredMediaOptions = mediaOptions.filter((mediaOption) => {\n              const curHdcpLevel = mediaOption.hdcpLevel;\n              return !curHdcpLevel || hdcpLevelToInt(curHdcpLevel) <= maxHdcpRanking;\n          });\n          filterMediaOptionInfoPrint('Hdcp', mediaOptions, filteredMediaOptions, logger);\n          return filteredMediaOptions;\n      }\n      function filterMediaOptionsBasedOnSecurityLevel(mediaOptions, maxSecurityLevel, keySystemId, logger) {\n          const securityLevels = KeySystemFactory$1.getKeySystemSecurityLevel(keySystemId);\n          const keyFormat = KeySystemFactory$1.getKeySystemFormat(keySystemId);\n          const getSecurityLevelRanking = function (curSecurityLevel) {\n              return isValidSecurityLevel(curSecurityLevel, keySystemId) ? securityLevels[curSecurityLevel] : -1;\n          };\n          const maxSecurityLevelRanking = getSecurityLevelRanking(maxSecurityLevel);\n          const filteredMediaOptions = mediaOptions.filter((mediaOption) => {\n              var _a, _b;\n              const cpcLabels = (_b = (_a = mediaOption.allowedCPCMap) === null || _a === void 0 ? void 0 : _a[keyFormat]) !== null && _b !== void 0 ? _b : [];\n              let selectLevel = true;\n              for (const currentLabelSecurityLevel of cpcLabels) {\n                  const currentLabelSecurityLevelRanking = getSecurityLevelRanking(currentLabelSecurityLevel);\n                  selectLevel = currentLabelSecurityLevelRanking <= maxSecurityLevelRanking;\n                  if (!selectLevel) {\n                      break;\n                  }\n              }\n              return selectLevel;\n          });\n          filterMediaOptionInfoPrint('Security Level', mediaOptions, filteredMediaOptions, logger);\n          return [...filteredMediaOptions];\n      }\n      function filterMediaOptionsBasedOnMediaKeySystemAccess(mediaOptions, keySystemId, logger) {\n          const cachedKeySystemConfig = new Map();\n          function handleKeySystem(keySystemId, levelInfo, isKeySystemSupportedPromises) {\n              const mediaCapabilities = keysystemutil.getCapabilities(levelInfo.videoCodecList, levelInfo.audioCodecList);\n              const configStr = JSON.stringify(mediaCapabilities);\n              let requestKeySystemPromise;\n              if (cachedKeySystemConfig.has(configStr)) {\n                  requestKeySystemPromise = cachedKeySystemConfig.get(configStr);\n              }\n              else {\n                  requestKeySystemPromise = KeySystemFactory$1.requestKeySystemAccess(keySystemId, mediaCapabilities, undefined, logger).pipe(map(() => {\n                      return true;\n                  }), catchError((error) => {\n                      logger.warn(`Request key system error: ${error.message}`);\n                      return of(false);\n                  }), shareReplay({ bufferSize: 1, refCount: true }));\n                  cachedKeySystemConfig.set(configStr, requestKeySystemPromise);\n              }\n              isKeySystemSupportedPromises.push(requestKeySystemPromise);\n          }\n          const isSupported = new Array();\n          mediaOptions.forEach((mediaOption) => {\n              const isKeySystemSupportedPromises = Array();\n              handleKeySystem(keySystemId, mediaOption, isKeySystemSupportedPromises);\n              const p = forkJoin(isKeySystemSupportedPromises).pipe(map((results) => {\n                  // If no unsupported config found then we're good\n                  if (results.find((supported) => supported === false) === undefined) {\n                      return mediaOption;\n                  }\n              }));\n              isSupported.push(p);\n          });\n          return forkJoin(isSupported).pipe(map((results) => {\n              return results.filter((r) => Boolean(r));\n          }));\n      }\n      /**\n       * Use MediaCapabilities API to determine whether we can play this.\n       * @param mediaOptions\n       * @param audioMediaOptions\n       */\n      function filterBasedOnMediaCapabilities(mediaOptions, audioMediaOptions, logger) {\n          logger.debug(loggerName$1, 'Using MediaCapabilities');\n          const observables = [];\n          const isSupportedInternal = createIsSupportedInternal();\n          const handleCodec = createHandleCodec(logger);\n          mediaOptions.forEach((mediaOption) => {\n              var _a, _b;\n              let isTypeSupportedObservables = [];\n              (_a = mediaOption.videoCodecList) === null || _a === void 0 ? void 0 : _a.forEach((codec) => {\n                  isTypeSupportedObservables = handleCodec(mediaOption, audioMediaOptions, codec, true, isTypeSupportedObservables);\n              });\n              if (((_b = mediaOption.audioCodecList) === null || _b === void 0 ? void 0 : _b.length) > 0) {\n                  const codec = RichestMedia.getRichestAudioCodec(mediaOption.audioCodecList);\n                  isTypeSupportedObservables = handleCodec(mediaOption, audioMediaOptions, codec, false, isTypeSupportedObservables);\n              }\n              let o = of(mediaOption);\n              if (isTypeSupportedObservables.length > 0) {\n                  o = forkJoin(isTypeSupportedObservables).pipe(map((results) => {\n                      const supported = results.find((supported) => supported === false) == undefined;\n                      if (!supported) {\n                          printMediaOptionInfo(mediaOption, logger);\n                      }\n                      return supported ? mediaOption : null;\n                  }), catchError((error) => {\n                      logger.warn(loggerName$1, `decodingInfo errror: ${error.message}`); // Missing field probably\n                      const supported = isSupportedInternal(mediaOption);\n                      if (!supported) {\n                          printMediaOptionInfo(mediaOption, logger);\n                      }\n                      return of(supported ? mediaOption : null);\n                  }));\n              }\n              observables.push(o);\n          });\n          return forkJoin(observables).pipe(map((list) => list.filter((item) => Boolean(item))));\n      }\n      function filterMediaOptionsBasedOnAudioAndVideoCodecs(mediaOptions, logger) {\n          const isSupportedInternal = createIsSupportedInternal();\n          const filteredMediaOptions = mediaOptions.filter(isSupportedInternal);\n          filterMediaOptionInfoPrint('Platform Supported Media Codec', mediaOptions, filteredMediaOptions, logger);\n          return filteredMediaOptions;\n      }\n      function filterMediaOptionsBasedOnExtendedAudioParameters(mediaOptions, audioMediaOptions, logger) {\n          const supportedMimeCodecs = new Set();\n          const unsupportedMimeCodecs = new Set();\n          /* Intentional negative tests to identify platform support for 'channels' and 'features' attributes via isTypeSupported().\n              - If the platform supports 'channels' & 'features' attributes, then the below calls will return false.\n              - Otherwise, if we get true, that means the platform ignores the 'channels' and/or 'features' attribute and we cannot rely on this API for testing them.\n          */\n          const shouldCheckChannels = !MediaSource.isTypeSupported('audio/mp4; codecs=\"mp4a.40.2\"; channels=\"-1\"');\n          const shouldCheckFeatures = shouldCheckChannels && !MediaSource.isTypeSupported('audio/mp4; codecs=\"mp4a.40.2\"; channels=\"2\"; features=\"INVALID\"');\n          logger.info(loggerName$1, `Platform support for channels: ${shouldCheckChannels}; features: ${shouldCheckFeatures}`);\n          const checkSupported = (codec, channels) => {\n              const parameters = channels.split('/');\n              const channelCount = parseInt(parameters[0]);\n              let mimeCodec;\n              let mimeCodecAlternate;\n              if (parameters.length > 1) {\n                  const features = parameters[1].split(',')[0]; // 'features' is the first in the comma separated list.\n                  mimeCodec = `audio/mp4;codecs=\"${codec}\";channels=\"${channelCount}\";features=\"${features}\"`;\n                  mimeCodecAlternate = `audio/mp4;codecs=\"${codec}\";channels=\"8\";features=\"${features}\"`;\n              }\n              else {\n                  mimeCodec = `audio/mp4;codecs=\"${codec}\";channels=\"${channelCount}\"`;\n              }\n              let isSupported = MediaSource.isTypeSupported(mimeCodec);\n              // LG doesn't return isTypeSupported correctly for 16ch ATMOS. This workaround uses 8ch test for ATMOS support.\n              // This code should be removed when LG firmware fix is in place.\n              if (!isSupported && mimeCodecAlternate) {\n                  isSupported = MediaSource.isTypeSupported(mimeCodecAlternate);\n                  logger.info(loggerName$1, `Using mimeCodecAlternate, isSupported: ${isSupported}; mimeCodecAlternate: ${mimeCodecAlternate}`);\n              }\n              return isSupported;\n          };\n          const updateCachedMimeCodecSetsIfNecessary = (codec, channels) => {\n              const mimeCodec = `${codec}/${channels}`;\n              if (!supportedMimeCodecs.has(mimeCodec) && !unsupportedMimeCodecs.has(mimeCodec)) {\n                  if (checkSupported(codec, channels)) {\n                      supportedMimeCodecs.add(mimeCodec);\n                  }\n                  else {\n                      unsupportedMimeCodecs.add(mimeCodec);\n                  }\n              }\n          };\n          // Update the mimeCodec support/notSupport cache based on MediaSource support.\n          // After that verify if that mimeCodec falls into unsupported category.\n          const checkUnsupportedMimeCodec = (codec, channels, logger) => {\n              const isAtmos = MediaUtil.isDolbyAtmos(codec, channels);\n              if (shouldCheckFeatures || (shouldCheckChannels && !isAtmos)) {\n                  // check for platform support\n                  updateCachedMimeCodecSetsIfNecessary(codec, channels);\n                  const mimeCodec = `${codec}/${channels}`;\n                  return unsupportedMimeCodecs.has(mimeCodec);\n              }\n              else {\n                  // Don't allow ATMOS if we cannot reliably check support via MediaSource.isTypeSupported()\n                  // All other cases are already handled via codec support\n                  return isAtmos ? true : false;\n              }\n          };\n          const filteredMediaOptions = mediaOptions.filter((mediaOption) => {\n              let foundUnsupportedMimeCodec = false;\n              // Extended parameters are valid only if there is an audio group\n              if (mediaOption.audioCodecList && mediaOption.audioGroupId) {\n                  const channels = RichestMedia.getRichestChannelLayoutForGroupId(mediaOption.audioGroupId, audioMediaOptions);\n                  if (mediaOption.audioCodecList.length > 0 && channels) {\n                      // pick the highest ranking audio codec to match with the channels tag\n                      const richestCodec = RichestMedia.getRichestAudioCodec(mediaOption.audioCodecList);\n                      // check only if channels attribute is present, otherwise, the case is already handled through audio codecs\n                      foundUnsupportedMimeCodec = checkUnsupportedMimeCodec(richestCodec, channels);\n                  }\n              }\n              return !foundUnsupportedMimeCodec;\n          });\n          filterMediaOptionInfoPrint('Richest Audio Codec Selection', mediaOptions, filteredMediaOptions, logger);\n          return filteredMediaOptions;\n      }\n      function getCapsForMediaOption(mediaOption, platformInfo) {\n          if (!platformInfo) {\n              return {\n                  highestPlayableAverageBitRate: undefined,\n                  highestPlayablePeakBitRate: undefined,\n                  highestPlayableWidth: undefined,\n                  highestPlayableHeight: undefined,\n                  highestPlayableFrameRate: undefined,\n              };\n          }\n          const firstMediaOptionCodec = mediaOption.videoCodec;\n          const firstMediaOptionVideoRange = mediaOption.videoRange;\n          const videoDynamicRangeFormats = platformInfo.videoDynamicRangeFormats;\n          const videoCodecs = platformInfo.videoCodecs;\n          const vdrType = MediaUtil.getDynamicRangeType(firstMediaOptionVideoRange, firstMediaOptionCodec);\n          const compressionType = MediaUtil.getCompressionType(firstMediaOptionCodec);\n          const caps = getCappingInfo(vdrType, compressionType, videoCodecs, videoDynamicRangeFormats);\n          // Ignore highestPlayablePeakBitRateForClearContent for all codecs and formats except VP9\n          if (compressionType !== CompressionType.VP09) {\n              caps.highestPlayablePeakBitRateForClearContent = undefined;\n          }\n          return caps;\n      }\n      function filterMediaOptionsByCaps(mediaOptions, sessionKeys, platformInfo, logger) {\n          const hasSessionKeys = (sessionKeys === null || sessionKeys === void 0 ? void 0 : sessionKeys.length) > 0;\n          const filteredMediaOptions = mediaOptions.filter((mediaOption) => {\n              const caps = getCapsForMediaOption(mediaOption, platformInfo);\n              const { highestPlayablePeakBitRateForClearContent } = caps;\n              // Use highestPlayablePeakBitRate|highestPlayablePeakBitRateForClearContent based on the presence of sessionKeys or allowedCPCMap which we assume means contents are encrypted\n              const assumeEncryptedContent = mediaOption.allowedCPCMap || hasSessionKeys;\n              const isWithinSafePeekBitRate = isWithinCap(mediaOption.bandwidth, caps.highestPlayablePeakBitRate);\n              const isWithinPeekBitRate = assumeEncryptedContent || !highestPlayablePeakBitRateForClearContent\n                  ? isWithinSafePeekBitRate\n                  : isWithinSafePeekBitRate || isWithinCap(mediaOption.bandwidth, highestPlayablePeakBitRateForClearContent);\n              return (isWithinPeekBitRate &&\n                  isWithinCap(mediaOption.avgBandwidth, caps.highestPlayableAverageBitRate) &&\n                  isWithinCap(mediaOption.width, caps.highestPlayableWidth) &&\n                  isWithinCap(mediaOption.height, caps.highestPlayableHeight) &&\n                  isWithinCap(mediaOption.frameRate, caps.highestPlayableFrameRate));\n          });\n          filterMediaOptionInfoPrint('Highest Playable Platform Caps', mediaOptions, filteredMediaOptions, logger);\n          return filteredMediaOptions;\n      }\n      function filterIframeMediaOptionsBasedOnCapOn1080p(mediaOptions, logger) {\n          // standard 1080p resolution with a slight tolerance of 1.2\n          const PIXELS_CAP = 2488320;\n          const filteredMediaOptions = mediaOptions.filter((mediaOption) => !mediaOption.iframes || !mediaOption.width || !mediaOption.height || mediaOption.width * mediaOption.height <= PIXELS_CAP);\n          filterMediaOptionInfoPrint('1080p iFrame', mediaOptions, filteredMediaOptions, logger);\n          return filteredMediaOptions;\n      }\n      function filterMediaOptionsBasedOnSupportedVideoFormats(mediaOptions, videoDynamicRangeFormats, logger) {\n          const supportedFormats = getSupportedVideoFormats(videoDynamicRangeFormats);\n          const { doViSupported, hdr10Supported, hlgSupported } = supportedFormats;\n          logger.info(loggerName$1, `Supported videoDynamicRangeFormats DoVi/HDR10/HLG: ${doViSupported}/${hdr10Supported}/${hlgSupported}`);\n          // filter based on supported videoDynamicRangeFormats\n          // only keep level with correct codec for video-range\n          const validMediaOptions = mediaOptions.reduce((prev, option) => {\n              var _a;\n              const vdr = MediaUtil.getDynamicRangeType(option.videoRange, (_a = option.videoCodec) !== null && _a !== void 0 ? _a : '');\n              switch (vdr) {\n                  case VideoDynamicRangeType.HDR:\n                  case VideoDynamicRangeType.HDR10:\n                      if (hdr10Supported) {\n                          prev.hdrMediaOptions.push(option);\n                      }\n                      break;\n                  case VideoDynamicRangeType.DolbyVision:\n                      if (doViSupported) {\n                          prev.hdrMediaOptions.push(option);\n                      }\n                      break;\n                  case VideoDynamicRangeType.HLG:\n                      if (hlgSupported) {\n                          prev.hdrMediaOptions.push(option);\n                      }\n                      break;\n                  default:\n                      // default is SDR\n                      if (option.videoRange === 'SDR' || option.videoRange == null) {\n                          prev.sdrMediaOptions.push(option);\n                      }\n              }\n              return prev;\n          }, { hdrMediaOptions: new Array(), sdrMediaOptions: new Array() });\n          logger.debug(loggerName$1, `HDR/SDR mediaOptions: ${validMediaOptions.hdrMediaOptions.length}/${validMediaOptions.sdrMediaOptions.length}`);\n          return validMediaOptions;\n      }\n      /**\n       * Filter root playlist. Remove all media options that should not ever be used on this platform based on\n       * capabilities (platformInfo and MediaCapabilities)\n       *\n       * @param mediaOptions        Original mediaOption list\n       * @param audioMediaOptions   Alternate mediaOption info\n       * @param platformInfo  Platform information for filtering out media options\n       * @param config        HLS Config option\n       * @returns { hdrMediaOptions: valid hdr media options, sdrMediaOptions: valid sdr media options }\n       */\n      function filterByPlatformCapabilities(mediaOptions, audioMediaOptions, sessionKeys, platformInfo, config, logger) {\n          const maxHdcpLevel = (platformInfo === null || platformInfo === void 0 ? void 0 : platformInfo.maxHdcpLevel) || undefined;\n          let filteredMediaOptions = [...mediaOptions];\n          if (config.disableVideoCodecList.size > 0 || config.disableAudioCodecList.size > 0) {\n              filteredMediaOptions = filterMediaOptionsBasedOnHlsConfig(filteredMediaOptions, config.disableVideoCodecList, config.disableAudioCodecList, logger);\n          }\n          if (maxHdcpLevel && isHdcpLevel(maxHdcpLevel)) {\n              filteredMediaOptions = filterMediaOptionsBasedOnMaxAllowedHdcpLevel(filteredMediaOptions, maxHdcpLevel, logger);\n          }\n          // Filter based on ALLOWED-CPC\n          const maxSecurityLevel = platformInfo === null || platformInfo === void 0 ? void 0 : platformInfo.maxSecurityLevel;\n          const keySystemId = config === null || config === void 0 ? void 0 : config.keySystemPreference;\n          if (maxSecurityLevel && keySystemId && isValidSecurityLevel(maxSecurityLevel, keySystemId)) {\n              filteredMediaOptions = filterMediaOptionsBasedOnSecurityLevel(filteredMediaOptions, maxSecurityLevel, keySystemId, logger);\n          }\n          // parse and set audioChannelCount property\n          filteredMediaOptions = filteredMediaOptions.map((mediaOption) => {\n              if (mediaOption.audioCodecList && mediaOption.audioGroupId) {\n                  const matchingTrack = audioMediaOptions.find((audio) => audio.groupId === mediaOption.audioGroupId);\n                  const channels = matchingTrack === null || matchingTrack === void 0 ? void 0 : matchingTrack.channels;\n                  if (channels) {\n                      mediaOption.audioChannelCount = parseInt(channels);\n                  }\n              }\n              return mediaOption;\n          });\n          const useMediaKeySystemAccessFilter = (config === null || config === void 0 ? void 0 : config.useMediaKeySystemAccessFilter) || false;\n          const keySystemAccessEnabled = useMediaKeySystemAccessFilter && keySystemId && navigator && typeof navigator.requestMediaKeySystemAccess === 'function';\n          const source = keySystemAccessEnabled ? filterMediaOptionsBasedOnMediaKeySystemAccess(filteredMediaOptions, keySystemId, logger) : of(filteredMediaOptions);\n          return source.pipe(switchMap((keySystemMediaOptions) => {\n              if (keySystemMediaOptions.length === 0 || onlyIframes(keySystemMediaOptions)) {\n                  throw new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, undefined, 'no media option with compatible codecs found in playlist', undefined);\n              }\n              if (keySystemAccessEnabled) {\n                  filterMediaOptionInfoPrint('Key System Support', filteredMediaOptions, keySystemMediaOptions, logger);\n              }\n              const mediaCapabilities = navigator && navigator.mediaCapabilities;\n              const useMediaCapabilities = (config === null || config === void 0 ? void 0 : config.useMediaCapabilities) || false;\n              const mediaCapabilitiesEnabled = useMediaCapabilities && mediaCapabilities && typeof mediaCapabilities.decodingInfo === 'function';\n              let source;\n              if (mediaCapabilitiesEnabled) {\n                  source = filterBasedOnMediaCapabilities(keySystemMediaOptions, audioMediaOptions, logger);\n              }\n              else {\n                  keySystemMediaOptions = filterMediaOptionsBasedOnAudioAndVideoCodecs(keySystemMediaOptions, logger);\n                  keySystemMediaOptions = filterMediaOptionsBasedOnExtendedAudioParameters(keySystemMediaOptions, audioMediaOptions, logger);\n                  source = of(keySystemMediaOptions);\n              }\n              return source.pipe(map((compatibleMediaOptions) => {\n                  if (compatibleMediaOptions.length === 0 || onlyIframes(compatibleMediaOptions)) {\n                      throw new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, undefined, 'no media option with compatible codecs found in manifest', undefined);\n                  }\n                  compatibleMediaOptions = filterMediaOptionsByCaps(compatibleMediaOptions, sessionKeys, platformInfo, logger);\n                  compatibleMediaOptions = filterIframeMediaOptionsBasedOnCapOn1080p(compatibleMediaOptions, logger);\n                  if (compatibleMediaOptions.length === 0 || onlyIframes(compatibleMediaOptions)) {\n                      throw new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, undefined, 'no media option with compatible codecs found in manifest', undefined);\n                  }\n                  // Seperate out fallback mediaOptions if needed\n                  let videoDynamicRangeFormats = (platformInfo === null || platformInfo === void 0 ? void 0 : platformInfo.videoDynamicRangeFormats) || [];\n                  if (mediaCapabilitiesEnabled && videoDynamicRangeFormats.length === 0) {\n                      // Just allow all types; MediaCapabilities API should have filtered out anything that was unsupported\n                      videoDynamicRangeFormats = [\n                          { type: VideoDynamicRangeType.SDR },\n                          { type: VideoDynamicRangeType.HDR },\n                          { type: VideoDynamicRangeType.HDR10 },\n                          { type: VideoDynamicRangeType.DolbyVision },\n                          { type: VideoDynamicRangeType.HLG },\n                      ];\n                  }\n                  const { hdrMediaOptions, sdrMediaOptions } = filterMediaOptionsBasedOnSupportedVideoFormats(compatibleMediaOptions, videoDynamicRangeFormats, logger);\n                  if ((hdrMediaOptions.length === 0 && sdrMediaOptions.length === 0) || (onlyIframes(hdrMediaOptions) && onlyIframes(sdrMediaOptions))) {\n                      throw new PlaylistParsingError(ErrorTypes.MEDIA_ERROR, ErrorDetails.MANIFEST_INCOMPATIBLE_VIDEO_RANGE_ERROR, undefined, 'mediaOption with compatible VIDEO-RANGE not found in manifest', undefined);\n                  }\n                  return { hdrMediaOptions, sdrMediaOptions };\n              }), catchError((err) => {\n                  if (err instanceof PlaylistParsingError) {\n                      err.fatal = true;\n                      err.response = ErrorResponses.IncompatibleAsset;\n                  }\n                  throw err;\n              }));\n          }));\n      }\n    \n      function mediaOptionToString(mediaOption) {\n          const MediaOptionLogAttributes = [\n              'persistentId',\n              'bitrate',\n              'bandwidth',\n              'avg-bandwidth',\n              'width',\n              'height',\n              'videoCodec',\n              'audioCodec',\n              'videoRange',\n              'iframes',\n              'frameRate',\n              'audioGroupId',\n              'score',\n          ];\n          return JSON.stringify(mediaOption, MediaOptionLogAttributes);\n      }\n    \n      function isValidCandidate(fromTrack, candidate) {\n          // Same persistentID but different rendition group\n          return candidate.mediaOptionId !== fromTrack.mediaOptionId && candidate.persistentID === fromTrack.persistentID && candidate.groupId !== fromTrack.groupId;\n      }\n      class AlternateMediaOptionListQuery extends MediaOptionListQuery {\n          constructor(store, itemId, mediaOptionType) {\n              super(store, itemId, mediaOptionType);\n          }\n          static makeFilters() {\n              return makeCommonFilters();\n          }\n          _initFilters() {\n              return AlternateMediaOptionListQuery.kAllowFilters;\n          }\n          // For convenience\n          get _mediaOptionType() {\n              return this.mediaOptionType;\n          }\n          get preferredHost() {\n              return null;\n          }\n          get preferredHost$() {\n              return of(null);\n          }\n          get mediaOptionListInfo() {\n              var _a, _b;\n              return (_b = (_a = this.getEntity(this.itemId)) === null || _a === void 0 ? void 0 : _a.mediaOptionListTuple[this._mediaOptionType]) !== null && _b !== void 0 ? _b : null;\n          }\n          get mediaOptionListInfo$() {\n              return this.selectEntity(this.itemId, (entity) => (entity && entity.mediaOptionListTuple ? entity.mediaOptionListTuple[this._mediaOptionType] : null)).pipe(filterNullOrUndefined());\n          }\n          // excludingVariants for skipping variants visited in successive getFallbackVariant; not applicable to alternates\n          // since we are looking for a *variant* fallback\n          getFallbackVariant(fromId, sdrOnly, shouldSwitchHosts, excludingVariants = undefined) {\n              var _a, _b;\n              const fromTrack = (_a = this.mediaOptionList) === null || _a === void 0 ? void 0 : _a.find((track) => track.mediaOptionId === fromId);\n              if (!fromTrack) {\n                  return null;\n              }\n              const filteredList = this.filteredMediaOptionList;\n              if (!filteredList) {\n                  return null;\n              }\n              // If shouldSwitchHosts is true, we must switch hosts\n              const fromHost = getHostName(fromTrack.url);\n              if (shouldSwitchHosts) {\n                  return (_b = filteredList.find((candidate) => isValidCandidate(fromTrack, candidate) && !hasMatchingHost(fromHost, candidate.url))) !== null && _b !== void 0 ? _b : null;\n              }\n              // else, allow any host but favor current if available\n              let newTrack = null;\n              for (const candidate of filteredList) {\n                  if (isValidCandidate(fromTrack, candidate) && (!newTrack || hasMatchingHost(fromHost, candidate.url))) {\n                      newTrack = candidate;\n                  }\n              }\n              return newTrack;\n          }\n          // excludingOptions for skipping soon-to-be-penalized alternates\n          getMatchingAlternateWithPersistentId(persistentId, variant, excludingOptions) {\n              var _a;\n              return ((_a = this.preferredMediaOptionList.find((option) => {\n                  if ((excludingOptions === null || excludingOptions === void 0 ? void 0 : excludingOptions.length) > 0 && excludingOptions.includes(option.mediaOptionId)) {\n                      return false;\n                  }\n                  if (!isFiniteNumber(persistentId) || option.persistentID === persistentId) {\n                      if (variant) {\n                          // match group and persistent id\n                          return this.matchGroup(option, variant.audioGroupId, variant.subtitleGroupId, variant.closedcaption);\n                      }\n                      else {\n                          // match only persistent id\n                          return true;\n                      }\n                  }\n                  else {\n                      return false;\n                  }\n              })) !== null && _a !== void 0 ? _a : null);\n          }\n          matchGroup(mediaOption, audioGroup, subtitleGroup, closedCaptionGroup) {\n              let result = false;\n              switch (mediaOption.type) {\n                  case 'CLOSED-CAPTIONS':\n                      result = !closedCaptionGroup || mediaOption.groupId === closedCaptionGroup;\n                      break;\n                  case 'SUBTITLES':\n                      result = !subtitleGroup || mediaOption.groupId === subtitleGroup;\n                      break;\n                  case 'AUDIO':\n                      result = !audioGroup || mediaOption.groupId === audioGroup;\n                      break;\n              }\n              return result;\n          }\n          getMatchingAlternate(fromId, variant) {\n              const fromAlternate = this.mediaOptionFromId(fromId);\n              return this.getMatchingAlternateWithPersistentId(fromAlternate === null || fromAlternate === void 0 ? void 0 : fromAlternate.persistentID, variant, []);\n          }\n          /**\n           * Package Alternate media Option\n           * Augment closed-captions mediaOption with the playlist URL of a supporting subtitle mediaOption.\n           * This allows Apple-style closed-caption track to include forced subtitles from the supporting WebVTT playlist.\n           *\n           * @param variantOption The variantMediaOption that is to be augmented.\n           * @param altOption The alternate media option (has to be of type closed caption) to be augmented\n           * @param useFilteredList boolean if true use a filtered list for packaging, hence do not include media in penalty Box\n           *                                if false use an unfiltered raw list as seen from the manifest.\n           * @return AlternateMediaOption A packaged alternate media option or altOption if packaging was not possible\n           */\n          packageAlternateMediaOption(variantOption, altOption, useFilteredList) {\n              return altOption.mediaType === MediaTypeFourCC.CLOSEDCAPTION ? this.augmentClosedCaptionsWithForcedSubtitles(variantOption === null || variantOption === void 0 ? void 0 : variantOption.subtitleGroupId, altOption, useFilteredList) : altOption;\n          }\n          augmentClosedCaptionsWithForcedSubtitles(subtitleGroup, closedCaptionMediaOption, useFilteredList) {\n              const forcedMediaOption = this.pairForcedSubtitleMediaOptionWithClosedCaption(subtitleGroup, closedCaptionMediaOption, useFilteredList);\n              return forcedMediaOption ? Object.assign(Object.assign({}, closedCaptionMediaOption), { url: forcedMediaOption.url, backingMediaOptionId: forcedMediaOption.mediaOptionId }) : closedCaptionMediaOption;\n          }\n          pairForcedSubtitleMediaOptionWithClosedCaption(subtitleGroup, selectedMediaOption, useFilteredList) {\n              let supportingOption;\n              if (selectedMediaOption && selectedMediaOption.mediaType === MediaTypeFourCC.CLOSEDCAPTION) {\n                  let list = this.mediaOptionList;\n                  if (useFilteredList) {\n                      list = this.preferredMediaOptionList;\n                  }\n                  supportingOption = AlternateMediaOptionListQuery.pairForcedSubtitleMediaOptionWithClosedCaptionInList(subtitleGroup, selectedMediaOption, list);\n              }\n              return supportingOption;\n          }\n          static pairForcedSubtitleMediaOptionWithClosedCaptionInList(subtitleGroup, selectedMediaOption, mediaOptionList) {\n              return mediaOptionList.find(function (option) {\n                  const match = option.mediaType === MediaTypeFourCC.SUBTITLE && option.lang === selectedMediaOption.lang && option.forced && option.autoselect && (!subtitleGroup || option.groupId === subtitleGroup);\n                  if (match) {\n                      getLogger().debug(`[subtitle] pick side track persistent id ${option.persistentID} option id ${option.id} option mediaOptionId ${option.mediaOptionId} group id ${option.groupId} (=${subtitleGroup})`);\n                  }\n                  return match;\n              });\n          }\n      }\n      AlternateMediaOptionListQuery.kAllowFilters = AlternateMediaOptionListQuery.makeFilters();\n    \n      /**\n       * @brief Query interface to the root playlist store\n       */\n      class RootPlaylistQuery extends QueryEntity {\n          constructor(rootPlaylistStore, itemId) {\n              super(rootPlaylistStore);\n              this.itemId = itemId;\n              this.mediaOptionListQueries = [\n                  new VariantMediaOptionListQuery(rootPlaylistStore, this.itemId),\n                  new AlternateMediaOptionListQuery(rootPlaylistStore, this.itemId, MediaOptionType.AltAudio),\n                  new AlternateMediaOptionListQuery(rootPlaylistStore, this.itemId, MediaOptionType.Subtitle),\n              ];\n          }\n          // getters\n          get rootPlaylistEntity() {\n              return this.getEntity(this.itemId);\n          }\n          /**\n           * @returns the unmodified original media options without filters applied\n           */\n          get rootMediaOptionsTuple() {\n              var _a;\n              const mediaOptionListTuple = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.mediaOptionListTuple;\n              if (mediaOptionListTuple) {\n                  return [mediaOptionListTuple[0].mediaOptions, mediaOptionListTuple[1].mediaOptions, mediaOptionListTuple[2].mediaOptions];\n              }\n              return [[], [], []];\n          }\n          /**\n           * @returns the position in media corresponding to the start of this item\n           */\n          get itemStartOffset() {\n              var _a, _b, _c;\n              if (((_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.itemStartOffset) && isFiniteNumber((_b = this.rootPlaylistEntity) === null || _b === void 0 ? void 0 : _b.itemStartOffset)) {\n                  return (_c = this.rootPlaylistEntity) === null || _c === void 0 ? void 0 : _c.itemStartOffset;\n              }\n              return 0;\n          }\n          get highestVideoCodec() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.highestVideoCodec;\n          }\n          get baseUrl() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.baseUrl;\n          }\n          get anchorTime() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.anchorTime;\n          }\n          get discoSeqNum() {\n              var _a, _b;\n              return (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.discoSeqNum) !== null && _b !== void 0 ? _b : NaN;\n          }\n          get discoSeqNum$() {\n              return this.selectEntity(this.itemId, 'discoSeqNum');\n          }\n          get audioMediaSelectionGroup() {\n              var _a, _b;\n              return (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.audioMediaSelectionGroup) !== null && _b !== void 0 ? _b : null;\n          }\n          get subtitleMediaSelectionGroup() {\n              var _a, _b;\n              return (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.subtitleMediaSelectionGroup) !== null && _b !== void 0 ? _b : null;\n          }\n          get audioMediaSelectionOptions() {\n              var _a, _b, _c;\n              return (_c = (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.audioMediaSelectionGroup) === null || _b === void 0 ? void 0 : _b.MediaSelectionGroupOptions) !== null && _c !== void 0 ? _c : [];\n          }\n          get subtitleMediaSelectionOptions() {\n              var _a, _b, _c;\n              return (_c = (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.subtitleMediaSelectionGroup) === null || _b === void 0 ? void 0 : _b.MediaSelectionGroupOptions) !== null && _c !== void 0 ? _c : [];\n          }\n          get contentSteeringOption() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.contentSteeringOption;\n          }\n          get masterVariableList() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.masterVariableList;\n          }\n          get loadStats() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.loadStats;\n          }\n          get isMediaPlaylist() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.isMediaPlaylist;\n          }\n          getInitPTS(discoSeqNum) {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.initPtsRecord[discoSeqNum];\n          }\n          get abrStatus$() {\n              return this.selectEntity(this.itemId, (entity) => entity === null || entity === void 0 ? void 0 : entity.abrStatus);\n          }\n          get abrStatus() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.abrStatus;\n          }\n          get nextMaxAutoOptionId() {\n              var _a, _b;\n              return (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.abrStatus) === null || _b === void 0 ? void 0 : _b.nextMaxAutoOptionId;\n          }\n          get nextMinAutoOptionId() {\n              var _a, _b;\n              return (_b = (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.abrStatus) === null || _b === void 0 ? void 0 : _b.nextMinAutoOptionId;\n          }\n          initPTS$(discoSeqNum) {\n              return this.selectEntity(this.itemId, ({ initPtsRecord }) => initPtsRecord[discoSeqNum]);\n          }\n          // observables\n          get rootPlaylistEntity$() {\n              return this.selectEntity(this.itemId).pipe(filter((rootEntity) => Boolean(rootEntity)), map((rootEntity) => rootEntity));\n          }\n          get rootPlaylistEntityAdded$() {\n              return this.selectEntityAction(EntityActions.Add).pipe(map((itemIds) => itemIds.map((itemId) => this.getEntity(itemId))));\n          }\n          /**\n           * @returns the unmodified original media options without filters applied\n           */\n          get rootMediaOptionsTuple$() {\n              return combineQueries([\n                  this.selectEntity(this.itemId, (entity) => entity.mediaOptionListTuple[0].mediaOptions),\n                  this.selectEntity(this.itemId, (entity) => entity.mediaOptionListTuple[1].mediaOptions),\n                  this.selectEntity(this.itemId, (entity) => entity.mediaOptionListTuple[2].mediaOptions),\n              ]);\n          }\n          get sessionData() {\n              var _a;\n              return (_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.sessionData;\n          }\n          get sessionData$() {\n              return this.selectEntity(this.itemId, ({ sessionData }) => sessionData).pipe(filterNullOrUndefined());\n          }\n          get anchorTime$() {\n              return this.selectEntity(this.itemId, 'anchorTime').pipe(switchMap((anchorTime) => {\n                  var _a, _b;\n                  if (!isFiniteNumber(anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos)) {\n                      return EMPTY;\n                  }\n                  if ((anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos) !== ((_a = this.anchorTime) === null || _a === void 0 ? void 0 : _a.pos)) {\n                      // Kind of hacky but sometimes this happens????\n                      getLogger().warn(`anchorTime doesn't match stored value! ${anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos} !== ${(_b = this.anchorTime) === null || _b === void 0 ? void 0 : _b.pos}`);\n                      return EMPTY;\n                  }\n                  return of(anchorTime);\n              }));\n          }\n          get pendingSeek$() {\n              return this.selectEntity(this.itemId, ({ pendingSeek }) => pendingSeek).pipe(distinctUntilChanged((a, b) => a === b || (typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b))));\n          }\n          get enabledMediaOptionKeys$() {\n              return this.selectEntity(this.itemId, 'enabledMediaOptionKeys').pipe(filter((keys) => Boolean(keys)));\n          }\n          get enabledMediaOptionKeys() {\n              var _a, _b;\n              return (_b = (_a = this.getEntity(this.itemId)) === null || _a === void 0 ? void 0 : _a.enabledMediaOptionKeys) !== null && _b !== void 0 ? _b : [NoMediaOption, NoMediaOption, NoMediaOption];\n          }\n          get enabledMediaOptionSwitchContexts() {\n              var _a, _b;\n              return (_b = (_a = this.getEntity(this.itemId)) === null || _a === void 0 ? void 0 : _a.mediaOptionSwitchContexts) !== null && _b !== void 0 ? _b : [null, null, null];\n          }\n          enabledMediaOptionSwitchContextsByType$(mediaOptionType) {\n              return this.selectEntity(this.itemId, 'mediaOptionSwitchContexts').pipe(map((contexts) => contexts === null || contexts === void 0 ? void 0 : contexts[mediaOptionType]));\n          }\n          get enabledMediaOptions$() {\n              return combineQueries([\n                  this.enabledMediaOptionByType$(MediaOptionType.Variant),\n                  this.enabledMediaOptionByType$(MediaOptionType.AltAudio),\n                  this.enabledMediaOptionByType$(MediaOptionType.Subtitle),\n              ]);\n          }\n          // Convenience method for just A/V\n          get enabledAVOptions$() {\n              return combineQueries([this.enabledMediaOptionByType$(MediaOptionType.Variant), this.enabledMediaOptionByType$(MediaOptionType.AltAudio)]);\n          }\n          rawEnabledMediaOptionByType$(mediaOptionType) {\n              return this.enabledMediaOptionKeys$.pipe(map((enabledMediaOptionKeys) => {\n                  const mediaOptionKey = enabledMediaOptionKeys[mediaOptionType];\n                  if (!isEnabledMediaOption(mediaOptionKey)) {\n                      // return NoMediaOption even if mediaOptionKey may have a valid itemId.\n                      // callers typically check for NoMediaOption only to see if a track is disabled.\n                      return NoMediaOption;\n                  }\n                  const options = this.rootMediaOptionsTuple[mediaOptionType];\n                  const foundOption = options.find((option) => mediaOptionKeyEquals(option, mediaOptionKey));\n                  return foundOption ? foundOption : NoMediaOption;\n              }));\n          }\n          enabledMediaOptionByType$(mediaOptionType) {\n              return this.rawEnabledMediaOptionByType$(mediaOptionType).pipe(distinctUntilChanged((a, b) => a.mediaOptionId === b.mediaOptionId && a.url === b.url));\n          }\n          /**\n           * Emits when selected option changes and returns switch information\n           */\n          enabledMediaOptionSwitchForType$(mediaOptionType) {\n              // Only trigger on option change, not when context is set\n              // rawEnabledMediaOptionByType does not de-dupe mediaOption changes\n              // so it's possible to snapshot/represent a switch to the same mediaOption { fromId: sameMediaOptionId, toId: sameMediaOptionId }\n              // when this happens, the observer will know no switching took place and it won't trigger any change event.\n              // enabledMediaOptionByType will always return a stale mediaOption switch from previous activities,\n              // potentially causing bogus emits and event triggers.\n              return this.rawEnabledMediaOptionByType$(mediaOptionType).pipe(withLatestFrom(this.enabledMediaOptionSwitchContextsByType$(mediaOptionType)), startWith(null), pairwise(), map(([a, b]) => {\n                  return { fromId: a === null || a === void 0 ? void 0 : a[0].mediaOptionId, toId: b === null || b === void 0 ? void 0 : b[0].mediaOptionId, switchContext: b === null || b === void 0 ? void 0 : b[1] };\n              }), distinctUntilChanged((x, y) => x.fromId === y.fromId && x.toId === y.toId));\n          }\n          enableMediaOptionSwitchedForType$(mediaOptionType) {\n              return this.enabledMediaOptionByType$(mediaOptionType).pipe(switchMap((mediaOption) => waitFor(combineLatest([of(mediaOption), this.enabledMediaOptionSwitchContextsByType$(mediaOptionType).pipe(pairwise())]), ([option, contexts]) => contexts[0] && !contexts[1])), \n              // drop the contexts because contexts[0] may be wrong in this sequence:\n              // 1. Request 1: setEnabledMediaOptions( englishMediaOption, { switchPosition: 0.0 });\n              // 2. Request 2: setEnabledMediaOptions( englishMediaOption, { switchPosition: 1.0 });\n              // 3. Request 2 succeeded: setEnabledMediaOptions( englishMediaOption, null);\n              // But this function will return [englishMediaOption, [{ switchPosition: 0.0 }, null]]\n              // Nonetheless, englishMediaOption did switch successfully.\n              map(([option]) => option));\n          }\n          enabledMediaOptionIdByType(mediaOptionType) {\n              return this.getEntity(this.itemId).enabledMediaOptionKeys[mediaOptionType].mediaOptionId;\n          }\n          get enabledVariantMediaOptionIdBeforeTrickplaySwitch() {\n              return this.getEntity(this.itemId).enabledVariantMediaOptionIdBeforeTrickplaySwitch;\n          }\n          variantMediaOptionById(mediaOptionId) {\n              return this.mediaOptionListQueries[MediaOptionType.Variant].mediaOptionFromId(mediaOptionId);\n          }\n          alternateMediaOptionById(mediaOptionType, mediaOptionId) {\n              return this.mediaOptionListQueries[mediaOptionType].mediaOptionFromId(mediaOptionId);\n          }\n          enabledAlternateMediaOptionByType(mediaOptionType) {\n              const enabledOptionId = this.enabledMediaOptionIdByType(mediaOptionType);\n              return this.alternateMediaOptionById(mediaOptionType, enabledOptionId);\n          }\n          get enabledVariantMediaOption() {\n              const enabledOptionId = this.enabledMediaOptionIdByType(MediaOptionType.Variant);\n              return this.variantMediaOptionById(enabledOptionId);\n          }\n          lastLoadedMediaOptionByType(mediaOptionType) {\n              var _a;\n              return (_a = this.getEntity(this.itemId).lastLoadedMediaOptionKeys) === null || _a === void 0 ? void 0 : _a[mediaOptionType];\n          }\n          /**\n           * Set by ABR and error handling. Next enabled media options to be used next time we are allowed to switch\n           */\n          get nextMediaOptionsKeys$() {\n              return this.selectEntity(this.itemId, 'nextMediaOptionKeys');\n          }\n          /**\n           * Return the filtered list with preferred host filtering\n           */\n          get preferredMediaOptions() {\n              return [this.mediaOptionListQueries[0].preferredMediaOptionList, this.mediaOptionListQueries[1].preferredMediaOptionList, this.mediaOptionListQueries[2].preferredMediaOptionList];\n          }\n          get preferredMediaOptions$() {\n              return combineQueries([\n                  this.mediaOptionListQueries[0].preferredMediaOptionList$,\n                  this.mediaOptionListQueries[1].preferredMediaOptionList$,\n                  this.mediaOptionListQueries[2].preferredMediaOptionList$,\n              ]);\n          }\n          get filteredMediaOptions() {\n              return [this.mediaOptionListQueries[0].filteredMediaOptionList, this.mediaOptionListQueries[1].filteredMediaOptionList, this.mediaOptionListQueries[2].filteredMediaOptionList];\n          }\n          getDisabledMediaOption(mediaOptionType) {\n              return { itemId: this.itemId, mediaOptionType, mediaOptionId: 'Nah' };\n          }\n          getEnabledMediaOptionMask() {\n              return this.enabledMediaOptionKeys.map((key) => isEnabledMediaOption(key));\n          }\n          /**\n           * Get filtered list with preferred host filtering by type\n           * @param mediaOptionType The type to get info about\n           */\n          getPreferredMediaOptionsByType$(mediaOptionType) {\n              return this.mediaOptionListQueries[mediaOptionType].preferredMediaOptionList$;\n          }\n          altMediaOptionHasValidUrl(mediaOptionType, mediaOptionId) {\n              const altOption = this.alternateMediaOptionById(mediaOptionType, mediaOptionId);\n              return Boolean(altOption === null || altOption === void 0 ? void 0 : altOption.url);\n          }\n          /**\n           * Return whether the preferred variant set is HDR\n           */\n          get hdrMode$() {\n              return this.mediaOptionListQueries[MediaOptionType.Variant].hdrMode$;\n          }\n          get maxHdcpLevel$() {\n              return this.mediaOptionListQueries[MediaOptionType.Variant].maxHdcpLevel$;\n          }\n          get currentPathwayID() {\n              return this.mediaOptionListQueries[MediaOptionType.Variant].currentPathwayID;\n          }\n          get preferredHost() {\n              return this.mediaOptionListQueries[MediaOptionType.Variant].preferredHost;\n          }\n          /**\n           * Get error info by type\n           * @param mediaOptionType The type to get info about\n           */\n          getErrorInfoByType(mediaOptionType) {\n              var _a;\n              if (((_a = this.rootPlaylistEntity) === null || _a === void 0 ? void 0 : _a.errorsByType) != null) {\n                  return this.rootPlaylistEntity.errorsByType[mediaOptionType];\n              }\n              return null;\n          }\n          getInFlightFragByType(mediaOptionType) {\n              var _a, _b, _c;\n              return (_c = (_b = (_a = this.getEntity(this.itemId)) === null || _a === void 0 ? void 0 : _a.inFlightFrags) === null || _b === void 0 ? void 0 : _b[mediaOptionType]) !== null && _c !== void 0 ? _c : null;\n          }\n          getInFlightFragByType$(mediaOptionType) {\n              return this.selectEntity(this.itemId, (entity) => { var _a; return (_a = entity === null || entity === void 0 ? void 0 : entity.inFlightFrags) === null || _a === void 0 ? void 0 : _a[mediaOptionType]; });\n          }\n          matchAlternates(currentVariant, audioPersistentId, subtitlePersistentId, excludingOptions) {\n              const audioAltMediaOption = isFiniteNumber(audioPersistentId)\n                  ? this.mediaOptionListQueries[MediaOptionType.AltAudio].getMatchingAlternateWithPersistentId(audioPersistentId, currentVariant, excludingOptions)\n                  : undefined;\n              const subtitleAltMediaOption = isFiniteNumber(subtitlePersistentId)\n                  ? this.mediaOptionListQueries[MediaOptionType.Subtitle].getMatchingAlternateWithPersistentId(subtitlePersistentId, currentVariant, excludingOptions)\n                  : undefined;\n              return [audioAltMediaOption ? audioAltMediaOption : NoMediaOption, subtitleAltMediaOption ? subtitleAltMediaOption : NoMediaOption];\n          }\n          getLegacyMatchingAlternateWithPersistentId(mediaOptionType, persistentId, currentVariant) {\n              let altMediaOption = this.mediaOptionListQueries[mediaOptionType].getMatchingAlternateWithPersistentId(persistentId, currentVariant, []);\n              if (!altMediaOption) {\n                  altMediaOption = this.mediaOptionListQueries[mediaOptionType].getMatchingAlternateWithPersistentId(persistentId, undefined, []); // just match persistent id\n              }\n              return altMediaOption;\n          }\n          isValidMediaOptionTuple(tuple, mediaOptionMask = undefined) {\n              const expectedEnabledMediaOptionMask = mediaOptionMask ? mediaOptionMask : this.getEnabledMediaOptionMask();\n              const result = [MediaOptionType.Variant, MediaOptionType.AltAudio, MediaOptionType.Subtitle].reduce((prev, cur) => {\n                  return prev && expectedEnabledMediaOptionMask[cur] === isEnabledMediaOption(tuple[cur]);\n              }, true);\n              return result;\n          }\n          matchGroup(mediaOption, audioGroup, subtitleGroup, closedCaptionGroup) {\n              const mediaType = mediaOption.mediaOptionType;\n              const altOptionQuery = this.mediaOptionListQueries[mediaType];\n              return altOptionQuery.matchGroup(mediaOption, audioGroup, subtitleGroup, closedCaptionGroup);\n          }\n          get preferHDR() {\n              return this.mediaOptionListQueries[MediaOptionType.Variant].mediaOptionListInfo.preferHDR;\n          }\n      }\n    \n      class RootPlaylistStore extends EntityStore {\n          constructor() {\n              super({}, { name: 'root-playlist-store', idKey: 'itemId', producerFn: produce_1 });\n          }\n          akitaPreAddEntity(newEntity) {\n              if (newEntity.errorsByType == null) {\n                  return Object.assign(Object.assign({}, newEntity), { errorsByType: [{ timeouts: { load: 0, append: 0, key: 0 } }, { timeouts: { load: 0, append: 0, key: 0 } }, { timeouts: { load: 0, append: 0, key: 0 } }] });\n              }\n              return newEntity;\n          }\n      }\n    \n      const loggerName = { name: 'rps' };\n      /**\n       * @brief Service for managing root playlist state.  Will fetch the root playlist and manage selected media options\n       */\n      const PENALTYBOX_TIMEOUT_MS = 120000; // 2 minutes\n      class RootPlaylistService {\n          constructor(store, logger) {\n              this.store = store;\n              this.logger = logger;\n          }\n          getQuery() {\n              return new QueryEntity(this.store);\n          }\n          getQueryForId(itemId) {\n              return new RootPlaylistQuery(this.store, itemId);\n          }\n          set rootPlaylistEntity(rootPlaylistEntity) {\n              logAction('root.add.rootPlaylist');\n              this.store.add(rootPlaylistEntity);\n          }\n          // Remove entity by item id\n          removeItems(itemIds) {\n              logAction(`root.add.remove ${JSON.stringify(itemIds)}`);\n              this.store.remove(itemIds);\n          }\n          // Remove all entities\n          removeAll() {\n              logAction('root.add.clear');\n              this.store.remove();\n          }\n          setRootPlaylistEntity(itemId, rootPlaylistEntity) {\n              logAction('root.set.rootPlaylistEntity');\n              this.store.update(itemId, (entity) => {\n                  // Must return this so that entire entity is updated\n                  return (rootPlaylistEntity);\n              });\n          }\n          setSessionData(itemId, sessionData) {\n              logAction('root.set.sessionData');\n              this.store.update(itemId, (rootPlaylistEntity) => {\n                  rootPlaylistEntity.sessionData = sessionData;\n              });\n          }\n          /**\n           * Update the position and discontinuity sequence number used for choosing fragments\n           * @param anchorTime  The anchor position\n           * @param discoSeqNum The discontinuity sequence number\n           */\n          setAnchorTime(itemId, anchorTime) {\n              logAction(`root.set.anchorTime: ${anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.pos} ${anchorTime === null || anchorTime === void 0 ? void 0 : anchorTime.discoSeqNum}`);\n              this.store.update(itemId, (rootPlaylistEntity) => {\n                  rootPlaylistEntity.anchorTime = anchorTime;\n              });\n          }\n          setDiscoSeqNum(itemId, cc) {\n              logAction(`root.set.discoSeqNum: ${cc}`);\n              this.store.update(itemId, (rootPlaylistEntity) => {\n                  rootPlaylistEntity.discoSeqNum = cc;\n              });\n          }\n          setPendingSeek(itemId, pendingSeek) {\n              logAction('root.set.pendingSeek');\n              this.store.update(itemId, (rootPlaylistEntity) => {\n                  rootPlaylistEntity.pendingSeek = pendingSeek;\n              });\n              if (pendingSeek === undefined) {\n                  globalHlsService().setUserSeek(pendingSeek);\n              }\n          }\n          setEnabledMediaOptionSwitchContextByType(itemId, mediaOptionType, mediaOptionId, context) {\n              this.logger.info(`root.set.mediaOptionSwitchContextByType: ${mediaOptionType} ${mediaOptionId} ${context === null || context === void 0 ? void 0 : context.userInitiated}`);\n              this.store.update(itemId, (entity) => {\n                  var _a;\n                  if (entity.enabledMediaOptionKeys[mediaOptionType].mediaOptionId === mediaOptionId) {\n                      const mediaOptionContextTuple = (_a = entity.mediaOptionSwitchContexts) !== null && _a !== void 0 ? _a : [null, null, null];\n                      mediaOptionContextTuple[mediaOptionType] = context ? { userInitiated: context.userInitiated, switchPosition: context.switchPosition } : null;\n                      entity.mediaOptionSwitchContexts = mediaOptionContextTuple;\n                  }\n                  else {\n                      // Don't update switch context for a different mediaOption\n                      logAction(`root.set.mediaOptionSwitchContextByType ${mediaOptionId} doesn't match existing mediaOption ${entity.enabledMediaOptionKeys[mediaOptionType].mediaOptionId}`);\n                  }\n              });\n          }\n          setEnabledVariantMediaOptionIdBeforeTrickplaySwitch(itemId, id) {\n              this.logger.info(`root.set.enabledVariantMediaOptionIdBeforeTrickplaySwitch: ${id}`);\n              this.store.update(itemId, (entity) => {\n                  entity.enabledVariantMediaOptionIdBeforeTrickplaySwitch = id;\n              });\n          }\n          setEnabledMediaOptionByType(itemId, mediaOptionType, mediaOption, replaceContext = false, context = undefined) {\n              if (!mediaOption) {\n                  mediaOption = { itemId, mediaOptionType, mediaOptionId: 'Nah' };\n              }\n              this.logger.info(`root.set.mediaOptionByType: ${mediaOptionType} ${mediaOption.mediaOptionId} replaceCtxt ${replaceContext} ctxt ${JSON.stringify(context === null || context === void 0 ? void 0 : context.userInitiated)}`);\n              this.store.update(itemId, (entity) => {\n                  var _a, _b;\n                  const mediaOptionKeyTuple = (_a = [...entity.enabledMediaOptionKeys]) !== null && _a !== void 0 ? _a : [NoMediaOption, NoMediaOption, NoMediaOption];\n                  mediaOptionKeyTuple[mediaOptionType] = { itemId, mediaOptionId: mediaOption.mediaOptionId };\n                  this._updateEnabledMediaOptionKeys(entity, mediaOptionKeyTuple);\n                  if (replaceContext) {\n                      // consider this sequence of events:\n                      // (1) user switches audio mediaOption. Such an alt audio switch will include a switchContext.\n                      // (2) While audio mediaOption is being handled, user switches subtitle mediaOption, hls.js *might* also switch the audio mediaOption to match the latest group-ids.\n                      // The \"silent\" audio track switch in (2) should not override the userInitiated switchContext in (1)\n                      // replaceContext should be true in (1) and false in (2)\n                      const mediaOptionContextTuple = (_b = entity.mediaOptionSwitchContexts) !== null && _b !== void 0 ? _b : [null, null, null];\n                      mediaOptionContextTuple[mediaOptionType] = context ? { userInitiated: context.userInitiated, switchPosition: context.switchPosition } : null;\n                      entity.mediaOptionSwitchContexts = mediaOptionContextTuple;\n                  }\n              });\n          }\n          _associateForcedSubtitleWithClosedCaption(entity, variantMediaOptionId, closedCaption, rootQuery) {\n              if ((closedCaption === null || closedCaption === void 0 ? void 0 : closedCaption.mediaType) === MediaTypeFourCC.CLOSEDCAPTION) {\n                  const variantOption = rootQuery.variantMediaOptionById(variantMediaOptionId);\n                  const newClosedCaption = rootQuery.mediaOptionListQueries[MediaOptionType.Subtitle].packageAlternateMediaOption(variantOption, closedCaption, true);\n                  getLogger().info(`[subtitle] new closedCaption ${redactUrl(newClosedCaption.url)} vs old ${redactUrl(closedCaption.url)}`);\n                  if (newClosedCaption.url !== closedCaption.url) {\n                      const newMediaOptions = replaceClosedCaptionInMediaOptionListIfNecessary(variantOption, newClosedCaption, entity.mediaOptionListTuple[MediaOptionType.Subtitle].mediaOptions, getLogger());\n                      entity.mediaOptionListTuple[MediaOptionType.Subtitle].mediaOptions = newMediaOptions;\n                  }\n              }\n          }\n          // Stuff that must be done always when setting enabledMediaOptionKeys\n          _updateEnabledMediaOptionKeys(entity, mediaOptionKeyTuple) {\n              var _a;\n              const enabledMediaOptionKeys = (_a = entity.enabledMediaOptionKeys) !== null && _a !== void 0 ? _a : [NoMediaOption, NoMediaOption, NoMediaOption];\n              let enabledVariantKey;\n              for (let type = 0; type < mediaOptionKeyTuple.length; ++type) {\n                  const newOption = mediaOptionKeyTuple[type];\n                  const didChange = enabledMediaOptionKeys[type].mediaOptionId !== newOption.mediaOptionId;\n                  if (didChange) {\n                      enabledMediaOptionKeys[type] = Object.assign({}, newOption);\n                  }\n                  if (type === MediaOptionType.Variant) {\n                      // Using all mediaOptions so that mediaOptions in PenaltyBox are also considered when setting highBWTrigger\n                      const unfilteredList = this.getQueryForId(newOption.itemId).mediaOptionListQueries[type].mediaOptionList;\n                      if (didChange) {\n                          entity.abrStatus = initializeAbrStatus(newOption.mediaOptionId, unfilteredList);\n                      }\n                      else {\n                          // Just update highBW trigger\n                          entity.abrStatus.highBWTrigger = getLowestSuperiorBW(newOption.mediaOptionId, unfilteredList);\n                      }\n                      enabledVariantKey = newOption;\n                  }\n                  else if (type === MediaOptionType.Subtitle && isEnabledMediaOption(newOption)) {\n                      const rootQuery = this.getQueryForId(newOption.itemId);\n                      const subtitleOption = rootQuery.alternateMediaOptionById(type, newOption.mediaOptionId);\n                      this._associateForcedSubtitleWithClosedCaption(entity, enabledVariantKey.mediaOptionId, subtitleOption, rootQuery);\n                  }\n              }\n              entity.enabledMediaOptionKeys = enabledMediaOptionKeys;\n              entity.nextMediaOptionKeys = undefined;\n          }\n          // Disables ABR. for development\n          setManualMode(itemId, manualMode) {\n              this.store.update(itemId, (entity) => {\n                  entity.manualMode = manualMode;\n              });\n          }\n          setEnabledMediaOptions(itemId, mediaOptions) {\n              this.logger.info(`root.set.enabledMediaOptions: ${JSON.stringify(mediaOptions.map((x) => x.mediaOptionId))}`);\n              this.store.update(itemId, (entity) => {\n                  const mediaOptionKeyTuple = mediaOptions.map(({ mediaOptionId, itemId }) => {\n                      const result = { mediaOptionId, itemId };\n                      return result;\n                  });\n                  this._updateEnabledMediaOptionKeys(entity, mediaOptionKeyTuple);\n              });\n          }\n          setEnabledMediaOptionsAndSwitchContexts(itemId, mediaOptions, switchContexts) {\n              this.logger.info(`root.set.enabledMediaOptionsAndSwitchContexts: ${JSON.stringify(mediaOptions.map((x) => x.mediaOptionId))} ctxt ${JSON.stringify(switchContexts)}`);\n              this.store.update(itemId, (entity) => {\n                  const mediaOptionKeyTuple = mediaOptions.map(({ mediaOptionId, itemId }) => {\n                      const result = { mediaOptionId, itemId };\n                      return result;\n                  });\n                  this._updateEnabledMediaOptionKeys(entity, mediaOptionKeyTuple);\n                  entity.mediaOptionSwitchContexts = switchContexts;\n              });\n          }\n          setNextMediaOptions(itemId, mediaOptions) {\n              logAction(`root.set.nextMediaOptions: ${JSON.stringify(mediaOptions === null || mediaOptions === void 0 ? void 0 : mediaOptions.map((x) => x.mediaOptionId))}`);\n              this.store.update(itemId, (entity) => {\n                  const keys = mediaOptions\n                      ? mediaOptions.map(({ itemId, mediaOptionId }) => {\n                          const result = { itemId, mediaOptionId };\n                          return result;\n                      })\n                      : null;\n                  entity.nextMediaOptionKeys = keys;\n              });\n          }\n          // updateEnabledMediaOptions should not touch the switch context\n          updateEnabledMediaOptions(itemId) {\n              logAction('root.set.updateEnabledMediaOptions');\n              this.store.update(itemId, (entity) => {\n                  if (entity.nextMediaOptionKeys && entity.manualMode !== true) {\n                      logAction(`root.set.updateEnabledMediaOptions ${JSON.stringify(entity.nextMediaOptionKeys)}`);\n                      this._updateEnabledMediaOptionKeys(entity, [...entity.nextMediaOptionKeys]);\n                  }\n                  entity.nextMediaOptionKeys = undefined;\n              });\n          }\n          setLastLoadedMediaOptionByType(itemId, mediaOptionType, mediaOption) {\n              if (!mediaOption) {\n                  mediaOption = { itemId, mediaOptionType, mediaOptionId: 'Nah' };\n              }\n              logAction(`root.set.lastLoadedMediaOptionByType: ${mediaOptionType} ${mediaOption.mediaOptionId}`);\n              this.store.update(itemId, (entity) => {\n                  var _a;\n                  const mediaOptionKeyTuple = (_a = entity.lastLoadedMediaOptionKeys) !== null && _a !== void 0 ? _a : [NoMediaOption, NoMediaOption, NoMediaOption];\n                  mediaOptionKeyTuple[mediaOptionType] = { itemId, mediaOptionId: mediaOption.mediaOptionId };\n                  entity.lastLoadedMediaOptionKeys = mediaOptionKeyTuple;\n              });\n          }\n          setPreferredHost(itemId, newHost) {\n              logAction(`root.set.preferredHost: ${newHost}`);\n              this.store.update(itemId, (entity) => {\n                  if (!entity) {\n                      return;\n                  }\n                  const optionListInfo = entity.mediaOptionListTuple[MediaOptionType.Variant];\n                  optionListInfo.preferredHost = newHost;\n              });\n          }\n          setViewportInfo(itemId, viewportInfo) {\n              logAction(`root.set.viewportInfo: ${JSON.stringify(viewportInfo)}`);\n              this.store.update(itemId, (entity) => {\n                  if (!entity) {\n                      return;\n                  }\n                  const optionListInfo = entity.mediaOptionListTuple[MediaOptionType.Variant];\n                  optionListInfo.viewportInfo = viewportInfo;\n              });\n          }\n          static getExistingPersistentIds(entity) {\n              var _a, _b;\n              const existingSelection = {};\n              const audioOptionId = (_a = entity.enabledMediaOptionKeys[MediaOptionType.AltAudio]) === null || _a === void 0 ? void 0 : _a.mediaOptionId;\n              if (audioOptionId !== 'Nah') {\n                  const audioOptionListInfo = entity.mediaOptionListTuple[MediaOptionType.AltAudio];\n                  const filteredAudio = applyFilters(audioOptionListInfo.mediaOptions, AlternateMediaOptionListQuery.kAllowFilters, audioOptionListInfo);\n                  const altAudioOption = filteredAudio.find((altOption) => altOption.mediaOptionId === audioOptionId);\n                  existingSelection.audioPersistentId = altAudioOption === null || altAudioOption === void 0 ? void 0 : altAudioOption.persistentID;\n              }\n              const subtitleOptionId = (_b = entity.enabledMediaOptionKeys[MediaOptionType.Subtitle]) === null || _b === void 0 ? void 0 : _b.mediaOptionId;\n              if (subtitleOptionId !== 'Nah') {\n                  const subtitleOptionListInfo = entity.mediaOptionListTuple[MediaOptionType.Subtitle];\n                  const filteredSubtitles = applyFilters(subtitleOptionListInfo.mediaOptions, AlternateMediaOptionListQuery.kAllowFilters, subtitleOptionListInfo);\n                  const subtitleOption = filteredSubtitles.find((altOption) => altOption.mediaOptionId === subtitleOptionId);\n                  existingSelection.subtitlePersistentId = subtitleOption === null || subtitleOption === void 0 ? void 0 : subtitleOption.persistentID;\n              }\n              return existingSelection;\n          }\n          static doUpdateRootHDRSwitch(entity, preferHDR, hasHdrLevels, logger) {\n              // immer complains if you try to modify and update the object in one go so make deep copy of mediaOptionListTuple\n              const mediaOptionListTuple = entity.mediaOptionListTuple.map((info) => (Object.assign({}, info)));\n              mediaOptionListTuple[MediaOptionType.Variant].preferHDR = preferHDR;\n              mediaOptionListTuple[MediaOptionType.Variant].hasHdrLevels = hasHdrLevels;\n              const hlsConf = getCurrentConfig();\n              const curItem = queueItemQuery.getEntity(entity.itemId);\n              const statsQuery = createStatsQuery(entity.itemId);\n              const bandwidthEstimate = statsQuery.getBandwidthEstimate(hlsConf, curItem === null || curItem === void 0 ? void 0 : curItem.serviceName);\n              const playlistEstimate = statsQuery.getPlaylistEstimate(hlsConf, curItem === null || curItem === void 0 ? void 0 : curItem.serviceName);\n              const fragEstimate = statsQuery.getFragEstimate(hlsConf, curItem === null || curItem === void 0 ? void 0 : curItem.serviceName);\n              const bufferEstimate = statsQuery.getBufferEstimate(hlsConf, curItem === null || curItem === void 0 ? void 0 : curItem.serviceName);\n              const adaptiveStartupConfig = {\n                  targetDuration: fragEstimate.maxDurationSec || (hlsConf === null || hlsConf === void 0 ? void 0 : hlsConf.defaultTargetDuration),\n                  targetStartupMs: hlsConf === null || hlsConf === void 0 ? void 0 : hlsConf.targetStartupMs,\n              };\n              const existingSelection = RootPlaylistService.getExistingPersistentIds(entity);\n              return updateRootPlaylistEntityWithEnabledMediaOptionKeys(Object.assign(Object.assign({}, entity), { mediaOptionListTuple, nextMediaOptionKeys: null }), existingSelection, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n          }\n          // For error handling. disable HDR playback but don't re-calculate enabled media options\n          switchToSDROnly(itemId) {\n              logAction('root.switchToSDROnly');\n              this.store.update(itemId, (entity) => {\n                  const { mediaOptionListTuple } = RootPlaylistService.doUpdateRootHDRSwitch(entity, false, false, this.logger);\n                  entity.mediaOptionListTuple = mediaOptionListTuple;\n              });\n          }\n          /**\n           * Update HDR preference and set enabled media options based on the preference\n           */\n          setHDRPreference(itemId, preferHDR, updateEnabledOptions) {\n              logAction(`root.set.HDRPreference: ${preferHDR}`);\n              this.store.update(itemId, (entity) => {\n                  const optionListInfo = entity.mediaOptionListTuple[MediaOptionType.Variant];\n                  if (optionListInfo.preferHDR === preferHDR || (preferHDR && !optionListInfo.hasHdrLevels)) {\n                      return;\n                  }\n                  const newEntity = RootPlaylistService.doUpdateRootHDRSwitch(entity, preferHDR, optionListInfo.hasHdrLevels, this.logger);\n                  if (!updateEnabledOptions) {\n                      entity.mediaOptionListTuple = newEntity.mediaOptionListTuple;\n                  }\n                  else {\n                      // Must return this so that entire entity is updated\n                      return (entity = newEntity);\n                  }\n              });\n          }\n          setPathwayPriority(itemId, pathwayPriority) {\n              logAction(`root.set.PathwayPriority: [ ${pathwayPriority.join(', ')} ]`);\n              this.store.update(itemId, (entity) => {\n                  if (!entity) {\n                      return;\n                  }\n                  const optionListInfo = entity.mediaOptionListTuple[MediaOptionType.Variant];\n                  optionListInfo.pathwayPriority = pathwayPriority;\n                  optionListInfo.preferredHost = null;\n              });\n          }\n          setCurrentPathwayID(itemId, currentPathwayID) {\n              logAction(`root.set.currentPathwayID: ${currentPathwayID}`);\n              this.store.update(itemId, (entity) => {\n                  if (!entity) {\n                      return;\n                  }\n                  const optionListInfo = entity.mediaOptionListTuple[MediaOptionType.Variant];\n                  optionListInfo.currentPathwayID = currentPathwayID;\n              });\n          }\n          setInitPTS(itemId, discoSeqNum, variantDTS, timelineOffset, offsetTimestamp, iframeMode) {\n              logAction(`root.set.initPTS: ${itemId} ${discoSeqNum} variantDTS:${JSON.stringify(variantDTS)} timelineOffset: ${timelineOffset}`);\n              this.store.update(itemId, (entity) => {\n                  entity.initPtsRecord[discoSeqNum] = { variantDTS, timelineOffset, offsetTimestamp, iframeMode };\n              });\n          }\n          /**\n           * Modify penaltyBoxQueue to remove all expired entries in place\n           * @param penaltyBoxQueue\n           * @param now\n           */\n          static prunePenaltyBox(penaltyBoxQueue, now) {\n              return penaltyBoxQueue.filter((x) => !isExpired(x.expiry, now));\n          }\n          /**\n           * Add entry to penaltyBoxQueue in place\n           * @param penaltyBoxQueue\n           * @param now\n           * @param mediaOptionId\n           */\n          static addToPenaltyBox(penaltyBoxQueue, now, mediaOptionId) {\n              return penaltyBoxQueue.push({ mediaOptionId, expiry: now + PENALTYBOX_TIMEOUT_MS });\n          }\n          /**\n           * Put a media option into the penalty box. It will stay there for 2 minutes\n           * @param filterListId The filter list to modify\n           * @param mediaOptionType The media option type\n           * @param mediaOptionId The media option to put into penalty box\n           */\n          addToPenaltyBox(itemId, mediaOptionType, mediaOptionId) {\n              logAction(`root.set.penaltyBox: ${mediaOptionType}: ${mediaOptionId}`);\n              this.store.update(itemId, ({ mediaOptionListTuple: mediaOptionsStates }) => {\n                  const optionListInfo = mediaOptionsStates[mediaOptionType];\n                  // TODO: dedup\n                  const now = performance.now();\n                  optionListInfo.penaltyBoxQueue = RootPlaylistService.prunePenaltyBox(optionListInfo.penaltyBoxQueue, now);\n                  RootPlaylistService.addToPenaltyBox(optionListInfo.penaltyBoxQueue, now, mediaOptionId);\n              });\n          }\n          /**\n           * Remove all expired entries from penalty box\n           * @param itemId  The queue item id\n           * @param mediaOptionType which media option type to prune penalty box for. if null, prune all\n           */\n          prunePenaltyBox(itemId, mediaOptionType = null) {\n              logAction(`root.set.prunePenaltyBox: ${mediaOptionType}`);\n              this.store.update(itemId, ({ mediaOptionListTuple }) => {\n                  const infoList = mediaOptionType ? [mediaOptionListTuple[mediaOptionType]] : mediaOptionListTuple;\n                  const now = performance.now();\n                  for (const info of infoList) {\n                      info.penaltyBoxQueue = RootPlaylistService.prunePenaltyBox(info.penaltyBoxQueue, now);\n                  }\n              });\n          }\n          /**\n           * Put a media option in the remove list. It will stay there permanently.\n           * @param itemId The filter list to modify\n           * @param mediaOptionType The media option type\n           * @param mediaOptionId The media option to put in remove list\n           */\n          removePermanently(itemId, mediaOptionType, mediaOptionId) {\n              logAction(`root.set.removePermanently: ${mediaOptionType}: ${mediaOptionId}`);\n              this.store.update(itemId, ({ mediaOptionListTuple: mediaOptionsStates }) => {\n                  const optionListInfo = mediaOptionsStates[mediaOptionType];\n                  // dedup. uncommon to remove so this should hopefully be small\n                  const removeSet = new Set(optionListInfo.removed);\n                  removeSet.add(mediaOptionId);\n                  optionListInfo.removed = Array.from(removeSet);\n              });\n          }\n          /**\n           *\n           * @param itemId The filter list to modify\n           * @param mediaOptionType Which media option list to update\n           * @param hostName The hostname used for matching\n           * @param remove if true, remove this host permanently from valid list. if false, put into penalty box\n           */\n          moveAllWithMatchingHosts(itemId, mediaOptionType, hostName, remove) {\n              logAction(`root.set.moveAllMatchingHosts: ${mediaOptionType}:${hostName} remove:${remove}`);\n              this.store.update(itemId, ({ mediaOptionListTuple: mediaOptionsStates }) => {\n                  const optionListInfo = mediaOptionsStates[mediaOptionType];\n                  const mediaOptionIdsToModify = [...optionListInfo.mediaOptions].filter((mo) => hasMatchingHost(hostName, mo.url)).map((x) => x.mediaOptionId);\n                  if (remove) {\n                      const merged = new Set([...optionListInfo.removed, ...mediaOptionIdsToModify]);\n                      optionListInfo.removed = Array.from(merged);\n                  }\n                  else {\n                      const now = performance.now();\n                      optionListInfo.penaltyBoxQueue = RootPlaylistService.prunePenaltyBox(optionListInfo.penaltyBoxQueue, now);\n                      for (const mediaOptionId of mediaOptionIdsToModify) {\n                          RootPlaylistService.addToPenaltyBox(optionListInfo.penaltyBoxQueue, now, mediaOptionId);\n                      }\n                  }\n              });\n          }\n          /**\n           * @param itemId the item id to modify\n           * @param maxHdcpLevel the maximum hdcp level allowed for this asset (exclusive). Only allow variants with hdcpLevel < maxHdcpLevel\n           * @param force if true, always update. if false, only update if maxHdcpLevel is < current maxHdcpLevel\n           */\n          setMaxHdcpLevel(itemId, maxHdcpLevel, force = false) {\n              logAction(`root.set.maxHdcpLevel: ${maxHdcpLevel}`);\n              this.store.update(itemId, ({ mediaOptionListTuple: mediaOptionsStates }) => {\n                  const optionListInfo = mediaOptionsStates[MediaOptionType.Variant];\n                  // Only can lower max hdcp level unless forced\n                  if (force || hdcpLevelToInt(maxHdcpLevel) < hdcpLevelToInt(optionListInfo.maxHdcpLevel)) {\n                      optionListInfo.maxHdcpLevel = maxHdcpLevel;\n                  }\n              });\n          }\n          /**\n           * @param itemId The queue item id\n           * @param mediaOptionType the mediaOptionType\n           * @param increment if true, increment else reset\n           * @param timeout Which type of timeout it was\n           */\n          updateConsecutiveTimeouts(itemId, mediaOptionType, increment, type) {\n              this.store.update(itemId, (entity) => {\n                  const errorHandlingInfo = entity.errorsByType || [\n                      { timeouts: { load: 0, append: 0, key: 0 } },\n                      { timeouts: { load: 0, append: 0, key: 0 } },\n                      { timeouts: { load: 0, append: 0, key: 0 } },\n                  ];\n                  if (increment) {\n                      ++errorHandlingInfo[mediaOptionType].timeouts[type];\n                  }\n                  else {\n                      errorHandlingInfo[mediaOptionType].timeouts[type] = 0;\n                  }\n                  entity.errorsByType = errorHandlingInfo;\n              });\n          }\n          // Update inflight fragment information. For now just hooking up Variant & AltAudio\n          updateInflightFrag(itemId, type, frag, state, sample) {\n              logAction('root.set.updateInflightFrag');\n              this.store.update(itemId, (entity) => {\n                  if (!entity.inFlightFrags) {\n                      entity.inFlightFrags = [null, null];\n                  }\n                  if (type === MediaOptionType.Subtitle || (frag && frag.itemId !== itemId)) {\n                      return;\n                  }\n                  if (!frag) {\n                      entity.inFlightFrags[type] = null;\n                      return;\n                  }\n                  let { start, duration } = frag;\n                  const { mediaOptionId, mediaSeqNum, discoSeqNum } = frag;\n                  const inFlight = entity.inFlightFrags[type];\n                  // Update tstart if state changed\n                  let tstart = inFlight === null || inFlight === void 0 ? void 0 : inFlight.tstart;\n                  if (state !== (inFlight === null || inFlight === void 0 ? void 0 : inFlight.state)) {\n                      tstart = performance.now();\n                  }\n                  if (fragEqual(inFlight, frag)) {\n                      start = inFlight.start;\n                      duration = inFlight.duration;\n                  }\n                  entity.inFlightFrags[type] = {\n                      itemId,\n                      mediaOptionId,\n                      mediaSeqNum,\n                      discoSeqNum,\n                      start,\n                      duration,\n                      tstart,\n                      state,\n                      bwSample: Object.assign({}, sample),\n                  };\n              });\n          }\n          setNextMaxAutoOptionId(itemId, nextMaxAutoOptionId) {\n              logAction(`root.set.nextMaxAutoOptionId: ${nextMaxAutoOptionId}`);\n              this.store.update(itemId, ({ abrStatus: abrs }) => {\n                  abrs.nextMaxAutoOptionId = nextMaxAutoOptionId;\n              });\n          }\n          setNextMinAutoOptionId(itemId, nextMinAutoOptionId) {\n              logAction(`root.set.nextMinAutoOptionId: ${nextMinAutoOptionId}`);\n              this.store.update(itemId, ({ abrStatus: abrs }) => {\n                  abrs.nextMinAutoOptionId = nextMinAutoOptionId;\n              });\n          }\n          setHighBWTrigger(itemId, value) {\n              logAction(`root.set.setHighBWTrigger: ${value}`);\n              this.store.update(itemId, ({ abrStatus: abrs }) => {\n                  abrs.highBWTrigger = value;\n              });\n          }\n          setFragLoadSlow(itemId, value) {\n              logAction(`root.set.setFragLoadSlow ${itemId} ${JSON.stringify(value)}`);\n              this.store.update(itemId, ({ abrStatus: abrs }) => {\n                  abrs.fragDownloadSlow = value.fragDownloadSlow;\n                  abrs.fragDownloadTooSlow = value.fragDownloadTooSlow;\n              });\n          }\n          pickMediaOptionTupleByPersistentId(rootQuery, mediaOptionType, persistentId, sdrOnly = false, shouldSwitchHost = false) {\n              const currentVariantId = rootQuery.enabledMediaOptionIdByType(MediaOptionType.Variant);\n              const variant = rootQuery.variantMediaOptionById(currentVariantId);\n              let audioPersistentId;\n              let subtitlePersistentId;\n              if (mediaOptionType === MediaOptionType.AltAudio) {\n                  const subtitleAltOption = rootQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle);\n                  subtitlePersistentId = subtitleAltOption === null || subtitleAltOption === void 0 ? void 0 : subtitleAltOption.persistentID;\n                  audioPersistentId = persistentId;\n              }\n              else {\n                  const audioAltOption = rootQuery.enabledAlternateMediaOptionByType(MediaOptionType.AltAudio);\n                  audioPersistentId = audioAltOption === null || audioAltOption === void 0 ? void 0 : audioAltOption.persistentID;\n                  subtitlePersistentId = persistentId;\n              }\n              const expectedEnabledMediaOptionMask = rootQuery.getEnabledMediaOptionMask();\n              expectedEnabledMediaOptionMask[mediaOptionType] = isFiniteNumber(persistentId) && persistentId >= 0 ? true : false;\n              return variant\n                  ? this.getBestMediaOptionTupleFromVariantAndPersistentId(rootQuery, variant, audioPersistentId, subtitlePersistentId, expectedEnabledMediaOptionMask, undefined, sdrOnly, shouldSwitchHost, false)\n                  : [NoMediaOption, NoMediaOption, NoMediaOption];\n          }\n          getFallbackMediaOptionTupleFromMediaOptionId(rootQuery, mediaOptionType, mediaOptionId, backingMediaOptionId, sdrOnly = false, shouldSwitchHosts = false, shouldDownswitch = false) {\n              const excludingOptions = backingMediaOptionId ? [backingMediaOptionId] : [mediaOptionId]; // always exclude mediaOptionId or backingMediaOptionId from result list since we are looking for its fallback\n              const currentVariantId = rootQuery.enabledMediaOptionIdByType(MediaOptionType.Variant); // getBestMediaOptionTupleFromVariantAndPersistentId will skip currentVariantId if it's mediaOptionId (excluded above)\n              const variant = rootQuery.variantMediaOptionById(currentVariantId);\n              const altAudio = mediaOptionType === MediaOptionType.AltAudio\n                  ? rootQuery.alternateMediaOptionById(MediaOptionType.AltAudio, mediaOptionId)\n                  : rootQuery.enabledAlternateMediaOptionByType(MediaOptionType.AltAudio);\n              const audioPersistentId = altAudio === null || altAudio === void 0 ? void 0 : altAudio.persistentID;\n              const subtitle = mediaOptionType === MediaOptionType.Subtitle\n                  ? rootQuery.alternateMediaOptionById(MediaOptionType.Subtitle, mediaOptionId)\n                  : rootQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle);\n              const subtitlePersistentId = subtitle === null || subtitle === void 0 ? void 0 : subtitle.persistentID;\n              return variant\n                  ? this.getBestMediaOptionTupleFromVariantAndPersistentId(rootQuery, variant, audioPersistentId, subtitlePersistentId, undefined, excludingOptions, sdrOnly, shouldSwitchHosts, shouldDownswitch)\n                  : [NoMediaOption, NoMediaOption, NoMediaOption];\n          }\n          hasFallbackMediaOptionTuple(rootQuery, mediaOptionType, fromId, shouldSwitchHosts) {\n              const fromOption = rootQuery.mediaOptionListQueries[mediaOptionType].mediaOptionFromId(fromId);\n              return rootQuery.isValidMediaOptionTuple(this.getFallbackMediaOptionTupleFromMediaOptionId(rootQuery, mediaOptionType, fromId, fromOption.backingMediaOptionId, false, shouldSwitchHosts));\n          }\n          setLegacyAlternateMediaOption(rootQuery, itemId, mediaOptionType, persistentId, switchContext = undefined) {\n              const currentVariantId = rootQuery.enabledMediaOptionIdByType(MediaOptionType.Variant);\n              const currentVariant = rootQuery.variantMediaOptionById(currentVariantId);\n              const newAltOption = rootQuery.getLegacyMatchingAlternateWithPersistentId(mediaOptionType, persistentId, currentVariant);\n              if (newAltOption) {\n                  this.setEnabledMediaOptionByType(itemId, mediaOptionType, newAltOption, true, switchContext);\n              }\n              else {\n                  this.logger.warn(`${MediaOptionNames[mediaOptionType]} can't find matching mediaOption for persistent id ${persistentId}`);\n              }\n          }\n          setEnabledMediaOptionTupleWithMatchedGroups(itemId, mediaOptionType, persistentId, switchContext = undefined) {\n              const rootQuery = createRootPlaylistQuery(itemId);\n              const newOptions = this.pickMediaOptionTupleByPersistentId(rootQuery, mediaOptionType, persistentId);\n              if (!rootQuery.isValidMediaOptionTuple(newOptions)) {\n                  // can't find matching variant and alternates combo,\n                  // just switch the alternate media option of mediaOptionType, potentially ignore preferred host and group\n                  return this.setLegacyAlternateMediaOption(rootQuery, itemId, mediaOptionType, persistentId, switchContext);\n              }\n              applyTransaction(() => {\n                  this.setEnabledMediaOptionByType(itemId, mediaOptionType, newOptions[mediaOptionType], true, switchContext);\n                  if (newOptions[MediaOptionType.Variant].mediaOptionId !== rootQuery.enabledMediaOptionIdByType(MediaOptionType.Variant)) {\n                      this.setPreferredHost(itemId, getHostName(newOptions[MediaOptionType.Variant].url));\n                  }\n                  // always update the variant mediaOption even if it has not changed. This will allow AVPipe's enabledMediaOptionSwitchForType call\n                  // to reflect the latest fromId->toId mediaOption switching.\n                  this.setEnabledMediaOptionByType(itemId, MediaOptionType.Variant, newOptions[MediaOptionType.Variant]);\n                  const otherType = mediaOptionType === MediaOptionType.AltAudio ? MediaOptionType.Subtitle : MediaOptionType.AltAudio;\n                  if (newOptions[otherType].mediaOptionId !== rootQuery.enabledMediaOptionIdByType(otherType)) {\n                      this.setEnabledMediaOptionByType(itemId, otherType, newOptions[otherType], false); // don't override switchContext of the other alternate\n                  }\n              });\n          }\n          canSwitchToSDR(rootQuery, mediaOptionId, shouldSwitchHosts, shouldDownswitch = false) {\n              const mediaOption = rootQuery.mediaOptionListQueries[MediaOptionType.Variant].mediaOptionFromId(mediaOptionId);\n              const newMediaOptions = this.getFallbackMediaOptionTupleFromMediaOptionId(rootQuery, MediaOptionType.Variant, mediaOptionId, mediaOption.backingMediaOptionId, true, shouldSwitchHosts, shouldDownswitch);\n              return rootQuery.isValidMediaOptionTuple(newMediaOptions);\n          }\n          getBestMediaOptionTupleFromVariantAndPersistentId(rootQuery, currentVariant, audioPersistentId, subtitlePersistentId, expectedEnabledMediaOptionMask, excludingOptions, sdrOnly, shouldSwitchHosts, shouldDownswitch) {\n              let alternates;\n              const fallbackVariantList = rootQuery.mediaOptionListQueries[MediaOptionType.Variant].listFallbackVariants(currentVariant.mediaOptionId, sdrOnly, shouldSwitchHosts, shouldDownswitch, excludingOptions);\n              let preferredFallback = [NoMediaOption, NoMediaOption, NoMediaOption];\n              for (let i = 0; i < fallbackVariantList.length; ++i) {\n                  const nextVariant = fallbackVariantList[i];\n                  alternates = rootQuery.matchAlternates(nextVariant, audioPersistentId, subtitlePersistentId, excludingOptions);\n                  if (rootQuery.isValidMediaOptionTuple([nextVariant, ...alternates], expectedEnabledMediaOptionMask)) {\n                      preferredFallback = [nextVariant, ...alternates];\n                      break; // found variant with valid alternates\n                  }\n              }\n              return preferredFallback;\n          }\n      }\n      const rootPlaylistStore = new RootPlaylistStore();\n      new QueryEntity(rootPlaylistStore);\n      let rootService = null; // To be instantiated in rootPlaylistService\n      /***********************************************\n       * Static helper functions that specifically use the above singletons\n       */\n      function createRootPlaylistQuery(itemId) {\n          return new RootPlaylistQuery(rootPlaylistStore, itemId);\n      }\n      /**\n       * @returns The global instance of RootPlaylistService that operates on global RootPlaylistStore\n       */\n      function rootPlaylistService(logger) {\n          rootService = new RootPlaylistService(rootPlaylistStore, logger);\n          return rootService;\n      }\n      /**\n       * Choose the audio track given the selection group and options\n       * @param groupId GroupID from variant\n       * @param audioMediaSelectionGroup\n       * @param audioAlternateOptions\n       */\n      const getAutoAudio = (persistentId, groupId, audioMediaSelectionGroup, audioAlternateOptions) => {\n          if (audioMediaSelectionGroup) {\n              let audioMediaOption;\n              if (isFiniteNumber(persistentId)) {\n                  audioMediaOption = audioMediaSelectionGroup.MediaSelectionGroupOptions.find(function (mediaOption) {\n                      return mediaOption.MediaSelectionOptionsPersistentID === persistentId;\n                  });\n              }\n              else {\n                  audioMediaOption = audioMediaSelectionGroup.MediaSelectionGroupOptions.find(function (mediaOption) {\n                      return mediaOption.MediaSelectionOptionsIsDefault;\n                  });\n              }\n              if (!audioMediaOption) {\n                  audioMediaOption = audioMediaSelectionGroup.MediaSelectionGroupOptions[0];\n                  getLogger().info(`no default audio: pick the first persistentId ${audioMediaOption.MediaSelectionOptionsPersistentID}`);\n              }\n              const audioTrackInfo = audioAlternateOptions.find((audioTrack) => {\n                  return (!groupId || audioTrack.groupId === groupId) && audioTrack.persistentID === (audioMediaOption === null || audioMediaOption === void 0 ? void 0 : audioMediaOption.MediaSelectionOptionsPersistentID);\n              });\n              return audioTrackInfo;\n          }\n      };\n      function logPlatformCapabilitiesFilterResults(hdrMediaOptions, sdrMediaOptions, el, config, displaySupportsHdr, logger) {\n          hdrMediaOptions.concat(sdrMediaOptions);\n          const devicePixelRatio = typeof window === 'object' && window.devicePixelRatio ? window.devicePixelRatio : 1;\n          const displaySize = config.useViewportSizeForLevelCap && el ? { width: el.clientWidth * devicePixelRatio, height: el.clientHeight * devicePixelRatio } : undefined;\n          logger.info(loggerName, `valid media options: hdr=${hdrMediaOptions.length} sdr=${sdrMediaOptions.length}, supportsHdr=${displaySupportsHdr}, displaySize=${displaySize ? JSON.stringify(displaySize) : null}`);\n      }\n      const updateBasedOnPlatformCapabilities = (loadRootMediaOptionsResult, platformInfo, config, displaySupportsHdr, logger) => {\n          const { rootMediaOptionsTuple, sessionKeys } = loadRootMediaOptionsResult;\n          const variantMediaOptions = Array.from(rootMediaOptionsTuple[MediaOptionType.Variant]);\n          const audioAlternateOptions = Array.from(rootMediaOptionsTuple[MediaOptionType.AltAudio]);\n          let videoCodecFound = false;\n          let audioCodecFound = false;\n          // regroup redundant variants together\n          let regroupedVariantMediaOptions = variantMediaOptions.map((mediaOption) => {\n              videoCodecFound = videoCodecFound || Boolean(mediaOption.videoCodec);\n              audioCodecFound = audioCodecFound || Boolean(mediaOption.audioCodec) || Boolean(mediaOption.audioGroupId);\n              return mediaOption;\n          });\n          // remove audio-only media options if we also have media options with audio+video codecs signaled\n          if (videoCodecFound && audioCodecFound) {\n              regroupedVariantMediaOptions = regroupedVariantMediaOptions.filter(({ videoCodec }) => Boolean(videoCodec));\n          }\n          logger.info(loggerName, `playlist has ${regroupedVariantMediaOptions.length} variantMediaOptions`);\n          return filterByPlatformCapabilities(variantMediaOptions, audioAlternateOptions, sessionKeys, platformInfo, config, logger).pipe(map(({ hdrMediaOptions, sdrMediaOptions }) => {\n              const allMediaOptions = hdrMediaOptions.concat(sdrMediaOptions);\n              const hasHdrMediaOptions = hdrMediaOptions.length > 0;\n              logPlatformCapabilitiesFilterResults(hdrMediaOptions, sdrMediaOptions, undefined, config, displaySupportsHdr, logger);\n              return makeRootPlaylistEntity(loadRootMediaOptionsResult, allMediaOptions, hasHdrMediaOptions, displaySupportsHdr);\n          }));\n      };\n      /**\n       * Choose the audio track given the selection group and options\n       * @param subtitleMediaSelectionGroup\n       * @param subtitleAlternateOptions\n       */\n      const getAutoSubtitle = (persistentId, closedCaptionGroup, subtitleGroup, subtitleMediaSelectionGroup, subtitleAlternateOptions, logger) => {\n          if (subtitleMediaSelectionGroup) {\n              let subtitleMediaOption;\n              if (isFiniteNumber(persistentId)) {\n                  subtitleMediaOption = subtitleMediaSelectionGroup.MediaSelectionGroupOptions.find(function (mediaOption) {\n                      return mediaOption.MediaSelectionOptionsPersistentID === persistentId;\n                  });\n              }\n              else {\n                  subtitleMediaOption = subtitleMediaSelectionGroup.MediaSelectionGroupOptions.find(function (mediaOption) {\n                      return mediaOption.MediaSelectionOptionsIsDefault;\n                  });\n              }\n              let subtitleTrackInfo;\n              if (subtitleMediaOption) {\n                  subtitleTrackInfo = subtitleAlternateOptions.find((subtitleTrack) => {\n                      if (subtitleTrack.mediaType === MediaTypeFourCC.CLOSEDCAPTION) {\n                          return (!closedCaptionGroup || subtitleTrack.groupId === closedCaptionGroup) && subtitleTrack.persistentID === subtitleMediaOption.MediaSelectionOptionsPersistentID;\n                      }\n                      else if (subtitleTrack.mediaType === MediaTypeFourCC.SUBTITLE) {\n                          return (!subtitleGroup || subtitleTrack.groupId === subtitleGroup) && subtitleTrack.persistentID === subtitleMediaOption.MediaSelectionOptionsPersistentID;\n                      }\n                      else {\n                          logger.warn(loggerName, `subtitle media option has unknown type ${subtitleTrack.mediaType}`);\n                      }\n                  });\n              }\n              return subtitleTrackInfo;\n          }\n      };\n      function makeRootPlaylistEntity(loadRootMediaOptionsResult, variantMediaOptions, hasHdrLevels, preferHDR) {\n          var _a;\n          const { itemId, itemStartOffset, rootMediaOptionsTuple, audioMediaSelectionGroup, subtitleMediaSelectionGroup } = loadRootMediaOptionsResult;\n          const audioAlternateOptions = Array.from(rootMediaOptionsTuple[MediaOptionType.AltAudio]);\n          const subtitleAlternateOptions = Array.from(rootMediaOptionsTuple[MediaOptionType.Subtitle]);\n          const hasScore = variantMediaOptions.every((x) => isFiniteNumber(x.score));\n          const hasIframeLevels = variantMediaOptions.some((x) => isIframeLevel(x));\n          const sortedVariantMediaOptions = sortVariants(variantMediaOptions, hasScore);\n          const compatibleVariants = null;\n          const compatibleAudioAlternates = null;\n          const baseUrl = loadRootMediaOptionsResult.baseUrl;\n          const initPathwayID = (_a = loadRootMediaOptionsResult.contentSteeringOption) === null || _a === void 0 ? void 0 : _a.initPathwayID;\n          const sessionData = loadRootMediaOptionsResult.sessionData;\n          const rootPlaylistEntity = {\n              itemId,\n              baseUrl,\n              mediaOptionListTuple: [\n                  {\n                      mediaOptions: sortedVariantMediaOptions,\n                      hasHdrLevels,\n                      hasIframeLevels,\n                      hasScore,\n                      preferHDR,\n                      compatibleIds: compatibleVariants,\n                      penaltyBoxQueue: [],\n                      removed: [],\n                      currentPathwayID: initPathwayID,\n                  },\n                  {\n                      mediaOptions: audioAlternateOptions,\n                      compatibleIds: compatibleAudioAlternates,\n                      penaltyBoxQueue: [],\n                      removed: [],\n                  },\n                  {\n                      mediaOptions: subtitleAlternateOptions,\n                      penaltyBoxQueue: [],\n                      removed: [],\n                  },\n              ],\n              audioMediaSelectionGroup,\n              subtitleMediaSelectionGroup,\n              enabledMediaOptionKeys: [NoMediaOption, NoMediaOption, NoMediaOption],\n              mediaOptionSwitchContexts: [null, null, null],\n              anchorTime: { pos: 0 },\n              discoSeqNum: NaN,\n              pendingSeek: undefined,\n              itemStartOffset,\n              initPtsRecord: {},\n              contentSteeringOption: loadRootMediaOptionsResult.contentSteeringOption,\n              masterVariableList: loadRootMediaOptionsResult.masterVariableList,\n              loadStats: loadRootMediaOptionsResult.stats,\n              isMediaPlaylist: loadRootMediaOptionsResult.isMediaPlaylist,\n              abrStatus: {\n                  fragDownloadSlow: false,\n                  fragDownloadTooSlow: false,\n                  nextMinAutoOptionId: NoMediaOption.mediaOptionId,\n                  nextMaxAutoOptionId: NoMediaOption.mediaOptionId,\n                  highBWTrigger: NaN,\n              },\n              sessionData,\n          };\n          return rootPlaylistEntity;\n      }\n      function selectStartingVariant(rootPlaylistEntity, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          const mediaOptionListInfo = rootPlaylistEntity.mediaOptionListTuple[MediaOptionType.Variant];\n          const filteredVariants = applyFilters(mediaOptionListInfo.mediaOptions, VariantMediaOptionListQuery.kAllowFilters, Object.assign(Object.assign({}, mediaOptionListInfo), { compatibleIds: null }));\n          const preferredVariants = getPreferredList(mediaOptionListInfo.preferredHost, filteredVariants);\n          const firstVariant = chooseFirstMediaOption(preferredVariants, firstMediaOptionSelectionMetrics, mediaOptionListInfo.hasScore, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n          return { firstVariant, filteredVariants, preferredVariants };\n      }\n      function replaceClosedCaptionInMediaOptionListIfNecessary(variant, closedCaption, subtitleMediaOptions, logger) {\n          if ((closedCaption === null || closedCaption === void 0 ? void 0 : closedCaption.mediaType) === MediaTypeFourCC.CLOSEDCAPTION) {\n              const forcedMediaOption = AlternateMediaOptionListQuery.pairForcedSubtitleMediaOptionWithClosedCaptionInList(variant.subtitleGroupId, closedCaption, subtitleMediaOptions);\n              if (forcedMediaOption) {\n                  closedCaption = Object.assign(Object.assign({}, closedCaption), { url: forcedMediaOption.url, backingMediaOptionId: forcedMediaOption.mediaOptionId });\n                  const newSubtitles = subtitleMediaOptions.map((option) => {\n                      if (option.mediaOptionId === closedCaption.mediaOptionId) {\n                          logger.info(`[subtitle] use closedCaption ${JSON.stringify(closedCaption)}`);\n                          return closedCaption;\n                      }\n                      return option;\n                  });\n                  return newSubtitles;\n              }\n          }\n          return subtitleMediaOptions; // no change\n      }\n      /**\n       * Modify rootPlaylistEntity (in-place), updating media options list and selecting a new set of enabled media options\n       */\n      function updateRootPlaylistEntityWithEnabledMediaOptionKeys(rootPlaylistEntity, existingSelection, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate) {\n          var _a, _b;\n          const itemId = rootPlaylistEntity.itemId;\n          const mediaOptionListInfo = rootPlaylistEntity.mediaOptionListTuple[MediaOptionType.Variant];\n          const audioOptionListInfo = rootPlaylistEntity.mediaOptionListTuple[MediaOptionType.AltAudio];\n          const subtitleOptionListInfo = rootPlaylistEntity.mediaOptionListTuple[MediaOptionType.Subtitle];\n          const filteredAudio = applyFilters(audioOptionListInfo.mediaOptions, AlternateMediaOptionListQuery.kAllowFilters, audioOptionListInfo);\n          const filteredSubtitles = applyFilters(subtitleOptionListInfo.mediaOptions, AlternateMediaOptionListQuery.kAllowFilters, subtitleOptionListInfo);\n          let { firstVariant, filteredVariants } = selectStartingVariant(rootPlaylistEntity, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n          if (!firstVariant) {\n              const preferHDR = mediaOptionListInfo.preferHDR;\n              if (preferHDR) {\n                  mediaOptionListInfo.preferHDR = false;\n              }\n              else {\n                  mediaOptionListInfo.preferHDR = mediaOptionListInfo.hasHdrLevels;\n              }\n              if (mediaOptionListInfo.preferHDR !== preferHDR) {\n                  logger.warn(`No valid first variant found, toggling hdr preference=${preferHDR}->${mediaOptionListInfo.preferHDR}`);\n                  ({ firstVariant, filteredVariants } = selectStartingVariant(rootPlaylistEntity, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate));\n              }\n          }\n          if (!firstVariant) {\n              throw new ExceptionError(true, 'No valid first variant found', ErrorResponses.NoValidAlternates);\n          }\n          const preferredHost = getHostName(firstVariant.url);\n          logger.info(loggerName, `First level ${itemId}: ${mediaOptionToString(firstVariant)}`);\n          const variantId = (_a = firstVariant === null || firstVariant === void 0 ? void 0 : firstVariant.mediaOptionId) !== null && _a !== void 0 ? _a : null;\n          const variantKey = { itemId, mediaOptionId: variantId };\n          const altAudioId = (filteredAudio === null || filteredAudio === void 0 ? void 0 : filteredAudio.length)\n              ? (_b = getAutoAudio(existingSelection === null || existingSelection === void 0 ? void 0 : existingSelection.audioPersistentId, firstVariant.audioGroupId, rootPlaylistEntity.audioMediaSelectionGroup, filteredAudio)) === null || _b === void 0 ? void 0 : _b.mediaOptionId\n              : null;\n          const altAudioKey = altAudioId ? { itemId, mediaOptionId: altAudioId } : NoMediaOption;\n          const firstSubtitle = getAutoSubtitle(existingSelection === null || existingSelection === void 0 ? void 0 : existingSelection.subtitlePersistentId, firstVariant.closedcaption, firstVariant.subtitleGroupId, rootPlaylistEntity.subtitleMediaSelectionGroup, filteredSubtitles, logger);\n          const subtitleId = (filteredSubtitles === null || filteredSubtitles === void 0 ? void 0 : filteredSubtitles.length) ? firstSubtitle === null || firstSubtitle === void 0 ? void 0 : firstSubtitle.mediaOptionId : null;\n          const subtitleKey = subtitleId ? { itemId, mediaOptionId: subtitleId, mediaOptionType: MediaOptionType.Subtitle } : NoMediaOption;\n          const { mediaOptions, audioGroups, subtitleGroups, closedCaptionGroups } = filterMediaOptionsBasedOnFirstMediaOptions(filteredVariants, firstVariant);\n          const compatibleVariants = Array.from(mediaOptions).map((mediaOption) => mediaOption.mediaOptionId);\n          const currentPathwayID = firstVariant.pathwayID;\n          const updatedMediaOptionListInfo = Object.assign(Object.assign({}, mediaOptionListInfo), { compatibleIds: compatibleVariants, preferredHost,\n              currentPathwayID });\n          // audio\n          const compatibleAudioAlternates = [];\n          const audioMediaOptions = audioOptionListInfo.mediaOptions;\n          const filteredAudioResults = audioMediaOptions.reduce((prev, cur) => {\n              if (audioGroups.has(cur.groupId)) {\n                  prev.persistentIds.add(cur.persistentID);\n                  compatibleAudioAlternates.push(cur.mediaOptionId);\n                  prev.filteredAudioMediaOptions.push(cur);\n                  if (!prev.altAudio) {\n                      prev.altAudio = !!cur.url;\n                  }\n              }\n              return prev;\n          }, { filteredAudioMediaOptions: [], persistentIds: new Set(), altAudio: false });\n          const updatedAudioOptionListInfo = Object.assign(Object.assign({}, audioOptionListInfo), { compatibleIds: compatibleAudioAlternates });\n          let audioMediaSelectionGroup = rootPlaylistEntity.audioMediaSelectionGroup;\n          const audioMediaSelectionOptions = audioMediaSelectionGroup === null || audioMediaSelectionGroup === void 0 ? void 0 : audioMediaSelectionGroup.MediaSelectionGroupOptions;\n          if (audioMediaSelectionOptions) {\n              const filteredAudioSelectionOptions = audioMediaSelectionOptions.reduce((prev, cur) => {\n                  if (filteredAudioResults.persistentIds.has(cur.MediaSelectionOptionsPersistentID)) {\n                      prev.push(cur);\n                  }\n                  return prev;\n              }, new Array());\n              audioMediaSelectionGroup = Object.assign(Object.assign({}, audioMediaSelectionGroup), { MediaSelectionGroupOptions: filteredAudioSelectionOptions });\n          }\n          // subtitle\n          subtitleOptionListInfo.mediaOptions = replaceClosedCaptionInMediaOptionListIfNecessary(firstVariant, firstSubtitle, subtitleOptionListInfo.mediaOptions, logger);\n          const subtitleMediaOptions = subtitleOptionListInfo.mediaOptions;\n          const filteredSubtitleResults = subtitleMediaOptions.reduce((prev, cur) => {\n              if (subtitleGroups.has(cur.groupId)) {\n                  // do NOT re-assign track id. They must be unique for the entire collection of subtitle and caption tracks\n                  // cur.id = prev.filteredSubtitleMediaOptions.length;\n                  prev.persistentIds.add(cur.persistentID);\n                  prev.filteredSubtitleMediaOptions.push(cur);\n              }\n              return prev;\n          }, { filteredSubtitleMediaOptions: [], persistentIds: new Set() });\n          let subtitleMediaSelectionGroup = rootPlaylistEntity.subtitleMediaSelectionGroup;\n          const subtitleMediaSelectionOptions = subtitleMediaSelectionGroup === null || subtitleMediaSelectionGroup === void 0 ? void 0 : subtitleMediaSelectionGroup.MediaSelectionGroupOptions;\n          if (subtitleMediaSelectionOptions) {\n              const filteredSubtitleSelectionOptions = subtitleMediaSelectionOptions.reduce((prev, cur) => {\n                  if (filteredSubtitleResults.persistentIds.has(cur.MediaSelectionOptionsPersistentID)) {\n                      prev.push(cur);\n                  }\n                  return prev;\n              }, new Array());\n              subtitleMediaSelectionGroup = Object.assign(Object.assign({}, subtitleMediaSelectionGroup), { MediaSelectionGroupOptions: filteredSubtitleSelectionOptions });\n          }\n          const mediaOptionListTuple = [updatedMediaOptionListInfo, updatedAudioOptionListInfo, subtitleOptionListInfo];\n          // Find the highest codec string per codec family\n          let highestVideoCodec = new Map();\n          const hlsConf = getCurrentConfig();\n          if (hlsConf.useHighestVideoCodecPrivate) {\n              highestVideoCodec = updatedMediaOptionListInfo === null || updatedMediaOptionListInfo === void 0 ? void 0 : updatedMediaOptionListInfo.mediaOptions.reduce((codecStringMap, mediaOption) => {\n                  const codecStringList = mediaOption.videoCodecList;\n                  if (codecStringList) {\n                      for (const codec of codecStringList) {\n                          const key = getVideoCodecFamily(codec);\n                          const currentCodec = codecStringMap.get(key);\n                          if (MediaUtil.isHigherCodecByFamily(currentCodec, codec)) {\n                              codecStringMap.set(key, codec);\n                          }\n                      }\n                  }\n                  return codecStringMap;\n              }, highestVideoCodec);\n          }\n          if (highestVideoCodec.size) {\n              highestVideoCodec.forEach((value, key) => logger.info(`override for ${key} family with codec ${value}`));\n          }\n          const abrStatus = {\n              fragDownloadSlow: false,\n              fragDownloadTooSlow: false,\n              nextMinAutoOptionId: NoMediaOption.mediaOptionId,\n              nextMaxAutoOptionId: NoMediaOption.mediaOptionId,\n              highBWTrigger: getLowestSuperiorBW(variantKey.mediaOptionId, updatedMediaOptionListInfo.mediaOptions),\n          };\n          return Object.assign(Object.assign({}, rootPlaylistEntity), { enabledMediaOptionKeys: [variantKey, altAudioKey, subtitleKey], mediaOptionListTuple,\n              audioMediaSelectionGroup,\n              abrStatus,\n              highestVideoCodec });\n      }\n      /**\n       * @brief Load the root playlist\n       *\n       */\n      const retrieveRootMediaOptions = (loadPolicy, rootPlaylistService, config, platformQuery, existingSelection, statsService, playerEvents) => (source) => {\n          return source.pipe(tag('retrieveRootMediaOptions.input'), switchMap((item) => {\n              var _a, _b;\n              if (!item)\n                  return EMPTY;\n              const { itemId, platformInfo } = item;\n              const rootPlaylistQuery = createRootPlaylistQuery(itemId);\n              const { logger } = rootPlaylistService;\n              if (rootPlaylistQuery.hasEntity(itemId)) {\n                  // these needs to handle failures and stuff\n                  return of(rootPlaylistQuery);\n              }\n              rootPlaylistStore.setLoading(true);\n              const tManifestLoadStart = performance.now();\n              return loadRootMediaOptions(item, loadPolicy, logger, config, statsService, (_b = (_a = globalHlsService()) === null || _a === void 0 ? void 0 : _a.getQuery()) === null || _b === void 0 ? void 0 : _b.extendMaxTTFB).pipe(tap((loadRootMediaOptionsResult) => playerEvents.triggerManifestLoaded(loadRootMediaOptionsResult)), tap(({ initialDetails, sessionData, stats }) => {\n                  if (initialDetails) {\n                      archiveMediaOptionDetails(initialDetails, stats, true);\n                  }\n              }), withLatestFrom(platformQuery.displaySupportsHdr$), switchMap(([loadRootMediaOptionsResult, displaySupportsHdr]) => updateBasedOnPlatformCapabilities(loadRootMediaOptionsResult, platformInfo, config, displaySupportsHdr, logger)), map((rootPlaylistEntity) => {\n                  rootPlaylistService.rootPlaylistEntity = initializeRootEntity(item, rootPlaylistEntity, existingSelection, tManifestLoadStart, config, logger);\n                  return rootPlaylistQuery;\n              }), addLoadErrorHandlingPolicy(itemId, null, getLoadConfig(item, loadPolicy), 0, false, rootPlaylistQuery, rootPlaylistService, statsService), finalize$1(() => {\n                  rootPlaylistStore.setLoading(false);\n              }));\n          }), tag('retrieveRootMediaOptions.emit'));\n      };\n      /**\n       * @brief Choose first media options and update initial seek position\n       * @returns updated RootPlaylistEntity with selected media options and seek time\n       */\n      function initializeRootEntity(item, rootPlaylistEntity, existingSelection, tManifestLoadStart, config, logger) {\n          const { itemId, initialSeekTime, itemStartOffset } = item;\n          const statsQuery = createStatsQuery(itemId);\n          const bandwidthEstimate = config.enableAdaptiveStartup ? statsQuery.getBandwidthEstimate(config, item.serviceName) : undefined;\n          const playlistEstimate = config.enableAdaptiveStartup ? statsQuery.getPlaylistEstimate(config, item.serviceName) : undefined;\n          const fragEstimate = config.enableAdaptiveStartup ? statsQuery.getFragEstimate(config, item.serviceName) : undefined;\n          const bufferEstimate = config.enableAdaptiveStartup ? statsQuery.getBufferEstimate(config, item.serviceName) : undefined;\n          const timeElapsed = performance.now() - tManifestLoadStart;\n          let targetStartupMs;\n          if (config.targetStartupMs > timeElapsed) {\n              targetStartupMs = config.targetStartupMs - timeElapsed;\n          }\n          else {\n              /* In some edge cases, such as network is too slow/lossy, it is seen that the manifestLoad takes longer resulting in timeElapsed go above config.targetStartupMs.\n                 To avoid targetStartupMs being negative, fall back to config.targetStartupMs */\n              targetStartupMs = config.targetStartupMs;\n              logger.warn(`Manifest load took ${timeElapsed}ms and exceeds targetStartupMs: ${config.targetStartupMs}; resetting targetStartupMs to ${config.targetStartupMs}`);\n          }\n          const adaptiveStartupConfig = config.enableAdaptiveStartup\n              ? {\n                  targetDuration: fragEstimate.maxDurationSec || config.defaultTargetDuration,\n                  targetStartupMs: targetStartupMs,\n              }\n              : undefined;\n          const updatedRootPlaylistEntity = updateRootPlaylistEntityWithEnabledMediaOptionKeys(rootPlaylistEntity, existingSelection, logger, bandwidthEstimate, adaptiveStartupConfig, playlistEstimate, fragEstimate, bufferEstimate);\n          // Initialize pendingSeek if this is not a preloading item. don't update anchorTime yet.\n          updatedRootPlaylistEntity.pendingSeek = initialSeekTime;\n          return updatedRootPlaylistEntity;\n      }\n    \n      /**\n       * @brief Create all adapters for hls. they will live while media is attached\n       */\n      function makeAdapters(itemRemove$, ksService, config, platformQuery, eventEmitter, rtcService, logger) {\n          return (source$) => {\n              const keySystemAdapter = makeKeySystemService(ksService, source$, itemRemove$, config, platformQuery, eventEmitter, rtcService, logger);\n              const legibleSystemAdapter = makeLegibleService(source$, config, eventEmitter, logger);\n              return combineLatest([keySystemAdapter, legibleSystemAdapter, source$]).pipe(map(([keySystemAdapter, legibleSystemAdapter, mediaSink]) => {\n                  return { keySystemAdapter, legibleSystemAdapter, mediaSink };\n              }));\n          };\n      }\n      function makeActiveItemAdapters(config, logger, rootPlaylistService, platformQuery, statsService, playerEvents, rpcClients) {\n          return (activeItem$) => activeItem$.pipe(filterNullOrUndefined(), switchMap((activeItem) => {\n              logger.info(`active item changed ${activeItem === null || activeItem === void 0 ? void 0 : activeItem.itemId}`);\n              if (!activeItem) {\n                  return of(null);\n              }\n              const rootPlaylistQuery$ = of(activeItem).pipe(retrieveRootMediaOptions(config.manifestLoadPolicy, rootPlaylistService, config, platformQuery, null, statsService, playerEvents));\n              return combineLatest([rootPlaylistQuery$, createMediaParser(config, logger, rpcClients.mux), createIframeMachine(config.trickPlaybackConfig, logger)]).pipe(map(([rootPlaylistQuery, mediaParser, iframeMachine]) => ({ rootPlaylistQuery, mediaParser, iframeMachine })));\n          }));\n      }\n      /**\n       * @brief Observable for updating platform information\n       */\n      function platformUpdater(platformService) {\n          return listenForHdrUpdates(platformService).pipe(switchMapTo(EMPTY));\n      }\n      /**\n       * @brief Top level class that handles setup of playback for a queue of items\n       */\n      class Hls$1 extends HlsEventEmitter {\n          constructor(userConfig = {}, logger) {\n              var _a;\n              super();\n              this.destroy$ = new Subject();\n              this.mediaElement$ = new BehaviorSubject(null);\n              this.publicQueriesInternal$ = new BehaviorSubject(null);\n              this.mediaElementAdapter = null;\n              this.rpcService = null;\n              this.rpcClients = null;\n              this.platformService = platformService();\n              this.keySystemAdapter = null;\n              this.legibleSystemAdapter = null;\n              this.sessionID = guid();\n              this.statsService = statsServiceSingleton();\n              this.gaplessCapable = true;\n              this.teardownWG$ = new WaitGroup();\n              this.itemQueue = new ItemQueue();\n              // Sanitize userConfig\n              if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {\n                  throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n              }\n              const config = Object.assign(Object.assign({}, hlsDefaultConfig), userConfig);\n              if (config.maxRequiredStartDuration < config.minRequiredStartDuration || config.minRequiredStartDuration < 0) {\n                  throw new Error('Illegal config: bad maxRequiredStartDuration or minRequiredStartDuration');\n              }\n              this.hlsConfig = config;\n              // setup the redact url function\n              setupRedactUrl(config.buildType);\n              // set up logger\n              const { sessionID: sessionId } = this;\n              let logLevel = 'silent';\n              if (userConfig.debug) {\n                  logLevel = config.debugLevel;\n              }\n              // rdar://88106960 (HLS with buildType \"production\" much slower than with buildType \"development\")\n              // setting autoFreeze to true follows default behavior with immer 8.0+\n              setAutoFreeze_1(true);\n              {\n                  // for unit tests only\n                  this.logger = logger;\n              }\n              this.logger =\n                  (_a = this.logger) !== null && _a !== void 0 ? _a : setupLoggerSingleton(sessionId, 'hls', getLoggerConfig({\n                      sendLogs: config.sendLogs || (config.log ? LoggerExternals$1().logStore : null),\n                      level: logLevel === 'log' ? 'debug' : logLevel,\n                      consoleOverride: typeof userConfig.debug !== 'boolean' ? userConfig.debug : undefined,\n                      buildType: config.buildType,\n                  }));\n              this.logger.qe({ critical: true, name: 'playerVersion', data: { version: Hls$1.version } });\n              {\n                  this.logger.qe({ critical: true, name: 'playerCommit', data: { hash: '0c65bb95' } });\n                  this.logger.qe({ critical: true, name: 'playerBranch', data: { hash: 'release/2.162' } });\n                  initialize(userConfig.socketurl, userConfig.socketid);\n                  setHls(this);\n                  setLogger(this.logger);\n              }\n              this.hlsConfig.audioPrimingDelay = 0;\n              this.logger.info(`force audioPrimingDelay to ${this.hlsConfig.audioPrimingDelay}`);\n              this.rootPlaylistService = rootPlaylistService(this.logger);\n              this.customUrlLoader = getCustomUrlLoader();\n              this.sessionDataLoader = new SessionDataLoader(config, fromXMLHttpRequest, this.customUrlLoader.load, this.logger);\n              const liveMaxLatencyDurationCount = config.liveMaxLatencyDurationCount;\n              const liveSyncDurationCount = config.liveSyncDurationCount;\n              if (isFiniteNumber(liveMaxLatencyDurationCount) && isFiniteNumber(liveSyncDurationCount) && liveMaxLatencyDurationCount <= liveSyncDurationCount) {\n                  throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n              }\n              if (isFiniteNumber(config.liveMaxLatencyDuration) && (config.liveMaxLatencyDuration <= config.liveSyncDuration || !isFiniteNumber(config.liveSyncDuration))) {\n                  throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n              }\n              const hlsService = globalHlsService();\n              this.logger.info(`start Hls sessionId:${sessionId}`);\n              hlsService.setHlsEntity({ id: sessionId, config });\n              const mediaLibService = mediaLibraryService();\n              const platformQuery = createPlatformQuery();\n              const ksService = keySystemService();\n              this.accessLogInstance = new AccessLog(this, sessionId);\n              this.rtcService = new RTCService(this, config, this.accessLogInstance, this.logger);\n              this.playerEvents = new HlsPlayerEvents(this, this.logger, this.rtcService);\n              // Update platform information (display, etc)\n              const updatePlatformInfo$ = platformUpdater(this.platformService);\n              const mediaSink$ = this.mediaElement$.pipe(mediaElementServiceEpic(() => {\n                  return new MediaSource();\n              }, config, this, this.logger, this.teardownWG$, this.rtcService), share() // Prevent us from making a new MediaSink for each thing subscribing to this observable\n              );\n              // Things that depend on active item.\n              const handleActiveItemChange$ = this.itemQueue.activeItemById$.pipe(switchMap((entity) => {\n                  if (!entity) {\n                      return EMPTY;\n                  }\n                  return statsProcessor(config, this.statsService, entity, this.logger);\n              }));\n              this.rpcService = (() => {\n                  let create = null;\n                  if (config.createRPCService != null) {\n                      create = createRPCServiceWithFallbacks(config.createRPCService, createRPCInlineService);\n                  }\n                  if (hasUMDWorker() && config.enableWorker) {\n                      if (create == null) {\n                          create = createRPCService;\n                      }\n                  }\n                  if (create == null) {\n                      create = createRPCInlineService;\n                  }\n                  return create(this.logger);\n              })();\n              this.rpcClients = createRPCClients(this.rpcService);\n              // Emits when we have all context available for pipeline.\n              // CAUTION: every time this observable emits it will cause pipelineCtxHandlers$ to\n              // teardown and re-subscribe (if applicable). Only emit on /changes/ to pipeline context!\n              const pipelineContext$ = combineLatest([\n                  // Emit when root playlist loaded\n                  this.itemQueue.activeItemById$.pipe(makeActiveItemAdapters(config, this.logger, this.rootPlaylistService, platformQuery, this.statsService, this.playerEvents, this.rpcClients), tap((rootAdapters) => {\n                      const rootPlaylistQuery = rootAdapters === null || rootAdapters === void 0 ? void 0 : rootAdapters.rootPlaylistQuery;\n                      // prep publicQueriesInternal to serve api calls, that\n                      // depend on rootPlaylistQuery exclusively.\n                      this.publicQueriesInternal$.next([rootPlaylistQuery, null]);\n                      this.iframeMachine = rootAdapters === null || rootAdapters === void 0 ? void 0 : rootAdapters.iframeMachine;\n                      if (rootPlaylistQuery) {\n                          // this is delayed trigger for manifest parsed, but doing it before\n                          // setting in publicQueriesInternal will make some api such as\n                          // sessionData non serviceable.\n                          this.playerEvents.triggerManifestParsed(rootPlaylistQuery);\n                      }\n                  })),\n                  // Emit when all adapters created / destroyed\n                  mediaSink$.pipe(makeAdapters(this.itemQueue.removedItems$, ksService, config, platformQuery, this, this.rtcService, this.logger), tap(({ keySystemAdapter, legibleSystemAdapter, mediaSink }) => {\n                      this.keySystemAdapter = keySystemAdapter;\n                      this.legibleSystemAdapter = legibleSystemAdapter;\n                      this.mediaElementAdapter = mediaSink;\n                  })),\n              ]).pipe(map(([activeItemAdapters, mediaAdapters]) => {\n                  const { keySystemAdapter, legibleSystemAdapter, mediaSink } = mediaAdapters;\n                  if (!activeItemAdapters || !keySystemAdapter || !legibleSystemAdapter || !mediaSink) {\n                      return null; // Stop everything depending on this\n                  }\n                  const { rootPlaylistQuery, iframeMachine, mediaParser } = activeItemAdapters;\n                  return {\n                      logger: this.logger,\n                      config,\n                      platformService: this.platformService,\n                      statsService: this.statsService,\n                      rtcService: this.rtcService,\n                      rpcClients: this.rpcClients,\n                      rootPlaylistService: this.rootPlaylistService,\n                      rootPlaylistQuery,\n                      mediaLibraryService: mediaLibService,\n                      keySystemAdapter,\n                      legibleSystemAdapter,\n                      mediaSink,\n                      mediaParser,\n                      iframeMachine,\n                      customUrlLoader: this.customUrlLoader,\n                      gaplessInstance: this,\n                  };\n              }), share());\n              // Things that depend on PipelineContext. This means rootPlaylist loaded && mediaSink != null\n              const pipelineCtxHandlers$ = pipelineContext$.pipe(switchMap((context) => {\n                  if (!context) {\n                      return EMPTY;\n                  }\n                  const { rootPlaylistQuery, mediaSink, mediaLibraryService } = context;\n                  this.publicQueriesInternal$.next([rootPlaylistQuery, mediaSink.mediaQuery]);\n                  const mediaQuery = mediaSink.mediaQuery;\n                  const mediaFragmentPipeline$ = of(context).pipe(mediaFragmentPipelineEpic());\n                  // TODO: Fix rdar://81171922 and re-enable content steering\n                  // const loadSteeringManifest$ = of(rootPlaylistQuery).pipe(contentSteeringEpic(context.rootPlaylistService, config, config.steeringManifestLoadPolicy, this.logger));\n                  // <rdar://81918939> AirPlay may pick the alternates before hls.rootQuery and rootQuery.rootPlaylistEntity are ready.\n                  // Delay these early selections when hls is instantiating.\n                  // We should not need these early alternate selections for gapless items since\n                  // (i) follow-up items should inherit the existing language selections.\n                  // (ii) hls.rootQuery has been setup and rootQuery.rootPlaylistEntity lifecycle (for the next itemId) is controlled by hls.js\n                  const earlySelection$ = rootPlaylistQuery.rootPlaylistEntity$.pipe(filterNullOrUndefined(), take(1), tap(() => {\n                      this.commitEarlySelection(context.logger); // earliest point where this._activeRootQuery is valid\n                  }));\n                  const loadSessionData$ = waitFor(combineLatest([mediaQuery.haveEnough$, rootPlaylistQuery.sessionData$]), ([haveEnough]) => haveEnough === true, 1).pipe(switchMap(([, sessionData]) => {\n                      return this.sessionDataLoader.loadSessionData(sessionData);\n                  }), tap((sessionData) => {\n                      this.rootPlaylistService.setSessionData(rootPlaylistQuery.itemId, sessionData);\n                  }), catchError((err) => {\n                      this.logger.error(err.message);\n                      return EMPTY;\n                  }));\n                  // Is this a good place to put this....\n                  const statsQuery = createStatsQuery(rootPlaylistQuery.itemId);\n                  const haveEnough$ = checkForHaveEnough(config, this.logger, rootPlaylistQuery, mediaSink, mediaLibraryService, statsQuery);\n                  const ended$ = checkForEndOfStream(context);\n                  const iframeAutoPause$ = checkForIframeAutoPause(context);\n                  const iframePrefetch$ = checkForIframePrefetch(context);\n                  const playbackInfo$ = waitFor(combineQueries([mediaQuery.gotPlaying$, mediaQuery.gotLoadStart$, mediaQuery.readyState$]), ([playing, loadStart, readyState]) => playing === true || loadStart === true || readyState >= 1).pipe(switchMap(() => mediaQuery.ended$), \n                  // on ended, fire once and stop, else every 1s\n                  switchMap((ended) => timer(0, ended ? undefined : 1000)), tap(() => {\n                      this.playbackInfo(config, mediaQuery);\n                  }));\n                  const updatePlayingId$ = mediaQuery.timeupdate$.pipe(map((pos) => {\n                      if (this.inGaplessMode && this.isPreloading) {\n                          if (isFiniteNumber(this.loadingItem.itemStartOffset) && pos >= this.loadingItem.itemStartOffset) {\n                              const prevItemId = this.itemQueue.playingItem.itemId;\n                              const nextItemId = this.itemQueue.loadingItem.itemId;\n                              const nextStartTime = this.loadingItem.itemStartOffset;\n                              const nextDuration = mediaQuery.msDuration - this.loadingItem.itemStartOffset;\n                              const data = { prevItemId, nextItemId, nextStartTime, nextDuration };\n                              this.logger.info(`[gapless] Item transitioned prevItem: ${prevItemId}, nextItem: ${nextItemId}, nextStartTime: ${nextStartTime}, nextDuration: ${nextDuration}`);\n                              this.itemQueue.updatePlayingItemId();\n                              this.trigger(HlsEvent.ITEM_TRANSITIONED, data);\n                              this.rtcService.itemTransitioned(prevItemId, nextItemId);\n                              this.logger.qe({ critical: true, name: 'gapless', data: { transitionFrom: prevItemId, transitionTo: nextItemId } });\n                          }\n                      }\n                  }));\n                  const liveSeekableRange$ = this.updateLiveSeekableRange(rootPlaylistQuery, mediaSink);\n                  const observableList = [\n                      earlySelection$,\n                      mediaFragmentPipeline$,\n                      // TODO: Fix rdar://81171922 and re-enable content steering\n                      // loadSteeringManifest$, // Load steering manifest\n                      loadSessionData$,\n                      haveEnough$,\n                      playbackInfo$,\n                      iframeAutoPause$,\n                      iframePrefetch$,\n                      updatePlayingId$,\n                      liveSeekableRange$,\n                      ended$, // Check for end of stream\n                  ];\n                  if (config.enablePerformanceLogging) {\n                      const tlog = this.logger.child({ name: 'timing' });\n                      // Log currently loading fragments\n                      const inFlightFrags$ = zip(...AVMediaOptionTypes.map((type) => {\n                          return rootPlaylistQuery.getInFlightFragByType$(type).pipe(distinctUntilChanged((a, b) => (a === null || a === void 0 ? void 0 : a.state) === (b === null || b === void 0 ? void 0 : b.state)), filterNullOrUndefined(), withLatestFrom(mediaQuery.bufferedRangeTuple$), tap(([inFlightInfo, bufferedRanges]) => {\n                              const payload = Object.assign(Object.assign({}, inFlightInfo), { event: 'fragment', name: MediaOptionNames[type], buffered: undefined });\n                              if (inFlightInfo.state === 'appended') {\n                                  payload.buffered = bufferedRanges;\n                              }\n                              tlog.info(JSON.stringify(payload));\n                          }), catchError(() => EMPTY));\n                      }));\n                      // Log whenever detailsLoading changes\n                      const loadingPlaylist$ = zip(...MediaOptionTypes.map((type) => {\n                          return rootPlaylistQuery.enabledMediaOptionByType$(type).pipe(switchMap((option) => {\n                              if ((option === null || option === void 0 ? void 0 : option.url) == null || !isEnabledMediaOption(option)) {\n                                  return EMPTY;\n                              }\n                              const query = createMediaLibraryQuery(option);\n                              return query.mediaOptionDetailsEntity$.pipe(filterNullOrUndefined(), map((entity) => ({ entity, option })), distinctUntilChanged((a, b) => (a === null || a === void 0 ? void 0 : a.entity.detailsLoading) === (b === null || b === void 0 ? void 0 : b.entity.detailsLoading)), tap(({ entity, option }) => {\n                                  if (!entity || !option) {\n                                      return;\n                                  }\n                                  const payload = {\n                                      event: 'playlist',\n                                      name: MediaOptionNames[option.mediaOptionType],\n                                      mediaOptionId: option.mediaOptionId,\n                                      state: entity.detailsLoading ? 'loading' : 'loaded',\n                                  };\n                                  tlog.info(JSON.stringify(payload));\n                              }));\n                          }), catchError(() => EMPTY));\n                      }));\n                      observableList.push(inFlightFrags$, loadingPlaylist$);\n                  }\n                  return merge(...observableList);\n              }));\n              const handleQueueItemRemove$ = this.itemQueue.removedItems$.pipe(withTransaction((ids) => {\n                  // Cleanup everything with lifecycle tied to QueueItem\n                  mediaLibraryRemove(ids);\n                  this.rootPlaylistService.removeItems(ids);\n              }));\n              const userSeek$ = hlsService.getQuery().userSeek$.pipe(userSeekEpic(this.itemQueue, this.rootPlaylistService));\n              const gotNewHls$ = hlsService\n                  .getQuery()\n                  .selectEntityAction(EntityActions.Add)\n                  .pipe(tap(() => {\n                  this.logger.warn(`new Hls instance added while old one still active sessionId:${sessionId}`);\n              }));\n              merge(\n              // Keep mediaSink alive even if other stuff errors out just in case we need play to end of buffer handling\n              // PipelineContext is subscribed to by pipelineCtxHandler$ so errors should be caught in other observable.\n              mediaSink$.pipe(catchError(() => EMPTY)), merge(updatePlatformInfo$, userSeek$, handleActiveItemChange$, handleQueueItemRemove$, pipelineCtxHandlers$, this.teardownWG$).pipe(catchError((err) => this._handleError(err))))\n                  .pipe(finalize$1(() => {\n                  var _a, _b;\n                  try {\n                      this.logger.info(`finalize Hls sessionId:${sessionId}`);\n                      // Clean up everything with lifecycle tied to HLS instance:\n                      this.detachMedia();\n                      this.trigger(HlsEvent.DESTROYING);\n                      this.playerEvents.destroy();\n                      (_a = this.accessLogInstance) === null || _a === void 0 ? void 0 : _a.destroy();\n                      (_b = this.rtcService) === null || _b === void 0 ? void 0 : _b.destroy();\n                      mediaLibraryClear();\n                      this.rootPlaylistService.removeAll();\n                      this.itemQueue.clearQueue();\n                      hlsService.removeEntity(this.sessionID);\n                  }\n                  catch (err) {\n                      this.logger.error(`Got error in finalize ${err.message}`);\n                  }\n              }), takeUntil(race(this.destroy$, gotNewHls$)))\n                  .subscribe();\n          }\n          get publicQueries$() {\n              return this.publicQueriesInternal$.pipe(filter((queries) => Boolean(queries) && Boolean(queries[0]) && Boolean(queries[1])));\n          }\n          get _activeRootQuery() {\n              var _a;\n              const publicQueries = this.publicQueriesInternal$.value;\n              return (_a = publicQueries === null || publicQueries === void 0 ? void 0 : publicQueries[0]) !== null && _a !== void 0 ? _a : null;\n          }\n          get _mediaElementQuery() {\n              var _a;\n              const publicQueries = this.publicQueriesInternal$.value;\n              return (_a = publicQueries === null || publicQueries === void 0 ? void 0 : publicQueries[1]) !== null && _a !== void 0 ? _a : null;\n          }\n          static get version() {\n              return '2.162.2';\n          }\n          /**\n           * @type {HlsEvent}\n           */\n          static get Events() {\n              return HlsEvent;\n          }\n          get Events() {\n              return Hls$1.Events;\n          }\n          /**\n           * @type {HlsConfig}\n           */\n          static get DefaultConfig() {\n              return deepCpy(hlsDefaultConfig);\n          }\n          get DefaultConfig() {\n              return Hls$1.DefaultConfig;\n          }\n          /**\n           * @type {boolean}\n           */\n          static isSupported() {\n              return isSupported();\n          }\n          commitEarlySelection(logger) {\n              const audioPersistentId = this.itemQueue.earlyAudioSelection;\n              if (isFiniteNumber(audioPersistentId)) {\n                  logger.info(`use early audio selection ${audioPersistentId}`);\n                  this.audioSelectedPersistentID = audioPersistentId;\n                  this.itemQueue.earlyAudioSelection = null;\n              }\n              const subtitlePersistentId = this.itemQueue.earlySubtitleSelection;\n              if (isFiniteNumber(subtitlePersistentId)) {\n                  logger.info(`use early subtitle selection ${subtitlePersistentId}`);\n                  this.subtitleSelectedPersistentID = subtitlePersistentId;\n                  this.itemQueue.earlySubtitleSelection = null;\n              }\n          }\n          /**\n           * Global error handler. If we've reached here, we've exhausted all other options\n           * and it's likely fatal. All errors should bubble up from the observables in the pipe\n           */\n          _handleError(err) {\n              var _a;\n              try {\n                  let errMessage = err.message;\n                  {\n                      errMessage += `\\n${err.stack}`;\n                  }\n                  this.logger.error(`Got unhandled or fatal error ${errMessage}`, err);\n                  (_a = this.rtcService) === null || _a === void 0 ? void 0 : _a.handleError(err);\n                  let newError;\n                  if (err instanceof HlsError) {\n                      newError = err;\n                  }\n                  else {\n                      newError = new ExceptionError(true, err.message, ErrorResponses.InternalError);\n                  }\n                  if (newError.fatal && this.isPreloading) {\n                      this.logger.warn('Fatal error seen while preloading, calling dequeueSource');\n                      this.dequeueSource('FatalErrorWhileLoading');\n                  }\n                  const shouldEscalateError = newError.fatal;\n                  if (shouldEscalateError) {\n                      this.logger.qe({ critical: true, name: 'fatalError', data: { msg: newError.message, stack: newError.stack } });\n                      let triggerError$ = VOID;\n                      if (this.mediaElementAdapter) {\n                          const mediaQuery = this.mediaElementAdapter.mediaQuery;\n                          const combinedBuffer = mediaQuery.getCombinedBufferInfo(mediaQuery.currentTime, 0);\n                          if ((combinedBuffer === null || combinedBuffer === void 0 ? void 0 : combinedBuffer.len) > 0) {\n                              this.logger.info(`playing to buffer end @${combinedBuffer.end}, pos=${mediaQuery.currentTime}`);\n                              triggerError$ = waitFor(this.mediaElementAdapter.mediaQuery.stallInfo$, (stallInfo) => stallInfo != null).pipe(map(() => { }));\n                          }\n                      }\n                      return triggerError$.pipe(switchMap(() => {\n                          this.trigger(HlsEvent.ERROR, newError);\n                          return EMPTY;\n                      }));\n                  }\n                  this.trigger(HlsEvent.ERROR, newError);\n              }\n              catch (thrownError) {\n                  this.logger.error(`Error thrown inside _handleError ${thrownError.message}`, thrownError);\n                  throw thrownError;\n              }\n              return EMPTY;\n          }\n          updateLiveSeekableRange(rootPlaylistQuery, mediaSink) {\n              return rootPlaylistQuery.enabledMediaOptionByType$(MediaOptionType.Variant).pipe(switchMap((mediaOption) => {\n                  const query = createMediaLibraryQuery(mediaOption);\n                  let lastUpdate = 0;\n                  // filter on entities that have loading set to false and have stats filled and have been updated\n                  return query.mediaOptionDetailsEntity$.pipe(filterNullOrUndefined(), filter((entity) => {\n                      var _a;\n                      const retValue = entity.stats !== null && entity.detailsLoading === false && entity.lastUpdateMillis > lastUpdate;\n                      lastUpdate = (_a = entity.lastUpdateMillis) !== null && _a !== void 0 ? _a : 0;\n                      return retValue;\n                  }));\n              }), switchMap((mediaDetailsEntity) => {\n                  if (mediaDetailsEntity.unchangedCount === 0) {\n                      if (mediaDetailsEntity.mediaOptionDetails.liveOrEvent) {\n                          mediaSink.updateLiveSeekableRange(mediaDetailsEntity.mediaOptionDetails);\n                      }\n                      else {\n                          mediaSink.clearLiveSeekableRange();\n                      }\n                  }\n                  return EMPTY;\n              }));\n          }\n          playbackInfo(config, mediaQuery) {\n              var _a;\n              const video = this.mediaElement$.getValue();\n              if (!video) {\n                  return;\n              }\n              const readyToPlay = video.readyState >= video.HAVE_FUTURE_DATA;\n              const playbackLikelyToKeepUp = mediaQuery.haveEnough && readyToPlay;\n              const playbackInfo = {\n                  readyToPlay: readyToPlay,\n                  playbackLikelyToKeepUp: playbackLikelyToKeepUp,\n                  rate: video.playbackRate,\n                  paused: video.paused,\n                  position: video.currentTime,\n                  duration: video.duration,\n                  seekableTimeRanges: MediaElementHelper.timeRangeToArray(video.seekable),\n                  loadedTimeRanges: MediaElementHelper.timeRangeToArray(video.buffered),\n              };\n              let droppedVideoFrames = 0, decodedFrameCount = 0;\n              if (MediaElementHelper.isHtmlVideoElement(video)) {\n                  const videoPlaybackQuality = video.getVideoPlaybackQuality;\n                  if (videoPlaybackQuality && typeof videoPlaybackQuality === typeof Function) {\n                      const videoQuality = video.getVideoPlaybackQuality();\n                      droppedVideoFrames = playbackInfo.droppedVideoFrames = videoQuality.droppedVideoFrames;\n                      playbackInfo.corruptedVideoFrames = videoQuality.corruptedVideoFrames;\n                      playbackInfo.totalVideoFrames = videoQuality.totalVideoFrames;\n                      decodedFrameCount = playbackInfo.totalVideoFrames - droppedVideoFrames;\n                  }\n              }\n              else if (MediaElementHelper.isWebkitMediaElement(video)) {\n                  droppedVideoFrames = playbackInfo.droppedVideoFrames = video.webkitDroppedFrameCount;\n                  decodedFrameCount = playbackInfo.decodedFrameCount = video.webkitDecodedFrameCount;\n              }\n              if (config.enablePerformanceLogging) {\n                  this.logger.qe({ critical: true, name: 'playbackInfo', data: playbackInfo });\n                  const [variantBufferInfo, altAudioBufferInfo] = mediaQuery.getCombinedMediaSourceBufferInfo(config.maxBufferHole);\n                  this.logger.qe({ critical: true, name: 'bufferInfo', data: { variant: variantBufferInfo, altAudio: altAudioBufferInfo } });\n              }\n              (_a = this.rtcService) === null || _a === void 0 ? void 0 : _a.handlePlaybackInfo(droppedVideoFrames, decodedFrameCount);\n          }\n          get currentItem() {\n              if (this.isPreloading) {\n                  this.logger.info('Currently preloading, returning playing item');\n                  return this.playingItem;\n              }\n              return this.itemQueue.activeItem;\n          }\n          get realCurrentTime() {\n              var _a, _b;\n              const mediaQuery = this._mediaElementQuery;\n              if (!mediaQuery) {\n                  return NaN;\n              }\n              // during trick-playback\n              if ((_a = this.iframeMachine) === null || _a === void 0 ? void 0 : _a.isStarted) {\n                  const duration = mediaQuery.mediaElementDuration;\n                  const ifct = this.iframeMachine.iframeClockTimeSeconds;\n                  return ifct > duration ? duration : ifct;\n              }\n              // After trick-play is stopped, before seek to postFlushSeek, return postFlushSeek time until postFlushSeek is set to undefined when seek complete\n              let currentTime = isFiniteNumber(mediaQuery.postFlushSeek) ? mediaQuery.postFlushSeek : mediaQuery.currentTime;\n              // if the playing item is a finite number, remove it from real current time.\n              // No need to check inGaplessMode mode here because there situations where inGaplessMode is false\n              // but itemStartOffset is finite e.g. when playing the last song in an album\n              if (isFiniteNumber(currentTime) && isFiniteNumber((_b = this.playingItem) === null || _b === void 0 ? void 0 : _b.itemStartOffset)) {\n                  currentTime -= this.playingItem.itemStartOffset;\n              }\n              return currentTime;\n          }\n          set realCurrentTime(value) {\n              var _a;\n              this.logger.info(`[seek] realCurrentTime ${value}`);\n              // if the playing item is a finite number, add it to the value.\n              // No need to check inGaplessMode mode here because there situations where inGaplessMode is false\n              // but itemStartOffset is finite e.g. when playing the last song in an album\n              if (isFiniteNumber((_a = this.playingItem) === null || _a === void 0 ? void 0 : _a.itemStartOffset)) {\n                  value += this.playingItem.itemStartOffset;\n              }\n              this.seekTo = value;\n          }\n          get bufferedDuration() {\n              var _a;\n              const mediaQuery = this._mediaElementQuery;\n              return (_a = mediaQuery === null || mediaQuery === void 0 ? void 0 : mediaQuery.getBufferedDuration()) !== null && _a !== void 0 ? _a : 0;\n          }\n          get sessionData() {\n              const rootPlaylistQuery = this._activeRootQuery;\n              return rootPlaylistQuery === null || rootPlaylistQuery === void 0 ? void 0 : rootPlaylistQuery.sessionData;\n          }\n          get supportedFrameRates() {\n              const { enabled } = this.hlsConfig.trickPlaybackConfig;\n              const supported = [0, 1];\n              const rootQuery = this._activeRootQuery;\n              const libQuery = mediaLibraryService().getQuery();\n              if (enabled && rootQuery && libQuery.getEntity(rootQuery.itemId)) {\n                  const isLive = libQuery.getEntity(rootQuery.itemId).liveOrEvent;\n                  if (isLive === false) {\n                      supported.push(8, 24, 48, 96);\n                  }\n              }\n              return supported;\n          }\n          loadSource(url, itemOptions, initialSeekTime) {\n              var _a, _b, _c, _d;\n              // If Playready key system is being requested and if it's not enabled for the browser, reject loading the source\n              if (this.config.keySystemPreference === 'playready' && !this.config.enablePlayReadyKeySystem) {\n                  throw new ExceptionError(true, 'Playready key system is not supported now', ErrorResponses.UnsupportedKeySystemError);\n              }\n              if (!url || !url.trim().length) {\n                  throw new ExceptionError(true, 'Empty loadSource url', ErrorResponses.EmptyLoadSourceError);\n              }\n              // inherit protocol from href\n              url = URLToolkit$1.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n              const logItemOptions = itemOptions &&\n                  Object.keys(itemOptions)\n                      .filter((key) => ['itemId', 'streamID'].indexOf(key) >= 0)\n                      .reduce((newObj, key) => (key in itemOptions ? Object.assign(newObj, { [key]: itemOptions[key] }) : newObj), {});\n              this.logger.qe({ critical: true, name: 'loadSource', data: { url: redactUrl(url), itemOptions: logItemOptions, initialSeekTime } });\n              if ((_a = itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.appData) === null || _a === void 0 ? void 0 : _a.reportingAgent) {\n                  this.reportingAgent = itemOptions.appData.reportingAgent;\n              }\n              if (itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.userInfo) {\n                  this.userInfo = itemOptions.userInfo;\n              }\n              (_b = this.accessLogInstance) === null || _b === void 0 ? void 0 : _b.setupReporter(itemOptions.appData);\n              if (itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.platformInfo) {\n                  this.platformService.updatePlatformInfo(itemOptions.platformInfo);\n              }\n              // Append queries specific to certain hosts\n              if (urlNeedsUpdate(url, this.config.enableQueryParamsForITunes)) {\n                  const queryParameters = {\n                      language: itemOptions.language,\n                      dsid: itemOptions.dsid,\n                      subs: itemOptions.subs,\n                  };\n                  url = updateUrlWithQueryStrings(url, itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.platformInfo, queryParameters);\n                  itemOptions.inheritQuery = false; // don't inherit queries to subsequent requests\n              }\n              this.itemQueue.setQueueItem(`item:${(_c = itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.itemId) !== null && _c !== void 0 ? _c : guid()}`, url, initialSeekTime, itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.platformInfo, (_d = itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.appData) === null || _d === void 0 ? void 0 : _d.serviceName);\n              // clear this out. only makes sense for first asset\n              globalHlsService().setStartTime(undefined);\n          }\n          queueSource(url, itemOptions, initialSeekTime) {\n              var _a, _b, _c, _d;\n              this.logger.qe({ critical: true, name: 'queueSource', data: { url: redactUrl(url), itemOptions, initialSeekTime } });\n              if (itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.userInfo) {\n                  this.userInfo = itemOptions.userInfo;\n              }\n              const combinedBuffer = (_a = this._mediaElementQuery) === null || _a === void 0 ? void 0 : _a.getCombinedBufferInfo((_b = this._mediaElementQuery) === null || _b === void 0 ? void 0 : _b.currentTime, 0);\n              let duration = 0;\n              if (combinedBuffer) {\n                  duration = combinedBuffer.end;\n              }\n              this.logger.info(`queueSource ${redactUrl(url)} initialSeekTime:${initialSeekTime === null || initialSeekTime === void 0 ? void 0 : initialSeekTime.toFixed(3)}`);\n              this.logger.qe({ critical: true, name: 'gapless', data: { itemLoadingAt: duration } });\n              this.itemQueue.addQueueItem(`item:${(_c = itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.itemId) !== null && _c !== void 0 ? _c : guid()}`, url, initialSeekTime, itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.platformInfo, duration, (_d = itemOptions === null || itemOptions === void 0 ? void 0 : itemOptions.appData) === null || _d === void 0 ? void 0 : _d.serviceName);\n          }\n          dequeueSource(reason = 'ApplicationInitiated') {\n              // if we are not preloading and this is the first item and it's invalid format, disallow gapless\n              // but do not evict the item. It's probably a video\n              if (!this.isPreloading && reason === 'InvalidFormat' && this.isFirstItem) {\n                  this.logger.error('First item has invalid format for gapless. Probably video. Disabling gapless.');\n                  this.gaplessCapable = false;\n                  return;\n              }\n              if (!this.isPreloading) {\n                  this.logger.warn(`Nothing to dequeue, no item is preloading dequeue reason: ${reason}`);\n                  return;\n              }\n              this.logger.qe({ critical: true, name: 'gapless', data: { event: 'clean up current source' } });\n              // Store loading item information\n              const itemToEvictUrl = this.loadingItem.url;\n              const itemToEvictId = this.loadingItem.itemId;\n              // flush all data from the loading item and set media sink duration\n              this.mediaElementAdapter.flushData(SourceBufferType.Variant, this.loadingItem.itemStartOffset, Infinity);\n              this.mediaElementAdapter.msDuration = this.loadingItem.itemStartOffset;\n              // clear loading item in queue and make playing item active.\n              this.itemQueue.resetLoadingItem();\n              // Disallow gapless on invalidFormat and FatalErrorWhileLoading\n              if (reason === 'InvalidFormat' || reason === 'FatalErrorWhileLoading') {\n                  // Disallow gapless\n                  this.gaplessCapable = false;\n              }\n              // Send out item evicted event\n              this.triggerItemEvicted({ url: itemToEvictUrl, itemId: itemToEvictId }, reason);\n          }\n          triggerItemEvicted(itemToEvict, reason) {\n              if (itemToEvict === null) {\n                  this.logger.error('dequeueSource called with no playing or loading item');\n                  return;\n              }\n              const data = { url: itemToEvict.url, evictedItemId: itemToEvict.itemId, reason };\n              const loggableData = Object.assign(Object.assign({}, data), { url: redactUrl(itemToEvict.url) });\n              this.logger.info('Item evicted evictedData: %o', loggableData);\n              this.trigger(HlsEvent.ITEM_EVICTED, data);\n          }\n          endSource() {\n              // When endSource is called, this hls instance is no longer gapless capable.\n              this.gaplessCapable = false;\n              this.logger.info('[gapless] end source');\n              // if preloading clear buffers and remove loading item\n              if (this.isPreloading) {\n                  this.logger.warn('EndSource called during preloading. Loading item will be removed');\n                  // flush all data from the loading item and set media sink duration\n                  this.mediaElementAdapter.flushData(SourceBufferType.Variant, this.loadingItem.itemStartOffset, Infinity);\n                  this.mediaElementAdapter.msDuration = this.loadingItem.itemStartOffset;\n                  // clear loading item in queue and make playing item active.\n                  this.itemQueue.resetLoadingItem();\n              }\n          }\n          get inGaplessMode() {\n              //return this.config.gapless; //&& figure out who should know if gapless is allowed... item OR rootPlaylistService\n              // Don't call this.config because it does deepCpy and is deprecated\n              return getCurrentConfig().gapless && this.gaplessCapable;\n          }\n          get isPreloading() {\n              return this.itemQueue.isPreloading();\n          }\n          get isFirstItem() {\n              return this.itemQueue.isFirstItem;\n          }\n          get loadingItem() {\n              return this.itemQueue.loadingItem;\n          }\n          get playingItem() {\n              return this.itemQueue.playingItem;\n          }\n          get url() {\n              if (this.playingItem) {\n                  return this.playingItem.url;\n              }\n              if (this.loadingItem) {\n                  return this.loadingItem.url;\n              }\n              return undefined;\n          }\n          destroy() {\n              const { logger } = this;\n              logger.info('destroy');\n              // See finalize in Hls constructor for what happens on destroy$\n              this.destroy$.next();\n              if (this.rpcService != null) {\n                  this.teardownWG$.add();\n                  this.rpcService.teardown((err) => {\n                      if (err) {\n                          logger.error('RPCService teardown error:', err);\n                      }\n                      this.teardownWG$.done();\n                  });\n                  this.rpcService = null;\n              }\n              if (this.iframeMachine != null) {\n                  this.iframeMachine.destroy();\n                  this.iframeMachine = null;\n              }\n              return this.teardownWG$.toPromise();\n          }\n          attachMedia(mediaElement) {\n              this.logger.info('attachMedia');\n              this.trigger(HlsEvent.MEDIA_ATTACHING, { media: mediaElement });\n              this.mediaElement$.next(mediaElement);\n              this.trigger(HlsEvent.MEDIA_ATTACHED, { media: mediaElement });\n          }\n          detachMedia() {\n              var _a;\n              if (!this.mediaElement$.getValue()) {\n                  this.logger.info('detachMedia called with no media element to detach');\n                  return;\n              }\n              this.logger.info('detachMedia');\n              this.trigger(HlsEvent.MEDIA_DETACHING);\n              (_a = this.rtcService) === null || _a === void 0 ? void 0 : _a.detachMedia();\n              if (this.iframeMachine != null) {\n                  this.iframeMachine.stop();\n              }\n              this.mediaElement$.next(null);\n              this.trigger(HlsEvent.MEDIA_DETACHED);\n          }\n          handleResolvedUri(originalURI, response) {\n              this.customUrlLoader.setCustomUrlResponse(originalURI, { uri: response.uri, response: response });\n          }\n          get variantOptions$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [rootQuery, meQuery] = queries;\n                  return combineLatest([rootQuery.preferredMediaOptions$, meQuery.desiredRate$]).pipe(map(([rootTuple]) => {\n                      const iframeMode = meQuery.isIframeRate;\n                      return rootTuple[MediaOptionType.Variant].filter((option) => { var _a; return ((_a = option.iframes) !== null && _a !== void 0 ? _a : false) === iframeMode; }).map((option) => option.mediaOptionId);\n                  }));\n              }));\n          }\n          get altAudioOptions$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [rootQuery] = queries;\n                  return of(rootQuery.audioMediaSelectionOptions);\n              }));\n          }\n          get subtitleOptions$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [rootQuery] = queries;\n                  const disableOption = [\n                      {\n                          MediaSelectionOptionsName: 'Disable subtitle',\n                          MediaSelectionOptionsPersistentID: -1,\n                      },\n                  ];\n                  return of(disableOption.concat(rootQuery.subtitleMediaSelectionOptions));\n              }));\n          }\n          // Old public API used by webapp\n          get levels() {\n              var _a, _b;\n              return (_b = (_a = this._activeRootQuery) === null || _a === void 0 ? void 0 : _a.preferredMediaOptions[MediaOptionType.Variant]) !== null && _b !== void 0 ? _b : [];\n          }\n          // Old public API used by webapp\n          get audioTracks() {\n              var _a, _b;\n              return (_b = (_a = this._activeRootQuery) === null || _a === void 0 ? void 0 : _a.preferredMediaOptions[MediaOptionType.AltAudio]) !== null && _b !== void 0 ? _b : [];\n          }\n          get audioMediaOptions() {\n              var _a, _b;\n              return (_b = (_a = this._activeRootQuery) === null || _a === void 0 ? void 0 : _a.audioMediaSelectionOptions) !== null && _b !== void 0 ? _b : [];\n          }\n          get subtitleMediaOptions() {\n              var _a, _b;\n              return (_b = (_a = this._activeRootQuery) === null || _a === void 0 ? void 0 : _a.subtitleMediaSelectionOptions) !== null && _b !== void 0 ? _b : [];\n          }\n          /**\n           * @returns whether we are likely to keep up based on network and buffer\n           */\n          get playbackLikelyToKeepUp() {\n              var _a, _b;\n              return (_b = (_a = this._mediaElementQuery) === null || _a === void 0 ? void 0 : _a.playbackLikelyToKeepUp) !== null && _b !== void 0 ? _b : false;\n          }\n          get duration$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [, mediaQuery] = queries;\n                  return mediaQuery.mediaElementDuration$;\n              }));\n          }\n          get timeupdate$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [, mediaQuery] = queries;\n                  return mediaQuery.timeupdate$;\n              }));\n          }\n          get playing$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [, mediaQuery] = queries;\n                  return mediaQuery.gotPlaying$;\n              }));\n          }\n          get desiredRate$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [, mediaQuery] = queries;\n                  return mediaQuery.desiredRate$;\n              }));\n          }\n          set desiredRate(desiredRate) {\n              if (desiredRate == null) {\n                  return;\n              }\n              this.setRate(desiredRate);\n          }\n          get desiredRate() {\n              var _a, _b;\n              return (_b = (_a = this._mediaElementQuery) === null || _a === void 0 ? void 0 : _a.desiredRate) !== null && _b !== void 0 ? _b : 0;\n          }\n          get effectiveRate() {\n              var _a, _b;\n              return (_b = (_a = this._mediaElementQuery) === null || _a === void 0 ? void 0 : _a.effectiveRate) !== null && _b !== void 0 ? _b : 0;\n          }\n          get iframeMode() {\n              var _a, _b;\n              return (_b = (_a = this._mediaElementQuery) === null || _a === void 0 ? void 0 : _a.isIframeRate) !== null && _b !== void 0 ? _b : false;\n          }\n          get accessLog() {\n              return this.accessLogInstance && this._activeRootQuery ? this.accessLogInstance.getAccessLog(this._activeRootQuery.itemId) : [];\n          }\n          get errorLog() {\n              return this.accessLogInstance ? this.accessLogInstance.errorLog : [];\n          }\n          setRate(newRate) {\n              var _a;\n              const Errors = { UNABLE_TO_SWITCH: -1, ALREADY_IN_RATE: -2, UNSUPPORTED_RATE: -3 };\n              const logger = this.logger.child({ name: 'iframes' });\n              const oldRate = this.desiredRate;\n              if (newRate === oldRate) {\n                  return Errors.ALREADY_IN_RATE;\n              }\n              logger.info(`setRate ${oldRate} -> ${newRate}`);\n              const mediaSink = this.mediaElementAdapter;\n              if (!mediaSink || isNaN(newRate)) {\n                  logger.warn('unable to switch to rate, missing adapter or newRate isNaN');\n                  return Errors.UNABLE_TO_SWITCH;\n              }\n              newRate = Number(newRate);\n              const absRate = Math.abs(newRate);\n              const isSupportedRate = this.supportedFrameRates.some((rate) => rate === absRate);\n              if (!isSupportedRate) {\n                  logger.warn(`unsupported rate(${newRate})`);\n                  return Errors.UNSUPPORTED_RATE;\n              }\n              const iframeRate = isIframeRate(newRate);\n              const iframeMachine = this.iframeMachine;\n              if (iframeRate) {\n                  const rootQuery = this._activeRootQuery;\n                  if (!(rootQuery === null || rootQuery === void 0 ? void 0 : rootQuery.mediaOptionListQueries[MediaOptionType.Variant].hasIframes)) {\n                      logger.warn('no iframe variants available');\n                      return Errors.UNABLE_TO_SWITCH;\n                  }\n                  mediaSink.postFlushSeek = null;\n              }\n              else if ((iframeMachine === null || iframeMachine === void 0 ? void 0 : iframeMachine.isStarted) && !isFiniteNumber((_a = mediaSink.mediaQuery) === null || _a === void 0 ? void 0 : _a.postFlushSeek)) {\n                  iframeMachine.pause();\n                  logger.info(`resuming from trick-play postFlushSeek=${iframeMachine.iframeClockTimeSeconds}`);\n                  mediaSink.postFlushSeek = iframeMachine.iframeClockTimeSeconds;\n              }\n              mediaSink.desiredRate = newRate;\n              return 0;\n          }\n          get sessionData$() {\n              return this.publicQueries$.pipe(switchMap(([rootPlaylistQuery]) => {\n                  return rootPlaylistQuery.sessionData$;\n              }));\n          }\n          set skip(skip) {\n              this.logger.info(`skip=${skip}`);\n              if (this._mediaElementQuery) {\n                  this.logger.info(`[seek] skip ${skip}`);\n                  this.realCurrentTime = Math.max(0, this.realCurrentTime + skip);\n              }\n          }\n          // Helper function for seeking when in gapless mode\n          gaplessSeekTo(seekTo) {\n              // Adjust seekTo Value if needed\n              this.logger.debug(`seekTo before gapless adjust: ${seekTo}, startOffset: ${this.playingItem.itemStartOffset}`);\n              if (seekTo < this.playingItem.itemStartOffset) {\n                  this.logger.warn(`[Gapless] Seeking past track boundary oldSeek=${seekTo}, adjustedSeek=${this.playingItem.itemStartOffset}`);\n                  seekTo = this.playingItem.itemStartOffset;\n              }\n              if (this.isPreloading) {\n                  if (seekTo > this.loadingItem.itemStartOffset) {\n                      this.logger.warn(`[Gapless] Seeking past track boundary oldSeek=${seekTo}, adjustedSeek=${this.loadingItem.itemStartOffset}`);\n                      seekTo = this.loadingItem.itemStartOffset;\n                  }\n                  const buf = this._mediaElementQuery.getBufferInfo(this._mediaElementQuery.currentTime, this.config.maxBufferHole);\n                  this.logger.info('Hls seekTo during preloading currentTime:%d seekTo:%d Buf:%o', this.realCurrentTime, seekTo, buf);\n                  if (seekTo < buf[0].buffered.start) {\n                      this.dequeueSource('SeekToUnbufferedTimeRanges');\n                  }\n              }\n              globalHlsService().setUserSeek(seekTo);\n          }\n          isIframeInternalSeek(seekTo) {\n              var _a;\n              return seekTo === ((_a = this.iframeMachine) === null || _a === void 0 ? void 0 : _a.mediaRootTime);\n          }\n          set seekTo(seekValue) {\n              var _a;\n              const seekTo = Number(seekValue);\n              if (!isFiniteNumber(seekTo)) {\n                  this.logger.error(`[seek] got invalid seek value ${seekValue}`);\n                  return;\n              }\n              this.logger.info(`[seek] seekTo=${seekTo}`);\n              if (this.inGaplessMode) {\n                  this.gaplessSeekTo(seekTo);\n                  return;\n              }\n              // After trick-play is stopped, before seek to postFlushSeek, update the post flush resume time\n              const mediaSink = this.mediaElementAdapter;\n              if (mediaSink && isFiniteNumber((_a = mediaSink.mediaQuery) === null || _a === void 0 ? void 0 : _a.postFlushSeek) && (!mediaSink.mediaQuery.seekTo || this.isIframeInternalSeek(mediaSink.mediaQuery.seekTo.pos))) {\n                  this.logger.info(`[seek] clearing seekTo ${JSON.stringify(mediaSink.mediaQuery.seekTo)} and resuming from trick-play postFlushSeek=${seekTo}`);\n                  mediaSink.schedulePostFlushSeek(seekTo);\n                  return;\n              }\n              // Store seek in userSeek to be processed by userSeekEpic\n              globalHlsService().setUserSeek(seekTo);\n          }\n          /**\n           * Seek to a date. Only valid for playlists with PROGRAM-DATE-TIME tags\n           * @param searchDate The date to seek to\n           */\n          seekToDate(searchDate) {\n              // Note: Airplay allows seekToDate() to occur before loadSource() so we must store it at Hls level\n              this.logger.info(`[seek] seekToDate=${searchDate.toISOString()}`);\n              globalHlsService().setUserSeek(searchDate);\n          }\n          /**\n           * @returns a map of Date (ms) to time in media element (s)\n           */\n          get availableProgramDateTime() {\n              return new Map(this._currentDateToMediaTimeTuple);\n          }\n          get _currentDateToMediaTimeTuple() {\n              var _a, _b;\n              if (!this._activeRootQuery) {\n                  return [];\n              }\n              const curVariant = this._activeRootQuery.enabledMediaOptionKeys[MediaOptionType.Variant];\n              if (!isEnabledMediaOption(curVariant)) {\n                  return [];\n              }\n              const libQuery = mediaLibraryService().getQueryForOption(curVariant);\n              return (_b = (_a = libQuery.mediaOptionDetails) === null || _a === void 0 ? void 0 : _a.dateMediaTimePairs) !== null && _b !== void 0 ? _b : [];\n          }\n          /**\n           * Convert the playing time into equivalent DateTime\n           */\n          get playingDate() {\n              return resolvePTSToDate(this._currentDateToMediaTimeTuple, this.realCurrentTime);\n          }\n          /**\n           * Manually set variantID. Only in development mode\n           */\n          set variantId(variantId) {\n              {\n                  const rootQuery = this._activeRootQuery;\n                  if (!rootQuery) {\n                      return;\n                  }\n                  this.logger.info(`variantId=${variantId}`);\n                  const itemId = rootQuery.itemId;\n                  const mediaOption = rootQuery.variantMediaOptionById(variantId);\n                  this.rootPlaylistService.setManualMode(itemId, true);\n                  this.rootPlaylistService.setEnabledMediaOptionByType(itemId, MediaOptionType.Variant, mediaOption);\n              }\n          }\n          set audioSelectedPersistentID(persistentID) {\n              const rootQuery = this._activeRootQuery;\n              const audioMediaOptions = rootQuery === null || rootQuery === void 0 ? void 0 : rootQuery.preferredMediaOptions[MediaOptionType.AltAudio];\n              if (audioMediaOptions) {\n                  const itemId = rootQuery.itemId;\n                  if (persistentID === this.audioSelectedPersistentID) {\n                      this.logger.info('skipping set audioSelectedPersistentID, id is same. PersistentID = %d', persistentID);\n                      return;\n                  }\n                  this.rootPlaylistService.setEnabledMediaOptionTupleWithMatchedGroups(itemId, MediaOptionType.AltAudio, persistentID, { userInitiated: true });\n              }\n              else {\n                  // MatchPoint spams audioSelectedPersistentID(-1) during startup (when hls is not ready)\n                  // hls 1.0 - 2.0 ignores them explicitly.\n                  // Otherwise, they may override a valid selection.\n                  if (!isFiniteNumber(persistentID) || persistentID < 0) {\n                      this.logger.info(`ignore early invalid audio selection: ${persistentID}`);\n                      return;\n                  }\n                  this.logger.warn(`[audio] no active item, defer audio track selection: persistentId ${persistentID}`);\n                  this.itemQueue.earlyAudioSelection = persistentID;\n              }\n          }\n          get audioSelectedPersistentID() {\n              var _a;\n              if (this._activeRootQuery) {\n                  return (_a = this._activeRootQuery.enabledAlternateMediaOptionByType(MediaOptionType.AltAudio)) === null || _a === void 0 ? void 0 : _a.persistentID;\n              }\n              else {\n                  return this.itemQueue.earlyAudioSelection;\n              }\n          }\n          /**\n           * @param persistentID = the persistentId\n           */\n          set subtitleSelectedPersistentID(persistentID) {\n              const rootQuery = this._activeRootQuery;\n              const subtitleMediaOptions = rootQuery === null || rootQuery === void 0 ? void 0 : rootQuery.preferredMediaOptions[MediaOptionType.Subtitle];\n              if (subtitleMediaOptions) {\n                  if (persistentID === this.subtitleSelectedPersistentID) {\n                      this.logger.info('skipping set subtitleSelectedPersistentID, id is same. PersistentID = %d', persistentID);\n                      return;\n                  }\n                  const itemId = rootQuery.itemId;\n                  if (subtitleMediaOptions.length === 0 && (!isFiniteNumber(persistentID) || persistentID < 0)) {\n                      this.logger.info(`ignore early invalid subtitle selection ${persistentID}; no subtitle media options yet`);\n                      return;\n                  }\n                  this.logger.info(`subtitleSelectedPersistentID ${persistentID}`);\n                  if (!isFiniteNumber(persistentID) || persistentID === -1) {\n                      // Disable subtitles\n                      this.rootPlaylistService.setEnabledMediaOptionByType(itemId, MediaOptionType.Subtitle, NoMediaOption);\n                  }\n                  else {\n                      this.rootPlaylistService.setEnabledMediaOptionTupleWithMatchedGroups(itemId, MediaOptionType.Subtitle, persistentID);\n                  }\n              }\n              else {\n                  // MatchPoint spams subtitleSelectedPersistentID(-1) during startup (when hls is not ready)\n                  // hls 1.0 - 2.0 ignores them explicitly.\n                  // Otherwise, they may override a valid selection.\n                  if (!isFiniteNumber(persistentID) || persistentID < 0) {\n                      this.logger.info(`ignore early invalid subtitle selection ${persistentID}`);\n                      return;\n                  }\n                  // cache valid selection\n                  this.logger.warn(`[subtitle] no active item, defer subtitle track selection: persistentId ${persistentID}`);\n                  this.itemQueue.earlySubtitleSelection = persistentID;\n              }\n          }\n          /**\n           * @returns the persistentID of the enabled subtitle\n           */\n          get subtitleSelectedPersistentID() {\n              var _a;\n              if (this._activeRootQuery) {\n                  return (_a = this._activeRootQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle)) === null || _a === void 0 ? void 0 : _a.persistentID;\n              }\n              else {\n                  return this.itemQueue.earlySubtitleSelection;\n              }\n          }\n          /**\n           * Get array of selected tracks\n           */\n          get selectedMediaArray() {\n              const rootQuery = this._activeRootQuery;\n              if (!rootQuery) {\n                  return [];\n              }\n              const selectedMediaArray = [];\n              const audioMediaOption = rootQuery.enabledAlternateMediaOptionByType(MediaOptionType.AltAudio);\n              const subtitleMediaOption = rootQuery.enabledAlternateMediaOptionByType(MediaOptionType.Subtitle);\n              const audioSelectedMediaOption = audioMediaOption ? rootQuery.audioMediaSelectionOptions.find((option) => option.MediaSelectionOptionsPersistentID === audioMediaOption.persistentID) : undefined;\n              const subtitleSelectedMediaOption = subtitleMediaOption\n                  ? rootQuery.subtitleMediaSelectionOptions.find((option) => option.MediaSelectionOptionsPersistentID === subtitleMediaOption.persistentID)\n                  : undefined;\n              if (audioSelectedMediaOption) {\n                  const selectedItem = {\n                      MediaSelectionGroupMediaType: MediaTypeFourCC.AUDIO,\n                      MediaSelectionOptionsPersistentID: audioSelectedMediaOption.MediaSelectionOptionsPersistentID,\n                  };\n                  selectedMediaArray.push(selectedItem);\n              }\n              if (subtitleSelectedMediaOption) {\n                  let showNonForcedSubtitles = Allowed.NO;\n                  if (subtitleSelectedMediaOption.MediaSelectionOptionsDisplaysNonForcedSubtitles) {\n                      showNonForcedSubtitles = subtitleSelectedMediaOption.MediaSelectionOptionsDisplaysNonForcedSubtitles;\n                  }\n                  const selectedItem = {\n                      MediaSelectionGroupMediaType: MediaTypeFourCC.SUBTITLE,\n                      MediaSelectionOptionsDisplaysNonForcedSubtitles: showNonForcedSubtitles,\n                      MediaSelectionOptionsPersistentID: subtitleSelectedMediaOption.MediaSelectionOptionsPersistentID,\n                  };\n                  selectedMediaArray.push(selectedItem);\n              }\n              this.logger.debug(`get selectedMediaArray: ${JSON.stringify(selectedMediaArray)}`);\n              return selectedMediaArray;\n          }\n          set selectedMediaArray(mediaArray) {\n              if (this._activeRootQuery) {\n                  this.logger.debug(`selectedMediaArray=${JSON.stringify(mediaArray)}`);\n                  mediaArray.forEach((selectedItem) => {\n                      if (selectedItem.MediaSelectionGroupMediaType === MediaTypeFourCC.AUDIO || selectedItem.MediaSelectionOptionsMediaType === MediaTypeFourCC.AUDIO) {\n                          this.audioSelectedPersistentID = selectedItem.MediaSelectionOptionsPersistentID;\n                      }\n                      else if (selectedItem.MediaSelectionGroupMediaType === MediaTypeFourCC.SUBTITLE ||\n                          selectedItem.MediaSelectionOptionsMediaType === MediaTypeFourCC.SUBTITLE ||\n                          selectedItem.MediaSelectionOptionsMediaType === MediaTypeFourCC.CLOSEDCAPTION) {\n                          this.subtitleSelectedPersistentID = selectedItem.MediaSelectionOptionsPersistentID;\n                      }\n                  });\n              }\n              else {\n                  this.logger.warn('selectedMediaArray: no active item');\n              }\n          }\n          getHTMLTextTrack(subtitleTrackId) {\n              return this.legibleSystemAdapter.getExistingHTMLTextTrackWithSubtitleTrackId(subtitleTrackId);\n          }\n          get keysystems() {\n              return this.keySystemAdapter.availableKeySystems;\n          }\n          setProtectionData(data) {\n              this.keySystemAdapter.initialize(data);\n          }\n          generateKeyRequest(keyuri, requestInfo) {\n              this.keySystemAdapter.generateRequest(keyuri, requestInfo);\n              this.rtcService.licenseChallengeReceived({ keyuri: keyuri });\n          }\n          setLicenseResponse(keyuri, response) {\n              this.keySystemAdapter.setLicenseResponse(keyuri, response);\n          }\n          get bufferInfo$() {\n              return this.publicQueries$.pipe(switchMap((queries) => {\n                  const [, mediaQuery] = queries;\n                  const config = createHlsQuery().currentConfig;\n                  return merge(mediaQuery.timeupdate$, mediaQuery.bufferedRangeTuple$).pipe(throttleTime(1000), map(() => {\n                      const pos = mediaQuery.currentTime;\n                      return {\n                          combined: mediaQuery.getCombinedBufferInfo(pos, config.maxBufferHole),\n                          sbTuple: mediaQuery.getBufferInfo(pos, config.maxBufferHole),\n                      };\n                  }));\n              }));\n          }\n          bufferInfoByType$(type) {\n              return this.bufferInfo$.pipe(map((bufInfoTuple) => {\n                  var _a;\n                  return (_a = bufInfoTuple === null || bufInfoTuple === void 0 ? void 0 : bufInfoTuple.sbTuple) === null || _a === void 0 ? void 0 : _a[type];\n              }));\n          }\n          /**\n           * DEPRECATED\n           */\n          levelWithPersistentId(levelId) {\n              this.logger.warn('levelWithPersistentId is deprecated');\n          }\n          /**\n           * DEPRECATED\n           */\n          startLoad(startTimeSec) {\n              this.logger.warn('startLoad is deprecated');\n              // Hack for Vuze. remove when they adopt initialSeekTime API.\n              if (isFiniteNumber(startTimeSec)) {\n                  this.logger.warn(`[seek] Seeking to ${startTimeSec === null || startTimeSec === void 0 ? void 0 : startTimeSec.toFixed(3)} via deprecated \"startLoad\" method. Use loadSource(url, options, startTime) instead.`);\n                  this.seekTo = startTimeSec;\n              }\n          }\n          /**\n           * DEPRECATED\n           */\n          stopLoad() { }\n          /**\n           * DEPRECATED\n           * @returns current config\n           */\n          get config() {\n              return Object.assign(Object.assign({}, deepCpy(getCurrentConfig())), { set startPosition(startTimeSec) {\n                      // Hack for airplay. remove when they adopt initialSeekTime API\n                      getLogger().warn(`Setting start position ${startTimeSec === null || startTimeSec === void 0 ? void 0 : startTimeSec.toFixed(3)} using deprecated method`);\n                      globalHlsService().setStartTime(startTimeSec);\n                  } });\n          }\n          /**\n           * DEPRECATED\n           * @returns if media is attached\n           */\n          get media() {\n              return this.mediaElement$.value != null;\n          }\n          /**\n           * DEPRECATED\n           */\n          set subtitleDisplay(subtitleDisplay) {\n              this.logger.warn(`set subtitleDisplay ${subtitleDisplay} is deprecated`);\n          }\n      }\n    \n      var Hls = Hls$1;\n    \n      return Hls;\n    \n    }));\n    })(false);"
  },
  {
    "path": "src/renderer/assets/fonts/Inter/inter.css",
    "content": "@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 100;\n  font-display: swap;\n  src: url(\"Inter-Thin.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Thin.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 100;\n  font-display: swap;\n  src: url(\"Inter-ThinItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-ThinItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 200;\n  font-display: swap;\n  src: url(\"Inter-ExtraLight.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-ExtraLight.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 200;\n  font-display: swap;\n  src: url(\"Inter-ExtraLightItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-ExtraLightItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 300;\n  font-display: swap;\n  src: url(\"Inter-Light.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Light.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 300;\n  font-display: swap;\n  src: url(\"Inter-LightItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-LightItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 400;\n  font-display: swap;\n  src: url(\"Inter-Regular.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Regular.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 400;\n  font-display: swap;\n  src: url(\"Inter-Italic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Italic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 500;\n  font-display: swap;\n  src: url(\"Inter-Medium.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Medium.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 500;\n  font-display: swap;\n  src: url(\"Inter-MediumItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-MediumItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 600;\n  font-display: swap;\n  src: url(\"Inter-SemiBold.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-SemiBold.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 600;\n  font-display: swap;\n  src: url(\"Inter-SemiBoldItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-SemiBoldItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 700;\n  font-display: swap;\n  src: url(\"Inter-Bold.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Bold.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 700;\n  font-display: swap;\n  src: url(\"Inter-BoldItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-BoldItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 800;\n  font-display: swap;\n  src: url(\"Inter-ExtraBold.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-ExtraBold.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 800;\n  font-display: swap;\n  src: url(\"Inter-ExtraBoldItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-ExtraBoldItalic.woff?v=3.19\") format(\"woff\");\n}\n\n@font-face {\n  font-family: \"Inter\";\n  font-style: normal;\n  font-weight: 900;\n  font-display: swap;\n  src: url(\"Inter-Black.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-Black.woff?v=3.19\") format(\"woff\");\n}\n@font-face {\n  font-family: \"Inter\";\n  font-style: italic;\n  font-weight: 900;\n  font-display: swap;\n  src: url(\"Inter-BlackItalic.woff2?v=3.19\") format(\"woff2\"), url(\"Inter-BlackItalic.woff?v=3.19\") format(\"woff\");\n}\n\n/* -------------------------------------------------------\nVariable font.\nUsage:\n\n  html { font-family: 'Inter', sans-serif; }\n  @supports (font-variation-settings: normal) {\n    html { font-family: 'Inter var', sans-serif; }\n  }\n*/\n@font-face {\n  font-family: \"Inter var\";\n  font-weight: 100 900;\n  font-display: swap;\n  font-style: normal;\n  font-named-instance: \"Regular\";\n  src: url(\"Inter-roman.var.woff2?v=3.19\") format(\"woff2\");\n}\n@font-face {\n  font-family: \"Inter var\";\n  font-weight: 100 900;\n  font-display: swap;\n  font-style: italic;\n  font-named-instance: \"Italic\";\n  src: url(\"Inter-italic.var.woff2?v=3.19\") format(\"woff2\");\n}\n\n/* --------------------------------------------------------------------------\n[EXPERIMENTAL] Multi-axis, single variable font.\n\nSlant axis is not yet widely supported (as of February 2019) and thus this\nmulti-axis single variable font is opt-in rather than the default.\n\nWhen using this, you will probably need to set font-variation-settings\nexplicitly, e.g.\n\n  * { font-variation-settings: \"slnt\" 0deg }\n  .italic { font-variation-settings: \"slnt\" 10deg }\n\n*/\n@font-face {\n  font-family: \"Inter var experimental\";\n  font-weight: 100 900;\n  font-display: swap;\n  font-style: oblique 0deg 10deg;\n  src: url(\"Inter.var.woff2?v=3.19\") format(\"woff2\");\n}\n"
  },
  {
    "path": "src/renderer/assets/fonts/Pretendard/pretendardvariable.css",
    "content": "/*\nCopyright (c) 2021 Kil Hyung-jin, with Reserved Font Name Pretendard.\nhttps://github.com/orioncactus/pretendard\n\nThis Font Software is licensed under the SIL Open Font License, Version 1.1.\nThis license is copied below, and is also available with a FAQ at:\nhttp://scripts.sil.org/OFL\n*/\n\n@font-face {\n  font-family: \"Pretendard Variable\";\n  font-weight: 45 920;\n  font-style: normal;\n  font-display: swap;\n  src: local(\"Pretendard Variable\"), url(\"./woff2/PretendardVariable.woff2\") format(\"woff2-variations\");\n}\n"
  },
  {
    "path": "src/renderer/audio/audio.js",
    "content": "const CiderAudio = {\n  context: null,\n  source: null,\n  audioNodes: {\n    gainNode: null,\n    spatialNode: null,\n    audioBands: null,\n    vibrantbassNode: null,\n    llpw: null,\n    recorderNode: null,\n    intelliGainComp: null,\n    atmosphereRealizer2: null,\n    atmosphereRealizer1: null,\n    opportunisticCorrection: null,\n    optimizedNode: null,\n  },\n  ccON: false,\n  mediaRecorder: null,\n  init: function (cb = function () {}) {\n    //AudioOutputs.fInit = true;\n    let searchInt = setInterval(function () {\n      if (document.getElementById(\"apple-music-player\")) {\n        //AudioOutputs.eqReady = true;\n        document.getElementById(\"apple-music-player\").crossOrigin = \"anonymous\";\n        CiderAudio.connectContext(document.getElementById(\"apple-music-player\"), 0);\n\n        cb();\n        clearInterval(searchInt);\n      }\n    }, 1000);\n  },\n  off: function () {\n    try {\n      try {\n        CiderAudio.audioNodes = {\n          gainNode: null,\n          spatialNode: null,\n          audioBands: null,\n          vibrantbassNode: null,\n          llpw: null,\n          recorderNode: null,\n          intelliGainComp: null,\n          atmosphereRealizer2: null,\n          atmosphereRealizer1: null,\n          opportunisticCorrection: null,\n          optimizedNode: null,\n        };\n      } catch (e) {}\n      CiderAudio.source.connect(CiderAudio.context.destination);\n    } catch (e) {}\n  },\n  connectContext: function (mediaElem) {\n    if (!CiderAudio.context) {\n      CiderAudio.context = new window.AudioContext({\n        sampleRate: 96000,\n        latencyHint: \"playback\",\n      }); // Don't ever remove the sample rate arg. Ask Maikiwi.\n      app.lyricOffset = CiderAudio.context.baseLatency + (CiderAudio.context.outputLatency ? CiderAudio.context.outputLatency : 0);\n    }\n    if (!CiderAudio.source) {\n      CiderAudio.source = CiderAudio.context.createMediaElementSource(mediaElem);\n    } else {\n      try {\n        CiderAudio.source.disconnect(CiderAudio.context.destination);\n      } catch (e) {}\n    }\n    CiderAudio.audioNodes.gainNode = CiderAudio.context.createGain();\n    CiderAudio.audioNodes.intelliGainComp = CiderAudio.context.createGain();\n    CiderAudio.source.connect(CiderAudio.audioNodes.intelliGainComp);\n    CiderAudio.audioNodes.intelliGainComp.connect(CiderAudio.audioNodes.gainNode);\n    if (app.cfg.audio.normalization) {\n      CiderAudio.normalizerOn();\n    }\n    CiderAudio.hierarchical_loading();\n  },\n  normalizerOn: function () {\n    try {\n      let previewURL = null;\n      try {\n        previewURL = app.mk.nowPlayingItem.previewURL;\n      } catch (e) {}\n      if (previewURL == null && (app.mk.nowPlayingItem?._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? app.mk.nowPlayingItem.relationships.catalog.data[0].id) != -1) {\n        app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/songs/${app.mk.nowPlayingItem?._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? app.mk.nowPlayingItem.relationships.catalog.data[0].id}`).then((response) => {\n          previewURL = response.data.data[0].attributes.previews[0].url;\n          if (previewURL) ipcRenderer.send(\"getPreviewURL\", previewURL);\n        });\n      } else {\n        if (previewURL) ipcRenderer.send(\"getPreviewURL\", previewURL);\n      }\n    } catch (e) {\n      console.debug(\"[Cider][MaikiwiSoundCheck] normalizer func err: \" + e);\n    }\n  },\n  normalizerOff: function () {\n    CiderAudio.audioNodes.gainNode.gain.exponentialRampToValueAtTime(1.0, CiderAudio.context.currentTime + 0.5);\n  },\n  spatialProfiles: [\n    {\n      id: \"maikiwi\",\n      file: \"./cideraudio/impulses/CiderSpatial_Maikiwi.wav\",\n      name: \"Maikiwi\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"maikiwiplus\",\n      file: \"./cideraudio/impulses/CiderSpatial_MaikiwiPlus.wav\",\n      name: \"Maikiwi+\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"71_420maikiwi\",\n      file: \"./cideraudio/impulses/CiderSpatial_v71.420_Maikiwi.wav\",\n      name: \"Soundstage\",\n      description: \"\",\n      gainComp: \"1.3963683610559376\",\n    },\n    {\n      id: \"70_422maikiwi\",\n      file: \"./cideraudio/impulses/CiderSpatial_v70.422_Maikiwi.wav\",\n      name: \"Separation\",\n      description: \"\",\n      gainComp: \"1.30767553892022\",\n    },\n    {\n      id: \"standard\",\n      file: \"./cideraudio/impulses/CiderSpatial_Natural.wav\",\n      name: \"Minimal\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"standardplus\",\n      file: \"./cideraudio/impulses/CiderSpatial_Natural+.wav\",\n      name: \"Minimal+\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"diffused\",\n      file: \"./cideraudio/impulses/CiderSpatial_Diffuse.wav\",\n      name: \"Diffused\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"BPLK\",\n      file: \"./cideraudio/impulses/CiderSpatial_BPLK.wav\",\n      name: \"BPLK\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"HW2K\",\n      file: \"./cideraudio/impulses/CiderSpatial_HW2K.wav\",\n      name: \"HW2K\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"live\",\n      file: \"./cideraudio/impulses/CiderSpatial_LIVE_2.wav\",\n      name: \"live\",\n      description: \"\",\n      gainComp: \"1.2647363474711515\",\n    },\n  ],\n  atmosphereRealizerProfiles: [\n    {\n      id: \"NATURAL_STANDARD\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_NaturalStandard.wav\",\n      name: \"ほうじ茶チーズクリーマティー\",\n      description: \"\",\n    },\n    {\n      id: \"NATURAL_PLUS\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Natural+.wav\",\n      name: \"玄米茶タピオカミルクティー\",\n      description: \"\",\n    },\n    {\n      id: \"E68_1\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_E68_1.5.wav\",\n      name: \"岩塩クリームチーズティー\",\n      description: \"Light\",\n    },\n    {\n      id: \"E68_2\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_E68_2.2.wav\",\n      name: \"抹茶ミルクティー\",\n      description: \"Dark\",\n    },\n    {\n      id: \"BSCBM\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_BSCBM.wav\",\n      name: \"BSCBM\",\n      description: \"BSCBM\",\n    },\n    {\n      id: \"CUDDLE\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Cuddle.wav\",\n      name: \"CUDDLE\",\n      description: \"CUDDLE\",\n    },\n    {\n      id: \"E168_1\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_E168_1.2.wav\",\n      name: \"春毫ジャスミンマキアート\",\n      description: \"Natural Air\",\n    },\n    {\n      id: \"Z3600\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z3600.wav\",\n      name: \"ロイヤルミルクティー\",\n      description: \"3600\",\n    },\n    {\n      id: \"Z8500A\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z8500_A.wav\",\n      name: \"ムーンライトソフトケーキ\",\n      description: \"8500\",\n    },\n    {\n      id: \"Z8500B\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z8500_B.wav\",\n      name: \"Clafoutis aux Cerises\",\n      description: \"8500\",\n    },\n    {\n      id: \"Z8500C\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z8500_C.wav\",\n      name: \"宇治抹茶だいふく\",\n      description: \"8500\",\n    },\n  ],\n  opportunisticCorrectionProfiles: [\n    {\n      id: \"CHU\",\n      file: \"./cideraudio/impulses/MoondropCHU_Cider.wav\",\n      name: \"Moondrop CHU Specific\",\n      description: \"\",\n    },\n  ],\n  spatial_ninf: function () {\n    CiderAudio.audioNodes.spatialNode = null;\n    CiderAudio.audioNodes.spatialNode = CiderAudio.context.createConvolver();\n    CiderAudio.audioNodes.spatialNode.normalize = false;\n\n    let spatialProfile = CiderAudio.spatialProfiles.find(function (profile) {\n      return profile.id === app.cfg.audio.maikiwiAudio.spatialProfile;\n    });\n\n    if (spatialProfile === undefined) {\n      spatialProfile = CiderAudio.spatialProfiles[0];\n    }\n    fetch(spatialProfile.file).then(async (impulseData) => {\n      let bufferedImpulse = await impulseData.arrayBuffer();\n      CiderAudio.audioNodes.spatialNode.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n    });\n\n    // Always destination\n    CiderAudio.audioNodes.spatialNode.connect(CiderAudio.context.destination);\n  },\n  spatialOff: function () {\n    CiderAudio.hierarchical_loading();\n  },\n  intelliGainComp_n0_0: function () {\n    let filters = [];\n    const precisionHz = 12;\n    // Biquad calculation\n    if (CiderAudio.audioNodes.audioBands !== null) {\n      filters = filters.concat(CiderAudio.audioNodes.audioBands);\n    }\n    if (CiderAudio.audioNodes.vibrantbassNode !== null) {\n      filters = filters.concat(CiderAudio.audioNodes.vibrantbassNode);\n    }\n    if (CiderAudio.audioNodes.llpw !== null && CiderAudio.audioNodes.llpw.length > 2) {\n      filters = filters.concat(CiderAudio.audioNodes.llpw);\n    }\n\n    if (!filters || filters.length === 0) {\n      let filterlessGain = 1;\n      // Impulse Calculation\n      if (CiderAudio.audioNodes.llpw !== null && CiderAudio.audioNodes.llpw.length <= 2) {\n        filterlessGain = filterlessGain * 1.109174815262401;\n      }\n      if (app.cfg.audio.maikiwiAudio.atmosphereRealizer2 === true) {\n        filterlessGain = filterlessGain * 1.096478196143185;\n      }\n      if (app.cfg.audio.maikiwiAudio.atmosphereRealizer1 === true) {\n        filterlessGain = filterlessGain * 1.096478196143185;\n      }\n      if (app.cfg.audio.maikiwiAudio.spatial == true) {\n        let spatialProfile = CiderAudio.spatialProfiles.find(function (profile) {\n          return profile.id === app.cfg.audio.maikiwiAudio.spatialProfile;\n        });\n        if (spatialProfile === undefined) {\n          spatialProfile = CiderAudio.spatialProfiles[0];\n        }\n        filterlessGain = filterlessGain * spatialProfile.gainComp;\n      }\n      filterlessGain = Math.pow(10, (-1 * (20 * Math.log10(filterlessGain))) / 20).toFixed(4);\n      filterlessGain > 1.0 ? CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(1.0, CiderAudio.context.currentTime + 0.3) : CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(filterlessGain, CiderAudio.context.currentTime + 0.3);\n      console.debug(`[Cider][Audio] IntelliGainComp: ${filterlessGain > 1.0 ? 0 : (20 * Math.log10(filterlessGain)).toFixed(2)} dB (${filterlessGain > 1.0 ? 1 : filterlessGain})`);\n      return;\n    }\n\n    filters.shift();\n    let steps = Math.ceil(96000 / precisionHz);\n    // Generate input array for getFrequencyResponse method\n    let frequencies = new Float32Array(steps);\n    for (let i = 0; i < steps; i++) {\n      frequencies[i] = (i + 1) * precisionHz;\n    }\n    // Here we will store combined amplitude response\n    let totalAmplitudeResp = new Float32Array(steps);\n    for (let i = 0; i < steps; i++) {\n      totalAmplitudeResp[i] = 1;\n    }\n    // Temporary container for every filter response\n    let amplitudeResp = new Float32Array(steps),\n      phaseResp = new Float32Array(steps);\n    for (let i = filters.length - 1; i >= 0; i--) {\n      let filter = filters[i];\n      // Get filter response and convolve it with existing response\n      filter.getFrequencyResponse(frequencies, amplitudeResp, phaseResp);\n      for (let j = 0; j < steps; j++) {\n        totalAmplitudeResp[j] *= amplitudeResp[j];\n      }\n    }\n    // Find max gain\n    let maxGain = -120;\n    for (let i = 0; i < steps; i++) {\n      let gain = totalAmplitudeResp[i];\n      if (gain > maxGain) maxGain = gain;\n    }\n\n    // Impulse Calculation\n    if (CiderAudio.audioNodes.llpw !== null && CiderAudio.audioNodes.llpw.length <= 2) {\n      maxGain = maxGain * 1.109174815262401;\n    }\n    if (app.cfg.audio.maikiwiAudio.atmosphereRealizer2 === true) {\n      maxGain = maxGain * 1.096478196143185;\n    }\n    if (app.cfg.audio.maikiwiAudio.atmosphereRealizer1 === true) {\n      maxGain = maxGain * 1.096478196143185;\n    }\n    if (app.cfg.audio.maikiwiAudio.spatial == true) {\n      let spatialProfile = CiderAudio.spatialProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.spatialProfile;\n      });\n      if (spatialProfile === undefined) {\n        spatialProfile = CiderAudio.spatialProfiles[0];\n      }\n      maxGain = maxGain * spatialProfile.gainComp;\n    }\n    maxGain = Math.pow(10, (-1 * (20 * Math.log10(maxGain))) / 20).toFixed(4);\n    maxGain > 1.0 ? CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(1.0, CiderAudio.context.currentTime + 0.3) : CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(maxGain, CiderAudio.context.currentTime + 0.3);\n    console.debug(`[Cider][Audio] IntelliGainComp: ${maxGain > 1.0 ? 0 : (20 * Math.log10(maxGain)).toFixed(2)} dB (${maxGain > 1.0 ? 1 : maxGain})`);\n  },\n  sendAudio: function () {\n    if (!CiderAudio.ccON) {\n      CiderAudio.ccON = true;\n      let searchInt = setInterval(async function () {\n        if (CiderAudio.context != null && CiderAudio.audioNodes.intelliGainComp != null) {\n          // var options = {\n          //     mimeType: 'audio/webm; codecs=opus'\n          // };\n          // var destnode = CiderAudio.context.createMediaStreamDestination();\n          // CiderAudio.audioNodes.intelliGainComp.connect(CiderAudio.audioNodes.gainNode);\n          //            CiderAudio.audioNodes.gainNode.connect(destnode)\n          // CiderAudio.mediaRecorder = new MediaRecorder(destnode.stream, options);\n          // CiderAudio.mediaRecorder.start(1);\n          // CiderAudio.mediaRecorder.ondataavailable = function (e) {\n          //     e.data.arrayBuffer().then(buffer => {\n          //         ipcRenderer.send('writeAudio', buffer)\n          //     }\n          //     );\n          // }\n          const worklet = `class RecorderWorkletProcessor extends AudioWorkletProcessor {\n                        static get parameterDescriptors() {\n                          return [{\n                            name: 'isRecording',\n                            defaultValue: 0\n                          },\n                          {\n                            name: 'numberOfChannels',\n                            defaultValue: 2\n                          }\n                        ];\n                        }\n\n                        constructor() {\n                          super();\n                          this._bufferSize = 2048;\n                          this._buffers = null;\n                          this._initBuffer();\n                        }\n                        _initBuffers(numberOfChannels) {\n                          this._buffers = [];\n                          for (let channel=0; channel < numberOfChannels; channel++) {\n                            this._buffers.push(new Float32Array(this._bufferSize));\n                          }\n                        }\n\n                        _initBuffer() {\n                          this._bytesWritten = 0;\n                        }\n\n                        _isBufferEmpty() {\n                          return this._bytesWritten === 0;\n                        }\n\n                        _isBufferFull() {\n                          return this._bytesWritten === this._bufferSize;\n                        }\n                        _pushToBuffers(audioRawData, numberOfChannels) {\n                          if (this._isBufferFull()) {\n                              this._flush();\n                          }\n                          let dataLength = audioRawData[0]?.length ?? 0;\n                          for (let idx=0; idx<dataLength; idx++) {\n                            for (let channel=0; channel < numberOfChannels; channel++) {\n                              try {\n                              let value = audioRawData[channel][idx];\n                              this._buffers[channel][this._bytesWritten] = value;} catch(e){}\n                            }\n                            this._bytesWritten += 1;\n                          }\n                        }\n\n                        _flush() {\n                          let buffers = [];\n                          this._buffers.forEach((buffer, channel) => {\n                            if (this._bytesWritten < this._bufferSize) {\n                              buffer = buffer.slice(0, this._bytesWritten);\n                            }\n                            buffers[channel] = buffer;\n                          });\n                          this.port.postMessage({\n                            eventType: 'data',\n                            audioBuffer: buffers,\n                            bufferSize: this._bufferSize\n                          });\n                          this._initBuffer();\n                        }\n\n                        _recordingStopped() {\n                          this.port.postMessage({\n                            eventType: 'stop'\n                          });\n                        }\n\n                        process(inputs, outputs, parameters) {\n                          const isRecordingValues = parameters.isRecording;\n                          const numberOfChannels = parameters.numberOfChannels[0];\n                          if (this._buffers === null) {\n                            this._initBuffers(numberOfChannels);\n                          }\n\n                          for (let dataIndex = 0; dataIndex < isRecordingValues.length; dataIndex++)\n                          {\n                            const shouldRecord = isRecordingValues[dataIndex] === 1;\n                            if (!shouldRecord && !this._isBufferEmpty()) {\n                              this._flush();\n                              this._recordingStopped();\n                            }\n\n                            if (shouldRecord) {\n                              let audioRawData = inputs[0];\n                              this._pushToBuffers(audioRawData, numberOfChannels);\n                            }\n                          }\n                          return true;\n                        }\n\n                      }\n\n                      registerProcessor('recorder-worklet', RecorderWorkletProcessor);`;\n          let blob = new Blob([worklet], { type: \"application/javascript\" });\n          await CiderAudio.context.audioWorklet.addModule(URL.createObjectURL(blob)).then(() => {\n            const channels = 2;\n            CiderAudio.audioNodes.recorderNode = new window.AudioWorkletNode(CiderAudio.context, \"recorder-worklet\", {\n              parameterData: { numberOfChannels: channels },\n            });\n            CiderAudio.audioNodes.recorderNode.port.onmessage = (e) => {\n              const data = e.data;\n              switch (data.eventType) {\n                case \"data\":\n                  const audioData = data.audioBuffer;\n                  const bufferSize = data.bufferSize;\n                  if (audioData[0].some((item) => item !== 0) || audioData[0].some((item) => item !== 0)) {\n                    ipcRenderer.send(\"writeWAV\", audioData[0], audioData[1], bufferSize);\n                  }\n                  break;\n                case \"stop\":\n                  break;\n              }\n            };\n            CiderAudio.audioNodes.recorderNode.parameters.get(\"isRecording\").setValueAtTime(1, CiderAudio.context.currentTime);\n            CiderAudio.audioNodes.intelliGainComp.connect(CiderAudio.audioNodes.recorderNode);\n          });\n          clearInterval(searchInt);\n        }\n      }, 1000);\n    } else {\n      if (CiderAudio.audioNodes.recorderNode != null && CiderAudio.context != null) {\n        CiderAudio.audioNodes.recorderNode.parameters.get(\"isRecording\").setValueAtTime(1, CiderAudio.context.currentTime);\n        // CiderAudio.audioNodes.recorderNode = null;\n        // CiderAudio.ccON = false;\n      }\n    }\n  },\n  stopAudio() {\n    if (CiderAudio.audioNodes.recorderNode != null && CiderAudio.context != null) {\n      CiderAudio.audioNodes.recorderNode.parameters.get(\"isRecording\").setValueAtTime(0, CiderAudio.context.currentTime);\n      // CiderAudio.audioNodes.recorderNode = null;\n      // CiderAudio.ccON = false;\n    }\n  },\n  atmosphereRealizer2_n6: function (status, destination) {\n    if (status === true) {\n      CiderAudio.audioNodes.atmosphereRealizer2 = CiderAudio.context.createConvolver();\n      CiderAudio.audioNodes.atmosphereRealizer2.normalize = false;\n      let atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.atmosphereRealizer2_value;\n      });\n\n      if (atmosphereRealizerProfile === undefined) {\n        atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles[0];\n      }\n      fetch(atmosphereRealizerProfile.file).then(async (impulseData) => {\n        let bufferedImpulse = await impulseData.arrayBuffer();\n        CiderAudio.audioNodes.atmosphereRealizer2.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n      });\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  atmosphereRealizer1_n5: function (status, destination) {\n    if (status === true) {\n      CiderAudio.audioNodes.atmosphereRealizer1 = CiderAudio.context.createConvolver();\n      CiderAudio.audioNodes.atmosphereRealizer1.normalize = false;\n      let atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.atmosphereRealizer1_value;\n      });\n\n      if (atmosphereRealizerProfile === undefined) {\n        atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles[0];\n      }\n      fetch(atmosphereRealizerProfile.file).then(async (impulseData) => {\n        let bufferedImpulse = await impulseData.arrayBuffer();\n        CiderAudio.audioNodes.atmosphereRealizer1.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n      });\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  opportunisticCorrection_n2: function (status, destination) {\n    if (status === true) {\n      CiderAudio.audioNodes.opportunisticCorrection = CiderAudio.context.createConvolver();\n      CiderAudio.audioNodes.opportunisticCorrection.normalize = false;\n      let opportunisticCorrectionProfile = CiderAudio.opportunisticCorrectionProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.opportunisticCorrection_state;\n      });\n\n      if (opportunisticCorrectionProfile === undefined) {\n        opportunisticCorrectionProfile = CiderAudio.opportunisticCorrectionProfiles[0];\n      }\n      fetch(opportunisticCorrectionProfile.file).then(async (impulseData) => {\n        let bufferedImpulse = await impulseData.arrayBuffer();\n        CiderAudio.audioNodes.opportunisticCorrection.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n      });\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.opportunisticCorrection[0]);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  llpw_n1: function (status, destination) {\n    if (status === true) {\n      let c_LLPW_Q = [1.25, 0.131, 10, 2.5, 2.293, 0.11, 14.14, 1.552, 28.28, 7.071, 2.847, 5, 0.625, 7.071, 3.856, 3.856, 20, 28.28, 20, 14.14, 2.102, 6.698, 3.536, 10];\n      let c_LLPW_GAIN = [-0.11, 0.27, -0.8, 0.57, 1.84, -0.38, 0.47, -1.56, 0.83, 1.58, -1.79, -0.45, 0.48, 1.22, -1.58, -1.59, -2.03, 2.56, -2.2, -2.48, 4.75, 10.5, 1.43, 3.76];\n      let c_LLPW_FREQUENCIES = [400.83, 5812.8, 8360, 10413, 10658, 12079, 12899, 13205, 14848, 15591, 15778, 15783, 16716, 16891, 17255, 17496, 18555, 18622, 19219, 19448, 19664, 21341, 21353, 22595];\n      let LLPW_Q = [5, 1, 3.536, 1.25, 8.409, 1.25, 14.14, 7.071, 5, 0.625, 16.82, 20, 20, 20, 28.28, 28.28, 28.28, 20, 33.64, 33.64, 10, 28.28, 7.071, 3.856];\n      let LLPW_GAIN = [0.38, -1.81, -0.23, -0.51, 0.4, 0.84, 0.36, -0.34, 0.27, -1.2, -0.42, -0.67, 0.81, 1.31, -0.71, 0.68, -1.04, 0.79, -0.73, -1.33, 1.17, 0.57, 0.35, 6.33];\n      let LLPW_FREQUENCIES = [16.452, 24.636, 37.134, 74.483, 159.54, 308.18, 670.21, 915.81, 1200.7, 2766.4, 2930.6, 4050.6, 4409.1, 5395.2, 5901.6, 6455.5, 7164.1, 7724.1, 8449, 10573, 12368, 14198, 17910, 18916];\n      CiderAudio.audioNodes.llpw = [];\n\n      switch (app.cfg.audio.maikiwiAudio.ciderPPE_value) {\n        case \"MAIKIWI\":\n          try {\n            switch (localStorage.getItem(\"playingBitrate\")) {\n              case \"64\":\n                CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n                CiderAudio.audioNodes.llpw[0].normalize = false;\n                fetch(\"./cideraudio/impulses/CAP_64.wav\").then(async (impulseData) => {\n                  let bufferedImpulse = await impulseData.arrayBuffer();\n                  CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n                });\n                console.debug(\"[Cider][Audio] CAP Adaptive - 64kbps\");\n\n                break;\n              case \"256\":\n                CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n                CiderAudio.audioNodes.llpw[0].normalize = false;\n                CiderAudio.audioNodes.llpw[1] = CiderAudio.context.createGain();\n                CiderAudio.audioNodes.llpw[1].gain.value = 2.37; // Post Gain Compensation\n                CiderAudio.audioNodes.llpw[0].connect(CiderAudio.audioNodes.llpw[1]);\n                fetch(\"./cideraudio/impulses/CAP_256_FINAL_48k.wav\").then(async (impulseData) => {\n                  let bufferedImpulse = await impulseData.arrayBuffer();\n                  CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n                });\n                console.debug(\"[Cider][Audio] CAP Adaptive - 256kbps\");\n\n                break;\n              default:\n                CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createGain();\n                CiderAudio.audioNodes.llpw[0].gain.value = 1;\n                console.debug(\"[Cider][Audio] CAP Disabled (Passthrough) : Non-Lossy Bitrate.\");\n\n                break;\n            }\n          } catch (e) {\n            CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n            CiderAudio.audioNodes.llpw[0].normalize = false;\n            CiderAudio.audioNodes.llpw[1] = CiderAudio.context.createGain();\n            CiderAudio.audioNodes.llpw[1].gain.value = 2.37;\n            CiderAudio.audioNodes.llpw[0].connect(CiderAudio.audioNodes.llpw[1]);\n            fetch(\"./cideraudio/impulses/CAP_256_FINAL_48k.wav\").then(async (impulseData) => {\n              let bufferedImpulse = await impulseData.arrayBuffer();\n              CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n            });\n            console.debug(\"[Cider][Audio] CAP Adaptive - (Error Fallback) 256kbps\");\n          }\n\n          break;\n        case \"MAIKIWI_LEGACY\":\n          CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n          CiderAudio.audioNodes.llpw[0].normalize = false;\n          fetch(\"./cideraudio/impulses/CAP_Maikiwi.wav\").then(async (impulseData) => {\n            let bufferedImpulse = await impulseData.arrayBuffer();\n            CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n          });\n          console.debug(\"[Cider][Audio] CAP - Maikiwi Signature Mode\");\n          break;\n        case \"NATURAL\":\n          CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n          CiderAudio.audioNodes.llpw[0].normalize = false;\n          fetch(\"./cideraudio/impulses/CAP_Natural.wav\").then(async (impulseData) => {\n            let bufferedImpulse = await impulseData.arrayBuffer();\n            CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n          });\n\n          console.debug(\"[Cider][Audio] CAP - Natural Mode\");\n          break;\n\n        case \"LEGACY\":\n          for (let i = 0; i < LLPW_FREQUENCIES.length; i++) {\n            CiderAudio.audioNodes.llpw[i] = CiderAudio.context.createBiquadFilter();\n            CiderAudio.audioNodes.llpw[i].type = \"peaking\"; // 'peaking';\n            CiderAudio.audioNodes.llpw[i].frequency.value = LLPW_FREQUENCIES[i];\n            CiderAudio.audioNodes.llpw[i].Q.value = LLPW_Q[i];\n            CiderAudio.audioNodes.llpw[i].gain.value = LLPW_GAIN[i];\n          }\n          for (let i = 1; i < LLPW_FREQUENCIES.length; i++) {\n            CiderAudio.audioNodes.llpw[i - 1].connect(CiderAudio.audioNodes.llpw[i]);\n          }\n          console.debug(\"[Cider][Audio] CAP - Legacy Mode\");\n\n          break;\n\n        default:\n          CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n          CiderAudio.audioNodes.llpw[0].normalize = false;\n          CiderAudio.audioNodes.llpw[1] = CiderAudio.context.createGain();\n          CiderAudio.audioNodes.llpw[1].gain.value = 2.57;\n          CiderAudio.audioNodes.llpw[0].connect(CiderAudio.audioNodes.llpw[1]);\n          fetch(\"./cideraudio/impulses/CAP_256_FINAL_48k.wav\").then(async (impulseData) => {\n            let bufferedImpulse = await impulseData.arrayBuffer();\n            CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n          });\n          app.cfg.audio.maikiwiAudio.ciderPPE_value = \"MAIKIWI\";\n\n          console.debug(\"[Cider][Audio] CAP - Maikiwi Adaptive Mode (Defaulted from broki config)\");\n          break;\n      }\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] llpw_n1 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] llpw_n1 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] llpw_n1 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] llpw_n1 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] llpw_n1 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] llpw_n1 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] llpw_n1 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] llpw_n1 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  vibrantbass_n4: function (status, destination) {\n    if (status === true) {\n      let VIBRANTBASSBANDS = app.cfg.audio.maikiwiAudio.vibrantBass.frequencies;\n      let VIBRANTBASSGAIN = app.cfg.audio.maikiwiAudio.vibrantBass.gain;\n      let VIBRANTBASSQ = app.cfg.audio.maikiwiAudio.vibrantBass.Q;\n      CiderAudio.audioNodes.vibrantbassNode = [];\n\n      for (let i = 0; i < VIBRANTBASSBANDS.length; i++) {\n        CiderAudio.audioNodes.vibrantbassNode[i] = CiderAudio.context.createBiquadFilter();\n        CiderAudio.audioNodes.vibrantbassNode[i].type = \"peaking\"; // 'peaking';\n        CiderAudio.audioNodes.vibrantbassNode[i].frequency.value = VIBRANTBASSBANDS[i];\n        CiderAudio.audioNodes.vibrantbassNode[i].Q.value = VIBRANTBASSQ[i];\n        CiderAudio.audioNodes.vibrantbassNode[i].gain.value = VIBRANTBASSGAIN[i] * (app.cfg.audio.equalizer.vibrantBass / 10);\n      }\n\n      for (let i = 1; i < VIBRANTBASSBANDS.length; i++) {\n        CiderAudio.audioNodes.vibrantbassNode[i - 1].connect(CiderAudio.audioNodes.vibrantbassNode[i]);\n      }\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> Spatial\");\n          } catch (e) {}\n          break;\n\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  hierarchical_unloading: function () {\n    try {\n      CiderAudio.audioNodes.spatialNode.disconnect();\n      CiderAudio.audioNodes.spatialNode = null;\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.gainNode.disconnect();\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.atmosphereRealizer2.disconnect();\n      CiderAudio.audioNodes.atmosphereRealizer2 = null;\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.atmosphereRealizer1.disconnect();\n      CiderAudio.audioNodes.atmosphereRealizer1 = null;\n    } catch (e) {}\n    try {\n      for (var i of CiderAudio.audioNodes.llpw) {\n        i.disconnect();\n      }\n      CiderAudio.audioNodes.llpw = null;\n    } catch (e) {}\n    try {\n      for (var i of CiderAudio.audioNodes.vibrantbassNode) {\n        i.disconnect();\n      }\n      CiderAudio.audioNodes.vibrantbassNode = null;\n    } catch (e) {}\n    try {\n      for (var i of CiderAudio.audioNodes.audioBands) {\n        i.disconnect();\n      }\n      CiderAudio.audioNodes.vibrantbassNode = null;\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.opportunisticCorrection.disconnect();\n      CiderAudio.audioNodes.opportunisticCorrection = null;\n    } catch (e) {}\n    console.debug(\"[Cider][Audio] Finished hierarchical unloading\");\n  },\n  hierarchical_loading: async function () {\n    const configMap = new Map([\n      [\"spatial\", app.cfg.audio.maikiwiAudio.spatial === true],\n      [\"n6\", app.cfg.audio.maikiwiAudio.atmosphereRealizer2 === true],\n      [\"n5\", app.cfg.audio.maikiwiAudio.atmosphereRealizer1 === true],\n      [\"n4\", app.cfg.audio.equalizer.vibrantBass != 0],\n      [\"n3\", Math.max(...app.cfg.audio.equalizer.gain) != 0],\n      [\"n2\", app.cfg.audio.maikiwiAudio.opportunisticCorrection_state !== \"OFF\"],\n      [\"n1\", app.cfg.audio.maikiwiAudio.ciderPPE === true],\n    ]);\n\n    CiderAudio.hierarchical_unloading();\n    let lastNode = \"n0\";\n    let index = 0;\n    let firstNode = \"n0\";\n    for (let [tier, value] of configMap.entries()) {\n      if (value === true) {\n        if (index === 0) {\n          firstNode = tier;\n        }\n        index++;\n        switch (tier) {\n          case \"spatial\":\n            CiderAudio.spatial_ninf();\n            lastNode = \"spatial\";\n            break;\n          case \"n6\":\n            app.cfg.audio.normalization = true;\n            CiderAudio.atmosphereRealizer2_n6(true, lastNode);\n            lastNode = \"n6\";\n            break;\n          case \"n5\":\n            app.cfg.audio.normalization = true;\n            CiderAudio.atmosphereRealizer1_n5(true, lastNode);\n            lastNode = \"n5\";\n            break;\n          case \"n4\":\n            CiderAudio.vibrantbass_n4(true, lastNode);\n            lastNode = \"n4\";\n            break;\n          case \"n3\":\n            CiderAudio.equalizer(true, lastNode);\n            lastNode = \"n3\";\n            break;\n          case \"n2\":\n            CiderAudio.opportunisticCorrection_n2(true, lastNode);\n            lastNode = \"n2\";\n            break;\n          case \"n1\":\n            app.cfg.audio.normalization = true;\n            CiderAudio.llpw_n1(true, lastNode);\n            lastNode = \"n1\";\n            break;\n        }\n      }\n    }\n\n    app.cfg.audio.maikiwiAudio.lastNode = lastNode;\n    app.cfg.audio.maikiwiAudio.firstNode = firstNode; // Sync last node & first\n\n    switch (lastNode) {\n      case \"spatial\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.spatialNode);\n        console.debug(\"[Cider][Audio] gainNode -> Spatial\");\n        break;\n      case \"n6\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n        console.debug(\"[Cider][Audio] gainNode -> atmosphereRealizer2\");\n        break;\n      case \"n5\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n        console.debug(\"[Cider][Audio] gainNode -> atmosphereRealizer1\");\n        break;\n      case \"n4\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n        console.debug(\"[Cider][Audio] gainNode -> vibrantbass\");\n        break;\n      case \"n3\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.audioBands[0]);\n        console.debug(\"[Cider][Audio] gainNode -> audioBands\");\n\n        break;\n      case \"n2\":\n        try {\n          CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.opportunisticCorrection);\n          console.debug(\"[Cider][Audio] gainNode -> opportunisticCorrection\");\n        } catch (e) {}\n        break;\n      case \"n1\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.llpw[0]);\n        console.debug(\"[Cider][Audio] gainNode -> llpw\");\n        break;\n      case \"n0\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.context.destination);\n        console.debug(\"[Cider][Audio] gainNode -> destination\");\n        break;\n    }\n\n    console.debug(\"[Cider][Audio]\\n\" + [...configMap.entries()] + \"\\n lastNode: \" + lastNode);\n\n    CiderAudio.intelliGainComp_n0_0();\n    console.debug(\"[Cider][Audio] Finished hierarchical loading\");\n  },\n\n  equalizer: function (status, destination) {\n    // n3_1\n    if (status === true) {\n      let BANDS = app.cfg.audio.equalizer.frequencies;\n      let GAIN = app.cfg.audio.equalizer.gain;\n      let Q = app.cfg.audio.equalizer.Q;\n\n      CiderAudio.audioNodes.audioBands = [];\n      for (let i = 0; i < BANDS.length; i++) {\n        CiderAudio.audioNodes.audioBands[i] = CiderAudio.context.createBiquadFilter();\n        CiderAudio.audioNodes.audioBands[i].type = \"peaking\"; // 'peaking';\n        CiderAudio.audioNodes.audioBands[i].frequency.value = BANDS[i];\n        CiderAudio.audioNodes.audioBands[i].Q.value = Q[i];\n        CiderAudio.audioNodes.audioBands[i].gain.value = GAIN[i] * app.cfg.audio.equalizer.mix;\n      }\n\n      for (let i = 1; i < BANDS.length; i++) {\n        CiderAudio.audioNodes.audioBands[i - 1].connect(CiderAudio.audioNodes.audioBands[i]);\n      }\n\n      switch (destination) {\n        case \"spatial\":\n          CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.spatialNode);\n          console.debug(\"[Cider][Audio] Equalizer -> Spatial\");\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] Equalizer -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] Equalizer -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] Equalizer -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] Equalizer -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] Equalizer -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] Equalizer -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] Equalizer -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n};\nexport { CiderAudio };\n"
  },
  {
    "path": "src/renderer/audio/cloud/audio.js",
    "content": "const CiderAudio = {\n  context: null,\n  source: null,\n  audioNodes: {\n    gainNode: null,\n    audioBands: null,\n    vibrantbassNode: null,\n    recorderNode: null,\n    intelliGainComp: null,\n    cloudProcessor: null,\n  },\n  ccON: false,\n  mediaRecorder: null,\n  init: function (cb = function () {}) {\n    //AudioOutputs.fInit = true;\n    let searchInt = setInterval(function () {\n      if (document.getElementById(\"apple-music-player\")) {\n        //AudioOutputs.eqReady = true;\n        document.getElementById(\"apple-music-player\").crossOrigin = \"anonymous\";\n        CiderAudio.connectContext(document.getElementById(\"apple-music-player\"), 0);\n\n        cb();\n        clearInterval(searchInt);\n      }\n    }, 1000);\n  },\n  off: function () {\n    try {\n      try {\n        CiderAudio.audioNodes = {\n          gainNode: null,\n          audioBands: null,\n          vibrantbassNode: null,\n          recorderNode: null,\n          intelliGainComp: null,\n          cloudProcessor: null,\n        };\n      } catch (e) {}\n      CiderAudio.source.connect(CiderAudio.context.destination);\n    } catch (e) {}\n  },\n  connectContext: function (mediaElem) {\n    if (!CiderAudio.context) {\n      CiderAudio.context = new window.AudioContext({\n        sampleRate: 96000,\n        latencyHint: \"playback\",\n      }); // Don't ever remove the sample rate arg. Ask Maikiwi.\n      app.lyricOffset = CiderAudio.context.baseLatency + (CiderAudio.context.outputLatency ? CiderAudio.context.outputLatency : 0);\n    }\n    if (!CiderAudio.source) {\n      CiderAudio.source = CiderAudio.context.createMediaElementSource(mediaElem);\n    } else {\n      try {\n        CiderAudio.source.disconnect(CiderAudio.context.destination);\n      } catch (e) {}\n    }\n    CiderAudio.audioNodes.gainNode = CiderAudio.context.createGain();\n    CiderAudio.audioNodes.intelliGainComp = CiderAudio.context.createGain();\n    CiderAudio.source.connect(CiderAudio.audioNodes.intelliGainComp);\n    CiderAudio.audioNodes.intelliGainComp.connect(CiderAudio.audioNodes.gainNode);\n    if (app.cfg.audio.normalization) {\n      CiderAudio.normalizerOn();\n    }\n    CiderAudio.hierarchical_loading();\n  },\n  normalizerOn: function () {\n    try {\n      let previewURL = null;\n      try {\n        previewURL = app.mk.nowPlayingItem.previewURL;\n      } catch (e) {}\n      if (previewURL == null && (app.mk.nowPlayingItem?._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? app.mk.nowPlayingItem.relationships.catalog.data[0].id) != -1) {\n        app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/songs/${app.mk.nowPlayingItem?._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? app.mk.nowPlayingItem.relationships.catalog.data[0].id}`).then((response) => {\n          previewURL = response.data.data[0].attributes.previews[0].url;\n          if (previewURL) ipcRenderer.send(\"getPreviewURL\", previewURL);\n        });\n      } else {\n        if (previewURL) ipcRenderer.send(\"getPreviewURL\", previewURL);\n      }\n    } catch (e) {\n      console.debug(\"[Cider][MaikiwiSoundCheck] normalizer func err: \" + e);\n    }\n  },\n  normalizerOff: function () {\n    CiderAudio.audioNodes.gainNode.gain.exponentialRampToValueAtTime(1.0, CiderAudio.context.currentTime + 0.5);\n  },\n  spatialProfiles: [\n    {\n      id: \"maikiwi\",\n      file: \"./cideraudio/impulses/CiderSpatial_Maikiwi.wav\",\n      name: \"Maikiwi\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"maikiwiplus\",\n      file: \"./cideraudio/impulses/CiderSpatial_MaikiwiPlus.wav\",\n      name: \"Maikiwi+\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"71_420maikiwi\",\n      file: \"./cideraudio/impulses/CiderSpatial_v71.420_Maikiwi.wav\",\n      name: \"Soundstage\",\n      description: \"\",\n      gainComp: \"1.3963683610559376\",\n    },\n    {\n      id: \"70_422maikiwi\",\n      file: \"./cideraudio/impulses/CiderSpatial_v70.422_Maikiwi.wav\",\n      name: \"Separation\",\n      description: \"\",\n      gainComp: \"1.30767553892022\",\n    },\n    {\n      id: \"standard\",\n      file: \"./cideraudio/impulses/CiderSpatial_Natural.wav\",\n      name: \"Minimal\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"standardplus\",\n      file: \"./cideraudio/impulses/CiderSpatial_Natural+.wav\",\n      name: \"Minimal+\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"diffused\",\n      file: \"./cideraudio/impulses/CiderSpatial_Diffuse.wav\",\n      name: \"Diffused\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"BPLK\",\n      file: \"./cideraudio/impulses/CiderSpatial_BPLK.wav\",\n      name: \"BPLK\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"HW2K\",\n      file: \"./cideraudio/impulses/CiderSpatial_HW2K.wav\",\n      name: \"HW2K\",\n      description: \"\",\n      gainComp: \"1.044\",\n    },\n    {\n      id: \"live\",\n      file: \"./cideraudio/impulses/CiderSpatial_LIVE_2.wav\",\n      name: \"live\",\n      description: \"\",\n      gainComp: \"1.2647363474711515\",\n    },\n  ],\n  atmosphereRealizerProfiles: [\n    {\n      id: \"NATURAL_STANDARD\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_NaturalStandard.wav\",\n      name: \"ほうじ茶チーズクリーマティー\",\n      description: \"\",\n    },\n    {\n      id: \"NATURAL_PLUS\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Natural+.wav\",\n      name: \"玄米茶タピオカミルクティー\",\n      description: \"\",\n    },\n    {\n      id: \"E68_1\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_E68_1.5.wav\",\n      name: \"岩塩クリームチーズティー\",\n      description: \"Light\",\n    },\n    {\n      id: \"E68_2\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_E68_2.2.wav\",\n      name: \"抹茶ミルクティー\",\n      description: \"Dark\",\n    },\n    {\n      id: \"BSCBM\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_BSCBM.wav\",\n      name: \"BSCBM\",\n      description: \"BSCBM\",\n    },\n    {\n      id: \"CUDDLE\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Cuddle.wav\",\n      name: \"CUDDLE\",\n      description: \"CUDDLE\",\n    },\n    {\n      id: \"E168_1\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_E168_1.2.wav\",\n      name: \"春毫ジャスミンマキアート\",\n      description: \"Natural Air\",\n    },\n    {\n      id: \"Z3600\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z3600.wav\",\n      name: \"ロイヤルミルクティー\",\n      description: \"3600\",\n    },\n    {\n      id: \"Z8500A\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z8500_A.wav\",\n      name: \"ムーンライトソフトケーキ\",\n      description: \"8500\",\n    },\n    {\n      id: \"Z8500B\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z8500_B.wav\",\n      name: \"Clafoutis aux Cerises\",\n      description: \"8500\",\n    },\n    {\n      id: \"Z8500C\",\n      file: \"./cideraudio/impulses/AtmosphereRealizer_Z8500_C.wav\",\n      name: \"宇治抹茶だいふく\",\n      description: \"8500\",\n    },\n  ],\n  opportunisticCorrectionProfiles: [\n    {\n      id: \"CHU\",\n      file: \"./cideraudio/impulses/MoondropCHU_Cider.wav\",\n      name: \"Moondrop CHU Specific\",\n      description: \"\",\n    },\n  ],\n  cloudProcessor_ninf: function () {\n    CiderAudio.audioNodes.cloudProcessor = null;\n    CiderAudio.audioNodes.cloudProcessor = CiderAudio.context.createConvolver();\n    CiderAudio.audioNodes.cloudProcessor.normalize = false;\n\n    // Always destination\n    CiderAudio.audioNodes.spatialNode.connect(CiderAudio.context.destination);\n  },\n  spatialOff: function () {\n    CiderAudio.hierarchical_loading();\n  },\n  intelliGainComp_n0_0: function () {\n    let filters = [];\n    const precisionHz = 12;\n    // Biquad calculation\n    if (CiderAudio.audioNodes.audioBands !== null) {\n      filters = filters.concat(CiderAudio.audioNodes.audioBands);\n    }\n    if (CiderAudio.audioNodes.vibrantbassNode !== null) {\n      filters = filters.concat(CiderAudio.audioNodes.vibrantbassNode);\n    }\n\n    if (!filters || filters.length === 0) {\n      let filterlessGain = 1;\n\n      CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(1.0, CiderAudio.context.currentTime + 0.3);\n      console.debug(`[Cider][Audio] IntelliGainComp: 0 dB (1.0)`);\n      return;\n    }\n\n    filters.shift();\n    let steps = Math.ceil(96000 / precisionHz);\n    // Generate input array for getFrequencyResponse method\n    let frequencies = new Float32Array(steps);\n    for (let i = 0; i < steps; i++) {\n      frequencies[i] = (i + 1) * precisionHz;\n    }\n    // Here we will store combined amplitude response\n    let totalAmplitudeResp = new Float32Array(steps);\n    for (let i = 0; i < steps; i++) {\n      totalAmplitudeResp[i] = 1;\n    }\n    // Temporary container for every filter response\n    let amplitudeResp = new Float32Array(steps),\n      phaseResp = new Float32Array(steps);\n    for (let i = filters.length - 1; i >= 0; i--) {\n      let filter = filters[i];\n      // Get filter response and convolve it with existing response\n      filter.getFrequencyResponse(frequencies, amplitudeResp, phaseResp);\n      for (let j = 0; j < steps; j++) {\n        totalAmplitudeResp[j] *= amplitudeResp[j];\n      }\n    }\n    // Find max gain\n    let maxGain = -120;\n    for (let i = 0; i < steps; i++) {\n      let gain = totalAmplitudeResp[i];\n      if (gain > maxGain) maxGain = gain;\n    }\n\n    maxGain = Math.pow(10, (-1 * (20 * Math.log10(maxGain))) / 20).toFixed(4);\n    maxGain > 1.0 ? CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(1.0, CiderAudio.context.currentTime + 0.3) : CiderAudio.audioNodes.intelliGainComp.gain.exponentialRampToValueAtTime(maxGain, CiderAudio.context.currentTime + 0.3);\n    console.debug(`[Cider][Audio] IntelliGainComp: ${maxGain > 1.0 ? 0 : (20 * Math.log10(maxGain)).toFixed(2)} dB (${maxGain > 1.0 ? 1 : maxGain})`);\n  },\n  sendAudio: function () {\n    if (!CiderAudio.ccON) {\n      CiderAudio.ccON = true;\n      let searchInt = setInterval(async function () {\n        if (CiderAudio.context != null && CiderAudio.audioNodes.intelliGainComp != null) {\n          // var options = {\n          //     mimeType: 'audio/webm; codecs=opus'\n          // };\n          // var destnode = CiderAudio.context.createMediaStreamDestination();\n          // CiderAudio.audioNodes.intelliGainComp.connect(CiderAudio.audioNodes.gainNode);\n          //            CiderAudio.audioNodes.gainNode.connect(destnode)\n          // CiderAudio.mediaRecorder = new MediaRecorder(destnode.stream, options);\n          // CiderAudio.mediaRecorder.start(1);\n          // CiderAudio.mediaRecorder.ondataavailable = function (e) {\n          //     e.data.arrayBuffer().then(buffer => {\n          //         ipcRenderer.send('writeAudio', buffer)\n          //     }\n          //     );\n          // }\n          const worklet = `class RecorderWorkletProcessor extends AudioWorkletProcessor {\n                        static get parameterDescriptors() {\n                          return [{\n                            name: 'isRecording',\n                            defaultValue: 0\n                          },\n                          {\n                            name: 'numberOfChannels',\n                            defaultValue: 2\n                          }\n                        ];\n                        }\n\n                        constructor() {\n                          super();\n                          this._bufferSize = 2048;\n                          this._buffers = null;\n                          this._initBuffer();\n                        }\n                        _initBuffers(numberOfChannels) {\n                          this._buffers = [];\n                          for (let channel=0; channel < numberOfChannels; channel++) {\n                            this._buffers.push(new Float32Array(this._bufferSize));\n                          }\n                        }\n\n                        _initBuffer() {\n                          this._bytesWritten = 0;\n                        }\n\n                        _isBufferEmpty() {\n                          return this._bytesWritten === 0;\n                        }\n\n                        _isBufferFull() {\n                          return this._bytesWritten === this._bufferSize;\n                        }\n                        _pushToBuffers(audioRawData, numberOfChannels) {\n                          if (this._isBufferFull()) {\n                              this._flush();\n                          }\n                          let dataLength = audioRawData[0]?.length ?? 0;\n                          for (let idx=0; idx<dataLength; idx++) {\n                            for (let channel=0; channel < numberOfChannels; channel++) {\n                              try {\n                              let value = audioRawData[channel][idx];\n                              this._buffers[channel][this._bytesWritten] = value;} catch(e){}\n                            }\n                            this._bytesWritten += 1;\n                          }\n                        }\n\n                        _flush() {\n                          let buffers = [];\n                          this._buffers.forEach((buffer, channel) => {\n                            if (this._bytesWritten < this._bufferSize) {\n                              buffer = buffer.slice(0, this._bytesWritten);\n                            }\n                            buffers[channel] = buffer;\n                          });\n                          this.port.postMessage({\n                            eventType: 'data',\n                            audioBuffer: buffers,\n                            bufferSize: this._bufferSize\n                          });\n                          this._initBuffer();\n                        }\n\n                        _recordingStopped() {\n                          this.port.postMessage({\n                            eventType: 'stop'\n                          });\n                        }\n\n                        process(inputs, outputs, parameters) {\n                          const isRecordingValues = parameters.isRecording;\n                          const numberOfChannels = parameters.numberOfChannels[0];\n                          if (this._buffers === null) {\n                            this._initBuffers(numberOfChannels);\n                          }\n\n                          for (let dataIndex = 0; dataIndex < isRecordingValues.length; dataIndex++)\n                          {\n                            const shouldRecord = isRecordingValues[dataIndex] === 1;\n                            if (!shouldRecord && !this._isBufferEmpty()) {\n                              this._flush();\n                              this._recordingStopped();\n                            }\n\n                            if (shouldRecord) {\n                              let audioRawData = inputs[0];\n                              this._pushToBuffers(audioRawData, numberOfChannels);\n                            }\n                          }\n                          return true;\n                        }\n\n                      }\n\n                      registerProcessor('recorder-worklet', RecorderWorkletProcessor);`;\n          let blob = new Blob([worklet], { type: \"application/javascript\" });\n          await CiderAudio.context.audioWorklet.addModule(URL.createObjectURL(blob)).then(() => {\n            const channels = 2;\n            CiderAudio.audioNodes.recorderNode = new window.AudioWorkletNode(CiderAudio.context, \"recorder-worklet\", {\n              parameterData: { numberOfChannels: channels },\n            });\n            CiderAudio.audioNodes.recorderNode.port.onmessage = (e) => {\n              const data = e.data;\n              switch (data.eventType) {\n                case \"data\":\n                  const audioData = data.audioBuffer;\n                  const bufferSize = data.bufferSize;\n                  if (audioData[0].some((item) => item !== 0) || audioData[0].some((item) => item !== 0)) {\n                    ipcRenderer.send(\"writeWAV\", audioData[0], audioData[1], bufferSize);\n                  }\n                  break;\n                case \"stop\":\n                  break;\n              }\n            };\n            CiderAudio.audioNodes.recorderNode.parameters.get(\"isRecording\").setValueAtTime(1, CiderAudio.context.currentTime);\n            CiderAudio.audioNodes.intelliGainComp.connect(CiderAudio.audioNodes.recorderNode);\n          });\n          clearInterval(searchInt);\n        }\n      }, 1000);\n    } else {\n      if (CiderAudio.audioNodes.recorderNode != null && CiderAudio.context != null) {\n        CiderAudio.audioNodes.recorderNode.parameters.get(\"isRecording\").setValueAtTime(1, CiderAudio.context.currentTime);\n        // CiderAudio.audioNodes.recorderNode = null;\n        // CiderAudio.ccON = false;\n      }\n    }\n  },\n  stopAudio() {\n    if (CiderAudio.audioNodes.recorderNode != null && CiderAudio.context != null) {\n      CiderAudio.audioNodes.recorderNode.parameters.get(\"isRecording\").setValueAtTime(0, CiderAudio.context.currentTime);\n      // CiderAudio.audioNodes.recorderNode = null;\n      // CiderAudio.ccON = false;\n    }\n  },\n  atmosphereRealizer2_n6: function (status, destination) {\n    if (status === true) {\n      CiderAudio.audioNodes.atmosphereRealizer2 = CiderAudio.context.createConvolver();\n      CiderAudio.audioNodes.atmosphereRealizer2.normalize = false;\n      let atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.atmosphereRealizer2_value;\n      });\n\n      if (atmosphereRealizerProfile === undefined) {\n        atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles[0];\n      }\n      fetch(atmosphereRealizerProfile.file).then(async (impulseData) => {\n        let bufferedImpulse = await impulseData.arrayBuffer();\n        CiderAudio.audioNodes.atmosphereRealizer2.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n      });\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer2.connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] atmosphereRealizer2_n6 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  atmosphereRealizer1_n5: function (status, destination) {\n    if (status === true) {\n      CiderAudio.audioNodes.atmosphereRealizer1 = CiderAudio.context.createConvolver();\n      CiderAudio.audioNodes.atmosphereRealizer1.normalize = false;\n      let atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.atmosphereRealizer1_value;\n      });\n\n      if (atmosphereRealizerProfile === undefined) {\n        atmosphereRealizerProfile = CiderAudio.atmosphereRealizerProfiles[0];\n      }\n      fetch(atmosphereRealizerProfile.file).then(async (impulseData) => {\n        let bufferedImpulse = await impulseData.arrayBuffer();\n        CiderAudio.audioNodes.atmosphereRealizer1.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n      });\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.atmosphereRealizer1.connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] atmosphereRealizer1_n5 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  opportunisticCorrection_n2: function (status, destination) {\n    if (status === true) {\n      CiderAudio.audioNodes.opportunisticCorrection = CiderAudio.context.createConvolver();\n      CiderAudio.audioNodes.opportunisticCorrection.normalize = false;\n      let opportunisticCorrectionProfile = CiderAudio.opportunisticCorrectionProfiles.find(function (profile) {\n        return profile.id === app.cfg.audio.maikiwiAudio.opportunisticCorrection_state;\n      });\n\n      if (opportunisticCorrectionProfile === undefined) {\n        opportunisticCorrectionProfile = CiderAudio.opportunisticCorrectionProfiles[0];\n      }\n      fetch(opportunisticCorrectionProfile.file).then(async (impulseData) => {\n        let bufferedImpulse = await impulseData.arrayBuffer();\n        CiderAudio.audioNodes.opportunisticCorrection.buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n      });\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.audioNodes.opportunisticCorrection[0]);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.opportunisticCorrection.connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] opportunisticCorrection_n2 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  llpw_n1: function (status, destination) {\n    if (status === true) {\n      let c_LLPW_Q = [1.25, 0.131, 10, 2.5, 2.293, 0.11, 14.14, 1.552, 28.28, 7.071, 2.847, 5, 0.625, 7.071, 3.856, 3.856, 20, 28.28, 20, 14.14, 2.102, 6.698, 3.536, 10];\n      let c_LLPW_GAIN = [-0.11, 0.27, -0.8, 0.57, 1.84, -0.38, 0.47, -1.56, 0.83, 1.58, -1.79, -0.45, 0.48, 1.22, -1.58, -1.59, -2.03, 2.56, -2.2, -2.48, 4.75, 10.5, 1.43, 3.76];\n      let c_LLPW_FREQUENCIES = [400.83, 5812.8, 8360, 10413, 10658, 12079, 12899, 13205, 14848, 15591, 15778, 15783, 16716, 16891, 17255, 17496, 18555, 18622, 19219, 19448, 19664, 21341, 21353, 22595];\n      let LLPW_Q = [5, 1, 3.536, 1.25, 8.409, 1.25, 14.14, 7.071, 5, 0.625, 16.82, 20, 20, 20, 28.28, 28.28, 28.28, 20, 33.64, 33.64, 10, 28.28, 7.071, 3.856];\n      let LLPW_GAIN = [0.38, -1.81, -0.23, -0.51, 0.4, 0.84, 0.36, -0.34, 0.27, -1.2, -0.42, -0.67, 0.81, 1.31, -0.71, 0.68, -1.04, 0.79, -0.73, -1.33, 1.17, 0.57, 0.35, 6.33];\n      let LLPW_FREQUENCIES = [16.452, 24.636, 37.134, 74.483, 159.54, 308.18, 670.21, 915.81, 1200.7, 2766.4, 2930.6, 4050.6, 4409.1, 5395.2, 5901.6, 6455.5, 7164.1, 7724.1, 8449, 10573, 12368, 14198, 17910, 18916];\n      CiderAudio.audioNodes.llpw = [];\n\n      switch (app.cfg.audio.maikiwiAudio.ciderPPE_value) {\n        case \"MAIKIWI\":\n          try {\n            switch (localStorage.getItem(\"playingBitrate\")) {\n              case \"64\":\n                CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n                CiderAudio.audioNodes.llpw[0].normalize = false;\n                fetch(\"./cideraudio/impulses/CAP_64.wav\").then(async (impulseData) => {\n                  let bufferedImpulse = await impulseData.arrayBuffer();\n                  CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n                });\n                console.debug(\"[Cider][Audio] CAP Adaptive - 64kbps\");\n\n                break;\n              case \"256\":\n                CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n                CiderAudio.audioNodes.llpw[0].normalize = false;\n                CiderAudio.audioNodes.llpw[1] = CiderAudio.context.createGain();\n                CiderAudio.audioNodes.llpw[1].gain.value = 2.37; // Post Gain Compensation\n                CiderAudio.audioNodes.llpw[0].connect(CiderAudio.audioNodes.llpw[1]);\n                fetch(\"./cideraudio/impulses/CAP_256_FINAL_48k.wav\").then(async (impulseData) => {\n                  let bufferedImpulse = await impulseData.arrayBuffer();\n                  CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n                });\n                console.debug(\"[Cider][Audio] CAP Adaptive - 256kbps\");\n\n                break;\n              default:\n                CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createGain();\n                CiderAudio.audioNodes.llpw[0].gain.value = 1;\n                console.debug(\"[Cider][Audio] CAP Disabled (Passthrough) : Non-Lossy Bitrate.\");\n\n                break;\n            }\n          } catch (e) {\n            CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n            CiderAudio.audioNodes.llpw[0].normalize = false;\n            CiderAudio.audioNodes.llpw[1] = CiderAudio.context.createGain();\n            CiderAudio.audioNodes.llpw[1].gain.value = 2.37;\n            CiderAudio.audioNodes.llpw[0].connect(CiderAudio.audioNodes.llpw[1]);\n            fetch(\"./cideraudio/impulses/CAP_256_FINAL_48k.wav\").then(async (impulseData) => {\n              let bufferedImpulse = await impulseData.arrayBuffer();\n              CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n            });\n            console.debug(\"[Cider][Audio] CAP Adaptive - (Error Fallback) 256kbps\");\n          }\n\n          break;\n        case \"MAIKIWI_LEGACY\":\n          CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n          CiderAudio.audioNodes.llpw[0].normalize = false;\n          fetch(\"./cideraudio/impulses/CAP_Maikiwi.wav\").then(async (impulseData) => {\n            let bufferedImpulse = await impulseData.arrayBuffer();\n            CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n          });\n          console.debug(\"[Cider][Audio] CAP - Maikiwi Signature Mode\");\n          break;\n        case \"NATURAL\":\n          CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n          CiderAudio.audioNodes.llpw[0].normalize = false;\n          fetch(\"./cideraudio/impulses/CAP_Natural.wav\").then(async (impulseData) => {\n            let bufferedImpulse = await impulseData.arrayBuffer();\n            CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n          });\n\n          console.debug(\"[Cider][Audio] CAP - Natural Mode\");\n          break;\n\n        case \"LEGACY\":\n          for (let i = 0; i < LLPW_FREQUENCIES.length; i++) {\n            CiderAudio.audioNodes.llpw[i] = CiderAudio.context.createBiquadFilter();\n            CiderAudio.audioNodes.llpw[i].type = \"peaking\"; // 'peaking';\n            CiderAudio.audioNodes.llpw[i].frequency.value = LLPW_FREQUENCIES[i];\n            CiderAudio.audioNodes.llpw[i].Q.value = LLPW_Q[i];\n            CiderAudio.audioNodes.llpw[i].gain.value = LLPW_GAIN[i];\n          }\n          for (let i = 1; i < LLPW_FREQUENCIES.length; i++) {\n            CiderAudio.audioNodes.llpw[i - 1].connect(CiderAudio.audioNodes.llpw[i]);\n          }\n          console.debug(\"[Cider][Audio] CAP - Legacy Mode\");\n\n          break;\n\n        default:\n          CiderAudio.audioNodes.llpw[0] = CiderAudio.context.createConvolver();\n          CiderAudio.audioNodes.llpw[0].normalize = false;\n          CiderAudio.audioNodes.llpw[1] = CiderAudio.context.createGain();\n          CiderAudio.audioNodes.llpw[1].gain.value = 2.57;\n          CiderAudio.audioNodes.llpw[0].connect(CiderAudio.audioNodes.llpw[1]);\n          fetch(\"./cideraudio/impulses/CAP_256_FINAL_48k.wav\").then(async (impulseData) => {\n            let bufferedImpulse = await impulseData.arrayBuffer();\n            CiderAudio.audioNodes.llpw[0].buffer = await CiderAudio.context.decodeAudioData(bufferedImpulse);\n          });\n          app.cfg.audio.maikiwiAudio.ciderPPE_value = \"MAIKIWI\";\n\n          console.debug(\"[Cider][Audio] CAP - Maikiwi Adaptive Mode (Defaulted from broki config)\");\n          break;\n      }\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] llpw_n1 -> Spatial\");\n          } catch (e) {}\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] llpw_n1 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] llpw_n1 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] llpw_n1 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] llpw_n1 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] llpw_n1 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] llpw_n1 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.llpw[CiderAudio.audioNodes.llpw.length - 1].connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] llpw_n1 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  vibrantbass_n4: function (status, destination) {\n    if (status === true) {\n      let VIBRANTBASSBANDS = app.cfg.audio.maikiwiAudio.vibrantBass.frequencies;\n      let VIBRANTBASSGAIN = app.cfg.audio.maikiwiAudio.vibrantBass.gain;\n      let VIBRANTBASSQ = app.cfg.audio.maikiwiAudio.vibrantBass.Q;\n      CiderAudio.audioNodes.vibrantbassNode = [];\n\n      for (let i = 0; i < VIBRANTBASSBANDS.length; i++) {\n        CiderAudio.audioNodes.vibrantbassNode[i] = CiderAudio.context.createBiquadFilter();\n        CiderAudio.audioNodes.vibrantbassNode[i].type = \"peaking\"; // 'peaking';\n        CiderAudio.audioNodes.vibrantbassNode[i].frequency.value = VIBRANTBASSBANDS[i];\n        CiderAudio.audioNodes.vibrantbassNode[i].Q.value = VIBRANTBASSQ[i];\n        CiderAudio.audioNodes.vibrantbassNode[i].gain.value = VIBRANTBASSGAIN[i] * (app.cfg.audio.equalizer.vibrantBass / 10);\n      }\n\n      for (let i = 1; i < VIBRANTBASSBANDS.length; i++) {\n        CiderAudio.audioNodes.vibrantbassNode[i - 1].connect(CiderAudio.audioNodes.vibrantbassNode[i]);\n      }\n\n      switch (destination) {\n        case \"spatial\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.spatialNode);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> Spatial\");\n          } catch (e) {}\n          break;\n\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.vibrantbassNode[CiderAudio.audioNodes.vibrantbassNode.length - 1].connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] vibrantbass_n4 -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n  hierarchical_unloading: function () {\n    try {\n      CiderAudio.audioNodes.spatialNode.disconnect();\n      CiderAudio.audioNodes.spatialNode = null;\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.gainNode.disconnect();\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.atmosphereRealizer2.disconnect();\n      CiderAudio.audioNodes.atmosphereRealizer2 = null;\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.atmosphereRealizer1.disconnect();\n      CiderAudio.audioNodes.atmosphereRealizer1 = null;\n    } catch (e) {}\n    try {\n      for (var i of CiderAudio.audioNodes.llpw) {\n        i.disconnect();\n      }\n      CiderAudio.audioNodes.llpw = null;\n    } catch (e) {}\n    try {\n      for (var i of CiderAudio.audioNodes.vibrantbassNode) {\n        i.disconnect();\n      }\n      CiderAudio.audioNodes.vibrantbassNode = null;\n    } catch (e) {}\n    try {\n      for (var i of CiderAudio.audioNodes.audioBands) {\n        i.disconnect();\n      }\n      CiderAudio.audioNodes.vibrantbassNode = null;\n    } catch (e) {}\n    try {\n      CiderAudio.audioNodes.opportunisticCorrection.disconnect();\n      CiderAudio.audioNodes.opportunisticCorrection = null;\n    } catch (e) {}\n    console.debug(\"[Cider][Audio] Finished hierarchical unloading\");\n  },\n  hierarchical_loading: async function () {\n    const configMap = new Map([\n      [\"spatial\", app.cfg.audio.maikiwiAudio.spatial === true],\n      [\"n6\", app.cfg.audio.maikiwiAudio.atmosphereRealizer2 === true],\n      [\"n5\", app.cfg.audio.maikiwiAudio.atmosphereRealizer1 === true],\n      [\"n4\", app.cfg.audio.equalizer.vibrantBass != 0],\n      [\"n3\", Math.max(...app.cfg.audio.equalizer.gain) != 0],\n      [\"n2\", app.cfg.audio.maikiwiAudio.opportunisticCorrection_state !== \"OFF\"],\n      [\"n1\", app.cfg.audio.maikiwiAudio.ciderPPE === true],\n    ]);\n\n    CiderAudio.hierarchical_unloading();\n    let lastNode = \"n0\";\n    let index = 0;\n    let firstNode = \"n0\";\n    for (let [tier, value] of configMap.entries()) {\n      if (value === true) {\n        if (index === 0) {\n          firstNode = tier;\n        }\n        index++;\n        switch (tier) {\n          case \"spatial\":\n            CiderAudio.spatial_ninf();\n            lastNode = \"spatial\";\n            break;\n          case \"n6\":\n            app.cfg.audio.normalization = true;\n            CiderAudio.atmosphereRealizer2_n6(true, lastNode);\n            lastNode = \"n6\";\n            break;\n          case \"n5\":\n            app.cfg.audio.normalization = true;\n            CiderAudio.atmosphereRealizer1_n5(true, lastNode);\n            lastNode = \"n5\";\n            break;\n          case \"n4\":\n            CiderAudio.vibrantbass_n4(true, lastNode);\n            lastNode = \"n4\";\n            break;\n          case \"n3\":\n            CiderAudio.equalizer(true, lastNode);\n            lastNode = \"n3\";\n            break;\n          case \"n2\":\n            CiderAudio.opportunisticCorrection_n2(true, lastNode);\n            lastNode = \"n2\";\n            break;\n          case \"n1\":\n            app.cfg.audio.normalization = true;\n            CiderAudio.llpw_n1(true, lastNode);\n            lastNode = \"n1\";\n            break;\n        }\n      }\n    }\n\n    app.cfg.audio.maikiwiAudio.lastNode = lastNode;\n    app.cfg.audio.maikiwiAudio.firstNode = firstNode; // Sync last node & first\n\n    switch (lastNode) {\n      case \"spatial\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.spatialNode);\n        console.debug(\"[Cider][Audio] gainNode -> Spatial\");\n        break;\n      case \"n6\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.atmosphereRealizer2);\n        console.debug(\"[Cider][Audio] gainNode -> atmosphereRealizer2\");\n        break;\n      case \"n5\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.atmosphereRealizer1);\n        console.debug(\"[Cider][Audio] gainNode -> atmosphereRealizer1\");\n        break;\n      case \"n4\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n        console.debug(\"[Cider][Audio] gainNode -> vibrantbass\");\n        break;\n      case \"n3\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.audioBands[0]);\n        console.debug(\"[Cider][Audio] gainNode -> audioBands\");\n\n        break;\n      case \"n2\":\n        try {\n          CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.opportunisticCorrection);\n          console.debug(\"[Cider][Audio] gainNode -> opportunisticCorrection\");\n        } catch (e) {}\n        break;\n      case \"n1\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.audioNodes.llpw[0]);\n        console.debug(\"[Cider][Audio] gainNode -> llpw\");\n        break;\n      case \"n0\":\n        CiderAudio.audioNodes.gainNode.connect(CiderAudio.context.destination);\n        console.debug(\"[Cider][Audio] gainNode -> destination\");\n        break;\n    }\n\n    console.debug(\"[Cider][Audio]\\n\" + [...configMap.entries()] + \"\\n lastNode: \" + lastNode);\n\n    CiderAudio.intelliGainComp_n0_0();\n    console.debug(\"[Cider][Audio] Finished hierarchical loading\");\n  },\n\n  equalizer: function (status, destination) {\n    // n3_1\n    if (status === true) {\n      let BANDS = app.cfg.audio.equalizer.frequencies;\n      let GAIN = app.cfg.audio.equalizer.gain;\n      let Q = app.cfg.audio.equalizer.Q;\n\n      CiderAudio.audioNodes.audioBands = [];\n      for (let i = 0; i < BANDS.length; i++) {\n        CiderAudio.audioNodes.audioBands[i] = CiderAudio.context.createBiquadFilter();\n        CiderAudio.audioNodes.audioBands[i].type = \"peaking\"; // 'peaking';\n        CiderAudio.audioNodes.audioBands[i].frequency.value = BANDS[i];\n        CiderAudio.audioNodes.audioBands[i].Q.value = Q[i];\n        CiderAudio.audioNodes.audioBands[i].gain.value = GAIN[i] * app.cfg.audio.equalizer.mix;\n      }\n\n      for (let i = 1; i < BANDS.length; i++) {\n        CiderAudio.audioNodes.audioBands[i - 1].connect(CiderAudio.audioNodes.audioBands[i]);\n      }\n\n      switch (destination) {\n        case \"spatial\":\n          CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.spatialNode);\n          console.debug(\"[Cider][Audio] Equalizer -> Spatial\");\n          break;\n        case \"n6\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer2);\n            console.debug(\"[Cider][Audio] Equalizer -> atmosphereRealizer2\");\n          } catch (e) {}\n          break;\n        case \"n5\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.atmosphereRealizer1);\n            console.debug(\"[Cider][Audio] Equalizer -> atmosphereRealizer1\");\n          } catch (e) {}\n          break;\n        case \"n4\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.vibrantbassNode[0]);\n            console.debug(\"[Cider][Audio] Equalizer -> vibrantbassNode\");\n          } catch (e) {}\n          break;\n        case \"n3\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.audioBands[0]);\n            console.debug(\"[Cider][Audio] Equalizer -> audioBands\");\n          } catch (e) {}\n          break;\n        case \"n2\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.opportunisticCorrection);\n            console.debug(\"[Cider][Audio] Equalizer -> opportunisticCorrection\");\n          } catch (e) {}\n          break;\n        case \"n1\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.audioNodes.llpw[0]);\n            console.debug(\"[Cider][Audio] Equalizer -> llpw\");\n          } catch (e) {}\n          break;\n        case \"n0\":\n          try {\n            CiderAudio.audioNodes.audioBands[CiderAudio.audioNodes.audioBands.length - 1].connect(CiderAudio.context.destination);\n            console.debug(\"[Cider][Audio] Equalizer -> destination\");\n          } catch (e) {}\n          break;\n      }\n    }\n  },\n};\nexport { CiderAudio };\n"
  },
  {
    "path": "src/renderer/hlscider.js",
    "content": "typeof window !== \"undefined\" &&\n  (function webpackUniversalModuleDefinition(root, factory) {\n    if (typeof exports === \"object\" && typeof module === \"object\") module.exports = factory();\n    else if (typeof define === \"function\" && define.amd) define([], factory);\n    else if (typeof exports === \"object\") exports[\"CiderHls\"] = factory();\n    else root[\"CiderHls\"] = factory();\n  })(this, function () {\n    return /******/ (function (modules) {\n      // webpackBootstrap\n      /******/ // The module cache\n      /******/ var installedModules = {};\n      /******/\n      /******/ // The require function\n      /******/ function __webpack_require__(moduleId) {\n        /******/\n        /******/ // Check if module is in cache\n        /******/ if (installedModules[moduleId]) {\n          /******/ return installedModules[moduleId].exports;\n          /******/\n        }\n        /******/ // Create a new module (and put it into the cache)\n        /******/ var module = (installedModules[moduleId] = {\n          /******/ i: moduleId,\n          /******/ l: false,\n          /******/ exports: {},\n          /******/\n        });\n        /******/\n        /******/ // Execute the module function\n        /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n        /******/\n        /******/ // Flag the module as loaded\n        /******/ module.l = true;\n        /******/\n        /******/ // Return the exports of the module\n        /******/ return module.exports;\n        /******/\n      }\n      /******/\n      /******/\n      /******/ // expose the modules object (__webpack_modules__)\n      /******/ __webpack_require__.m = modules;\n      /******/\n      /******/ // expose the module cache\n      /******/ __webpack_require__.c = installedModules;\n      /******/\n      /******/ // define getter function for harmony exports\n      /******/ __webpack_require__.d = function (exports, name, getter) {\n        /******/ if (!__webpack_require__.o(exports, name)) {\n          /******/ Object.defineProperty(exports, name, {\n            enumerable: true,\n            get: getter,\n          });\n          /******/\n        }\n        /******/\n      };\n      /******/\n      /******/ // define __esModule on exports\n      /******/ __webpack_require__.r = function (exports) {\n        /******/ if (typeof Symbol !== \"undefined\" && Symbol.toStringTag) {\n          /******/ Object.defineProperty(exports, Symbol.toStringTag, {\n            value: \"Module\",\n          });\n          /******/\n        }\n        /******/ Object.defineProperty(exports, \"__esModule\", { value: true });\n        /******/\n      };\n      /******/\n      /******/ // create a fake namespace object\n      /******/ // mode & 1: value is a module id, require it\n      /******/ // mode & 2: merge all properties of value into the ns\n      /******/ // mode & 4: return value when already ns object\n      /******/ // mode & 8|1: behave like require\n      /******/ __webpack_require__.t = function (value, mode) {\n        /******/ if (mode & 1) value = __webpack_require__(value);\n        /******/ if (mode & 8) return value;\n        /******/ if (mode & 4 && typeof value === \"object\" && value && value.__esModule) return value;\n        /******/ var ns = Object.create(null);\n        /******/ __webpack_require__.r(ns);\n        /******/ Object.defineProperty(ns, \"default\", {\n          enumerable: true,\n          value: value,\n        });\n        /******/ if (mode & 2 && typeof value != \"string\")\n          for (var key in value)\n            __webpack_require__.d(\n              ns,\n              key,\n              function (key) {\n                return value[key];\n              }.bind(null, key)\n            );\n        /******/ return ns;\n        /******/\n      };\n      /******/\n      /******/ // getDefaultExport function for compatibility with non-harmony modules\n      /******/ __webpack_require__.n = function (module) {\n        /******/ var getter =\n          module && module.__esModule\n            ? /******/ function getDefault() {\n                return module[\"default\"];\n              }\n            : /******/ function getModuleExports() {\n                return module;\n              };\n        /******/ __webpack_require__.d(getter, \"a\", getter);\n        /******/ return getter;\n        /******/\n      };\n      /******/\n      /******/ // Object.prototype.hasOwnProperty.call\n      /******/ __webpack_require__.o = function (object, property) {\n        return Object.prototype.hasOwnProperty.call(object, property);\n      };\n      /******/\n      /******/ // __webpack_public_path__\n      /******/ __webpack_require__.p = \"/dist/\";\n      /******/\n      /******/\n      /******/ // Load entry module and return exports\n      /******/ return __webpack_require__((__webpack_require__.s = \"./src/CiderHls.ts\"));\n      /******/\n    })(\n      /************************************************************************/\n      /******/ {\n        /***/ \"./node_modules/eventemitter3/index.js\":\n          /*!*********************************************!*\\\n  !*** ./node_modules/eventemitter3/index.js ***!\n  \\*********************************************/\n          /*! no static exports found */\n          /***/ function (module, exports, __webpack_require__) {\n            \"use strict\";\n\n            var has = Object.prototype.hasOwnProperty,\n              prefix = \"~\";\n\n            /**\n             * Constructor to create a storage for our `EE` objects.\n             * An `Events` instance is a plain object whose properties are event names.\n             *\n             * @constructor\n             * @private\n             */\n            function Events() {}\n\n            //\n            // We try to not inherit from `Object.prototype`. In some engines creating an\n            // instance in this way is faster than calling `Object.create(null)` directly.\n            // If `Object.create(null)` is not supported we prefix the event names with a\n            // character to make sure that the built-in object properties are not\n            // overridden or used as an attack vector.\n            //\n            if (Object.create) {\n              Events.prototype = Object.create(null);\n\n              //\n              // This hack is needed because the `__proto__` property is still inherited in\n              // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n              //\n              if (!new Events().__proto__) prefix = false;\n            }\n\n            /**\n             * Representation of a single event listener.\n             *\n             * @param {Function} fn The listener function.\n             * @param {*} context The context to invoke the listener with.\n             * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n             * @constructor\n             * @private\n             */\n            function EE(fn, context, once) {\n              this.fn = fn;\n              this.context = context;\n              this.once = once || false;\n            }\n\n            /**\n             * Add a listener for a given event.\n             *\n             * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n             * @param {(String|Symbol)} event The event name.\n             * @param {Function} fn The listener function.\n             * @param {*} context The context to invoke the listener with.\n             * @param {Boolean} once Specify if the listener is a one-time listener.\n             * @returns {EventEmitter}\n             * @private\n             */\n            function addListener(emitter, event, fn, context, once) {\n              if (typeof fn !== \"function\") {\n                throw new TypeError(\"The listener must be a function\");\n              }\n\n              var listener = new EE(fn, context || emitter, once),\n                evt = prefix ? prefix + event : event;\n\n              if (!emitter._events[evt]) (emitter._events[evt] = listener), emitter._eventsCount++;\n              else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n              else emitter._events[evt] = [emitter._events[evt], listener];\n\n              return emitter;\n            }\n\n            /**\n             * Clear event by name.\n             *\n             * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n             * @param {(String|Symbol)} evt The Event name.\n             * @private\n             */\n            function clearEvent(emitter, evt) {\n              if (--emitter._eventsCount === 0) emitter._events = new Events();\n              else delete emitter._events[evt];\n            }\n\n            /**\n             * Minimal `EventEmitter` interface that is molded against the Node.js\n             * `EventEmitter` interface.\n             *\n             * @constructor\n             * @public\n             */\n            function EventEmitter() {\n              this._events = new Events();\n              this._eventsCount = 0;\n            }\n\n            /**\n             * Return an array listing the events for which the emitter has registered\n             * listeners.\n             *\n             * @returns {Array}\n             * @public\n             */\n            EventEmitter.prototype.eventNames = function eventNames() {\n              var names = [],\n                events,\n                name;\n\n              if (this._eventsCount === 0) return names;\n\n              for (name in (events = this._events)) {\n                if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n              }\n\n              if (Object.getOwnPropertySymbols) {\n                return names.concat(Object.getOwnPropertySymbols(events));\n              }\n\n              return names;\n            };\n\n            /**\n             * Return the listeners registered for a given event.\n             *\n             * @param {(String|Symbol)} event The event name.\n             * @returns {Array} The registered listeners.\n             * @public\n             */\n            EventEmitter.prototype.listeners = function listeners(event) {\n              var evt = prefix ? prefix + event : event,\n                handlers = this._events[evt];\n\n              if (!handlers) return [];\n              if (handlers.fn) return [handlers.fn];\n\n              for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n                ee[i] = handlers[i].fn;\n              }\n\n              return ee;\n            };\n\n            /**\n             * Return the number of listeners listening to a given event.\n             *\n             * @param {(String|Symbol)} event The event name.\n             * @returns {Number} The number of listeners.\n             * @public\n             */\n            EventEmitter.prototype.listenerCount = function listenerCount(event) {\n              var evt = prefix ? prefix + event : event,\n                listeners = this._events[evt];\n\n              if (!listeners) return 0;\n              if (listeners.fn) return 1;\n              return listeners.length;\n            };\n\n            /**\n             * Calls each of the listeners registered for a given event.\n             *\n             * @param {(String|Symbol)} event The event name.\n             * @returns {Boolean} `true` if the event had listeners, else `false`.\n             * @public\n             */\n            EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n              var evt = prefix ? prefix + event : event;\n\n              if (!this._events[evt]) return false;\n\n              var listeners = this._events[evt],\n                len = arguments.length,\n                args,\n                i;\n\n              if (listeners.fn) {\n                if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n                switch (len) {\n                  case 1:\n                    return listeners.fn.call(listeners.context), true;\n                  case 2:\n                    return listeners.fn.call(listeners.context, a1), true;\n                  case 3:\n                    return listeners.fn.call(listeners.context, a1, a2), true;\n                  case 4:\n                    return listeners.fn.call(listeners.context, a1, a2, a3), true;\n                  case 5:\n                    return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n                  case 6:\n                    return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n                }\n\n                for (i = 1, args = new Array(len - 1); i < len; i++) {\n                  args[i - 1] = arguments[i];\n                }\n\n                listeners.fn.apply(listeners.context, args);\n              } else {\n                var length = listeners.length,\n                  j;\n\n                for (i = 0; i < length; i++) {\n                  if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n                  switch (len) {\n                    case 1:\n                      listeners[i].fn.call(listeners[i].context);\n                      break;\n                    case 2:\n                      listeners[i].fn.call(listeners[i].context, a1);\n                      break;\n                    case 3:\n                      listeners[i].fn.call(listeners[i].context, a1, a2);\n                      break;\n                    case 4:\n                      listeners[i].fn.call(listeners[i].context, a1, a2, a3);\n                      break;\n                    default:\n                      if (!args)\n                        for (j = 1, args = new Array(len - 1); j < len; j++) {\n                          args[j - 1] = arguments[j];\n                        }\n\n                      listeners[i].fn.apply(listeners[i].context, args);\n                  }\n                }\n              }\n\n              return true;\n            };\n\n            /**\n             * Add a listener for a given event.\n             *\n             * @param {(String|Symbol)} event The event name.\n             * @param {Function} fn The listener function.\n             * @param {*} [context=this] The context to invoke the listener with.\n             * @returns {EventEmitter} `this`.\n             * @public\n             */\n            EventEmitter.prototype.on = function on(event, fn, context) {\n              return addListener(this, event, fn, context, false);\n            };\n\n            /**\n             * Add a one-time listener for a given event.\n             *\n             * @param {(String|Symbol)} event The event name.\n             * @param {Function} fn The listener function.\n             * @param {*} [context=this] The context to invoke the listener with.\n             * @returns {EventEmitter} `this`.\n             * @public\n             */\n            EventEmitter.prototype.once = function once(event, fn, context) {\n              return addListener(this, event, fn, context, true);\n            };\n\n            /**\n             * Remove the listeners of a given event.\n             *\n             * @param {(String|Symbol)} event The event name.\n             * @param {Function} fn Only remove the listeners that match this function.\n             * @param {*} context Only remove the listeners that have this context.\n             * @param {Boolean} once Only remove one-time listeners.\n             * @returns {EventEmitter} `this`.\n             * @public\n             */\n            EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n              var evt = prefix ? prefix + event : event;\n\n              if (!this._events[evt]) return this;\n              if (!fn) {\n                clearEvent(this, evt);\n                return this;\n              }\n\n              var listeners = this._events[evt];\n\n              if (listeners.fn) {\n                if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {\n                  clearEvent(this, evt);\n                }\n              } else {\n                for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n                  if (listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context)) {\n                    events.push(listeners[i]);\n                  }\n                }\n\n                //\n                // Reset the array, or remove it completely if we have no more listeners.\n                //\n                if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n                else clearEvent(this, evt);\n              }\n\n              return this;\n            };\n\n            /**\n             * Remove all listeners, or those of the specified event.\n             *\n             * @param {(String|Symbol)} [event] The event name.\n             * @returns {EventEmitter} `this`.\n             * @public\n             */\n            EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n              var evt;\n\n              if (event) {\n                evt = prefix ? prefix + event : event;\n                if (this._events[evt]) clearEvent(this, evt);\n              } else {\n                this._events = new Events();\n                this._eventsCount = 0;\n              }\n\n              return this;\n            };\n\n            //\n            // Alias methods names because people roll like that.\n            //\n            EventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n            EventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n            //\n            // Expose the prefix.\n            //\n            EventEmitter.prefixed = prefix;\n\n            //\n            // Allow `EventEmitter` to be imported as module namespace.\n            //\n            EventEmitter.EventEmitter = EventEmitter;\n\n            //\n            // Expose the module.\n            //\n            if (true) {\n              module.exports = EventEmitter;\n            }\n\n            /***/\n          },\n\n        /***/ \"./node_modules/url-toolkit/src/url-toolkit.js\":\n          /*!*****************************************************!*\\\n  !*** ./node_modules/url-toolkit/src/url-toolkit.js ***!\n  \\*****************************************************/\n          /*! no static exports found */\n          /***/ function (module, exports, __webpack_require__) {\n            // see https://tools.ietf.org/html/rfc1808\n\n            (function (root) {\n              var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/?#]*)?((?:[^\\/?#]*\\/)*[^;?#]*)?(;[^?#]*)?(\\?[^#]*)?(#[^]*)?$/;\n              var FIRST_SEGMENT_REGEX = /^([^\\/?#]*)([^]*)$/;\n              var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n              var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n              var URLToolkit = {\n                // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n                // E.g\n                // With opts.alwaysNormalize = false (default, spec compliant)\n                // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n                // With opts.alwaysNormalize = true (not spec compliant)\n                // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n                buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n                  opts = opts || {};\n                  // remove any remaining space and CRLF\n                  baseURL = baseURL.trim();\n                  relativeURL = relativeURL.trim();\n                  if (!relativeURL) {\n                    // 2a) If the embedded URL is entirely empty, it inherits the\n                    // entire base URL (i.e., is set equal to the base URL)\n                    // and we are done.\n                    if (!opts.alwaysNormalize) {\n                      return baseURL;\n                    }\n                    var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n                    if (!basePartsForNormalise) {\n                      throw new Error(\"Error trying to parse base URL.\");\n                    }\n                    basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);\n                    return URLToolkit.buildURLFromParts(basePartsForNormalise);\n                  }\n                  var relativeParts = URLToolkit.parseURL(relativeURL);\n                  if (!relativeParts) {\n                    throw new Error(\"Error trying to parse relative URL.\");\n                  }\n                  if (relativeParts.scheme) {\n                    // 2b) If the embedded URL starts with a scheme name, it is\n                    // interpreted as an absolute URL and we are done.\n                    if (!opts.alwaysNormalize) {\n                      return relativeURL;\n                    }\n                    relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n                    return URLToolkit.buildURLFromParts(relativeParts);\n                  }\n                  var baseParts = URLToolkit.parseURL(baseURL);\n                  if (!baseParts) {\n                    throw new Error(\"Error trying to parse base URL.\");\n                  }\n                  if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== \"/\") {\n                    // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n                    // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n                    var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n                    baseParts.netLoc = pathParts[1];\n                    baseParts.path = pathParts[2];\n                  }\n                  if (baseParts.netLoc && !baseParts.path) {\n                    baseParts.path = \"/\";\n                  }\n                  var builtParts = {\n                    // 2c) Otherwise, the embedded URL inherits the scheme of\n                    // the base URL.\n                    scheme: baseParts.scheme,\n                    netLoc: relativeParts.netLoc,\n                    path: null,\n                    params: relativeParts.params,\n                    query: relativeParts.query,\n                    fragment: relativeParts.fragment,\n                  };\n                  if (!relativeParts.netLoc) {\n                    // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n                    // Step 7.  Otherwise, the embedded URL inherits the <net_loc>\n                    // (if any) of the base URL.\n                    builtParts.netLoc = baseParts.netLoc;\n                    // 4) If the embedded URL path is preceded by a slash \"/\", the\n                    // path is not relative and we skip to Step 7.\n                    if (relativeParts.path[0] !== \"/\") {\n                      if (!relativeParts.path) {\n                        // 5) If the embedded URL path is empty (and not preceded by a\n                        // slash), then the embedded URL inherits the base URL path\n                        builtParts.path = baseParts.path;\n                        // 5a) if the embedded URL's <params> is non-empty, we skip to\n                        // step 7; otherwise, it inherits the <params> of the base\n                        // URL (if any) and\n                        if (!relativeParts.params) {\n                          builtParts.params = baseParts.params;\n                          // 5b) if the embedded URL's <query> is non-empty, we skip to\n                          // step 7; otherwise, it inherits the <query> of the base\n                          // URL (if any) and we skip to step 7.\n                          if (!relativeParts.query) {\n                            builtParts.query = baseParts.query;\n                          }\n                        }\n                      } else {\n                        // 6) The last segment of the base URL's path (anything\n                        // following the rightmost slash \"/\", or the entire path if no\n                        // slash is present) is removed and the embedded URL's path is\n                        // appended in its place.\n                        var baseURLPath = baseParts.path;\n                        var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf(\"/\") + 1) + relativeParts.path;\n                        builtParts.path = URLToolkit.normalizePath(newPath);\n                      }\n                    }\n                  }\n                  if (builtParts.path === null) {\n                    builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;\n                  }\n                  return URLToolkit.buildURLFromParts(builtParts);\n                },\n                parseURL: function (url) {\n                  var parts = URL_REGEX.exec(url);\n                  if (!parts) {\n                    return null;\n                  }\n                  return {\n                    scheme: parts[1] || \"\",\n                    netLoc: parts[2] || \"\",\n                    path: parts[3] || \"\",\n                    params: parts[4] || \"\",\n                    query: parts[5] || \"\",\n                    fragment: parts[6] || \"\",\n                  };\n                },\n                normalizePath: function (path) {\n                  // The following operations are\n                  // then applied, in order, to the new path:\n                  // 6a) All occurrences of \"./\", where \".\" is a complete path\n                  // segment, are removed.\n                  // 6b) If the path ends with \".\" as a complete path segment,\n                  // that \".\" is removed.\n                  path = path.split(\"\").reverse().join(\"\").replace(SLASH_DOT_REGEX, \"\");\n                  // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n                  // complete path segment not equal to \"..\", are removed.\n                  // Removal of these path segments is performed iteratively,\n                  // removing the leftmost matching pattern on each iteration,\n                  // until no matching pattern remains.\n                  // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n                  // complete path segment not equal to \"..\", that\n                  // \"<segment>/..\" is removed.\n                  while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, \"\")).length) {}\n                  return path.split(\"\").reverse().join(\"\");\n                },\n                buildURLFromParts: function (parts) {\n                  return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;\n                },\n              };\n\n              if (true) module.exports = URLToolkit;\n              else {\n              }\n            })(this);\n\n            /***/\n          },\n\n        /***/ \"./node_modules/webworkify-webpack/index.js\":\n          /*!**************************************************!*\\\n  !*** ./node_modules/webworkify-webpack/index.js ***!\n  \\**************************************************/\n          /*! no static exports found */\n          /***/ function (module, exports, __webpack_require__) {\n            function webpackBootstrapFunc(modules) {\n              /******/ // The module cache\n              /******/ var installedModules = {};\n\n              /******/ // The require function\n              /******/ function __webpack_require__(moduleId) {\n                /******/ // Check if module is in cache\n                /******/ if (installedModules[moduleId]) /******/ return installedModules[moduleId].exports;\n\n                /******/ // Create a new module (and put it into the cache)\n                /******/ var module = (installedModules[moduleId] = {\n                  /******/ i: moduleId,\n                  /******/ l: false,\n                  /******/ exports: {},\n                  /******/\n                });\n\n                /******/ // Execute the module function\n                /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n                /******/ // Flag the module as loaded\n                /******/ module.l = true;\n\n                /******/ // Return the exports of the module\n                /******/ return module.exports;\n                /******/\n              }\n\n              /******/ // expose the modules object (__webpack_modules__)\n              /******/ __webpack_require__.m = modules;\n\n              /******/ // expose the module cache\n              /******/ __webpack_require__.c = installedModules;\n\n              /******/ // identity function for calling harmony imports with the correct context\n              /******/ __webpack_require__.i = function (value) {\n                return value;\n              };\n\n              /******/ // define getter function for harmony exports\n              /******/ __webpack_require__.d = function (exports, name, getter) {\n                /******/ if (!__webpack_require__.o(exports, name)) {\n                  /******/ Object.defineProperty(exports, name, {\n                    /******/ configurable: false,\n                    /******/ enumerable: true,\n                    /******/ get: getter,\n                    /******/\n                  });\n                  /******/\n                }\n                /******/\n              };\n\n              /******/ // define __esModule on exports\n              /******/ __webpack_require__.r = function (exports) {\n                /******/ Object.defineProperty(exports, \"__esModule\", {\n                  value: true,\n                });\n                /******/\n              };\n\n              /******/ // getDefaultExport function for compatibility with non-harmony modules\n              /******/ __webpack_require__.n = function (module) {\n                /******/ var getter =\n                  module && module.__esModule\n                    ? /******/ function getDefault() {\n                        return module[\"default\"];\n                      }\n                    : /******/ function getModuleExports() {\n                        return module;\n                      };\n                /******/ __webpack_require__.d(getter, \"a\", getter);\n                /******/ return getter;\n                /******/\n              };\n\n              /******/ // Object.prototype.hasOwnProperty.call\n              /******/ __webpack_require__.o = function (object, property) {\n                return Object.prototype.hasOwnProperty.call(object, property);\n              };\n\n              /******/ // __webpack_public_path__\n              /******/ __webpack_require__.p = \"/\";\n\n              /******/ // on error function for async loading\n              /******/ __webpack_require__.oe = function (err) {\n                console.error(err);\n                throw err;\n              };\n\n              var f = __webpack_require__((__webpack_require__.s = ENTRY_MODULE));\n              return f.default || f; // try to call default if defined to also support babel esmodule exports\n            }\n\n            var moduleNameReqExp = \"[\\\\.|\\\\-|\\\\+|\\\\w|/|@]+\";\n            var dependencyRegExp = \"\\\\(\\\\s*(/\\\\*.*?\\\\*/)?\\\\s*.*?(\" + moduleNameReqExp + \").*?\\\\)\"; // additional chars when output.pathinfo is true\n\n            // http://stackoverflow.com/a/2593661/130442\n            function quoteRegExp(str) {\n              return (str + \"\").replace(/[.?*+^$[\\]\\\\(){}|-]/g, \"\\\\$&\");\n            }\n\n            function isNumeric(n) {\n              return !isNaN(1 * n); // 1 * n converts integers, integers as string (\"123\"), 1e3 and \"1e3\" to integers and strings to NaN\n            }\n\n            function getModuleDependencies(sources, module, queueName) {\n              var retval = {};\n              retval[queueName] = [];\n\n              var fnString = module.toString();\n              var wrapperSignature = fnString.match(/^function\\s?\\w*\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/);\n              if (!wrapperSignature) return retval;\n              var webpackRequireName = wrapperSignature[1];\n\n              // main bundle deps\n              var re = new RegExp(\"(\\\\\\\\n|\\\\W)\" + quoteRegExp(webpackRequireName) + dependencyRegExp, \"g\");\n              var match;\n              while ((match = re.exec(fnString))) {\n                if (match[3] === \"dll-reference\") continue;\n                retval[queueName].push(match[3]);\n              }\n\n              // dll deps\n              re = new RegExp(\"\\\\(\" + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, \"g\");\n              while ((match = re.exec(fnString))) {\n                if (!sources[match[2]]) {\n                  retval[queueName].push(match[1]);\n                  sources[match[2]] = __webpack_require__(match[1]).m;\n                }\n                retval[match[2]] = retval[match[2]] || [];\n                retval[match[2]].push(match[4]);\n              }\n\n              // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3\n              var keys = Object.keys(retval);\n              for (var i = 0; i < keys.length; i++) {\n                for (var j = 0; j < retval[keys[i]].length; j++) {\n                  if (isNumeric(retval[keys[i]][j])) {\n                    retval[keys[i]][j] = 1 * retval[keys[i]][j];\n                  }\n                }\n              }\n\n              return retval;\n            }\n\n            function hasValuesInQueues(queues) {\n              var keys = Object.keys(queues);\n              return keys.reduce(function (hasValues, key) {\n                return hasValues || queues[key].length > 0;\n              }, false);\n            }\n\n            function getRequiredModules(sources, moduleId) {\n              var modulesQueue = {\n                main: [moduleId],\n              };\n              var requiredModules = {\n                main: [],\n              };\n              var seenModules = {\n                main: {},\n              };\n\n              while (hasValuesInQueues(modulesQueue)) {\n                var queues = Object.keys(modulesQueue);\n                for (var i = 0; i < queues.length; i++) {\n                  var queueName = queues[i];\n                  var queue = modulesQueue[queueName];\n                  var moduleToCheck = queue.pop();\n                  seenModules[queueName] = seenModules[queueName] || {};\n                  if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue;\n                  seenModules[queueName][moduleToCheck] = true;\n                  requiredModules[queueName] = requiredModules[queueName] || [];\n                  requiredModules[queueName].push(moduleToCheck);\n                  var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName);\n                  var newModulesKeys = Object.keys(newModules);\n                  for (var j = 0; j < newModulesKeys.length; j++) {\n                    modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [];\n                    modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]);\n                  }\n                }\n              }\n\n              return requiredModules;\n            }\n\n            module.exports = function (moduleId, options) {\n              options = options || {};\n              var sources = {\n                main: __webpack_require__.m,\n              };\n\n              var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId);\n\n              var src = \"\";\n\n              Object.keys(requiredModules)\n                .filter(function (m) {\n                  return m !== \"main\";\n                })\n                .forEach(function (module) {\n                  var entryModule = 0;\n                  while (requiredModules[module][entryModule]) {\n                    entryModule++;\n                  }\n                  requiredModules[module].push(entryModule);\n                  sources[module][entryModule] = \"(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })\";\n                  src =\n                    src +\n                    \"var \" +\n                    module +\n                    \" = (\" +\n                    webpackBootstrapFunc.toString().replace(\"ENTRY_MODULE\", JSON.stringify(entryModule)) +\n                    \")({\" +\n                    requiredModules[module]\n                      .map(function (id) {\n                        return \"\" + JSON.stringify(id) + \": \" + sources[module][id].toString();\n                      })\n                      .join(\",\") +\n                    \"});\\n\";\n                });\n\n              src =\n                src +\n                \"new ((\" +\n                webpackBootstrapFunc.toString().replace(\"ENTRY_MODULE\", JSON.stringify(moduleId)) +\n                \")({\" +\n                requiredModules.main\n                  .map(function (id) {\n                    return \"\" + JSON.stringify(id) + \": \" + sources.main[id].toString();\n                  })\n                  .join(\",\") +\n                \"}))(self);\";\n\n              var blob = new window.Blob([src], { type: \"text/javascript\" });\n              if (options.bare) {\n                return blob;\n              }\n\n              var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;\n\n              var workerUrl = URL.createObjectURL(blob);\n              var worker = new window.Worker(workerUrl);\n              worker.objectURL = workerUrl;\n\n              return worker;\n            };\n\n            /***/\n          },\n\n        /***/ \"./src/config.ts\":\n          /*!***********************!*\\\n  !*** ./src/config.ts ***!\n  \\***********************/\n          /*! exports provided: CiderHlsDefaultConfig, mergeConfig, enableStreamingMode */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CiderHlsDefaultConfig\", function () {\n              return CiderHlsDefaultConfig;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"mergeConfig\", function () {\n              return mergeConfig;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"enableStreamingMode\", function () {\n              return enableStreamingMode;\n            });\n            /* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ \"./src/controller/abr-controller.ts\");\n            /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ \"./src/controller/audio-stream-controller.ts\");\n            /* harmony import */ var _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/audio-track-controller */ \"./src/controller/audio-track-controller.ts\");\n            /* harmony import */ var _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/subtitle-stream-controller */ \"./src/controller/subtitle-stream-controller.ts\");\n            /* harmony import */ var _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/subtitle-track-controller */ \"./src/controller/subtitle-track-controller.ts\");\n            /* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/buffer-controller */ \"./src/controller/buffer-controller.ts\");\n            /* harmony import */ var _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/timeline-controller */ \"./src/controller/timeline-controller.ts\");\n            /* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/cap-level-controller */ \"./src/controller/cap-level-controller.ts\");\n            /* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./controller/fps-controller */ \"./src/controller/fps-controller.ts\");\n            /* harmony import */ var _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./controller/eme-controller */ \"./src/controller/eme-controller.ts\");\n            /* harmony import */ var _controller_cmcd_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./controller/cmcd-controller */ \"./src/controller/cmcd-controller.ts\");\n            /* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/xhr-loader */ \"./src/utils/xhr-loader.ts\");\n            /* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/fetch-loader */ \"./src/utils/fetch-loader.ts\");\n            /* harmony import */ var _utils_cues__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils/cues */ \"./src/utils/cues.ts\");\n            /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/mediakeys-helper */ \"./src/utils/mediakeys-helper.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./utils/logger */ \"./src/utils/logger.ts\");\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            function ownKeys(object, enumerableOnly) {\n              var keys = Object.keys(object);\n              if (Object.getOwnPropertySymbols) {\n                var symbols = Object.getOwnPropertySymbols(object);\n                if (enumerableOnly) {\n                  symbols = symbols.filter(function (sym) {\n                    return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n                  });\n                }\n                keys.push.apply(keys, symbols);\n              }\n              return keys;\n            }\n\n            function _objectSpread(target) {\n              for (var i = 1; i < arguments.length; i++) {\n                var source = arguments[i] != null ? arguments[i] : {};\n                if (i % 2) {\n                  ownKeys(Object(source), true).forEach(function (key) {\n                    _defineProperty(target, key, source[key]);\n                  });\n                } else if (Object.getOwnPropertyDescriptors) {\n                  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n                } else {\n                  ownKeys(Object(source)).forEach(function (key) {\n                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n                  });\n                }\n              }\n              return target;\n            }\n\n            function _defineProperty(obj, key, value) {\n              if (key in obj) {\n                Object.defineProperty(obj, key, {\n                  value: value,\n                  enumerable: true,\n                  configurable: true,\n                  writable: true,\n                });\n              } else {\n                obj[key] = value;\n              }\n              return obj;\n            }\n\n            // If possible, keep CiderHlsDefaultConfig shallow\n            // It is cloned whenever a new CiderHls instance is created, by keeping the config\n            // shallow the properties are cloned, and we don't end up manipulating the default\n            var CiderHlsDefaultConfig = _objectSpread(\n              _objectSpread(\n                {\n                  autoStartLoad: true,\n                  // used by stream-controller\n                  startPosition: -1,\n                  // used by stream-controller\n                  defaultAudioCodec: undefined,\n                  // used by stream-controller\n                  debug: false,\n                  // used by logger\n                  capLevelOnFPSDrop: false,\n                  // used by fps-controller\n                  capLevelToPlayerSize: false,\n                  // used by cap-level-controller\n                  initialLiveManifestSize: 1,\n                  // used by stream-controller\n                  maxBufferLength: 30,\n                  // used by stream-controller\n                  backBufferLength: Infinity,\n                  // used by buffer-controller\n                  maxBufferSize: 60 * 1000 * 1000,\n                  // used by stream-controller\n                  maxBufferHole: 0.1,\n                  // used by stream-controller\n                  highBufferWatchdogPeriod: 2,\n                  // used by stream-controller\n                  nudgeOffset: 0.1,\n                  // used by stream-controller\n                  nudgeMaxRetry: 3,\n                  // used by stream-controller\n                  maxFragLookUpTolerance: 0.25,\n                  // used by stream-controller\n                  liveSyncDurationCount: 3,\n                  // used by latency-controller\n                  liveMaxLatencyDurationCount: Infinity,\n                  // used by latency-controller\n                  liveSyncDuration: undefined,\n                  // used by latency-controller\n                  liveMaxLatencyDuration: undefined,\n                  // used by latency-controller\n                  maxLiveSyncPlaybackRate: 1,\n                  // used by latency-controller\n                  liveDurationInfinity: false,\n                  // used by buffer-controller\n                  liveBackBufferLength: null,\n                  // used by buffer-controller\n                  maxMaxBufferLength: 600,\n                  // used by stream-controller\n                  enableWorker: true,\n                  // used by demuxer\n                  enableSoftwareAES: true,\n                  // used by decrypter\n                  manifestLoadingTimeOut: 10000,\n                  // used by playlist-loader\n                  manifestLoadingMaxRetry: 1,\n                  // used by playlist-loader\n                  manifestLoadingRetryDelay: 1000,\n                  // used by playlist-loader\n                  manifestLoadingMaxRetryTimeout: 64000,\n                  // used by playlist-loader\n                  startLevel: undefined,\n                  // used by level-controller\n                  levelLoadingTimeOut: 10000,\n                  // used by playlist-loader\n                  levelLoadingMaxRetry: 4,\n                  // used by playlist-loader\n                  levelLoadingRetryDelay: 1000,\n                  // used by playlist-loader\n                  levelLoadingMaxRetryTimeout: 64000,\n                  // used by playlist-loader\n                  fragLoadingTimeOut: 20000,\n                  // used by fragment-loader\n                  fragLoadingMaxRetry: 6,\n                  // used by fragment-loader\n                  fragLoadingRetryDelay: 1000,\n                  // used by fragment-loader\n                  fragLoadingMaxRetryTimeout: 64000,\n                  // used by fragment-loader\n                  startFragPrefetch: false,\n                  // used by stream-controller\n                  fpsDroppedMonitoringPeriod: 5000,\n                  // used by fps-controller\n                  fpsDroppedMonitoringThreshold: 0.2,\n                  // used by fps-controller\n                  appendErrorMaxRetry: 3,\n                  // used by buffer-controller\n                  loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__[\"default\"],\n                  // loader: FetchLoader,\n                  fLoader: undefined,\n                  // used by fragment-loader\n                  pLoader: undefined,\n                  // used by playlist-loader\n                  xhrSetup: undefined,\n                  // used by xhr-loader\n                  licenseXhrSetup: undefined,\n                  // used by eme-controller\n                  licenseResponseCallback: undefined,\n                  // used by eme-controller\n                  abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__[\"default\"],\n                  bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__[\"default\"],\n                  capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__[\"default\"],\n                  fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__[\"default\"],\n                  stretchShortVideoTrack: false,\n                  // used by mp4-remuxer\n                  maxAudioFramesDrift: 1,\n                  // used by mp4-remuxer\n                  forceKeyFrameOnDiscontinuity: true,\n                  // used by ts-demuxer\n                  abrEwmaFastLive: 3,\n                  // used by abr-controller\n                  abrEwmaSlowLive: 9,\n                  // used by abr-controller\n                  abrEwmaFastVoD: 3,\n                  // used by abr-controller\n                  abrEwmaSlowVoD: 9,\n                  // used by abr-controller\n                  abrEwmaDefaultEstimate: 5e5,\n                  // 500 kbps  // used by abr-controller\n                  abrBandWidthFactor: 0.95,\n                  // used by abr-controller\n                  abrBandWidthUpFactor: 0.7,\n                  // used by abr-controller\n                  abrMaxWithRealBitrate: false,\n                  // used by abr-controller\n                  maxStarvationDelay: 4,\n                  // used by abr-controller\n                  maxLoadingDelay: 4,\n                  // used by abr-controller\n                  minAutoBitrate: 0,\n                  // used by CiderHls\n                  emeEnabled: false,\n                  // used by eme-controller\n                  widevineLicenseUrl: undefined,\n                  // used by eme-controller\n                  drmSystemOptions: {},\n                  // used by eme-controller\n                  requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_14__[\"requestMediaKeySystemAccess\"],\n                  // used by eme-controller\n                  testBandwidth: true,\n                  progressive: false,\n                  lowLatencyMode: true,\n                  cmcd: undefined,\n                },\n                timelineConfig()\n              ),\n              {},\n              {\n                subtitleStreamController: true ? _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__[\"SubtitleStreamController\"] : undefined,\n                subtitleTrackController: true ? _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__[\"default\"] : undefined,\n                timelineController: true ? _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__[\"TimelineController\"] : undefined,\n                audioStreamController: true ? _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"default\"] : undefined,\n                audioTrackController: true ? _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__[\"default\"] : undefined,\n                emeController: true ? _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__[\"default\"] : undefined,\n                cmcdController: true ? _controller_cmcd_controller__WEBPACK_IMPORTED_MODULE_10__[\"default\"] : undefined,\n              }\n            );\n\n            function timelineConfig() {\n              return {\n                cueHandler: _utils_cues__WEBPACK_IMPORTED_MODULE_13__[\"default\"],\n                // used by timeline-controller\n                enableCEA708Captions: true,\n                // used by timeline-controller\n                enableWebVTT: true,\n                // used by timeline-controller\n                enableIMSC1: true,\n                // used by timeline-controller\n                captionsTextTrack1Label: \"English\",\n                // used by timeline-controller\n                captionsTextTrack1LanguageCode: \"en\",\n                // used by timeline-controller\n                captionsTextTrack2Label: \"Spanish\",\n                // used by timeline-controller\n                captionsTextTrack2LanguageCode: \"es\",\n                // used by timeline-controller\n                captionsTextTrack3Label: \"Unknown CC\",\n                // used by timeline-controller\n                captionsTextTrack3LanguageCode: \"\",\n                // used by timeline-controller\n                captionsTextTrack4Label: \"Unknown CC\",\n                // used by timeline-controller\n                captionsTextTrack4LanguageCode: \"\",\n                // used by timeline-controller\n                renderTextTracksNatively: true,\n              };\n            }\n\n            function mergeConfig(defaultConfig, userConfig) {\n              if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {\n                throw new Error(\"Illegal CiderHls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration\");\n              }\n\n              if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {\n                throw new Error('Illegal CiderHls.js config: \"liveMaxLatencyDurationCount\" must be greater than \"liveSyncDurationCount\"');\n              }\n\n              if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {\n                throw new Error('Illegal CiderHls.js config: \"liveMaxLatencyDuration\" must be greater than \"liveSyncDuration\"');\n              }\n\n              return _extends({}, defaultConfig, userConfig);\n            }\n            function enableStreamingMode(config) {\n              var currentLoader = config.loader;\n\n              if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__[\"default\"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__[\"default\"]) {\n                // If a developer has configured their own loader, respect that choice\n                _utils_logger__WEBPACK_IMPORTED_MODULE_15__[\"logger\"].log(\"[config]: Custom loader detected, cannot enable progressive streaming\");\n                config.progressive = false;\n              } else {\n                var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__[\"fetchSupported\"])();\n\n                if (canStreamProgressively) {\n                  config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__[\"default\"];\n                  config.progressive = true;\n                  config.enableSoftwareAES = true;\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_15__[\"logger\"].log(\"[config]: Progressive streaming enabled, using FetchLoader\");\n                }\n              }\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/controller/abr-controller.ts\":\n          /*!******************************************!*\\\n  !*** ./src/controller/abr-controller.ts ***!\n  \\******************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ \"./src/utils/ewma-bandwidth-estimator.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            var AbrController = /*#__PURE__*/ (function () {\n              function AbrController(CiderHls) {\n                this.CiderHls = void 0;\n                this.lastLoadedFragLevel = 0;\n                this._nextAutoLevel = -1;\n                this.timer = void 0;\n                this.onCheck = this._abandonRulesCheck.bind(this);\n                this.fragCurrent = null;\n                this.partCurrent = null;\n                this.bitrateTestDelay = 0;\n                this.bwEstimator = void 0;\n                this.CiderHls = CiderHls;\n                var config = CiderHls.config;\n                this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__[\"default\"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);\n                this.registerListeners();\n              }\n\n              var _proto = AbrController.prototype;\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_LOADING, this.onFragLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_LOADING, this.onFragLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners();\n                this.clearTimer(); // @ts-ignore\n\n                this.CiderHls = this.onCheck = null;\n                this.fragCurrent = this.partCurrent = null;\n              };\n\n              _proto.onFragLoading = function onFragLoading(event, data) {\n                var frag = data.frag;\n\n                if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__[\"PlaylistLevelType\"].MAIN) {\n                  if (!this.timer) {\n                    var _data$part;\n\n                    this.fragCurrent = frag;\n                    this.partCurrent = (_data$part = data.part) != null ? _data$part : null;\n                    this.timer = self.setInterval(this.onCheck, 100);\n                  }\n                }\n              };\n\n              _proto.onLevelLoaded = function onLevelLoaded(event, data) {\n                var config = this.CiderHls.config;\n\n                if (data.details.live) {\n                  this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);\n                } else {\n                  this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);\n                }\n              };\n              /*\n      This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load\n      quickly enough to prevent underbuffering\n    */\n\n              _proto._abandonRulesCheck = function _abandonRulesCheck() {\n                var frag = this.fragCurrent,\n                  part = this.partCurrent,\n                  CiderHls = this.CiderHls;\n                var autoLevelEnabled = CiderHls.autoLevelEnabled,\n                  config = CiderHls.config,\n                  media = CiderHls.media;\n\n                if (!frag || !media) {\n                  return;\n                }\n\n                var stats = part ? part.stats : frag.stats;\n                var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return\n\n                if (stats.aborted) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].warn(\"frag loader destroy or aborted, disarm abandonRules\");\n                  this.clearTimer(); // reset forced auto level value so that next level will be selected\n\n                  this._nextAutoLevel = -1;\n                  return;\n                } // This check only runs if we're in ABR mode and actually playing\n\n                if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {\n                  return;\n                }\n\n                var requestDelay = performance.now() - stats.loading.start;\n                var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded\n\n                if (requestDelay <= (500 * duration) / playbackRate) {\n                  return;\n                }\n\n                var levels = CiderHls.levels,\n                  minAutoLevel = CiderHls.minAutoLevel;\n                var level = levels[frag.level];\n                var expectedLen = stats.total || Math.max(stats.loaded, Math.round((duration * level.maxBitrate) / 8));\n                var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : (stats.loaded * 1000) / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment\n\n                var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;\n                var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer\n\n                var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading\n                // the current fragment is greater than the amount of buffer we have left\n\n                if (bufferStarvationDelay >= (2 * duration) / playbackRate || fragLoadedDelay <= bufferStarvationDelay) {\n                  return;\n                }\n\n                var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;\n                var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering\n\n                for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {\n                  // compute time to load next fragment at lower level\n                  // 0.8 : consider only 80% of current bw to be conservative\n                  // 8 = bits per byte (bps/Bps)\n                  var levelNextBitrate = levels[nextLoadLevel].maxBitrate;\n                  fragLevelNextLoadedDelay = (duration * levelNextBitrate) / (8 * 0.8 * loadRate);\n\n                  if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n                    break;\n                  }\n                } // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing\n                // to load the current one\n\n                if (fragLevelNextLoadedDelay >= fragLoadedDelay) {\n                  return;\n                }\n\n                var bwEstimate = this.bwEstimator.getEstimate();\n                _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].warn(\n                  \"Fragment \" +\n                    frag.sn +\n                    (part ? \" part \" + part.index : \"\") +\n                    \" of level \" +\n                    frag.level +\n                    \" is loading too slowly and will cause an underbuffer; aborting and switching to level \" +\n                    nextLoadLevel +\n                    \"\\n      Current BW estimate: \" +\n                    (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : \"Unknown\") +\n                    \" Kb/s\\n      Estimated load time for current fragment: \" +\n                    fragLoadedDelay.toFixed(3) +\n                    \" s\\n      Estimated load time for the next fragment: \" +\n                    fragLevelNextLoadedDelay.toFixed(3) +\n                    \" s\\n      Time to underbuffer: \" +\n                    bufferStarvationDelay.toFixed(3) +\n                    \" s\"\n                );\n                CiderHls.nextLoadLevel = nextLoadLevel;\n                this.bwEstimator.sample(requestDelay, stats.loaded);\n                this.clearTimer();\n\n                if (frag.loader) {\n                  this.fragCurrent = this.partCurrent = null;\n                  frag.loader.abort();\n                }\n\n                CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_LOAD_EMERGENCY_ABORTED, {\n                  frag: frag,\n                  part: part,\n                  stats: stats,\n                });\n              };\n\n              _proto.onFragLoaded = function onFragLoaded(event, _ref) {\n                var frag = _ref.frag,\n                  part = _ref.part;\n\n                if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__[\"PlaylistLevelType\"].MAIN && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(frag.sn)) {\n                  var stats = part ? part.stats : frag.stats;\n                  var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded\n\n                  this.clearTimer(); // store level id after successful fragment load\n\n                  this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected\n\n                  this._nextAutoLevel = -1; // compute level average bitrate\n\n                  if (this.CiderHls.config.abrMaxWithRealBitrate) {\n                    var level = this.CiderHls.levels[frag.level];\n                    var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;\n                    var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;\n                    level.loaded = {\n                      bytes: loadedBytes,\n                      duration: loadedDuration,\n                    };\n                    level.realBitrate = Math.round((8 * loadedBytes) / loadedDuration);\n                  }\n\n                  if (frag.bitrateTest) {\n                    var fragBufferedData = {\n                      stats: stats,\n                      frag: frag,\n                      part: part,\n                      id: frag.type,\n                    };\n                    this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_BUFFERED, fragBufferedData);\n                    frag.bitrateTest = false;\n                  }\n                }\n              };\n\n              _proto.onFragBuffered = function onFragBuffered(event, data) {\n                var frag = data.frag,\n                  part = data.part;\n                var stats = part ? part.stats : frag.stats;\n\n                if (stats.aborted) {\n                  return;\n                } // Only count non-alt-audio frags which were actually buffered in our BW calculations\n\n                if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__[\"PlaylistLevelType\"].MAIN || frag.sn === \"initSegment\") {\n                  return;\n                } // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;\n                // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch\n                // is used. If we used buffering in that case, our BW estimate sample will be very large.\n\n                var processingMs = stats.parsing.end - stats.loading.start;\n                this.bwEstimator.sample(processingMs, stats.loaded);\n                stats.bwEstimate = this.bwEstimator.getEstimate();\n\n                if (frag.bitrateTest) {\n                  this.bitrateTestDelay = processingMs / 1000;\n                } else {\n                  this.bitrateTestDelay = 0;\n                }\n              };\n\n              _proto.onError = function onError(event, data) {\n                // stop timer in case of frag loading error\n                switch (data.details) {\n                  case _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorDetails\"].FRAG_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorDetails\"].FRAG_LOAD_TIMEOUT:\n                    this.clearTimer();\n                    break;\n\n                  default:\n                    break;\n                }\n              };\n\n              _proto.clearTimer = function clearTimer() {\n                self.clearInterval(this.timer);\n                this.timer = undefined;\n              }; // return next auto level\n\n              _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {\n                var fragCurrent = this.fragCurrent,\n                  partCurrent = this.partCurrent,\n                  CiderHls = this.CiderHls;\n                var maxAutoLevel = CiderHls.maxAutoLevel,\n                  config = CiderHls.config,\n                  minAutoLevel = CiderHls.minAutoLevel,\n                  media = CiderHls.media;\n                var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;\n                var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as\n                // if we're playing back at the normal rate.\n\n                var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;\n                var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n\n                var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n\n                var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);\n\n                if (bestLevel >= 0) {\n                  return bestLevel;\n                }\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].trace((bufferStarvationDelay ? \"rebuffering expected\" : \"buffer is empty\") + \", finding optimal quality level\"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n                // if no matching level found, logic will return 0\n\n                var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;\n                var bwFactor = config.abrBandWidthFactor;\n                var bwUpFactor = config.abrBandWidthUpFactor;\n\n                if (!bufferStarvationDelay) {\n                  // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n                  var bitrateTestDelay = this.bitrateTestDelay;\n\n                  if (bitrateTestDelay) {\n                    // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n                    // max video loading delay used in  automatic start level selection :\n                    // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n                    // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n                    // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n                    var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n                    maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].trace(\"bitrate test took \" + Math.round(1000 * bitrateTestDelay) + \"ms, set first fragment max fetchDuration to \" + Math.round(1000 * maxStarvationDelay) + \" ms\"); // don't use conservative factor on bitrate test\n\n                    bwFactor = bwUpFactor = 1;\n                  }\n                }\n\n                bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);\n                return Math.max(bestLevel, 0);\n              };\n\n              _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {\n                var _level$details;\n\n                var fragCurrent = this.fragCurrent,\n                  partCurrent = this.partCurrent,\n                  currentLevel = this.lastLoadedFragLevel;\n                var levels = this.CiderHls.levels;\n                var level = levels[currentLevel];\n                var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);\n                var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;\n                var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;\n\n                for (var i = maxAutoLevel; i >= minAutoLevel; i--) {\n                  var levelInfo = levels[i];\n\n                  if (!levelInfo || (currentCodecSet && levelInfo.codecSet !== currentCodecSet)) {\n                    continue;\n                  }\n\n                  var levelDetails = levelInfo.details;\n                  var avgDuration = (partCurrent ? (levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget) : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;\n                  var adjustedbw = void 0; // follow algorithm captured from stagefright :\n                  // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n                  // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n                  // consider only 80% of the available bandwidth, but if we are switching up,\n                  // be even more conservative (70%) to avoid overestimating and immediately\n                  // switching back.\n\n                  if (i <= currentLevel) {\n                    adjustedbw = bwFactor * currentBw;\n                  } else {\n                    adjustedbw = bwUpFactor * currentBw;\n                  }\n\n                  var bitrate = levels[i].maxBitrate;\n                  var fetchDuration = (bitrate * avgDuration) / adjustedbw;\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].trace(\"level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: \" + i + \"/\" + Math.round(adjustedbw) + \"/\" + bitrate + \"/\" + avgDuration + \"/\" + maxFetchDuration + \"/\" + fetchDuration); // if adjusted bw is greater than level bitrate AND\n\n                  if (\n                    adjustedbw > bitrate && // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n                    // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n                    // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1\n                    (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration)\n                  ) {\n                    // as we are looping from highest to lowest, this will return the best achievable quality level\n                    return i;\n                  }\n                } // not enough time budget even with quality level 0 ... rebuffering might happen\n\n                return -1;\n              };\n\n              _createClass(AbrController, [\n                {\n                  key: \"nextAutoLevel\",\n                  get: function get() {\n                    var forcedAutoLevel = this._nextAutoLevel;\n                    var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value\n\n                    if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n                      return forcedAutoLevel;\n                    } // compute next level using ABR logic\n\n                    var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level\n\n                    if (forcedAutoLevel !== -1) {\n                      nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n                    }\n\n                    return nextABRAutoLevel;\n                  },\n                  set: function set(nextLevel) {\n                    this._nextAutoLevel = nextLevel;\n                  },\n                },\n              ]);\n\n              return AbrController;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = AbrController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/audio-stream-controller.ts\":\n          /*!***************************************************!*\\\n  !*** ./src/controller/audio-stream-controller.ts ***!\n  \\***************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ \"./src/controller/base-stream-controller.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ \"./src/controller/fragment-tracker.ts\");\n            /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/level */ \"./src/types/level.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ \"./src/loader/fragment.ts\");\n            /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/chunk-cache */ \"./src/demux/chunk-cache.ts\");\n            /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../demux/transmuxer-interface */ \"./src/demux/transmuxer-interface.ts\");\n            /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../types/transmuxer */ \"./src/types/transmuxer.ts\");\n            /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ \"./src/controller/fragment-finders.ts\");\n            /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/discontinuities */ \"./src/utils/discontinuities.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            var TICK_INTERVAL = 100; // how often to tick in ms\n\n            var AudioStreamController = /*#__PURE__*/ (function (_BaseStreamController) {\n              _inheritsLoose(AudioStreamController, _BaseStreamController);\n\n              function AudioStreamController(CiderHls, fragmentTracker) {\n                var _this;\n\n                _this = _BaseStreamController.call(this, CiderHls, fragmentTracker, \"[audio-stream-controller]\") || this;\n                _this.videoBuffer = null;\n                _this.videoTrackCC = -1;\n                _this.waitingVideoCC = -1;\n                _this.audioSwitch = false;\n                _this.trackId = -1;\n                _this.waitingData = null;\n                _this.mainDetails = null;\n                _this.bufferFlushed = false;\n\n                _this._registerListeners();\n\n                return _this;\n              }\n\n              var _proto = AudioStreamController.prototype;\n\n              _proto.onHandlerDestroying = function onHandlerDestroying() {\n                this._unregisterListeners();\n\n                this.mainDetails = null;\n              };\n\n              _proto._registerListeners = function _registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, this.onError, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_RESET, this.onBufferReset, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_CREATED, this.onBufferCreated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_FLUSHED, this.onBufferFlushed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].INIT_PTS_FOUND, this.onInitPtsFound, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, this.onError, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_RESET, this.onBufferReset, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_CREATED, this.onBufferCreated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_FLUSHED, this.onBufferFlushed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].INIT_PTS_FOUND, this.onInitPtsFound, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n              }; // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value\n\n              _proto.onInitPtsFound = function onInitPtsFound(event, _ref) {\n                var frag = _ref.frag,\n                  id = _ref.id,\n                  initPTS = _ref.initPTS;\n\n                // Always update the new INIT PTS\n                // Can change due level switch\n                if (id === \"main\") {\n                  var cc = frag.cc;\n                  this.initPTS[frag.cc] = initPTS;\n                  this.log(\"InitPTS for cc: \" + cc + \" found from main: \" + initPTS);\n                  this.videoTrackCC = cc; // If we are waiting, tick immediately to unblock audio fragment transmuxing\n\n                  if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_INIT_PTS) {\n                    this.tick();\n                  }\n                }\n              };\n\n              _proto.startLoad = function startLoad(startPosition) {\n                if (!this.levels) {\n                  this.startPosition = startPosition;\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].STOPPED;\n                  return;\n                }\n\n                var lastCurrentTime = this.lastCurrentTime;\n                this.stopLoad();\n                this.setInterval(TICK_INTERVAL);\n                this.fragLoadError = 0;\n\n                if (lastCurrentTime > 0 && startPosition === -1) {\n                  this.log(\"Override startPosition with lastCurrentTime @\" + lastCurrentTime.toFixed(3));\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                } else {\n                  this.loadedmetadata = false;\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_TRACK;\n                }\n\n                this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n                this.tick();\n              };\n\n              _proto.doTick = function doTick() {\n                switch (this.state) {\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE:\n                    this.doTickIdle();\n                    break;\n\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_TRACK: {\n                    var _levels$trackId;\n\n                    var levels = this.levels,\n                      trackId = this.trackId;\n                    var details = levels === null || levels === void 0 ? void 0 : (_levels$trackId = levels[trackId]) === null || _levels$trackId === void 0 ? void 0 : _levels$trackId.details;\n\n                    if (details) {\n                      if (this.waitForCdnTuneIn(details)) {\n                        break;\n                      }\n\n                      this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_INIT_PTS;\n                    }\n\n                    break;\n                  }\n\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].FRAG_LOADING_WAITING_RETRY: {\n                    var _this$media;\n\n                    var now = performance.now();\n                    var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n\n                    if (!retryDate || now >= retryDate || ((_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking)) {\n                      this.log(\"RetryDate reached, switch back to IDLE state\");\n                      this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                    }\n\n                    break;\n                  }\n\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_INIT_PTS: {\n                    // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n                    var waitingData = this.waitingData;\n\n                    if (waitingData) {\n                      var frag = waitingData.frag,\n                        part = waitingData.part,\n                        cache = waitingData.cache,\n                        complete = waitingData.complete;\n\n                      if (this.initPTS[frag.cc] !== undefined) {\n                        this.waitingData = null;\n                        this.waitingVideoCC = -1;\n                        this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].FRAG_LOADING;\n                        var payload = cache.flush();\n                        var data = {\n                          frag: frag,\n                          part: part,\n                          payload: payload,\n                          networkDetails: null,\n                        };\n\n                        this._handleFragmentLoadProgress(data);\n\n                        if (complete) {\n                          _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data);\n                        }\n                      } else if (this.videoTrackCC !== this.waitingVideoCC) {\n                        // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_14__[\"logger\"].log(\"Waiting fragment cc (\" + frag.cc + \") cancelled because video is at cc \" + this.videoTrackCC);\n                        this.clearWaitingFragment();\n                      } else {\n                        // Drop waiting fragment if an earlier fragment is needed\n                        var pos = this.getLoadPosition();\n                        var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole);\n                        var waitingFragmentAtPosition = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__[\"fragmentWithinToleranceTest\"])(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);\n\n                        if (waitingFragmentAtPosition < 0) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_14__[\"logger\"].log(\"Waiting fragment cc (\" + frag.cc + \") @ \" + frag.start + \" cancelled because another fragment at \" + bufferInfo.end + \" is needed\");\n                          this.clearWaitingFragment();\n                        }\n                      }\n                    } else {\n                      this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                    }\n                  }\n                }\n\n                this.onTickEnd();\n              };\n\n              _proto.clearWaitingFragment = function clearWaitingFragment() {\n                var waitingData = this.waitingData;\n\n                if (waitingData) {\n                  this.fragmentTracker.removeFragment(waitingData.frag);\n                  this.waitingData = null;\n                  this.waitingVideoCC = -1;\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                }\n              };\n\n              _proto.onTickEnd = function onTickEnd() {\n                var media = this.media;\n\n                if (!media || !media.readyState) {\n                  // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n                  return;\n                }\n\n                var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n                var buffered = mediaBuffer.buffered;\n\n                if (!this.loadedmetadata && buffered.length) {\n                  this.loadedmetadata = true;\n                }\n\n                this.lastCurrentTime = media.currentTime;\n              };\n\n              _proto.doTickIdle = function doTickIdle() {\n                var _frag$decryptdata, _frag$decryptdata2;\n\n                var CiderHls = this.CiderHls,\n                  levels = this.levels,\n                  media = this.media,\n                  trackId = this.trackId;\n                var config = CiderHls.config;\n\n                if (!levels || !levels[trackId]) {\n                  return;\n                } // if video not attached AND\n                // start fragment already requested OR start frag prefetch not enabled\n                // exit loop\n                // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n\n                if (!media && (this.startFragRequested || !config.startFragPrefetch)) {\n                  return;\n                }\n\n                var levelInfo = levels[trackId];\n                var trackDetails = levelInfo.details;\n\n                if (!trackDetails || (trackDetails.live && this.levelLastLoaded !== trackId) || this.waitForCdnTuneIn(trackDetails)) {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_TRACK;\n                  return;\n                }\n\n                if (this.bufferFlushed) {\n                  this.bufferFlushed = false;\n                  this.afterBufferFlushed(this.mediaBuffer ? this.mediaBuffer : this.media, _loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO);\n                }\n\n                var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO);\n\n                if (bufferInfo === null) {\n                  return;\n                }\n\n                var bufferLen = bufferInfo.len;\n                var maxBufLen = this.getMaxBufferLength();\n                var audioSwitch = this.audioSwitch; // if buffer length is less than maxBufLen try to load a new fragment\n\n                if (bufferLen >= maxBufLen && !audioSwitch) {\n                  return;\n                }\n\n                if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_EOS, {\n                    type: \"audio\",\n                  });\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].ENDED;\n                  return;\n                }\n\n                var fragments = trackDetails.fragments;\n                var start = fragments[0].start;\n                var targetBufferTime = bufferInfo.end;\n\n                if (audioSwitch) {\n                  var pos = this.getLoadPosition();\n                  targetBufferTime = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n\n                  if (trackDetails.PTSKnown && pos < start) {\n                    // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n                    if (bufferInfo.end > start || bufferInfo.nextStart) {\n                      this.log(\"Alt audio track ahead of main track, seek to start of alt audio track\");\n                      media.currentTime = start + 0.05;\n                    }\n                  }\n                }\n\n                var frag = this.getNextFragment(targetBufferTime, trackDetails);\n\n                if (!frag) {\n                  this.bufferFlushed = true;\n                  return;\n                }\n\n                if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === \"identity\" && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {\n                  this.loadKey(frag, trackDetails);\n                } else {\n                  this.loadFragment(frag, trackDetails, targetBufferTime);\n                }\n              };\n\n              _proto.getMaxBufferLength = function getMaxBufferLength() {\n                var maxConfigBuffer = _BaseStreamController.prototype.getMaxBufferLength.call(this);\n\n                var mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN);\n\n                if (mainBufferInfo === null) {\n                  return maxConfigBuffer;\n                }\n\n                return Math.max(maxConfigBuffer, mainBufferInfo.len);\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                this.videoBuffer = null;\n\n                _BaseStreamController.prototype.onMediaDetaching.call(this);\n              };\n\n              _proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) {\n                var audioTracks = _ref2.audioTracks;\n                this.resetTransmuxer();\n                this.levels = audioTracks.map(function (mediaPlaylist) {\n                  return new _types_level__WEBPACK_IMPORTED_MODULE_5__[\"Level\"](mediaPlaylist);\n                });\n              };\n\n              _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {\n                // if any URL found on new audio track, it is an alternate audio track\n                var altAudio = !!data.url;\n                this.trackId = data.id;\n                var fragCurrent = this.fragCurrent;\n\n                if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {\n                  fragCurrent.loader.abort();\n                }\n\n                this.fragCurrent = null;\n                this.clearWaitingFragment(); // destroy useless transmuxer when switching audio to main\n\n                if (!altAudio) {\n                  this.resetTransmuxer();\n                } else {\n                  // switching to audio track, start timer if not already started\n                  this.setInterval(TICK_INTERVAL);\n                } // should we switch tracks ?\n\n                if (altAudio) {\n                  this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track\n\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                } else {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].STOPPED;\n                }\n\n                this.tick();\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                this.mainDetails = null;\n                this.fragmentTracker.removeAllFragments();\n                this.startPosition = this.lastCurrentTime = 0;\n                this.bufferFlushed = false;\n              };\n\n              _proto.onLevelLoaded = function onLevelLoaded(event, data) {\n                this.mainDetails = data.details;\n              };\n\n              _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {\n                var _track$details;\n\n                var levels = this.levels;\n                var newDetails = data.details,\n                  trackId = data.id;\n\n                if (!levels) {\n                  this.warn(\"Audio tracks were reset while loading level \" + trackId);\n                  return;\n                }\n\n                this.log(\"Track \" + trackId + \" loaded [\" + newDetails.startSN + \",\" + newDetails.endSN + \"],duration:\" + newDetails.totalduration);\n                var track = levels[trackId];\n                var sliding = 0;\n\n                if (newDetails.live || ((_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live)) {\n                  var mainDetails = this.mainDetails;\n\n                  if (!newDetails.fragments[0]) {\n                    newDetails.deltaUpdateFailed = true;\n                  }\n\n                  if (newDetails.deltaUpdateFailed || !mainDetails) {\n                    return;\n                  }\n\n                  if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {\n                    // Make sure our audio rendition is aligned with the \"main\" rendition, using\n                    // pdt as our reference times.\n                    Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__[\"alignMediaPlaylistByPDT\"])(newDetails, mainDetails);\n                    sliding = newDetails.fragments[0].start;\n                  } else {\n                    sliding = this.alignPlaylists(newDetails, track.details);\n                  }\n                }\n\n                track.details = newDetails;\n                this.levelLastLoaded = trackId; // compute start position if we are aligned with the main playlist\n\n                if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n                  this.setStartPosition(track.details, sliding);\n                } // only switch back to IDLE state if we were waiting for track to start downloading a new fragment\n\n                if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                } // trigger handler right now\n\n                this.tick();\n              };\n\n              _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {\n                var _frag$initSegment;\n\n                var frag = data.frag,\n                  part = data.part,\n                  payload = data.payload;\n                var config = this.config,\n                  trackId = this.trackId,\n                  levels = this.levels;\n\n                if (!levels) {\n                  this.warn(\"Audio tracks were reset while fragment load was in progress. Fragment \" + frag.sn + \" of level \" + frag.level + \" will not be buffered\");\n                  return;\n                }\n\n                var track = levels[trackId];\n                console.assert(track, \"Audio track is defined on fragment load progress\");\n                var details = track.details;\n                console.assert(details, \"Audio track details are defined on fragment load progress\");\n                var audioCodec = config.defaultAudioCodec || track.audioCodec || \"mp4a.40.2\";\n                var transmuxer = this.transmuxer;\n\n                if (!transmuxer) {\n                  transmuxer = this.transmuxer = new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__[\"default\"](this.CiderHls, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));\n                } // Check if we have video initPTS\n                // If not we need to wait for it\n\n                var initPTS = this.initPTS[frag.cc];\n                var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;\n\n                if (initPTS !== undefined) {\n                  // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n                  // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n                  var accurateTimeOffset = false; // details.PTSKnown || !details.live;\n\n                  var partIndex = part ? part.index : -1;\n                  var partial = partIndex !== -1;\n                  var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__[\"ChunkMetadata\"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);\n                  transmuxer.push(payload, initSegmentData, audioCodec, \"\", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);\n                } else {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_14__[\"logger\"].log(\"Unknown video PTS for cc \" + frag.cc + \", waiting for video PTS before demuxing audio frag \" + frag.sn + \" of [\" + details.startSN + \" ,\" + details.endSN + \"],track \" + trackId);\n\n                  var _this$waitingData = (this.waitingData = this.waitingData || {\n                      frag: frag,\n                      part: part,\n                      cache: new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__[\"default\"](),\n                      complete: false,\n                    }),\n                    cache = _this$waitingData.cache;\n\n                  cache.push(new Uint8Array(payload));\n                  this.waitingVideoCC = this.videoTrackCC;\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_INIT_PTS;\n                }\n              };\n\n              _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {\n                if (this.waitingData) {\n                  this.waitingData.complete = true;\n                  return;\n                }\n\n                _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData);\n              };\n\n              _proto.onBufferReset = function /* event: Events.BUFFER_RESET */\n              onBufferReset() {\n                // reset reference to sourcebuffers\n                this.mediaBuffer = this.videoBuffer = null;\n                this.loadedmetadata = false;\n              };\n\n              _proto.onBufferCreated = function onBufferCreated(event, data) {\n                var audioTrack = data.tracks.audio;\n\n                if (audioTrack) {\n                  this.mediaBuffer = audioTrack.buffer;\n                }\n\n                if (data.tracks.video) {\n                  this.videoBuffer = data.tracks.video.buffer;\n                }\n              };\n\n              _proto.onFragBuffered = function onFragBuffered(event, data) {\n                var frag = data.frag,\n                  part = data.part;\n\n                if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO) {\n                  return;\n                }\n\n                if (this.fragContextChanged(frag)) {\n                  // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n                  // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer\n                  this.warn(\"Fragment \" + frag.sn + (part ? \" p: \" + part.index : \"\") + \" of level \" + frag.level + \" finished buffering, but was aborted. state: \" + this.state + \", audioSwitch: \" + this.audioSwitch);\n                  return;\n                }\n\n                if (frag.sn !== \"initSegment\") {\n                  this.fragPrevious = frag;\n\n                  if (this.audioSwitch) {\n                    this.audioSwitch = false;\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACK_SWITCHED, {\n                      id: this.trackId,\n                    });\n                  }\n                }\n\n                this.fragBufferedComplete(frag, part);\n              };\n\n              _proto.onError = function onError(event, data) {\n                switch (data.details) {\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].FRAG_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].FRAG_LOAD_TIMEOUT:\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].KEY_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].KEY_LOAD_TIMEOUT:\n                    // TODO: Skip fragments that do not belong to this.fragCurrent audio-group id\n                    this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO, data);\n                    break;\n\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].AUDIO_TRACK_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].AUDIO_TRACK_LOAD_TIMEOUT:\n                    //  when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n                    if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].ERROR && this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].STOPPED) {\n                      // if fatal error, stop processing, otherwise move to IDLE to retry loading\n                      this.state = data.fatal ? _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].ERROR : _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                      this.warn(data.details + \" while loading frag, switching to \" + this.state + \" state\");\n                    }\n\n                    break;\n\n                  case _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].BUFFER_FULL_ERROR:\n                    // if in appending state\n                    if (data.parent === \"audio\" && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSED)) {\n                      var flushBuffer = true;\n                      var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n                      // reduce max buf len if current position is buffered\n\n                      if (bufferedInfo && bufferedInfo.len > 0.5) {\n                        flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);\n                      }\n\n                      if (flushBuffer) {\n                        // current position is not buffered, but browser is still complaining about buffer full error\n                        // this happens on IE/Edge, refer to https://github.com/video-dev/CiderHls.js/pull/708\n                        // in that case flush the whole audio buffer to recover\n                        this.warn(\"Buffer full error also media.currentTime is not buffered, flush audio buffer\");\n                        this.fragCurrent = null;\n\n                        _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, \"audio\");\n                      }\n\n                      this.resetLoadingState();\n                    }\n\n                    break;\n\n                  default:\n                    break;\n                }\n              };\n\n              _proto.onBufferFlushed = function onBufferFlushed(event, _ref3) {\n                var type = _ref3.type;\n\n                if (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO) {\n                  this.bufferFlushed = true;\n                }\n              };\n\n              _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {\n                var _id3$samples;\n\n                var id = \"audio\";\n                var CiderHls = this.CiderHls;\n                var remuxResult = transmuxResult.remuxResult,\n                  chunkMeta = transmuxResult.chunkMeta;\n                var context = this.getCurrentContext(chunkMeta);\n\n                if (!context) {\n                  this.warn(\"The loading context changed while buffering fragment \" + chunkMeta.sn + \" of level \" + chunkMeta.level + \". This chunk will not be buffered.\");\n                  this.resetLiveStartWhenNotLoaded(chunkMeta.level);\n                  return;\n                }\n\n                var frag = context.frag,\n                  part = context.part;\n                var audio = remuxResult.audio,\n                  text = remuxResult.text,\n                  id3 = remuxResult.id3,\n                  initSegment = remuxResult.initSegment; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n                // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n\n                if (this.fragContextChanged(frag)) {\n                  return;\n                }\n\n                this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSING;\n\n                if (this.audioSwitch && audio) {\n                  this.completeAudioSwitch();\n                }\n\n                if (initSegment !== null && initSegment !== void 0 && initSegment.tracks) {\n                  this._bufferInitSegment(initSegment.tracks, frag, chunkMeta);\n\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_PARSING_INIT_SEGMENT, {\n                    frag: frag,\n                    id: id,\n                    tracks: initSegment.tracks,\n                  }); // Only flush audio from old audio tracks when PTS is known on new audio track\n                }\n\n                if (audio) {\n                  var startPTS = audio.startPTS,\n                    endPTS = audio.endPTS,\n                    startDTS = audio.startDTS,\n                    endDTS = audio.endDTS;\n\n                  if (part) {\n                    part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO] = {\n                      startPTS: startPTS,\n                      endPTS: endPTS,\n                      startDTS: startDTS,\n                      endDTS: endDTS,\n                    };\n                  }\n\n                  frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO, startPTS, endPTS, startDTS, endDTS);\n                  this.bufferFragmentData(audio, frag, part, chunkMeta);\n                }\n\n                if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {\n                  var emittedID3 = _extends(\n                    {\n                      frag: frag,\n                      id: id,\n                    },\n                    id3\n                  );\n\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_PARSING_METADATA, emittedID3);\n                }\n\n                if (text) {\n                  var emittedText = _extends(\n                    {\n                      frag: frag,\n                      id: id,\n                    },\n                    text\n                  );\n\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].FRAG_PARSING_USERDATA, emittedText);\n                }\n              };\n\n              _proto._bufferInitSegment = function _bufferInitSegment(tracks, frag, chunkMeta) {\n                if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSING) {\n                  return;\n                } // delete any video track found on audio transmuxer\n\n                if (tracks.video) {\n                  delete tracks.video;\n                } // include levelCodec in audio and video tracks\n\n                var track = tracks.audio;\n\n                if (!track) {\n                  return;\n                }\n\n                track.levelCodec = track.codec;\n                track.id = \"audio\";\n                this.log(\"Init audio buffer, container:\" + track.container + \", codecs[parsed]=[\" + track.codec + \"]\");\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_CODECS, tracks);\n                var initSegment = track.initSegment;\n\n                if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {\n                  var segment = {\n                    type: \"audio\",\n                    frag: frag,\n                    part: null,\n                    chunkMeta: chunkMeta,\n                    parent: frag.type,\n                    data: initSegment,\n                  };\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].BUFFER_APPENDING, segment);\n                } // trigger handler right now\n\n                this.tick();\n              };\n\n              _proto.loadFragment = function loadFragment(frag, trackDetails, targetBufferTime) {\n                // only load if fragment is not loaded or if in audio switch\n                var fragState = this.fragmentTracker.getState(frag);\n                this.fragCurrent = frag; // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n\n                if (this.audioSwitch || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__[\"FragmentState\"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__[\"FragmentState\"].PARTIAL) {\n                  if (frag.sn === \"initSegment\") {\n                    this._loadInitSegment(frag);\n                  } else if (trackDetails.live && !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(this.initPTS[frag.cc])) {\n                    this.log(\"Waiting for video PTS in continuity counter \" + frag.cc + \" of live stream before loading audio fragment \" + frag.sn + \" of level \" + this.trackId);\n                    this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_INIT_PTS;\n                  } else {\n                    this.startFragRequested = true;\n\n                    _BaseStreamController.prototype.loadFragment.call(this, frag, trackDetails, targetBufferTime);\n                  }\n                }\n              };\n\n              _proto.completeAudioSwitch = function completeAudioSwitch() {\n                var CiderHls = this.CiderHls,\n                  media = this.media,\n                  trackId = this.trackId;\n\n                if (media) {\n                  this.log(\"Switching audio track : flushing all audio\");\n\n                  _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, \"audio\");\n                }\n\n                this.audioSwitch = false;\n                CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].AUDIO_TRACK_SWITCHED, {\n                  id: trackId,\n                });\n              };\n\n              return AudioStreamController;\n            })(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"default\"]);\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = AudioStreamController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/audio-track-controller.ts\":\n          /*!**************************************************!*\\\n  !*** ./src/controller/audio-track-controller.ts ***!\n  \\**************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ \"./src/controller/base-playlist-controller.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            var AudioTrackController = /*#__PURE__*/ (function (_BasePlaylistControll) {\n              _inheritsLoose(AudioTrackController, _BasePlaylistControll);\n\n              function AudioTrackController(CiderHls) {\n                var _this;\n\n                _this = _BasePlaylistControll.call(this, CiderHls, \"[audio-track-controller]\") || this;\n                _this.tracks = [];\n                _this.groupId = null;\n                _this.tracksInGroup = [];\n                _this.trackId = -1;\n                _this.trackName = \"\";\n                _this.selectDefaultTrack = true;\n\n                _this.registerListeners();\n\n                return _this;\n              }\n\n              var _proto = AudioTrackController.prototype;\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_SWITCHING, this.onLevelSwitching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_SWITCHING, this.onLevelSwitching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners();\n                this.tracks.length = 0;\n                this.tracksInGroup.length = 0;\n\n                _BasePlaylistControll.prototype.destroy.call(this);\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                this.tracks = [];\n                this.groupId = null;\n                this.tracksInGroup = [];\n                this.trackId = -1;\n                this.trackName = \"\";\n                this.selectDefaultTrack = true;\n              };\n\n              _proto.onManifestParsed = function onManifestParsed(event, data) {\n                this.tracks = data.audioTracks || [];\n              };\n\n              _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {\n                var id = data.id,\n                  details = data.details;\n                var currentTrack = this.tracksInGroup[id];\n\n                if (!currentTrack) {\n                  this.warn(\"Invalid audio track id \" + id);\n                  return;\n                }\n\n                var curDetails = currentTrack.details;\n                currentTrack.details = data.details;\n                this.log(\"audioTrack \" + id + \" loaded [\" + details.startSN + \"-\" + details.endSN + \"]\");\n\n                if (id === this.trackId) {\n                  this.retryCount = 0;\n                  this.playlistLoaded(id, data, curDetails);\n                }\n              };\n\n              _proto.onLevelLoading = function onLevelLoading(event, data) {\n                this.switchLevel(data.level);\n              };\n\n              _proto.onLevelSwitching = function onLevelSwitching(event, data) {\n                this.switchLevel(data.level);\n              };\n\n              _proto.switchLevel = function switchLevel(levelIndex) {\n                var levelInfo = this.CiderHls.levels[levelIndex];\n\n                if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.audioGroupIds)) {\n                  return;\n                }\n\n                var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n\n                if (this.groupId !== audioGroupId) {\n                  this.groupId = audioGroupId;\n                  var audioTracks = this.tracks.filter(function (track) {\n                    return !audioGroupId || track.groupId === audioGroupId;\n                  }); // Disable selectDefaultTrack if there are no default tracks\n\n                  if (\n                    this.selectDefaultTrack &&\n                    !audioTracks.some(function (track) {\n                      return track.default;\n                    })\n                  ) {\n                    this.selectDefaultTrack = false;\n                  }\n\n                  this.tracksInGroup = audioTracks;\n                  var audioTracksUpdated = {\n                    audioTracks: audioTracks,\n                  };\n                  this.log(\"Updating audio tracks, \" + audioTracks.length + ' track(s) found in \"' + audioGroupId + '\" group-id');\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].AUDIO_TRACKS_UPDATED, audioTracksUpdated);\n                  this.selectInitialTrack();\n                }\n              };\n\n              _proto.onError = function onError(event, data) {\n                _BasePlaylistControll.prototype.onError.call(this, event, data);\n\n                if (data.fatal || !data.context) {\n                  return;\n                }\n\n                if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__[\"PlaylistContextType\"].AUDIO_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {\n                  this.retryLoadingOrFail(data);\n                }\n              };\n\n              _proto.setAudioTrack = function setAudioTrack(newId) {\n                var tracks = this.tracksInGroup; // check if level idx is valid\n\n                if (newId < 0 || newId >= tracks.length) {\n                  this.warn(\"Invalid id passed to audio-track controller\");\n                  return;\n                } // stopping live reloading timer if any\n\n                this.clearTimer();\n                var lastTrack = tracks[this.trackId];\n                this.log(\"Now switching to audio-track index \" + newId);\n                var track = tracks[newId];\n                var id = track.id,\n                  _track$groupId = track.groupId,\n                  groupId = _track$groupId === void 0 ? \"\" : _track$groupId,\n                  name = track.name,\n                  type = track.type,\n                  url = track.url;\n                this.trackId = newId;\n                this.trackName = name;\n                this.selectDefaultTrack = false;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].AUDIO_TRACK_SWITCHING, {\n                  id: id,\n                  groupId: groupId,\n                  name: name,\n                  type: type,\n                  url: url,\n                }); // Do not reload track unless live\n\n                if (track.details && !track.details.live) {\n                  return;\n                }\n\n                var CiderHlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);\n                this.loadPlaylist(CiderHlsUrlParameters);\n              };\n\n              _proto.selectInitialTrack = function selectInitialTrack() {\n                var audioTracks = this.tracksInGroup;\n                console.assert(audioTracks.length, \"Initial audio track should be selected when tracks are known\");\n                var currentAudioTrackName = this.trackName;\n                var trackId = this.findTrackId(currentAudioTrackName) || this.findTrackId();\n\n                if (trackId !== -1) {\n                  this.setAudioTrack(trackId);\n                } else {\n                  this.warn(\"No track found for running audio group-ID: \" + this.groupId);\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].AUDIO_TRACK_LOAD_ERROR,\n                    fatal: true,\n                  });\n                }\n              };\n\n              _proto.findTrackId = function findTrackId(name) {\n                var audioTracks = this.tracksInGroup;\n\n                for (var i = 0; i < audioTracks.length; i++) {\n                  var track = audioTracks[i];\n\n                  if (!this.selectDefaultTrack || track.default) {\n                    if (!name || name === track.name) {\n                      return track.id;\n                    }\n                  }\n                }\n\n                return -1;\n              };\n\n              _proto.loadPlaylist = function loadPlaylist(CiderHlsUrlParameters) {\n                var audioTrack = this.tracksInGroup[this.trackId];\n\n                if (this.shouldLoadTrack(audioTrack)) {\n                  var id = audioTrack.id;\n                  var groupId = audioTrack.groupId;\n                  var url = audioTrack.url;\n\n                  if (CiderHlsUrlParameters) {\n                    try {\n                      url = CiderHlsUrlParameters.addDirectives(url);\n                    } catch (error) {\n                      this.warn(\"Could not construct new URL with CiderHls Delivery Directives: \" + error);\n                    }\n                  } // track not retrieved yet, or live playlist we need to (re)load it\n\n                  this.log(\"loading audio-track playlist for id: \" + id);\n                  this.clearTimer();\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].AUDIO_TRACK_LOADING, {\n                    url: url,\n                    id: id,\n                    groupId: groupId,\n                    deliveryDirectives: CiderHlsUrlParameters || null,\n                  });\n                }\n              };\n\n              _createClass(AudioTrackController, [\n                {\n                  key: \"audioTracks\",\n                  get: function get() {\n                    return this.tracksInGroup;\n                  },\n                },\n                {\n                  key: \"audioTrack\",\n                  get: function get() {\n                    return this.trackId;\n                  },\n                  set: function set(newId) {\n                    // If audio track is selected from API then don't choose from the manifest default track\n                    this.selectDefaultTrack = false;\n                    this.setAudioTrack(newId);\n                  },\n                },\n              ]);\n\n              return AudioTrackController;\n            })(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = AudioTrackController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/base-playlist-controller.ts\":\n          /*!****************************************************!*\\\n  !*** ./src/controller/base-playlist-controller.ts ***!\n  \\****************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return BasePlaylistController;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ \"./src/types/level.ts\");\n            /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ \"./src/controller/level-helper.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n\n            var BasePlaylistController = /*#__PURE__*/ (function () {\n              function BasePlaylistController(CiderHls, logPrefix) {\n                this.CiderHls = void 0;\n                this.timer = -1;\n                this.canLoad = false;\n                this.retryCount = 0;\n                this.log = void 0;\n                this.warn = void 0;\n                this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"], logPrefix + \":\");\n                this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"], logPrefix + \":\");\n                this.CiderHls = CiderHls;\n              }\n\n              var _proto = BasePlaylistController.prototype;\n\n              _proto.destroy = function destroy() {\n                this.clearTimer(); // @ts-ignore\n\n                this.CiderHls = this.log = this.warn = null;\n              };\n\n              _proto.onError = function onError(event, data) {\n                if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorTypes\"].NETWORK_ERROR) {\n                  this.clearTimer();\n                }\n              };\n\n              _proto.clearTimer = function clearTimer() {\n                clearTimeout(this.timer);\n                this.timer = -1;\n              };\n\n              _proto.startLoad = function startLoad() {\n                this.canLoad = true;\n                this.retryCount = 0;\n                this.loadPlaylist();\n              };\n\n              _proto.stopLoad = function stopLoad() {\n                this.canLoad = false;\n                this.clearTimer();\n              };\n\n              _proto.switchParams = function switchParams(playlistUri, previous) {\n                var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;\n\n                if (renditionReports) {\n                  for (var i = 0; i < renditionReports.length; i++) {\n                    var attr = renditionReports[i];\n                    var uri = \"\" + attr.URI;\n\n                    if (uri === playlistUri.substr(-uri.length)) {\n                      var msn = parseInt(attr[\"LAST-MSN\"]);\n                      var part = parseInt(attr[\"LAST-PART\"]);\n\n                      if (previous && this.CiderHls.config.lowLatencyMode) {\n                        var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);\n\n                        if (part !== undefined && currentGoal > previous.partTarget) {\n                          part += 1;\n                        }\n                      }\n\n                      if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(msn)) {\n                        return new _types_level__WEBPACK_IMPORTED_MODULE_1__[\"CiderHlsUrlParameters\"](\n                          msn,\n                          Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(part) ? part : undefined,\n                          _types_level__WEBPACK_IMPORTED_MODULE_1__[\"CiderHlsSkip\"].No\n                        );\n                      }\n                    }\n                  }\n                }\n              };\n\n              _proto.loadPlaylist = function loadPlaylist(CiderHlsUrlParameters) {};\n\n              _proto.shouldLoadTrack = function shouldLoadTrack(track) {\n                return this.canLoad && track && !!track.url && (!track.details || track.details.live);\n              };\n\n              _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {\n                var _this = this;\n\n                var details = data.details,\n                  stats = data.stats; // Set last updated date-time\n\n                var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0;\n                details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it\n\n                if (details.live || (previousDetails !== null && previousDetails !== void 0 && previousDetails.live)) {\n                  details.reloaded(previousDetails);\n\n                  if (previousDetails) {\n                    this.log(\"live playlist \" + index + \" \" + (details.advanced ? \"REFRESHED \" + details.lastPartSn + \"-\" + details.lastPartIndex : \"MISSED\"));\n                  } // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments\n\n                  if (previousDetails && details.fragments.length > 0) {\n                    Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__[\"mergeDetails\"])(previousDetails, details);\n                  }\n\n                  if (!this.canLoad || !details.live) {\n                    return;\n                  }\n\n                  var deliveryDirectives;\n                  var msn = undefined;\n                  var part = undefined;\n\n                  if (details.canBlockReload && details.endSN && details.advanced) {\n                    // Load level with LL-CiderHls delivery directives\n                    var lowLatencyMode = this.CiderHls.config.lowLatencyMode;\n                    var lastPartSn = details.lastPartSn;\n                    var endSn = details.endSN;\n                    var lastPartIndex = details.lastPartIndex;\n                    var hasParts = lastPartIndex !== -1;\n                    var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found\n\n                    var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;\n\n                    if (hasParts) {\n                      msn = lastPart ? endSn + 1 : lastPartSn;\n                      part = lastPart ? nextSnStartIndex : lastPartIndex + 1;\n                    } else {\n                      msn = endSn + 1;\n                    } // Low-Latency CDN Tune-in: \"age\" header and time since load indicates we're behind by more than one part\n                    // Update directives to obtain the Playlist that has the estimated additional duration of media\n\n                    var lastAdvanced = details.age;\n                    var cdnAge = lastAdvanced + details.ageHeader;\n                    var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);\n\n                    if (currentGoal > 0) {\n                      if (previousDetails && currentGoal > previousDetails.tuneInGoal) {\n                        // If we attempted to get the next or latest playlist update, but currentGoal increased,\n                        // then we either can't catchup, or the \"age\" header cannot be trusted.\n                        this.warn(\"CDN Tune-in goal increased from: \" + previousDetails.tuneInGoal + \" to: \" + currentGoal + \" with playlist age: \" + details.age);\n                        currentGoal = 0;\n                      } else {\n                        var segments = Math.floor(currentGoal / details.targetduration);\n                        msn += segments;\n\n                        if (part !== undefined) {\n                          var parts = Math.round((currentGoal % details.targetduration) / details.partTarget);\n                          part += parts;\n                        }\n\n                        this.log(\"CDN Tune-in age: \" + details.ageHeader + \"s last advanced \" + lastAdvanced.toFixed(2) + \"s goal: \" + currentGoal + \" skip sn \" + segments + \" to part \" + part);\n                      }\n\n                      details.tuneInGoal = currentGoal;\n                    }\n\n                    deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);\n\n                    if (lowLatencyMode || !lastPart) {\n                      this.loadPlaylist(deliveryDirectives);\n                      return;\n                    }\n                  } else {\n                    deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);\n                  }\n\n                  var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__[\"computeReloadInterval\"])(details, stats);\n\n                  if (msn !== undefined && details.canBlockReload) {\n                    reloadInterval -= details.partTarget || 1;\n                  }\n\n                  this.log(\"reload live playlist \" + index + \" in \" + Math.round(reloadInterval) + \" ms\");\n                  this.timer = self.setTimeout(function () {\n                    return _this.loadPlaylist(deliveryDirectives);\n                  }, reloadInterval);\n                } else {\n                  this.clearTimer();\n                }\n              };\n\n              _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {\n                var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__[\"getSkipValue\"])(details, msn);\n\n                if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {\n                  msn = previousDeliveryDirectives.msn;\n                  part = previousDeliveryDirectives.part;\n                  skip = _types_level__WEBPACK_IMPORTED_MODULE_1__[\"CiderHlsSkip\"].No;\n                }\n\n                return new _types_level__WEBPACK_IMPORTED_MODULE_1__[\"CiderHlsUrlParameters\"](msn, part, skip);\n              };\n\n              _proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {\n                var _this2 = this;\n\n                var config = this.CiderHls.config;\n                var retry = this.retryCount < config.levelLoadingMaxRetry;\n\n                if (retry) {\n                  var _errorEvent$context;\n\n                  this.retryCount++;\n\n                  if (errorEvent.details.indexOf(\"LoadTimeOut\") > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {\n                    // The LL-CiderHls request already timed out so retry immediately\n                    this.warn(\"retry playlist loading #\" + this.retryCount + ' after \"' + errorEvent.details + '\"');\n                    this.loadPlaylist();\n                  } else {\n                    // exponential backoff capped to max retry timeout\n                    var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload\n\n                    this.timer = self.setTimeout(function () {\n                      return _this2.loadPlaylist();\n                    }, delay);\n                    this.warn(\"retry playlist loading #\" + this.retryCount + \" in \" + delay + ' ms after \"' + errorEvent.details + '\"');\n                  }\n                } else {\n                  this.warn('cannot recover from error \"' + errorEvent.details + '\"'); // stopping live reloading timer if any\n\n                  this.clearTimer(); // switch error to fatal\n\n                  errorEvent.fatal = true;\n                }\n\n                return retry;\n              };\n\n              return BasePlaylistController;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/controller/base-stream-controller.ts\":\n          /*!**************************************************!*\\\n  !*** ./src/controller/base-stream-controller.ts ***!\n  \\**************************************************/\n          /*! exports provided: State, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"State\", function () {\n              return State;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return BaseStreamController;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ \"./src/task-loop.ts\");\n            /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ \"./src/controller/fragment-tracker.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ \"./src/types/transmuxer.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ \"./src/utils/discontinuities.ts\");\n            /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ \"./src/controller/fragment-finders.ts\");\n            /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ \"./src/controller/level-helper.ts\");\n            /* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ \"./src/loader/fragment-loader.ts\");\n            /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ \"./src/crypt/decrypter.ts\");\n            /* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ \"./src/utils/time-ranges.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _assertThisInitialized(self) {\n              if (self === void 0) {\n                throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n              }\n              return self;\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            var State = {\n              STOPPED: \"STOPPED\",\n              IDLE: \"IDLE\",\n              KEY_LOADING: \"KEY_LOADING\",\n              FRAG_LOADING: \"FRAG_LOADING\",\n              FRAG_LOADING_WAITING_RETRY: \"FRAG_LOADING_WAITING_RETRY\",\n              WAITING_TRACK: \"WAITING_TRACK\",\n              PARSING: \"PARSING\",\n              PARSED: \"PARSED\",\n              BACKTRACKING: \"BACKTRACKING\",\n              ENDED: \"ENDED\",\n              ERROR: \"ERROR\",\n              WAITING_INIT_PTS: \"WAITING_INIT_PTS\",\n              WAITING_LEVEL: \"WAITING_LEVEL\",\n            };\n\n            var BaseStreamController = /*#__PURE__*/ (function (_TaskLoop) {\n              _inheritsLoose(BaseStreamController, _TaskLoop);\n\n              function BaseStreamController(CiderHls, fragmentTracker, logPrefix) {\n                var _this;\n\n                _this = _TaskLoop.call(this) || this;\n                _this.CiderHls = void 0;\n                _this.fragPrevious = null;\n                _this.fragCurrent = null;\n                _this.fragmentTracker = void 0;\n                _this.transmuxer = null;\n                _this._state = State.STOPPED;\n                _this.media = void 0;\n                _this.mediaBuffer = void 0;\n                _this.config = void 0;\n                _this.bitrateTest = false;\n                _this.lastCurrentTime = 0;\n                _this.nextLoadPosition = 0;\n                _this.startPosition = 0;\n                _this.loadedmetadata = false;\n                _this.fragLoadError = 0;\n                _this.retryDate = 0;\n                _this.levels = null;\n                _this.fragmentLoader = void 0;\n                _this.levelLastLoaded = null;\n                _this.startFragRequested = false;\n                _this.decrypter = void 0;\n                _this.initPTS = [];\n                _this.onvseeking = null;\n                _this.onvended = null;\n                _this.logPrefix = \"\";\n                _this.log = void 0;\n                _this.warn = void 0;\n                _this.logPrefix = logPrefix;\n                _this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__[\"logger\"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__[\"logger\"], logPrefix + \":\");\n                _this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__[\"logger\"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__[\"logger\"], logPrefix + \":\");\n                _this.CiderHls = CiderHls;\n                _this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__[\"default\"](CiderHls.config);\n                _this.fragmentTracker = fragmentTracker;\n                _this.config = CiderHls.config;\n                _this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__[\"default\"](CiderHls, CiderHls.config);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this));\n                return _this;\n              }\n\n              var _proto = BaseStreamController.prototype;\n\n              _proto.doTick = function doTick() {\n                this.onTickEnd();\n              };\n\n              _proto.onTickEnd = function onTickEnd() {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars\n\n              _proto.startLoad = function startLoad(startPosition) {};\n\n              _proto.stopLoad = function stopLoad() {\n                this.fragmentLoader.abort();\n                var frag = this.fragCurrent;\n\n                if (frag) {\n                  this.fragmentTracker.removeFragment(frag);\n                }\n\n                this.resetTransmuxer();\n                this.fragCurrent = null;\n                this.fragPrevious = null;\n                this.clearInterval();\n                this.clearNextTick();\n                this.state = State.STOPPED;\n              };\n\n              _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {\n                var fragCurrent = this.fragCurrent,\n                  fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...\n                // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between\n                // so we should not switch to ENDED in that case, to be able to buffer them\n\n                if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {\n                  var fragState = fragmentTracker.getState(fragCurrent);\n                  return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__[\"FragmentState\"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__[\"FragmentState\"].OK;\n                }\n\n                return false;\n              };\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                var media = (this.media = this.mediaBuffer = data.media);\n                this.onvseeking = this.onMediaSeeking.bind(this);\n                this.onvended = this.onMediaEnded.bind(this);\n                media.addEventListener(\"seeking\", this.onvseeking);\n                media.addEventListener(\"ended\", this.onvended);\n                var config = this.config;\n\n                if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {\n                  this.startLoad(config.startPosition);\n                }\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                var media = this.media;\n\n                if (media !== null && media !== void 0 && media.ended) {\n                  this.log(\"MSE detaching and video ended, reset startPosition\");\n                  this.startPosition = this.lastCurrentTime = 0;\n                } // remove video listeners\n\n                if (media) {\n                  media.removeEventListener(\"seeking\", this.onvseeking);\n                  media.removeEventListener(\"ended\", this.onvended);\n                  this.onvseeking = this.onvended = null;\n                }\n\n                this.media = this.mediaBuffer = null;\n                this.loadedmetadata = false;\n                this.fragmentTracker.removeAllFragments();\n                this.stopLoad();\n              };\n\n              _proto.onMediaSeeking = function onMediaSeeking() {\n                var config = this.config,\n                  fragCurrent = this.fragCurrent,\n                  media = this.media,\n                  mediaBuffer = this.mediaBuffer,\n                  state = this.state;\n                var currentTime = media ? media.currentTime : 0;\n                var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole);\n                this.log(\"media seeking to \" + (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(currentTime) ? currentTime.toFixed(3) : currentTime) + \", state: \" + state);\n\n                if (state === State.ENDED) {\n                  this.resetLoadingState();\n                } else if (fragCurrent && !bufferInfo.len) {\n                  // check if we are seeking to a unbuffered area AND if frag loading is in progress\n                  var tolerance = config.maxFragLookUpTolerance;\n                  var fragStartOffset = fragCurrent.start - tolerance;\n                  var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n                  var pastFragment = currentTime > fragEndOffset; // check if the seek position is past current fragment, and if so abort loading\n\n                  if (currentTime < fragStartOffset || pastFragment) {\n                    if (pastFragment && fragCurrent.loader) {\n                      this.log(\"seeking outside of buffer while fragment load in progress, cancel fragment load\");\n                      fragCurrent.loader.abort();\n                    }\n\n                    this.resetLoadingState();\n                  }\n                }\n\n                if (media) {\n                  this.lastCurrentTime = currentTime;\n                } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n\n                if (!this.loadedmetadata && !bufferInfo.len) {\n                  this.nextLoadPosition = this.startPosition = currentTime;\n                } // Async tick to speed up processing\n\n                this.tickImmediate();\n              };\n\n              _proto.onMediaEnded = function onMediaEnded() {\n                // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n                this.startPosition = this.lastCurrentTime = 0;\n              };\n\n              _proto.onKeyLoaded = function onKeyLoaded(event, data) {\n                if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) {\n                  return;\n                }\n\n                this.state = State.IDLE;\n                var levelDetails = this.levels[data.frag.level].details;\n\n                if (levelDetails) {\n                  this.loadFragment(data.frag, levelDetails, data.frag.start);\n                }\n              };\n\n              _proto.onHandlerDestroying = function onHandlerDestroying() {\n                this.stopLoad();\n\n                _TaskLoop.prototype.onHandlerDestroying.call(this);\n              };\n\n              _proto.onHandlerDestroyed = function onHandlerDestroyed() {\n                this.state = State.STOPPED;\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].KEY_LOADED, this.onKeyLoaded, this);\n\n                if (this.fragmentLoader) {\n                  this.fragmentLoader.destroy();\n                }\n\n                if (this.decrypter) {\n                  this.decrypter.destroy();\n                }\n\n                this.CiderHls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;\n\n                _TaskLoop.prototype.onHandlerDestroyed.call(this);\n              };\n\n              _proto.loadKey = function loadKey(frag, details) {\n                this.log(\"Loading key for \" + frag.sn + \" of [\" + details.startSN + \"-\" + details.endSN + \"], \" + (this.logPrefix === \"[stream-controller]\" ? \"level\" : \"track\") + \" \" + frag.level);\n                this.state = State.KEY_LOADING;\n                this.fragCurrent = frag;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].KEY_LOADING, {\n                  frag: frag,\n                });\n              };\n\n              _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {\n                this._loadFragForPlayback(frag, levelDetails, targetBufferTime);\n              };\n\n              _proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {\n                var _this2 = this;\n\n                var progressCallback = function progressCallback(data) {\n                  if (_this2.fragContextChanged(frag)) {\n                    _this2.warn(\"Fragment \" + frag.sn + (data.part ? \" p: \" + data.part.index : \"\") + \" of level \" + frag.level + \" was dropped during download.\");\n\n                    _this2.fragmentTracker.removeFragment(frag);\n\n                    return;\n                  }\n\n                  frag.stats.chunkCount++;\n\n                  _this2._handleFragmentLoadProgress(data);\n                };\n\n                this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback)\n                  .then(function (data) {\n                    if (!data) {\n                      // if we're here we probably needed to backtrack or are waiting for more parts\n                      return;\n                    }\n\n                    _this2.fragLoadError = 0;\n                    var state = _this2.state;\n\n                    if (_this2.fragContextChanged(frag)) {\n                      if (state === State.FRAG_LOADING || state === State.BACKTRACKING || (!_this2.fragCurrent && state === State.PARSING)) {\n                        _this2.fragmentTracker.removeFragment(frag);\n\n                        _this2.state = State.IDLE;\n                      }\n\n                      return;\n                    }\n\n                    if (\"payload\" in data) {\n                      _this2.log(\"Loaded fragment \" + frag.sn + \" of level \" + frag.level);\n\n                      _this2.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED\n                      // This happens after handleTransmuxComplete when the worker or progressive is disabled\n\n                      if (_this2.state === State.BACKTRACKING) {\n                        _this2.fragmentTracker.backtrack(frag, data);\n\n                        _this2.resetFragmentLoading(frag);\n\n                        return;\n                      }\n                    } // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback\n\n                    _this2._handleFragmentLoadComplete(data);\n                  })\n                  .catch(function (reason) {\n                    _this2.warn(reason);\n\n                    _this2.resetFragmentLoading(frag);\n                  });\n              };\n\n              _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {\n                if (type === void 0) {\n                  type = null;\n                }\n\n                if (!(startOffset - endOffset)) {\n                  return;\n                } // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,\n                // passing a null type flushes both buffers\n\n                var flushScope = {\n                  startOffset: startOffset,\n                  endOffset: endOffset,\n                  type: type,\n                }; // Reset load errors on flush\n\n                this.fragLoadError = 0;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].BUFFER_FLUSHING, flushScope);\n              };\n\n              _proto._loadInitSegment = function _loadInitSegment(frag) {\n                var _this3 = this;\n\n                this._doFragLoad(frag)\n                  .then(function (data) {\n                    if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {\n                      throw new Error(\"init load aborted\");\n                    }\n\n                    return data;\n                  })\n                  .then(function (data) {\n                    var CiderHls = _this3.CiderHls;\n                    var payload = data.payload;\n                    var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted\n\n                    if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === \"AES-128\") {\n                      var startTime = self.performance.now(); // decrypt the subtitles\n\n                      return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {\n                        var endTime = self.performance.now();\n                        CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_DECRYPTED, {\n                          frag: frag,\n                          payload: decryptedData,\n                          stats: {\n                            tstart: startTime,\n                            tdecrypt: endTime,\n                          },\n                        });\n                        data.payload = decryptedData;\n                        return data;\n                      });\n                    }\n\n                    return data;\n                  })\n                  .then(function (data) {\n                    var fragCurrent = _this3.fragCurrent,\n                      CiderHls = _this3.CiderHls,\n                      levels = _this3.levels;\n\n                    if (!levels) {\n                      throw new Error(\"init load aborted, missing levels\");\n                    }\n\n                    var details = levels[frag.level].details;\n                    console.assert(details, \"Level details are defined when init segment is loaded\");\n                    var stats = frag.stats;\n                    _this3.state = State.IDLE;\n                    _this3.fragLoadError = 0;\n                    frag.data = new Uint8Array(data.payload);\n                    stats.parsing.start = stats.buffering.start = self.performance.now();\n                    stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null\n\n                    if (data.frag === fragCurrent) {\n                      CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_BUFFERED, {\n                        stats: stats,\n                        frag: fragCurrent,\n                        part: null,\n                        id: frag.type,\n                      });\n                    }\n\n                    _this3.tick();\n                  })\n                  .catch(function (reason) {\n                    _this3.warn(reason);\n\n                    _this3.resetFragmentLoading(frag);\n                  });\n              };\n\n              _proto.fragContextChanged = function fragContextChanged(frag) {\n                var fragCurrent = this.fragCurrent;\n                return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;\n              };\n\n              _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {\n                var media = this.mediaBuffer ? this.mediaBuffer : this.media;\n                this.log(\n                  \"Buffered \" +\n                    frag.type +\n                    \" sn: \" +\n                    frag.sn +\n                    (part ? \" part: \" + part.index : \"\") +\n                    \" of \" +\n                    (this.logPrefix === \"[stream-controller]\" ? \"level\" : \"track\") +\n                    \" \" +\n                    frag.level +\n                    \" \" +\n                    _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__[\"default\"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].getBuffered(media))\n                );\n                this.state = State.IDLE;\n                this.tick();\n              };\n\n              _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {\n                var transmuxer = this.transmuxer;\n\n                if (!transmuxer) {\n                  return;\n                }\n\n                var frag = fragLoadedEndData.frag,\n                  part = fragLoadedEndData.part,\n                  partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data\n\n                var complete =\n                  !partsLoaded ||\n                  partsLoaded.length === 0 ||\n                  partsLoaded.some(function (fragLoaded) {\n                    return !fragLoaded;\n                  });\n                var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__[\"ChunkMetadata\"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);\n                transmuxer.flush(chunkMeta);\n              }; // eslint-disable-next-line @typescript-eslint/no-unused-vars\n\n              _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};\n\n              _proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {\n                var _this4 = this;\n\n                if (targetBufferTime === void 0) {\n                  targetBufferTime = null;\n                }\n\n                if (!this.levels) {\n                  throw new Error(\"frag load aborted, missing levels\");\n                }\n\n                targetBufferTime = Math.max(frag.start, targetBufferTime || 0);\n\n                if (this.config.lowLatencyMode && details) {\n                  var partList = details.partList;\n\n                  if (partList && progressCallback) {\n                    if (targetBufferTime > frag.end && details.fragmentHint) {\n                      frag = details.fragmentHint;\n                    }\n\n                    var partIndex = this.getNextPart(partList, frag, targetBufferTime);\n\n                    if (partIndex > -1) {\n                      var part = partList[partIndex];\n                      this.log(\n                        \"Loading part sn: \" +\n                          frag.sn +\n                          \" p: \" +\n                          part.index +\n                          \" cc: \" +\n                          frag.cc +\n                          \" of playlist [\" +\n                          details.startSN +\n                          \"-\" +\n                          details.endSN +\n                          \"] parts [0-\" +\n                          partIndex +\n                          \"-\" +\n                          (partList.length - 1) +\n                          \"] \" +\n                          (this.logPrefix === \"[stream-controller]\" ? \"level\" : \"track\") +\n                          \": \" +\n                          frag.level +\n                          \", target: \" +\n                          parseFloat(targetBufferTime.toFixed(3))\n                      );\n                      this.nextLoadPosition = part.start + part.duration;\n                      this.state = State.FRAG_LOADING;\n                      this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_LOADING, {\n                        frag: frag,\n                        part: partList[partIndex],\n                        targetBufferTime: targetBufferTime,\n                      });\n                      return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {\n                        return _this4.handleFragLoadError(error);\n                      });\n                    } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {\n                      // Fragment hint has no parts\n                      return Promise.resolve(null);\n                    }\n                  }\n                }\n\n                this.log(\"Loading fragment \" + frag.sn + \" cc: \" + frag.cc + \" \" + (details ? \"of [\" + details.startSN + \"-\" + details.endSN + \"] \" : \"\") + (this.logPrefix === \"[stream-controller]\" ? \"level\" : \"track\") + \": \" + frag.level + \", target: \" + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered\n\n                if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(frag.sn) && !this.bitrateTest) {\n                  this.nextLoadPosition = frag.start + frag.duration;\n                }\n\n                this.state = State.FRAG_LOADING;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_LOADING, {\n                  frag: frag,\n                  targetBufferTime: targetBufferTime,\n                });\n                return this.fragmentLoader.load(frag, progressCallback).catch(function (error) {\n                  return _this4.handleFragLoadError(error);\n                });\n              };\n\n              _proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {\n                var _this5 = this;\n\n                return new Promise(function (resolve, reject) {\n                  var partsLoaded = [];\n\n                  var loadPartIndex = function loadPartIndex(index) {\n                    var part = partList[index];\n\n                    _this5.fragmentLoader\n                      .loadPart(frag, part, progressCallback)\n                      .then(function (partLoadedData) {\n                        partsLoaded[part.index] = partLoadedData;\n                        var loadedPart = partLoadedData.part;\n\n                        _this5.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_LOADED, partLoadedData);\n\n                        var nextPart = partList[index + 1];\n\n                        if (nextPart && nextPart.fragment === frag) {\n                          loadPartIndex(index + 1);\n                        } else {\n                          return resolve({\n                            frag: frag,\n                            part: loadedPart,\n                            partsLoaded: partsLoaded,\n                          });\n                        }\n                      })\n                      .catch(reject);\n                  };\n\n                  loadPartIndex(partIndex);\n                });\n              };\n\n              _proto.handleFragLoadError = function handleFragLoadError(_ref) {\n                var data = _ref.data;\n\n                if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__[\"ErrorDetails\"].INTERNAL_ABORTED) {\n                  this.handleFragLoadAborted(data.frag, data.part);\n                } else {\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].ERROR, data);\n                }\n\n                return null;\n              };\n\n              _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {\n                var context = this.getCurrentContext(chunkMeta);\n\n                if (!context || this.state !== State.PARSING) {\n                  if (!this.fragCurrent) {\n                    this.state = State.IDLE;\n                  }\n\n                  return;\n                }\n\n                var frag = context.frag,\n                  part = context.part,\n                  level = context.level;\n                var now = self.performance.now();\n                frag.stats.parsing.end = now;\n\n                if (part) {\n                  part.stats.parsing.end = now;\n                }\n\n                this.updateLevelTiming(frag, part, level, chunkMeta.partial);\n              };\n\n              _proto.getCurrentContext = function getCurrentContext(chunkMeta) {\n                var levels = this.levels;\n                var levelIndex = chunkMeta.level,\n                  sn = chunkMeta.sn,\n                  partIndex = chunkMeta.part;\n\n                if (!levels || !levels[levelIndex]) {\n                  this.warn(\"Levels object was unset while buffering fragment \" + sn + \" of level \" + levelIndex + \". The current chunk will not be buffered.\");\n                  return null;\n                }\n\n                var level = levels[levelIndex];\n                var part = partIndex > -1 ? Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__[\"getPartWith\"])(level, sn, partIndex) : null;\n                var frag = part ? part.fragment : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__[\"getFragmentWithSN\"])(level, sn, this.fragCurrent);\n\n                if (!frag) {\n                  return null;\n                }\n\n                return {\n                  frag: frag,\n                  part: part,\n                  level: level,\n                };\n              };\n\n              _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {\n                if (!data || this.state !== State.PARSING) {\n                  return;\n                }\n\n                var data1 = data.data1,\n                  data2 = data.data2;\n                var buffer = data1;\n\n                if (data1 && data2) {\n                  // Combine the moof + mdat so that we buffer with a single append\n                  buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__[\"appendUint8Array\"])(data1, data2);\n                }\n\n                if (!buffer || !buffer.length) {\n                  return;\n                }\n\n                var segment = {\n                  type: data.type,\n                  frag: frag,\n                  part: part,\n                  chunkMeta: chunkMeta,\n                  parent: frag.type,\n                  data: buffer,\n                };\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].BUFFER_APPENDING, segment);\n\n                if (data.dropped && data.independent && !part) {\n                  // Clear buffer so that we reload previous segments sequentially if required\n                  this.flushBufferGap(frag);\n                }\n              };\n\n              _proto.flushBufferGap = function flushBufferGap(frag) {\n                var media = this.media;\n\n                if (!media) {\n                  return;\n                } // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed\n\n                if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].isBuffered(media, media.currentTime)) {\n                  this.flushMainBuffer(0, frag.start);\n                  return;\n                } // Remove back-buffer without interrupting playback to allow back tracking\n\n                var currentTime = media.currentTime;\n                var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(media, currentTime, 0);\n                var fragDuration = frag.duration;\n                var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);\n                var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);\n\n                if (frag.start - start > segmentFraction) {\n                  this.flushMainBuffer(start, frag.start);\n                }\n              };\n\n              _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {\n                var config = this.config;\n                var pos = this.getLoadPosition();\n\n                if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(pos)) {\n                  return null;\n                }\n\n                var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(bufferable, pos, config.maxBufferHole); // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos\n\n                if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {\n                  var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);\n\n                  if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {\n                    return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole));\n                  }\n                }\n\n                return bufferInfo;\n              };\n\n              _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {\n                var config = this.config;\n                var maxBufLen;\n\n                if (levelBitrate) {\n                  maxBufLen = Math.max((8 * config.maxBufferSize) / levelBitrate, config.maxBufferLength);\n                } else {\n                  maxBufLen = config.maxBufferLength;\n                }\n\n                return Math.min(maxBufLen, config.maxMaxBufferLength);\n              };\n\n              _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {\n                var config = this.config;\n                var minLength = threshold || config.maxBufferLength;\n\n                if (config.maxMaxBufferLength >= minLength) {\n                  // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n                  config.maxMaxBufferLength /= 2;\n                  this.warn(\"Reduce max buffer length to \" + config.maxMaxBufferLength + \"s\");\n                  return true;\n                }\n\n                return false;\n              };\n\n              _proto.getNextFragment = function getNextFragment(pos, levelDetails) {\n                var _frag, _frag2;\n\n                var fragments = levelDetails.fragments;\n                var fragLen = fragments.length;\n\n                if (!fragLen) {\n                  return null;\n                } // find fragment index, contiguous with end of buffer position\n\n                var config = this.config;\n                var start = fragments[0].start;\n                var frag;\n\n                if (levelDetails.live) {\n                  var initialLiveManifestSize = config.initialLiveManifestSize;\n\n                  if (fragLen < initialLiveManifestSize) {\n                    this.warn(\"Not enough fragments to start playback (have: \" + fragLen + \", need: \" + initialLiveManifestSize + \")\");\n                    return null;\n                  } // The real fragment start times for a live stream are only known after the PTS range for that level is known.\n                  // In order to discover the range, we load the best matching fragment for that level and demux it.\n                  // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that\n                  // we get the fragment matching that start time\n\n                  if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) {\n                    frag = this.getInitialLiveFragment(levelDetails, fragments);\n                    this.startPosition = frag ? this.CiderHls.liveSyncPosition || frag.start : pos;\n                  }\n                } else if (pos <= start) {\n                  // VoD playlist: if loadPosition before start of playlist, load first fragment\n                  frag = fragments[0];\n                } // If we haven't run into any special cases already, just load the fragment most closely matching the requested position\n\n                if (!frag) {\n                  var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;\n                  frag = this.getFragmentAtPosition(pos, end, levelDetails);\n                } // If an initSegment is present, it must be buffered first\n\n                if ((_frag = frag) !== null && _frag !== void 0 && _frag.initSegment && !((_frag2 = frag) !== null && _frag2 !== void 0 && _frag2.initSegment.data) && !this.bitrateTest) {\n                  frag = frag.initSegment;\n                }\n\n                return frag;\n              };\n\n              _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {\n                var nextPart = -1;\n                var contiguous = false;\n                var independentAttrOmitted = true;\n\n                for (var i = 0, len = partList.length; i < len; i++) {\n                  var part = partList[i];\n                  independentAttrOmitted = independentAttrOmitted && !part.independent;\n\n                  if (nextPart > -1 && targetBufferTime < part.start) {\n                    break;\n                  }\n\n                  var loaded = part.loaded;\n\n                  if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {\n                    nextPart = i;\n                  }\n\n                  contiguous = loaded;\n                }\n\n                return nextPart;\n              };\n\n              _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {\n                var lastPart = partList[partList.length - 1];\n                return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;\n              };\n              /*\n   This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the\n   \"sliding\" of the playlist, which is its offset from the start of playback. After sliding we can compute the real\n   start and end times for each fragment in the playlist (after which this method will not need to be called).\n  */\n\n              _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {\n                var fragPrevious = this.fragPrevious;\n                var frag = null;\n\n                if (fragPrevious) {\n                  if (levelDetails.hasProgramDateTime) {\n                    // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding\n                    this.log(\"Live playlist, switching playlist, load frag with same PDT: \" + fragPrevious.programDateTime);\n                    frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__[\"findFragmentByPDT\"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);\n                  }\n\n                  if (!frag) {\n                    // SN does not need to be accurate between renditions, but depending on the packaging it may be so.\n                    var targetSN = fragPrevious.sn + 1;\n\n                    if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n                      var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range\n\n                      if (fragPrevious.cc === fragNext.cc) {\n                        frag = fragNext;\n                        this.log(\"Live playlist, switching playlist, load frag with next SN: \" + frag.sn);\n                      }\n                    } // It's important to stay within the continuity range if available; otherwise the fragments in the playlist\n                    // will have the wrong start times\n\n                    if (!frag) {\n                      frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__[\"findFragWithCC\"])(fragments, fragPrevious.cc);\n\n                      if (frag) {\n                        this.log(\"Live playlist, switching playlist, load frag with same CC: \" + frag.sn);\n                      }\n                    }\n                  }\n                } else {\n                  // Find a new start fragment when fragPrevious is null\n                  var liveStart = this.CiderHls.liveSyncPosition;\n\n                  if (liveStart !== null) {\n                    frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);\n                  }\n                }\n\n                return frag;\n              };\n              /*\n  This method finds the best matching fragment given the provided position.\n   */\n\n              _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {\n                var config = this.config,\n                  fragPrevious = this.fragPrevious;\n                var fragments = levelDetails.fragments,\n                  endSN = levelDetails.endSN;\n                var fragmentHint = levelDetails.fragmentHint;\n                var tolerance = config.maxFragLookUpTolerance;\n                var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);\n\n                if (loadingParts && fragmentHint && !this.bitrateTest) {\n                  // Include incomplete fragment with parts at end\n                  fragments = fragments.concat(fragmentHint);\n                  endSN = fragmentHint.sn;\n                }\n\n                var frag;\n\n                if (bufferEnd < end) {\n                  var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n                  // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n\n                  frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__[\"findFragmentByPTS\"])(fragPrevious, fragments, bufferEnd, lookupTolerance);\n                } else {\n                  // reach end of playlist\n                  frag = fragments[fragments.length - 1];\n                }\n\n                if (frag) {\n                  var curSNIdx = frag.sn - levelDetails.startSN;\n                  var sameLevel = fragPrevious && frag.level === fragPrevious.level;\n                  var nextFrag = fragments[curSNIdx + 1];\n                  var fragState = this.fragmentTracker.getState(frag);\n\n                  if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__[\"FragmentState\"].BACKTRACKED) {\n                    frag = null;\n                    var i = curSNIdx;\n\n                    while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__[\"FragmentState\"].BACKTRACKED) {\n                      // When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading\n                      // When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering\n                      if (!fragPrevious) {\n                        frag = fragments[--i];\n                      } else {\n                        frag = fragments[i--];\n                      }\n                    }\n\n                    if (!frag) {\n                      frag = nextFrag;\n                    }\n                  } else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {\n                    // Force the next fragment to load if the previous one was already selected. This can occasionally happen with\n                    // non-uniform fragment durations\n                    if (sameLevel) {\n                      if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__[\"FragmentState\"].OK) {\n                        this.log(\"SN \" + frag.sn + \" just loaded, load next one: \" + nextFrag.sn);\n                        frag = nextFrag;\n                      } else {\n                        frag = null;\n                      }\n                    }\n                  }\n                }\n\n                return frag;\n              };\n\n              _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {\n                var config = this.config,\n                  media = this.media;\n\n                if (!media) {\n                  return;\n                }\n\n                var liveSyncPosition = this.CiderHls.liveSyncPosition;\n                var currentTime = media.currentTime;\n                var start = levelDetails.fragments[0].start;\n                var end = levelDetails.edge;\n                var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window\n\n                if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {\n                  // Continue if buffer is starving or if current time is behind max latency\n                  var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n\n                  if ((!withinSlidingWindow && media.readyState < 4) || currentTime < end - maxLatency) {\n                    if (!this.loadedmetadata) {\n                      this.nextLoadPosition = liveSyncPosition;\n                    } // Only seek if ready and there is not a significant forward buffer available for playback\n\n                    if (media.readyState) {\n                      this.warn(\"Playback: \" + currentTime.toFixed(3) + \" is located too far from the end of live sliding playlist: \" + end + \", reset currentTime to : \" + liveSyncPosition.toFixed(3));\n                      media.currentTime = liveSyncPosition;\n                    }\n                  }\n                }\n              };\n\n              _proto.alignPlaylists = function alignPlaylists(details, previousDetails) {\n                var levels = this.levels,\n                  levelLastLoaded = this.levelLastLoaded,\n                  fragPrevious = this.fragPrevious;\n                var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,\n                //  this could all go in level-helper mergeDetails()\n\n                var length = details.fragments.length;\n\n                if (!length) {\n                  this.warn(\"No fragments in live playlist\");\n                  return 0;\n                }\n\n                var slidingStart = details.fragments[0].start;\n                var firstLevelLoad = !previousDetails;\n\n                var aligned = details.alignedSliding && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(slidingStart);\n\n                if (firstLevelLoad || (!aligned && !slidingStart)) {\n                  Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__[\"alignStream\"])(fragPrevious, lastLevel, details);\n                  var alignedSlidingStart = details.fragments[0].start;\n                  this.log(\"Live playlist sliding: \" + alignedSlidingStart.toFixed(2) + \" start-sn: \" + (previousDetails ? previousDetails.startSN : \"na\") + \"->\" + details.startSN + \" prev-sn: \" + (fragPrevious ? fragPrevious.sn : \"na\") + \" fragments: \" + length);\n                  return alignedSlidingStart;\n                }\n\n                return slidingStart;\n              };\n\n              _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {\n                // Wait for Low-Latency CDN Tune-in to get an updated playlist\n                var advancePartLimit = 3;\n                return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);\n              };\n\n              _proto.setStartPosition = function setStartPosition(details, sliding) {\n                // compute start position if set to -1. use it straight away if value is defined\n                var startPosition = this.startPosition;\n\n                if (startPosition < sliding) {\n                  startPosition = -1;\n                }\n\n                if (startPosition === -1 || this.lastCurrentTime === -1) {\n                  // first, check if start time offset has been set in playlist, if yes, use this value\n                  var startTimeOffset = details.startTimeOffset;\n\n                  if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(startTimeOffset)) {\n                    startPosition = sliding + startTimeOffset;\n\n                    if (startTimeOffset < 0) {\n                      startPosition += details.totalduration;\n                    }\n\n                    startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);\n                    this.log(\"Start time offset \" + startTimeOffset + \" found in playlist, adjust startPosition to \" + startPosition);\n                    this.startPosition = startPosition;\n                  } else if (details.live) {\n                    // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has\n                    // not been specified via the config or an as an argument to startLoad (#3736).\n                    startPosition = this.CiderHls.liveSyncPosition || sliding;\n                  } else {\n                    this.startPosition = startPosition = 0;\n                  }\n\n                  this.lastCurrentTime = startPosition;\n                }\n\n                this.nextLoadPosition = startPosition;\n              };\n\n              _proto.getLoadPosition = function getLoadPosition() {\n                var media = this.media; // if we have not yet loaded any fragment, start loading from start position\n\n                var pos = 0;\n\n                if (this.loadedmetadata && media) {\n                  pos = media.currentTime;\n                } else if (this.nextLoadPosition) {\n                  pos = this.nextLoadPosition;\n                }\n\n                return pos;\n              };\n\n              _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {\n                if (this.transmuxer && frag.sn !== \"initSegment\" && frag.stats.aborted) {\n                  this.warn(\"Fragment \" + frag.sn + (part ? \" part\" + part.index : \"\") + \" of level \" + frag.level + \" was aborted\");\n                  this.resetFragmentLoading(frag);\n                }\n              };\n\n              _proto.resetFragmentLoading = function resetFragmentLoading(frag) {\n                if (!this.fragCurrent || !this.fragContextChanged(frag)) {\n                  this.state = State.IDLE;\n                }\n              };\n\n              _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {\n                if (data.fatal) {\n                  return;\n                }\n\n                var frag = data.frag; // Handle frag error related to caller's filterType\n\n                if (!frag || frag.type !== filterType) {\n                  return;\n                }\n\n                var fragCurrent = this.fragCurrent;\n                console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, \"Frag load error must match current frag to retry\");\n                var config = this.config; // keep retrying until the limit will be reached\n\n                if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {\n                  if (this.resetLiveStartWhenNotLoaded(frag.level)) {\n                    return;\n                  } // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n\n                  var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);\n                  this.warn(\"Fragment \" + frag.sn + \" of \" + filterType + \" \" + frag.level + \" failed to load, retrying in \" + delay + \"ms\");\n                  this.retryDate = self.performance.now() + delay;\n                  this.fragLoadError++;\n                  this.state = State.FRAG_LOADING_WAITING_RETRY;\n                } else if (data.levelRetry) {\n                  if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__[\"PlaylistLevelType\"].AUDIO) {\n                    // Reset current fragment since audio track audio is essential and may not have a fail-over track\n                    this.fragCurrent = null;\n                  } // Fragment errors that result in a level switch or redundant fail-over\n                  // should reset the stream controller state to idle\n\n                  this.fragLoadError = 0;\n                  this.state = State.IDLE;\n                } else {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_4__[\"logger\"].error(data.details + \" reaches max retry, redispatch as fatal ...\"); // switch error to fatal\n\n                  data.fatal = true;\n                  this.CiderHls.stopLoad();\n                  this.state = State.ERROR;\n                }\n              };\n\n              _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {\n                if (!media) {\n                  return;\n                } // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media\n                // (so that we will check against video.buffered ranges in case of alt audio track)\n\n                var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__[\"BufferHelper\"].getBuffered(media);\n                this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);\n\n                if (this.state === State.ENDED) {\n                  this.resetLoadingState();\n                }\n              };\n\n              _proto.resetLoadingState = function resetLoadingState() {\n                this.fragCurrent = null;\n                this.fragPrevious = null;\n                this.state = State.IDLE;\n              };\n\n              _proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) {\n                // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n                // in that case, reset startFragRequested flag\n                if (!this.loadedmetadata) {\n                  this.startFragRequested = false;\n                  var details = this.levels ? this.levels[level].details : null;\n\n                  if (details !== null && details !== void 0 && details.live) {\n                    // We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.\n                    this.startPosition = -1;\n                    this.setStartPosition(details, 0);\n                    this.resetLoadingState();\n                    return true;\n                  }\n\n                  this.nextLoadPosition = this.startPosition;\n                }\n\n                return false;\n              };\n\n              _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {\n                var _this6 = this;\n\n                var details = level.details;\n                console.assert(!!details, \"level.details must be defined\");\n                var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {\n                  var info = frag.elementaryStreams[type];\n\n                  if (info) {\n                    var parsedDuration = info.endPTS - info.startPTS;\n\n                    if (parsedDuration <= 0) {\n                      // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.\n                      // The new transmuxer will be configured with a time offset matching the next fragment start,\n                      // preventing the timeline from shifting.\n                      _this6.warn(\"Could not parse fragment \" + frag.sn + \" \" + type + \" duration reliably (\" + parsedDuration + \") resetting transmuxer to fallback to playlist timing\");\n\n                      _this6.resetTransmuxer();\n\n                      return result || false;\n                    }\n\n                    var drift = partial ? 0 : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__[\"updateFragPTSDTS\"])(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);\n\n                    _this6.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].LEVEL_PTS_UPDATED, {\n                      details: details,\n                      level: level,\n                      drift: drift,\n                      type: type,\n                      frag: frag,\n                      start: info.startPTS,\n                      end: info.endPTS,\n                    });\n\n                    return true;\n                  }\n\n                  return result;\n                }, false);\n\n                if (parsed) {\n                  this.state = State.PARSED;\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].FRAG_PARSED, {\n                    frag: frag,\n                    part: part,\n                  });\n                } else {\n                  this.resetLoadingState();\n                }\n              };\n\n              _proto.resetTransmuxer = function resetTransmuxer() {\n                if (this.transmuxer) {\n                  this.transmuxer.destroy();\n                  this.transmuxer = null;\n                }\n              };\n\n              _createClass(BaseStreamController, [\n                {\n                  key: \"state\",\n                  get: function get() {\n                    return this._state;\n                  },\n                  set: function set(nextState) {\n                    var previousState = this._state;\n\n                    if (previousState !== nextState) {\n                      this._state = nextState;\n                      this.log(previousState + \"->\" + nextState);\n                    }\n                  },\n                },\n              ]);\n\n              return BaseStreamController;\n            })(_task_loop__WEBPACK_IMPORTED_MODULE_1__[\"default\"]);\n\n            /***/\n          },\n\n        /***/ \"./src/controller/buffer-controller.ts\":\n          /*!*********************************************!*\\\n  !*** ./src/controller/buffer-controller.ts ***!\n  \\*********************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return BufferController;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ \"./src/utils/mediasource-helper.ts\");\n            /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ \"./src/loader/fragment.ts\");\n            /* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ \"./src/controller/buffer-operation-queue.ts\");\n\n            var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__[\"getMediaSource\"])();\n            var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\\.[^.,]+)+/;\n\n            var BufferController = /*#__PURE__*/ (function () {\n              // The level details used to determine duration, target-duration and live\n              // cache the self generated object url to detect hijack of video tag\n              // A queue of buffer operations which require the SourceBuffer to not be updating upon execution\n              // References to event listeners for each SourceBuffer, so that they can be referenced for event removal\n              // The number of BUFFER_CODEC events received before any sourceBuffers are created\n              // The total number of BUFFER_CODEC events received\n              // A reference to the attached media element\n              // A reference to the active media source\n              // counters\n              function BufferController(_CiderHls) {\n                var _this = this;\n\n                this.details = null;\n                this._objectUrl = null;\n                this.operationQueue = void 0;\n                this.listeners = void 0;\n                this.CiderHls = void 0;\n                this.bufferCodecEventsExpected = 0;\n                this._bufferCodecEventsTotal = 0;\n                this.media = null;\n                this.mediaSource = null;\n                this.appendError = 0;\n                this.tracks = {};\n                this.pendingTracks = {};\n                this.sourceBuffer = void 0;\n\n                this._onMediaSourceOpen = function () {\n                  var CiderHls = _this.CiderHls,\n                    media = _this.media,\n                    mediaSource = _this.mediaSource;\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Media source opened\");\n\n                  if (media) {\n                    _this.updateMediaElementDuration();\n\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHED, {\n                      media: media,\n                    });\n                  }\n\n                  if (mediaSource) {\n                    // once received, don't listen anymore to sourceopen event\n                    mediaSource.removeEventListener(\"sourceopen\", _this._onMediaSourceOpen);\n                  }\n\n                  _this.checkPendingTracks();\n                };\n\n                this._onMediaSourceClose = function () {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Media source closed\");\n                };\n\n                this._onMediaSourceEnded = function () {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Media source ended\");\n                };\n\n                this.CiderHls = _CiderHls;\n\n                this._initSourceBuffer();\n\n                this.registerListeners();\n              }\n\n              var _proto = BufferController.prototype;\n\n              _proto.hasSourceTypes = function hasSourceTypes() {\n                return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;\n              };\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners();\n                this.details = null;\n              };\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_RESET, this.onBufferReset, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_APPENDING, this.onBufferAppending, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_CODECS, this.onBufferCodecs, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_EOS, this.onBufferEos, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_UPDATED, this.onLevelUpdated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_PARSED, this.onFragParsed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_CHANGED, this.onFragChanged, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_RESET, this.onBufferReset, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_APPENDING, this.onBufferAppending, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_CODECS, this.onBufferCodecs, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_EOS, this.onBufferEos, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_UPDATED, this.onLevelUpdated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_PARSED, this.onFragParsed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_CHANGED, this.onFragChanged, this);\n              };\n\n              _proto._initSourceBuffer = function _initSourceBuffer() {\n                this.sourceBuffer = {};\n                this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__[\"default\"](this.sourceBuffer);\n                this.listeners = {\n                  audio: [],\n                  video: [],\n                  audiovideo: [],\n                };\n              };\n\n              _proto.onManifestParsed = function onManifestParsed(event, data) {\n                // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n                // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n                // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n                // it will contain the expected nb of source buffers, no need to compute it\n                var codecEvents = 2;\n\n                if ((data.audio && !data.video) || !data.altAudio) {\n                  codecEvents = 1;\n                }\n\n                this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n                this.details = null;\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(this.bufferCodecEventsExpected + \" bufferCodec event(s) expected\");\n              };\n\n              _proto.onMediaAttaching = function onMediaAttaching(event, data) {\n                var media = (this.media = data.media);\n\n                if (media && MediaSource) {\n                  var ms = (this.mediaSource = new MediaSource()); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound\n\n                  ms.addEventListener(\"sourceopen\", this._onMediaSourceOpen);\n                  ms.addEventListener(\"sourceended\", this._onMediaSourceEnded);\n                  ms.addEventListener(\"sourceclose\", this._onMediaSourceClose); // link video and media Source\n\n                  media.src = self.URL.createObjectURL(ms); // cache the locally generated object url\n\n                  this._objectUrl = media.src;\n                }\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                var media = this.media,\n                  mediaSource = this.mediaSource,\n                  _objectUrl = this._objectUrl;\n\n                if (mediaSource) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: media source detaching\");\n\n                  if (mediaSource.readyState === \"open\") {\n                    try {\n                      // endOfStream could trigger exception if any sourcebuffer is in updating state\n                      // we don't really care about checking sourcebuffer state here,\n                      // as we are anyway detaching the MediaSource\n                      // let's just avoid this exception to propagate\n                      mediaSource.endOfStream();\n                    } catch (err) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: onMediaDetaching: \" + err.message + \" while calling endOfStream\");\n                    }\n                  } // Clean up the SourceBuffers by invoking onBufferReset\n\n                  this.onBufferReset();\n                  mediaSource.removeEventListener(\"sourceopen\", this._onMediaSourceOpen);\n                  mediaSource.removeEventListener(\"sourceended\", this._onMediaSourceEnded);\n                  mediaSource.removeEventListener(\"sourceclose\", this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as\n                  // suggested in https://github.com/w3c/media-source/issues/53.\n\n                  if (media) {\n                    if (_objectUrl) {\n                      self.URL.revokeObjectURL(_objectUrl);\n                    } // clean up video tag src only if it's our own url. some external libraries might\n                    // hijack the video tag and change its 'src' without destroying the CiderHls instance first\n\n                    if (media.src === _objectUrl) {\n                      media.removeAttribute(\"src\");\n                      media.load();\n                    } else {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: media.src was changed by a third party - skip cleanup\");\n                    }\n                  }\n\n                  this.mediaSource = null;\n                  this.media = null;\n                  this._objectUrl = null;\n                  this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n                  this.pendingTracks = {};\n                  this.tracks = {};\n                }\n\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHED, undefined);\n              };\n\n              _proto.onBufferReset = function onBufferReset() {\n                var _this2 = this;\n\n                this.getSourceBufferTypes().forEach(function (type) {\n                  var sb = _this2.sourceBuffer[type];\n\n                  try {\n                    if (sb) {\n                      _this2.removeBufferListeners(type);\n\n                      if (_this2.mediaSource) {\n                        _this2.mediaSource.removeSourceBuffer(sb);\n                      } // Synchronously remove the SB from the map before the next call in order to prevent an async function from\n                      // accessing it\n\n                      _this2.sourceBuffer[type] = undefined;\n                    }\n                  } catch (err) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: Failed to reset the \" + type + \" buffer\", err);\n                  }\n                });\n\n                this._initSourceBuffer();\n              };\n\n              _proto.onBufferCodecs = function onBufferCodecs(event, data) {\n                var _this3 = this;\n\n                var sourceBufferCount = this.getSourceBufferTypes().length;\n                Object.keys(data).forEach(function (trackName) {\n                  if (sourceBufferCount) {\n                    // check if SourceBuffer codec needs to change\n                    var track = _this3.tracks[trackName];\n\n                    if (track && typeof track.buffer.changeType === \"function\") {\n                      var _data$trackName = data[trackName],\n                        codec = _data$trackName.codec,\n                        levelCodec = _data$trackName.levelCodec,\n                        container = _data$trackName.container;\n                      var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, \"$1\");\n                      var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, \"$1\");\n\n                      if (currentCodec !== nextCodec) {\n                        var mimeType = container + \";codecs=\" + (levelCodec || codec);\n\n                        _this3.appendChangeType(trackName, mimeType);\n                      }\n                    }\n                  } else {\n                    // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n                    _this3.pendingTracks[trackName] = data[trackName];\n                  }\n                }); // if sourcebuffers already created, do nothing ...\n\n                if (sourceBufferCount) {\n                  return;\n                }\n\n                this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);\n\n                if (this.mediaSource && this.mediaSource.readyState === \"open\") {\n                  this.checkPendingTracks();\n                }\n              };\n\n              _proto.appendChangeType = function appendChangeType(type, mimeType) {\n                var _this4 = this;\n\n                var operationQueue = this.operationQueue;\n                var operation = {\n                  execute: function execute() {\n                    var sb = _this4.sourceBuffer[type];\n\n                    if (sb) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: changing \" + type + \" sourceBuffer type to \" + mimeType);\n                      sb.changeType(mimeType);\n                    }\n\n                    operationQueue.shiftAndExecuteNext(type);\n                  },\n                  onStart: function onStart() {},\n                  onComplete: function onComplete() {},\n                  onError: function onError(e) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: Failed to change \" + type + \" SourceBuffer type\", e);\n                  },\n                };\n                operationQueue.append(operation, type);\n              };\n\n              _proto.onBufferAppending = function onBufferAppending(event, eventData) {\n                var _this5 = this;\n\n                var CiderHls = this.CiderHls,\n                  operationQueue = this.operationQueue,\n                  tracks = this.tracks;\n                var data = eventData.data,\n                  type = eventData.type,\n                  frag = eventData.frag,\n                  part = eventData.part,\n                  chunkMeta = eventData.chunkMeta;\n                var chunkStats = chunkMeta.buffering[type];\n                var bufferAppendingStart = self.performance.now();\n                chunkStats.start = bufferAppendingStart;\n                var fragBuffering = frag.stats.buffering;\n                var partBuffering = part ? part.stats.buffering : null;\n\n                if (fragBuffering.start === 0) {\n                  fragBuffering.start = bufferAppendingStart;\n                }\n\n                if (partBuffering && partBuffering.start === 0) {\n                  partBuffering.start = bufferAppendingStart;\n                } // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended\n                // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n                // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n                // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).\n                // More info here: https://github.com/video-dev/CiderHls.js/issues/332#issuecomment-257986486\n\n                var audioTrack = tracks.audio;\n                var checkTimestampOffset = type === \"audio\" && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === \"audio/mpeg\";\n                var operation = {\n                  execute: function execute() {\n                    chunkStats.executeStart = self.performance.now();\n\n                    if (checkTimestampOffset) {\n                      var sb = _this5.sourceBuffer[type];\n\n                      if (sb) {\n                        var delta = frag.start - sb.timestampOffset;\n\n                        if (Math.abs(delta) >= 0.1) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Updating audio SourceBuffer timestampOffset to \" + frag.start + \" (delta: \" + delta + \") sn: \" + frag.sn + \")\");\n                          sb.timestampOffset = frag.start;\n                        }\n                      }\n                    }\n\n                    _this5.appendExecutor(data, type);\n                  },\n                  onStart: function onStart() {\n                    // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);\n                  },\n                  onComplete: function onComplete() {\n                    // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);\n                    var end = self.performance.now();\n                    chunkStats.executeEnd = chunkStats.end = end;\n\n                    if (fragBuffering.first === 0) {\n                      fragBuffering.first = end;\n                    }\n\n                    if (partBuffering && partBuffering.first === 0) {\n                      partBuffering.first = end;\n                    }\n\n                    var sourceBuffer = _this5.sourceBuffer;\n                    var timeRanges = {};\n\n                    for (var _type in sourceBuffer) {\n                      timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__[\"BufferHelper\"].getBuffered(sourceBuffer[_type]);\n                    }\n\n                    _this5.appendError = 0;\n\n                    _this5.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_APPENDED, {\n                      type: type,\n                      frag: frag,\n                      part: part,\n                      chunkMeta: chunkMeta,\n                      parent: frag.type,\n                      timeRanges: timeRanges,\n                    });\n                  },\n                  onError: function onError(err) {\n                    // in case any error occured while appending, put back segment in segments table\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"[buffer-controller]: Error encountered while trying to append to the \" + type + \" SourceBuffer\", err);\n                    var event = {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorTypes\"].MEDIA_ERROR,\n                      parent: frag.type,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorDetails\"].BUFFER_APPEND_ERROR,\n                      err: err,\n                      fatal: false,\n                    };\n\n                    if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {\n                      // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n                      // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n                      event.details = _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorDetails\"].BUFFER_FULL_ERROR;\n                    } else {\n                      _this5.appendError++;\n                      event.details = _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorDetails\"].BUFFER_APPEND_ERROR;\n                      /* with UHD content, we could get loop of quota exceeded error until\n            browser is able to evict some data from sourcebuffer. Retrying can help recover.\n          */\n\n                      if (_this5.appendError > CiderHls.config.appendErrorMaxRetry) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"[buffer-controller]: Failed \" + CiderHls.config.appendErrorMaxRetry + \" times to append segment in sourceBuffer\");\n                        event.fatal = true;\n                      }\n                    }\n\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, event);\n                  },\n                };\n                operationQueue.append(operation, type);\n              };\n\n              _proto.onBufferFlushing = function onBufferFlushing(event, data) {\n                var _this6 = this;\n\n                var operationQueue = this.operationQueue;\n\n                var flushOperation = function flushOperation(type) {\n                  return {\n                    execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),\n                    onStart: function onStart() {\n                      // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n                    },\n                    onComplete: function onComplete() {\n                      // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n                      _this6.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_FLUSHED, {\n                        type: type,\n                      });\n                    },\n                    onError: function onError(e) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: Failed to remove from \" + type + \" SourceBuffer\", e);\n                    },\n                  };\n                };\n\n                if (data.type) {\n                  operationQueue.append(flushOperation(data.type), data.type);\n                } else {\n                  this.getSourceBufferTypes().forEach(function (type) {\n                    operationQueue.append(flushOperation(type), type);\n                  });\n                }\n              };\n\n              _proto.onFragParsed = function onFragParsed(event, data) {\n                var _this7 = this;\n\n                var frag = data.frag,\n                  part = data.part;\n                var buffersAppendedTo = [];\n                var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;\n\n                if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__[\"ElementaryStreamTypes\"].AUDIOVIDEO]) {\n                  buffersAppendedTo.push(\"audiovideo\");\n                } else {\n                  if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__[\"ElementaryStreamTypes\"].AUDIO]) {\n                    buffersAppendedTo.push(\"audio\");\n                  }\n\n                  if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__[\"ElementaryStreamTypes\"].VIDEO]) {\n                    buffersAppendedTo.push(\"video\");\n                  }\n                }\n\n                var onUnblocked = function onUnblocked() {\n                  var now = self.performance.now();\n                  frag.stats.buffering.end = now;\n\n                  if (part) {\n                    part.stats.buffering.end = now;\n                  }\n\n                  var stats = part ? part.stats : frag.stats;\n\n                  _this7.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_BUFFERED, {\n                    frag: frag,\n                    part: part,\n                    stats: stats,\n                    id: frag.type,\n                  });\n                };\n\n                if (buffersAppendedTo.length === 0) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"Fragments must have at least one ElementaryStreamType set. type: \" + frag.type + \" level: \" + frag.level + \" sn: \" + frag.sn);\n                }\n\n                this.blockBuffers(onUnblocked, buffersAppendedTo);\n              };\n\n              _proto.onFragChanged = function onFragChanged(event, data) {\n                this.flushBackBuffer();\n              }; // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n              // an undefined data.type will mark all buffers as EOS.\n\n              _proto.onBufferEos = function onBufferEos(event, data) {\n                var _this8 = this;\n\n                var ended = this.getSourceBufferTypes().reduce(function (acc, type) {\n                  var sb = _this8.sourceBuffer[type];\n\n                  if (!data.type || data.type === type) {\n                    if (sb && !sb.ended) {\n                      sb.ended = true;\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: \" + type + \" sourceBuffer now EOS\");\n                    }\n                  }\n\n                  return acc && !!(!sb || sb.ended);\n                }, true);\n\n                if (ended) {\n                  this.blockBuffers(function () {\n                    var mediaSource = _this8.mediaSource;\n\n                    if (!mediaSource || mediaSource.readyState !== \"open\") {\n                      return;\n                    } // Allow this to throw and be caught by the enqueueing function\n\n                    mediaSource.endOfStream();\n                  });\n                }\n              };\n\n              _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {\n                var details = _ref.details;\n\n                if (!details.fragments.length) {\n                  return;\n                }\n\n                this.details = details;\n\n                if (this.getSourceBufferTypes().length) {\n                  this.blockBuffers(this.updateMediaElementDuration.bind(this));\n                } else {\n                  this.updateMediaElementDuration();\n                }\n              };\n\n              _proto.flushBackBuffer = function flushBackBuffer() {\n                var CiderHls = this.CiderHls,\n                  details = this.details,\n                  media = this.media,\n                  sourceBuffer = this.sourceBuffer;\n\n                if (!media || details === null) {\n                  return;\n                }\n\n                var sourceBufferTypes = this.getSourceBufferTypes();\n\n                if (!sourceBufferTypes.length) {\n                  return;\n                } // Support for deprecated liveBackBufferLength\n\n                var backBufferLength = details.live && CiderHls.config.liveBackBufferLength !== null ? CiderHls.config.liveBackBufferLength : CiderHls.config.backBufferLength;\n\n                if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(backBufferLength) || backBufferLength < 0) {\n                  return;\n                }\n\n                var currentTime = media.currentTime;\n                var targetDuration = details.levelTargetDuration;\n                var maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n                var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;\n                sourceBufferTypes.forEach(function (type) {\n                  var sb = sourceBuffer[type];\n\n                  if (sb) {\n                    var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__[\"BufferHelper\"].getBuffered(sb); // when target buffer start exceeds actual buffer start\n\n                    if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {\n                      CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BACK_BUFFER_REACHED, {\n                        bufferEnd: targetBackBufferPosition,\n                      }); // Support for deprecated event:\n\n                      if (details.live) {\n                        CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LIVE_BACK_BUFFER_REACHED, {\n                          bufferEnd: targetBackBufferPosition,\n                        });\n                      }\n\n                      CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_FLUSHING, {\n                        startOffset: 0,\n                        endOffset: targetBackBufferPosition,\n                        type: type,\n                      });\n                    }\n                  }\n                });\n              };\n              /**\n               * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n               * 'liveDurationInfinity` is set to `true`\n               * More details: https://github.com/video-dev/CiderHls.js/issues/355\n               */\n\n              _proto.updateMediaElementDuration = function updateMediaElementDuration() {\n                if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== \"open\") {\n                  return;\n                }\n\n                var details = this.details,\n                  CiderHls = this.CiderHls,\n                  media = this.media,\n                  mediaSource = this.mediaSource;\n                var levelDuration = details.fragments[0].start + details.totalduration;\n                var mediaDuration = media.duration;\n                var msDuration = Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(mediaSource.duration) ? mediaSource.duration : 0;\n\n                if (details.live && CiderHls.config.liveDurationInfinity) {\n                  // Override duration to Infinity\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Media Source duration is set to Infinity\");\n                  mediaSource.duration = Infinity;\n                  this.updateSeekableRange(details);\n                } else if ((levelDuration > msDuration && levelDuration > mediaDuration) || !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(mediaDuration)) {\n                  // levelDuration was the last value we set.\n                  // not using mediaSource.duration as the browser may tweak this value\n                  // only update Media Source duration if its value increase, this is to avoid\n                  // flushing already buffered portion when switching between quality level\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Updating Media Source duration to \" + levelDuration.toFixed(3));\n                  mediaSource.duration = levelDuration;\n                }\n              };\n\n              _proto.updateSeekableRange = function updateSeekableRange(levelDetails) {\n                var mediaSource = this.mediaSource;\n                var fragments = levelDetails.fragments;\n                var len = fragments.length;\n\n                if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {\n                  var start = Math.max(0, fragments[0].start);\n                  var end = Math.max(start, start + levelDetails.totalduration);\n                  mediaSource.setLiveSeekableRange(start, end);\n                }\n              };\n\n              _proto.checkPendingTracks = function checkPendingTracks() {\n                var bufferCodecEventsExpected = this.bufferCodecEventsExpected,\n                  operationQueue = this.operationQueue,\n                  pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n                // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n                // data has been appended to existing ones.\n                // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n\n                var pendingTracksCount = Object.keys(pendingTracks).length;\n\n                if ((pendingTracksCount && !bufferCodecEventsExpected) || pendingTracksCount === 2) {\n                  // ok, let's create them now !\n                  this.createSourceBuffers(pendingTracks);\n                  this.pendingTracks = {}; // append any pending segments now !\n\n                  var buffers = this.getSourceBufferTypes();\n\n                  if (buffers.length === 0) {\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorTypes\"].MEDIA_ERROR,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorDetails\"].BUFFER_INCOMPATIBLE_CODECS_ERROR,\n                      fatal: true,\n                      reason: \"could not create source buffer for media codec(s)\",\n                    });\n                    return;\n                  }\n\n                  buffers.forEach(function (type) {\n                    operationQueue.executeNext(type);\n                  });\n                }\n              };\n\n              _proto.createSourceBuffers = function createSourceBuffers(tracks) {\n                var sourceBuffer = this.sourceBuffer,\n                  mediaSource = this.mediaSource;\n\n                if (!mediaSource) {\n                  throw Error(\"createSourceBuffers called when mediaSource was null\");\n                }\n\n                var tracksCreated = 0;\n\n                for (var trackName in tracks) {\n                  if (!sourceBuffer[trackName]) {\n                    var track = tracks[trackName];\n\n                    if (!track) {\n                      throw Error(\"source buffer exists for track \" + trackName + \", however track does not\");\n                    } // use levelCodec as first priority\n\n                    var codec = track.levelCodec || track.codec;\n                    var mimeType = track.container + \";codecs=\" + codec;\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: creating sourceBuffer(\" + mimeType + \")\");\n\n                    try {\n                      var sb = (sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType));\n                      var sbName = trackName;\n                      this.addBufferListener(sbName, \"updatestart\", this._onSBUpdateStart);\n                      this.addBufferListener(sbName, \"updateend\", this._onSBUpdateEnd);\n                      this.addBufferListener(sbName, \"error\", this._onSBUpdateError);\n                      this.tracks[trackName] = {\n                        buffer: sb,\n                        codec: codec,\n                        container: track.container,\n                        levelCodec: track.levelCodec,\n                        id: track.id,\n                      };\n                      tracksCreated++;\n                    } catch (err) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"[buffer-controller]: error while trying to add sourceBuffer: \" + err.message);\n                      this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                        type: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorTypes\"].MEDIA_ERROR,\n                        details: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorDetails\"].BUFFER_ADD_CODEC_ERROR,\n                        fatal: false,\n                        error: err,\n                        mimeType: mimeType,\n                      });\n                    }\n                  }\n                }\n\n                if (tracksCreated) {\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_CREATED, {\n                    tracks: this.tracks,\n                  });\n                }\n              }; // Keep as arrow functions so that we can directly reference these functions directly as event listeners\n\n              _proto._onSBUpdateStart = function _onSBUpdateStart(type) {\n                var operationQueue = this.operationQueue;\n                var operation = operationQueue.current(type);\n                operation.onStart();\n              };\n\n              _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {\n                var operationQueue = this.operationQueue;\n                var operation = operationQueue.current(type);\n                operation.onComplete();\n                operationQueue.shiftAndExecuteNext(type);\n              };\n\n              _proto._onSBUpdateError = function _onSBUpdateError(type, event) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"[buffer-controller]: \" + type + \" SourceBuffer error\", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n                // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event\n\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                  type: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorTypes\"].MEDIA_ERROR,\n                  details: _errors__WEBPACK_IMPORTED_MODULE_3__[\"ErrorDetails\"].BUFFER_APPENDING_ERROR,\n                  fatal: false,\n                }); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue\n\n                var operation = this.operationQueue.current(type);\n\n                if (operation) {\n                  operation.onError(event);\n                }\n              }; // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually\n\n              _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {\n                var media = this.media,\n                  mediaSource = this.mediaSource,\n                  operationQueue = this.operationQueue,\n                  sourceBuffer = this.sourceBuffer;\n                var sb = sourceBuffer[type];\n\n                if (!media || !mediaSource || !sb) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: Attempting to remove from the \" + type + \" SourceBuffer, but it does not exist\");\n                  operationQueue.shiftAndExecuteNext(type);\n                  return;\n                }\n\n                var mediaDuration = Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(media.duration) ? media.duration : Infinity;\n                var msDuration = Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(mediaSource.duration) ? mediaSource.duration : Infinity;\n                var removeStart = Math.max(0, startOffset);\n                var removeEnd = Math.min(endOffset, mediaDuration, msDuration);\n\n                if (removeEnd > removeStart) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Removing [\" + removeStart + \",\" + removeEnd + \"] from the \" + type + \" SourceBuffer\");\n                  console.assert(!sb.updating, type + \" sourceBuffer must not be updating\");\n                  sb.remove(removeStart, removeEnd);\n                } else {\n                  // Cycle the queue\n                  operationQueue.shiftAndExecuteNext(type);\n                }\n              }; // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually\n\n              _proto.appendExecutor = function appendExecutor(data, type) {\n                var operationQueue = this.operationQueue,\n                  sourceBuffer = this.sourceBuffer;\n                var sb = sourceBuffer[type];\n\n                if (!sb) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[buffer-controller]: Attempting to append to the \" + type + \" SourceBuffer, but it does not exist\");\n                  operationQueue.shiftAndExecuteNext(type);\n                  return;\n                }\n\n                sb.ended = false;\n                console.assert(!sb.updating, type + \" sourceBuffer must not be updating\");\n                sb.appendBuffer(data);\n              }; // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises\n              // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue\n              // upon completion, since we already do it here\n\n              _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {\n                var _this9 = this;\n\n                if (buffers === void 0) {\n                  buffers = this.getSourceBufferTypes();\n                }\n\n                if (!buffers.length) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"[buffer-controller]: Blocking operation requested, but no SourceBuffers exist\");\n                  Promise.resolve(onUnblocked);\n                  return;\n                }\n\n                var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);\n\n                var blockingOperations = buffers.map(function (type) {\n                  return operationQueue.appendBlocker(type);\n                });\n                Promise.all(blockingOperations).then(function () {\n                  // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);\n                  onUnblocked();\n                  buffers.forEach(function (type) {\n                    var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to\n                    // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)\n                    // While this is a workaround, it's probably useful to have around\n\n                    if (!sb || !sb.updating) {\n                      operationQueue.shiftAndExecuteNext(type);\n                    }\n                  });\n                });\n              };\n\n              _proto.getSourceBufferTypes = function getSourceBufferTypes() {\n                return Object.keys(this.sourceBuffer);\n              };\n\n              _proto.addBufferListener = function addBufferListener(type, event, fn) {\n                var buffer = this.sourceBuffer[type];\n\n                if (!buffer) {\n                  return;\n                }\n\n                var listener = fn.bind(this, type);\n                this.listeners[type].push({\n                  event: event,\n                  listener: listener,\n                });\n                buffer.addEventListener(event, listener);\n              };\n\n              _proto.removeBufferListeners = function removeBufferListeners(type) {\n                var buffer = this.sourceBuffer[type];\n\n                if (!buffer) {\n                  return;\n                }\n\n                this.listeners[type].forEach(function (l) {\n                  buffer.removeEventListener(l.event, l.listener);\n                });\n              };\n\n              return BufferController;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/controller/buffer-operation-queue.ts\":\n          /*!**************************************************!*\\\n  !*** ./src/controller/buffer-operation-queue.ts ***!\n  \\**************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return BufferOperationQueue;\n            });\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            var BufferOperationQueue = /*#__PURE__*/ (function () {\n              function BufferOperationQueue(sourceBufferReference) {\n                this.buffers = void 0;\n                this.queues = {\n                  video: [],\n                  audio: [],\n                  audiovideo: [],\n                };\n                this.buffers = sourceBufferReference;\n              }\n\n              var _proto = BufferOperationQueue.prototype;\n\n              _proto.append = function append(operation, type) {\n                var queue = this.queues[type];\n                queue.push(operation);\n\n                if (queue.length === 1 && this.buffers[type]) {\n                  this.executeNext(type);\n                }\n              };\n\n              _proto.insertAbort = function insertAbort(operation, type) {\n                var queue = this.queues[type];\n                queue.unshift(operation);\n                this.executeNext(type);\n              };\n\n              _proto.appendBlocker = function appendBlocker(type) {\n                var execute;\n                var promise = new Promise(function (resolve) {\n                  execute = resolve;\n                });\n                var operation = {\n                  execute: execute,\n                  onStart: function onStart() {},\n                  onComplete: function onComplete() {},\n                  onError: function onError() {},\n                };\n                this.append(operation, type);\n                return promise;\n              };\n\n              _proto.executeNext = function executeNext(type) {\n                var buffers = this.buffers,\n                  queues = this.queues;\n                var sb = buffers[type];\n                var queue = queues[type];\n\n                if (queue.length) {\n                  var operation = queue[0];\n\n                  try {\n                    // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations\n                    // which do not end with this event must call _onSBUpdateEnd manually\n                    operation.execute();\n                  } catch (e) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].warn(\"[buffer-operation-queue]: Unhandled exception executing the current operation\");\n                    operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us\n\n                    if (!sb || !sb.updating) {\n                      queue.shift();\n                      this.executeNext(type);\n                    }\n                  }\n                }\n              };\n\n              _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {\n                this.queues[type].shift();\n                this.executeNext(type);\n              };\n\n              _proto.current = function current(type) {\n                return this.queues[type][0];\n              };\n\n              return BufferOperationQueue;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/controller/cap-level-controller.ts\":\n          /*!************************************************!*\\\n  !*** ./src/controller/cap-level-controller.ts ***!\n  \\************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            /*\n             * cap stream level to media size dimension controller\n             */\n\n            var CapLevelController = /*#__PURE__*/ (function () {\n              function CapLevelController(CiderHls) {\n                this.autoLevelCapping = void 0;\n                this.firstLevel = void 0;\n                this.media = void 0;\n                this.restrictedLevels = void 0;\n                this.timer = void 0;\n                this.CiderHls = void 0;\n                this.streamController = void 0;\n                this.clientRect = void 0;\n                this.CiderHls = CiderHls;\n                this.autoLevelCapping = Number.POSITIVE_INFINITY;\n                this.firstLevel = -1;\n                this.media = null;\n                this.restrictedLevels = [];\n                this.timer = undefined;\n                this.clientRect = null;\n                this.registerListeners();\n              }\n\n              var _proto = CapLevelController.prototype;\n\n              _proto.setStreamController = function setStreamController(streamController) {\n                this.streamController = streamController;\n              };\n\n              _proto.destroy = function destroy() {\n                this.unregisterListener();\n\n                if (this.CiderHls.config.capLevelToPlayerSize) {\n                  this.stopCapping();\n                }\n\n                this.media = null;\n                this.clientRect = null; // @ts-ignore\n\n                this.CiderHls = this.streamController = null;\n              };\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_CODECS, this.onBufferCodecs, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n              };\n\n              _proto.unregisterListener = function unregisterListener() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_CODECS, this.onBufferCodecs, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n              };\n\n              _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {\n                // Don't add a restricted level more than once\n                if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\n                  this.restrictedLevels.push(data.droppedLevel);\n                }\n              };\n\n              _proto.onMediaAttaching = function onMediaAttaching(event, data) {\n                this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n              };\n\n              _proto.onManifestParsed = function onManifestParsed(event, data) {\n                var CiderHls = this.CiderHls;\n                this.restrictedLevels = [];\n                this.firstLevel = data.firstLevel;\n\n                if (CiderHls.config.capLevelToPlayerSize && data.video) {\n                  // Start capping immediately if the manifest has signaled video codecs\n                  this.startCapping();\n                }\n              }; // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n              // to the first level\n\n              _proto.onBufferCodecs = function onBufferCodecs(event, data) {\n                var CiderHls = this.CiderHls;\n\n                if (CiderHls.config.capLevelToPlayerSize && data.video) {\n                  // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n                  this.startCapping();\n                }\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                this.stopCapping();\n              };\n\n              _proto.detectPlayerSize = function detectPlayerSize() {\n                if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {\n                  var levels = this.CiderHls.levels;\n\n                  if (levels.length) {\n                    var CiderHls = this.CiderHls;\n                    CiderHls.autoLevelCapping = this.getMaxLevel(levels.length - 1);\n\n                    if (CiderHls.autoLevelCapping > this.autoLevelCapping && this.streamController) {\n                      // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n                      // usually happen when the user go to the fullscreen mode.\n                      this.streamController.nextLevelSwitch();\n                    }\n\n                    this.autoLevelCapping = CiderHls.autoLevelCapping;\n                  }\n                }\n              };\n              /*\n               * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n               */\n\n              _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {\n                var _this = this;\n\n                var levels = this.CiderHls.levels;\n\n                if (!levels.length) {\n                  return -1;\n                }\n\n                var validLevels = levels.filter(function (level, index) {\n                  return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;\n                });\n                this.clientRect = null;\n                return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n              };\n\n              _proto.startCapping = function startCapping() {\n                if (this.timer) {\n                  // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n                  return;\n                }\n\n                this.autoLevelCapping = Number.POSITIVE_INFINITY;\n                this.CiderHls.firstLevel = this.getMaxLevel(this.firstLevel);\n                self.clearInterval(this.timer);\n                this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);\n                this.detectPlayerSize();\n              };\n\n              _proto.stopCapping = function stopCapping() {\n                this.restrictedLevels = [];\n                this.firstLevel = -1;\n                this.autoLevelCapping = Number.POSITIVE_INFINITY;\n\n                if (this.timer) {\n                  self.clearInterval(this.timer);\n                  this.timer = undefined;\n                }\n              };\n\n              _proto.getDimensions = function getDimensions() {\n                if (this.clientRect) {\n                  return this.clientRect;\n                }\n\n                var media = this.media;\n                var boundsRect = {\n                  width: 0,\n                  height: 0,\n                };\n\n                if (media) {\n                  var clientRect = media.getBoundingClientRect();\n                  boundsRect.width = clientRect.width;\n                  boundsRect.height = clientRect.height;\n\n                  if (!boundsRect.width && !boundsRect.height) {\n                    // When the media element has no width or height (equivalent to not being in the DOM),\n                    // then use its width and height attributes (media.width, media.height)\n                    boundsRect.width = clientRect.right - clientRect.left || media.width || 0;\n                    boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;\n                  }\n                }\n\n                this.clientRect = boundsRect;\n                return boundsRect;\n              };\n\n              CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {\n                if (restrictedLevels === void 0) {\n                  restrictedLevels = [];\n                }\n\n                return restrictedLevels.indexOf(level) === -1;\n              };\n\n              CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {\n                if (!levels || !levels.length) {\n                  return -1;\n                } // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n                // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n\n                var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {\n                  if (!nextLevel) {\n                    return true;\n                  }\n\n                  return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n                }; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n                // the max level\n\n                var maxLevelIndex = levels.length - 1;\n\n                for (var i = 0; i < levels.length; i += 1) {\n                  var level = levels[i];\n\n                  if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n                    maxLevelIndex = i;\n                    break;\n                  }\n                }\n\n                return maxLevelIndex;\n              };\n\n              _createClass(\n                CapLevelController,\n                [\n                  {\n                    key: \"mediaWidth\",\n                    get: function get() {\n                      return this.getDimensions().width * CapLevelController.contentScaleFactor;\n                    },\n                  },\n                  {\n                    key: \"mediaHeight\",\n                    get: function get() {\n                      return this.getDimensions().height * CapLevelController.contentScaleFactor;\n                    },\n                  },\n                ],\n                [\n                  {\n                    key: \"contentScaleFactor\",\n                    get: function get() {\n                      var pixelRatio = 1;\n\n                      try {\n                        pixelRatio = self.devicePixelRatio;\n                      } catch (e) {\n                        /* no-op */\n                      }\n\n                      return pixelRatio;\n                    },\n                  },\n                ]\n              );\n\n              return CapLevelController;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = CapLevelController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/cmcd-controller.ts\":\n          /*!*******************************************!*\\\n  !*** ./src/controller/cmcd-controller.ts ***!\n  \\*******************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return CMCDController;\n            });\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _types_cmcd__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/cmcd */ \"./src/types/cmcd.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _createForOfIteratorHelperLoose(o, allowArrayLike) {\n              var it = (typeof Symbol !== \"undefined\" && o[Symbol.iterator]) || o[\"@@iterator\"];\n              if (it) return (it = it.call(o)).next.bind(it);\n              if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || (allowArrayLike && o && typeof o.length === \"number\")) {\n                if (it) o = it;\n                var i = 0;\n                return function () {\n                  if (i >= o.length) return { done: true };\n                  return { done: false, value: o[i++] };\n                };\n              }\n              throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n            }\n\n            function _unsupportedIterableToArray(o, minLen) {\n              if (!o) return;\n              if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n              var n = Object.prototype.toString.call(o).slice(8, -1);\n              if (n === \"Object\" && o.constructor) n = o.constructor.name;\n              if (n === \"Map\" || n === \"Set\") return Array.from(o);\n              if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n            }\n\n            function _arrayLikeToArray(arr, len) {\n              if (len == null || len > arr.length) len = arr.length;\n              for (var i = 0, arr2 = new Array(len); i < len; i++) {\n                arr2[i] = arr[i];\n              }\n              return arr2;\n            }\n\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            /**\n             * Controller to deal with Common Media Client Data (CMCD)\n             * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf\n             */\n\n            var CMCDController = /*#__PURE__*/ (function () {\n              // eslint-disable-line no-restricted-globals\n              // eslint-disable-line no-restricted-globals\n              function CMCDController(CiderHls) {\n                var _this = this;\n\n                this.CiderHls = void 0;\n                this.config = void 0;\n                this.media = void 0;\n                this.sid = void 0;\n                this.cid = void 0;\n                this.useHeaders = false;\n                this.initialized = false;\n                this.starved = false;\n                this.buffering = true;\n                this.audioBuffer = void 0;\n                this.videoBuffer = void 0;\n\n                this.onWaiting = function () {\n                  if (_this.initialized) {\n                    _this.starved = true;\n                  }\n\n                  _this.buffering = true;\n                };\n\n                this.onPlaying = function () {\n                  if (!_this.initialized) {\n                    _this.initialized = true;\n                  }\n\n                  _this.buffering = false;\n                };\n\n                this.applyPlaylistData = function (context) {\n                  try {\n                    _this.apply(context, {\n                      ot: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].MANIFEST,\n                      su: !_this.initialized,\n                    });\n                  } catch (error) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Could not generate manifest CMCD data.\", error);\n                  }\n                };\n\n                this.applyFragmentData = function (context) {\n                  try {\n                    var fragment = context.frag;\n                    var level = _this.CiderHls.levels[fragment.level];\n\n                    var ot = _this.getObjectType(fragment);\n\n                    var data = {\n                      d: fragment.duration * 1000,\n                      ot: ot,\n                    };\n\n                    if (ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].VIDEO || ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].AUDIO || ot == _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].MUXED) {\n                      data.br = level.bitrate / 1000;\n                      data.tb = _this.getTopBandwidth(ot);\n                      data.bl = _this.getBufferLength(ot);\n                    }\n\n                    _this.apply(context, data);\n                  } catch (error) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Could not generate segment CMCD data.\", error);\n                  }\n                };\n\n                this.CiderHls = CiderHls;\n                var config = (this.config = CiderHls.config);\n                var cmcd = config.cmcd;\n\n                if (cmcd != null) {\n                  config.pLoader = this.createPlaylistLoader();\n                  config.fLoader = this.createFragmentLoader();\n                  this.sid = cmcd.sessionId || CMCDController.uuid();\n                  this.cid = cmcd.contentId;\n                  this.useHeaders = cmcd.useHeaders === true;\n                  this.registerListeners();\n                }\n              }\n\n              var _proto = CMCDController.prototype;\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHED, this.onMediaDetached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_CREATED, this.onBufferCreated, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHED, this.onMediaDetached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_CREATED, this.onBufferCreated, this);\n                this.onMediaDetached();\n              };\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners(); // @ts-ignore\n\n                this.CiderHls = this.config = this.audioBuffer = this.videoBuffer = null;\n              };\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                this.media = data.media;\n                this.media.addEventListener(\"waiting\", this.onWaiting);\n                this.media.addEventListener(\"playing\", this.onPlaying);\n              };\n\n              _proto.onMediaDetached = function onMediaDetached() {\n                if (!this.media) {\n                  return;\n                }\n\n                this.media.removeEventListener(\"waiting\", this.onWaiting);\n                this.media.removeEventListener(\"playing\", this.onPlaying); // @ts-ignore\n\n                this.media = null;\n              };\n\n              _proto.onBufferCreated = function onBufferCreated(event, data) {\n                var _data$tracks$audio, _data$tracks$video;\n\n                this.audioBuffer = (_data$tracks$audio = data.tracks.audio) === null || _data$tracks$audio === void 0 ? void 0 : _data$tracks$audio.buffer;\n                this.videoBuffer = (_data$tracks$video = data.tracks.video) === null || _data$tracks$video === void 0 ? void 0 : _data$tracks$video.buffer;\n              };\n\n              /**\n               * Create baseline CMCD data\n               */\n              _proto.createData = function createData() {\n                var _this$media;\n\n                return {\n                  v: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDVersion\"],\n                  sf: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDStreamingFormat\"].CiderHls,\n                  sid: this.sid,\n                  cid: this.cid,\n                  pr: (_this$media = this.media) === null || _this$media === void 0 ? void 0 : _this$media.playbackRate,\n                  mtp: this.CiderHls.bandwidthEstimate / 1000,\n                };\n              };\n              /**\n               * Apply CMCD data to a request.\n               */\n\n              _proto.apply = function apply(context, data) {\n                if (data === void 0) {\n                  data = {};\n                }\n\n                // apply baseline data\n                _extends(data, this.createData());\n\n                var isVideo = data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].INIT || data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].VIDEO || data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].MUXED;\n\n                if (this.starved && isVideo) {\n                  data.bs = true;\n                  data.su = true;\n                  this.starved = false;\n                }\n\n                if (data.su == null) {\n                  data.su = this.buffering;\n                } // TODO: Implement rtp, nrr, nor, dl\n\n                if (this.useHeaders) {\n                  var headers = CMCDController.toHeaders(data);\n\n                  if (!Object.keys(headers).length) {\n                    return;\n                  }\n\n                  if (!context.headers) {\n                    context.headers = {};\n                  }\n\n                  _extends(context.headers, headers);\n                } else {\n                  var query = CMCDController.toQuery(data);\n\n                  if (!query) {\n                    return;\n                  }\n\n                  context.url = CMCDController.appendQueryToUri(context.url, query);\n                }\n              };\n              /**\n               * Apply CMCD data to a manifest request.\n               */\n\n              /**\n               * The CMCD object type.\n               */\n              _proto.getObjectType = function getObjectType(fragment) {\n                var type = fragment.type;\n\n                if (type === \"subtitle\") {\n                  return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].TIMED_TEXT;\n                }\n\n                if (fragment.sn === \"initSegment\") {\n                  return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].INIT;\n                }\n\n                if (type === \"audio\") {\n                  return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].AUDIO;\n                }\n\n                if (type === \"main\") {\n                  if (!this.CiderHls.audioTracks.length) {\n                    return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].MUXED;\n                  }\n\n                  return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].VIDEO;\n                }\n\n                return undefined;\n              };\n              /**\n               * Get the highest bitrate.\n               */\n\n              _proto.getTopBandwidth = function getTopBandwidth(type) {\n                var bitrate = 0;\n                var levels = type === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].AUDIO ? this.CiderHls.audioTracks : this.CiderHls.levels;\n\n                for (var _iterator = _createForOfIteratorHelperLoose(levels), _step; !(_step = _iterator()).done; ) {\n                  var level = _step.value;\n\n                  if (level.bitrate > bitrate) {\n                    bitrate = level.bitrate;\n                  }\n                }\n\n                return bitrate > 0 ? bitrate : NaN;\n              };\n              /**\n               * Get the buffer length for a media type in milliseconds\n               */\n\n              _proto.getBufferLength = function getBufferLength(type) {\n                var media = this.CiderHls.media;\n                var buffer = type === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__[\"CMCDObjectType\"].AUDIO ? this.audioBuffer : this.videoBuffer;\n\n                if (!buffer || !media) {\n                  return NaN;\n                }\n\n                var info = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__[\"BufferHelper\"].bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);\n                return info.len * 1000;\n              };\n              /**\n               * Create a playlist loader\n               */\n\n              _proto.createPlaylistLoader = function createPlaylistLoader() {\n                var pLoader = this.config.pLoader;\n                var apply = this.applyPlaylistData;\n                var Ctor = pLoader || this.config.loader;\n                return /*#__PURE__*/ (function () {\n                  function CmcdPlaylistLoader(config) {\n                    this.loader = void 0;\n                    this.loader = new Ctor(config);\n                  }\n\n                  var _proto2 = CmcdPlaylistLoader.prototype;\n\n                  _proto2.destroy = function destroy() {\n                    this.loader.destroy();\n                  };\n\n                  _proto2.abort = function abort() {\n                    this.loader.abort();\n                  };\n\n                  _proto2.load = function load(context, config, callbacks) {\n                    apply(context);\n                    this.loader.load(context, config, callbacks);\n                  };\n\n                  _createClass(CmcdPlaylistLoader, [\n                    {\n                      key: \"stats\",\n                      get: function get() {\n                        return this.loader.stats;\n                      },\n                    },\n                    {\n                      key: \"context\",\n                      get: function get() {\n                        return this.loader.context;\n                      },\n                    },\n                  ]);\n\n                  return CmcdPlaylistLoader;\n                })();\n              };\n              /**\n               * Create a playlist loader\n               */\n\n              _proto.createFragmentLoader = function createFragmentLoader() {\n                var fLoader = this.config.fLoader;\n                var apply = this.applyFragmentData;\n                var Ctor = fLoader || this.config.loader;\n                return /*#__PURE__*/ (function () {\n                  function CmcdFragmentLoader(config) {\n                    this.loader = void 0;\n                    this.loader = new Ctor(config);\n                  }\n\n                  var _proto3 = CmcdFragmentLoader.prototype;\n\n                  _proto3.destroy = function destroy() {\n                    this.loader.destroy();\n                  };\n\n                  _proto3.abort = function abort() {\n                    this.loader.abort();\n                  };\n\n                  _proto3.load = function load(context, config, callbacks) {\n                    apply(context);\n                    this.loader.load(context, config, callbacks);\n                  };\n\n                  _createClass(CmcdFragmentLoader, [\n                    {\n                      key: \"stats\",\n                      get: function get() {\n                        return this.loader.stats;\n                      },\n                    },\n                    {\n                      key: \"context\",\n                      get: function get() {\n                        return this.loader.context;\n                      },\n                    },\n                  ]);\n\n                  return CmcdFragmentLoader;\n                })();\n              };\n              /**\n               * Generate a random v4 UUI\n               *\n               * @returns {string}\n               */\n\n              CMCDController.uuid = function uuid() {\n                var url = URL.createObjectURL(new Blob());\n                var uuid = url.toString();\n                URL.revokeObjectURL(url);\n                return uuid.substr(uuid.lastIndexOf(\"/\") + 1);\n              };\n              /**\n               * Serialize a CMCD data object according to the rules defined in the\n               * section 3.2 of\n               * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n               */\n\n              CMCDController.serialize = function serialize(data) {\n                var results = [];\n\n                var isValid = function isValid(value) {\n                  return !Number.isNaN(value) && value != null && value !== \"\" && value !== false;\n                };\n\n                var toRounded = function toRounded(value) {\n                  return Math.round(value);\n                };\n\n                var toHundred = function toHundred(value) {\n                  return toRounded(value / 100) * 100;\n                };\n\n                var toUrlSafe = function toUrlSafe(value) {\n                  return encodeURIComponent(value);\n                };\n\n                var formatters = {\n                  br: toRounded,\n                  d: toRounded,\n                  bl: toHundred,\n                  dl: toHundred,\n                  mtp: toHundred,\n                  nor: toUrlSafe,\n                  rtp: toHundred,\n                  tb: toRounded,\n                };\n                var keys = Object.keys(data || {}).sort();\n\n                for (var _iterator2 = _createForOfIteratorHelperLoose(keys), _step2; !(_step2 = _iterator2()).done; ) {\n                  var key = _step2.value;\n                  var value = data[key]; // ignore invalid values\n\n                  if (!isValid(value)) {\n                    continue;\n                  } // Version should only be reported if not equal to 1.\n\n                  if (key === \"v\" && value === 1) {\n                    continue;\n                  } // Playback rate should only be sent if not equal to 1.\n\n                  if (key == \"pr\" && value === 1) {\n                    continue;\n                  } // Certain values require special formatting\n\n                  var formatter = formatters[key];\n\n                  if (formatter) {\n                    value = formatter(value);\n                  } // Serialize the key/value pair\n\n                  var type = typeof value;\n                  var result = void 0;\n\n                  if (key === \"ot\" || key === \"sf\" || key === \"st\") {\n                    result = key + \"=\" + value;\n                  } else if (type === \"boolean\") {\n                    result = key;\n                  } else if (type === \"number\") {\n                    result = key + \"=\" + value;\n                  } else {\n                    result = key + \"=\" + JSON.stringify(value);\n                  }\n\n                  results.push(result);\n                }\n\n                return results.join(\",\");\n              };\n              /**\n               * Convert a CMCD data object to request headers according to the rules\n               * defined in the section 2.1 and 3.2 of\n               * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n               */\n\n              CMCDController.toHeaders = function toHeaders(data) {\n                var keys = Object.keys(data);\n                var headers = {};\n                var headerNames = [\"Object\", \"Request\", \"Session\", \"Status\"];\n                var headerGroups = [{}, {}, {}, {}];\n                var headerMap = {\n                  br: 0,\n                  d: 0,\n                  ot: 0,\n                  tb: 0,\n                  bl: 1,\n                  dl: 1,\n                  mtp: 1,\n                  nor: 1,\n                  nrr: 1,\n                  su: 1,\n                  cid: 2,\n                  pr: 2,\n                  sf: 2,\n                  sid: 2,\n                  st: 2,\n                  v: 2,\n                  bs: 3,\n                  rtp: 3,\n                };\n\n                for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {\n                  var key = _keys[_i];\n                  // Unmapped fields are mapped to the Request header\n                  var index = headerMap[key] != null ? headerMap[key] : 1;\n                  headerGroups[index][key] = data[key];\n                }\n\n                for (var i = 0; i < headerGroups.length; i++) {\n                  var value = CMCDController.serialize(headerGroups[i]);\n\n                  if (value) {\n                    headers[\"CMCD-\" + headerNames[i]] = value;\n                  }\n                }\n\n                return headers;\n              };\n              /**\n               * Convert a CMCD data object to query args according to the rules\n               * defined in the section 2.2 and 3.2 of\n               * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n               */\n\n              CMCDController.toQuery = function toQuery(data) {\n                return \"CMCD=\" + encodeURIComponent(CMCDController.serialize(data));\n              };\n              /**\n               * Append query args to a uri.\n               */\n\n              CMCDController.appendQueryToUri = function appendQueryToUri(uri, query) {\n                if (!query) {\n                  return uri;\n                }\n\n                var separator = uri.includes(\"?\") ? \"&\" : \"?\";\n                return \"\" + uri + separator + query;\n              };\n\n              return CMCDController;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/controller/eme-controller.ts\":\n          /*!******************************************!*\\\n  !*** ./src/controller/eme-controller.ts ***!\n  \\******************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mediakeys-helper */ \"./src/utils/mediakeys-helper.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            /**\n             * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n             *\n             * DRM support for CiderHls.js\n             */\n\n            var MAX_LICENSE_REQUEST_FAILURES = 3;\n            /**\n             * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n             * @param {Array<string>} audioCodecs List of required audio codecs to support\n             * @param {Array<string>} videoCodecs List of required video codecs to support\n             * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n             * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n             */\n\n            var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {\n              /* jshint ignore:line */\n              var baseConfig = {\n                // initDataTypes: ['keyids', 'mp4'],\n                // label: \"\",\n                // persistentState: \"not-allowed\", // or \"required\" ?\n                // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n                // sessionTypes: ['temporary'],\n                audioCapabilities: [],\n                // { contentType: 'audio/mp4; codecs=\"mp4a.40.2\"' }\n                videoCapabilities: [], // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n              };\n              audioCodecs.forEach(function (codec) {\n                baseConfig.audioCapabilities.push({\n                  contentType: 'audio/mp4; codecs=\"' + codec + '\"',\n                  robustness: drmSystemOptions.audioRobustness || \"\",\n                });\n              });\n              videoCodecs.forEach(function (codec) {\n                baseConfig.videoCapabilities.push({\n                  contentType: 'video/mp4; codecs=\"' + codec + '\"',\n                  robustness: drmSystemOptions.videoRobustness || \"\",\n                });\n              });\n              return [baseConfig];\n            };\n            /**\n             * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n             * in order to work with the local requestMediaKeySystemAccess method.\n             *\n             * We can also rule-out platform-related key-system support at this point by throwing an error.\n             *\n             * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n             * @param {Array<string>} audioCodecs List of required audio codecs to support\n             * @param {Array<string>} videoCodecs List of required video codecs to support\n             * @throws will throw an error if a unknown key system is passed\n             * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects\n             */\n\n            var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {\n              switch (keySystem) {\n                case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__[\"KeySystems\"].WIDEVINE:\n                  return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);\n\n                default:\n                  throw new Error(\"Unknown key-system: \" + keySystem);\n              }\n            };\n\n            /**\n             * Controller to deal with encrypted media extensions (EME)\n             * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n             *\n             * @class\n             * @constructor\n             */\n            var EMEController = /*#__PURE__*/ (function () {\n              /**\n               * @constructs\n               * @param {CiderHls} CiderHls Our CiderHls.js instance\n               */\n              function EMEController(CiderHls) {\n                this.CiderHls = void 0;\n                this._widevineLicenseUrl = void 0;\n                this._licenseXhrSetup = void 0;\n                this._licenseResponseCallback = void 0;\n                this._emeEnabled = void 0;\n                this._requestMediaKeySystemAccess = void 0;\n                this._drmSystemOptions = void 0;\n                this._config = void 0;\n                this._mediaKeysList = [];\n                this._media = null;\n                this._hasSetMediaKeys = false;\n                this._requestLicenseFailureCount = 0;\n                this.mediaKeysPromise = null;\n                this._onMediaEncrypted = this.onMediaEncrypted.bind(this);\n                this.CiderHls = CiderHls;\n                this._config = CiderHls.config;\n                this._widevineLicenseUrl = this._config.widevineLicenseUrl;\n                this._licenseXhrSetup = this._config.licenseXhrSetup;\n                this._licenseResponseCallback = this._config.licenseResponseCallback;\n                this._emeEnabled = this._config.emeEnabled;\n                this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;\n                this._drmSystemOptions = this._config.drmSystemOptions;\n\n                this._registerListeners();\n              }\n\n              var _proto = EMEController.prototype;\n\n              _proto.destroy = function destroy() {\n                this._unregisterListeners(); // @ts-ignore\n\n                this.CiderHls = this._onMediaEncrypted = null;\n                this._requestMediaKeySystemAccess = null;\n              };\n\n              _proto._registerListeners = function _registerListeners() {\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHED, this.onMediaDetached, this);\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHED, this.onMediaDetached, this);\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n              };\n              /**\n               * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n               * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n               * @throws if a unsupported keysystem is passed\n               */\n\n              _proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {\n                switch (keySystem) {\n                  case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__[\"KeySystems\"].WIDEVINE:\n                    if (!this._widevineLicenseUrl) {\n                      break;\n                    }\n\n                    return this._widevineLicenseUrl;\n                }\n\n                throw new Error('no license server URL configured for key-system \"' + keySystem + '\"');\n              };\n              /**\n               * Requests access object and adds it to our list upon success\n               * @private\n               * @param {string} keySystem System ID (see `KeySystems`)\n               * @param {Array<string>} audioCodecs List of required audio codecs to support\n               * @param {Array<string>} videoCodecs List of required video codecs to support\n               * @throws When a unsupported KeySystem is passed\n               */\n\n              _proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {\n                var _this = this;\n\n                // This can throw, but is caught in event handler callpath\n                var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"Requesting encrypted media key-system access\"); // expecting interface like window.navigator.requestMediaKeySystemAccess\n\n                var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);\n                this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {\n                  return _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);\n                });\n                keySystemAccessPromise.catch(function (err) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error('Failed to obtain key-system \"' + keySystem + '\" access:', err);\n                });\n              };\n\n              /**\n               * Handles obtaining access to a key-system\n               * @private\n               * @param {string} keySystem\n               * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n               */\n              _proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {\n                var _this2 = this;\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log('Access for key-system \"' + keySystem + '\" obtained');\n                var mediaKeysListItem = {\n                  mediaKeysSessionInitialized: false,\n                  mediaKeySystemAccess: mediaKeySystemAccess,\n                  mediaKeySystemDomain: keySystem,\n                };\n\n                this._mediaKeysList.push(mediaKeysListItem);\n\n                var mediaKeysPromise = Promise.resolve()\n                  .then(function () {\n                    return mediaKeySystemAccess.createMediaKeys();\n                  })\n                  .then(function (mediaKeys) {\n                    mediaKeysListItem.mediaKeys = mediaKeys;\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log('Media-keys created for key-system \"' + keySystem + '\"');\n\n                    _this2._onMediaKeysCreated();\n\n                    return mediaKeys;\n                  });\n                mediaKeysPromise.catch(function (err) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Failed to create media-keys:\", err);\n                });\n                return mediaKeysPromise;\n              };\n              /**\n               * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n               * for all existing keys where no session exists yet.\n               *\n               * @private\n               */\n\n              _proto._onMediaKeysCreated = function _onMediaKeysCreated() {\n                var _this3 = this;\n\n                // check for all key-list items if a session exists, otherwise, create one\n                this._mediaKeysList.forEach(function (mediaKeysListItem) {\n                  if (!mediaKeysListItem.mediaKeysSession) {\n                    // mediaKeys is definitely initialized here\n                    mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();\n\n                    _this3._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n                  }\n                });\n              };\n              /**\n               * @private\n               * @param {*} keySession\n               */\n\n              _proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {\n                var _this4 = this;\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"New key-system session \" + keySession.sessionId);\n                keySession.addEventListener(\n                  \"message\",\n                  function (event) {\n                    _this4._onKeySessionMessage(keySession, event.message);\n                  },\n                  false\n                );\n              };\n              /**\n               * @private\n               * @param {MediaKeySession} keySession\n               * @param {ArrayBuffer} message\n               */\n\n              _proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"Got EME message event, creating license request\");\n\n                this._requestLicense(message, function (data) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"Received license data (length: \" + (data ? data.byteLength : data) + \"), updating key-session\");\n                  keySession.update(data);\n                });\n              };\n              /**\n               * @private\n               * @param e {MediaEncryptedEvent}\n               */\n\n              _proto.onMediaEncrypted = function onMediaEncrypted(e) {\n                var _this5 = this;\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log('Media is encrypted using \"' + e.initDataType + '\" init data type');\n\n                if (!this.mediaKeysPromise) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Fatal: Media is encrypted but no CDM access or no keys have been requested\");\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_KEYS,\n                    fatal: true,\n                  });\n                  return;\n                }\n\n                var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {\n                  if (!_this5._media) {\n                    return;\n                  }\n\n                  _this5._attemptSetMediaKeys(mediaKeys);\n\n                  _this5._generateRequestWithPreferredKeySession(e.initDataType, e.initData);\n                }; // Could use `Promise.finally` but some Promise polyfills are missing it\n\n                this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);\n              };\n              /**\n               * @private\n               */\n\n              _proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {\n                if (!this._media) {\n                  throw new Error(\"Attempted to set mediaKeys without first attaching a media element\");\n                }\n\n                if (!this._hasSetMediaKeys) {\n                  // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n                  var keysListItem = this._mediaKeysList[0];\n\n                  if (!keysListItem || !keysListItem.mediaKeys) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Fatal: Media is encrypted but no CDM access or no keys have been obtained yet\");\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_KEYS,\n                      fatal: true,\n                    });\n                    return;\n                  }\n\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"Setting keys for encrypted media\");\n\n                  this._media.setMediaKeys(keysListItem.mediaKeys);\n\n                  this._hasSetMediaKeys = true;\n                }\n              };\n              /**\n               * @private\n               */\n\n              _proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {\n                var _this6 = this;\n\n                // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n                var keysListItem = this._mediaKeysList[0];\n\n                if (!keysListItem) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Fatal: Media is encrypted but not any key-system access has been obtained yet\");\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_ACCESS,\n                    fatal: true,\n                  });\n                  return;\n                }\n\n                if (keysListItem.mediaKeysSessionInitialized) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"Key-Session already initialized but requested again\");\n                  return;\n                }\n\n                var keySession = keysListItem.mediaKeysSession;\n\n                if (!keySession) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Fatal: Media is encrypted but no key-session existing\");\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_SESSION,\n                    fatal: true,\n                  });\n                  return;\n                } // initData is null if the media is not CORS-same-origin\n\n                if (!initData) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"Fatal: initData required for generating a key session is null\");\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_INIT_DATA,\n                    fatal: true,\n                  });\n                  return;\n                }\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log('Generating key-session request for \"' + initDataType + '\" init data type');\n                keysListItem.mediaKeysSessionInitialized = true;\n                keySession\n                  .generateRequest(initDataType, initData)\n                  .then(function () {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].debug(\"Key-session generation succeeded\");\n                  })\n                  .catch(function (err) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Error generating key-session request:\", err);\n\n                    _this6.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_SESSION,\n                      fatal: false,\n                    });\n                  });\n              };\n              /**\n               * @private\n               * @param {string} url License server URL\n               * @param {ArrayBuffer} keyMessage Message data issued by key-system\n               * @param {function} callback Called when XHR has succeeded\n               * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n               * @throws if XMLHttpRequest construction failed\n               */\n\n              _proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {\n                var xhr = new XMLHttpRequest();\n                xhr.responseType = \"arraybuffer\";\n                xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n                var licenseXhrSetup = this._licenseXhrSetup;\n\n                if (licenseXhrSetup) {\n                  try {\n                    licenseXhrSetup.call(this.CiderHls, xhr, url);\n                    licenseXhrSetup = undefined;\n                  } catch (e) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(e);\n                  }\n                }\n\n                try {\n                  // if licenseXhrSetup did not yet call open, let's do it now\n                  if (!xhr.readyState) {\n                    xhr.open(\"POST\", url, true);\n                  }\n\n                  if (licenseXhrSetup) {\n                    licenseXhrSetup.call(this.CiderHls, xhr, url);\n                  }\n                } catch (e) {\n                  // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n                  throw new Error(\"issue setting up KeySystem license XHR \" + e);\n                }\n\n                return xhr;\n              };\n              /**\n               * @private\n               * @param {XMLHttpRequest} xhr\n               * @param {string} url License server URL\n               * @param {ArrayBuffer} keyMessage Message data issued by key-system\n               * @param {function} callback Called when XHR has succeeded\n               */\n\n              _proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {\n                switch (xhr.readyState) {\n                  case 4:\n                    if (xhr.status === 200) {\n                      this._requestLicenseFailureCount = 0;\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"License request succeeded\");\n                      var _data = xhr.response;\n                      var licenseResponseCallback = this._licenseResponseCallback;\n\n                      if (licenseResponseCallback) {\n                        try {\n                          _data = licenseResponseCallback.call(this.CiderHls, xhr, url);\n                        } catch (e) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(e);\n                        }\n                      }\n\n                      callback(_data);\n                    } else {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"License Request XHR failed (\" + url + \"). Status: \" + xhr.status + \" (\" + xhr.statusText + \")\");\n                      this._requestLicenseFailureCount++;\n\n                      if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {\n                        this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n                          fatal: true,\n                        });\n                        return;\n                      }\n\n                      var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"Retrying license request, \" + attemptsLeft + \" attempts left\");\n\n                      this._requestLicense(keyMessage, callback);\n                    }\n\n                    break;\n                }\n              };\n              /**\n               * @private\n               * @param {MediaKeysListItem} keysListItem\n               * @param {ArrayBuffer} keyMessage\n               * @returns {ArrayBuffer} Challenge data posted to license server\n               * @throws if KeySystem is unsupported\n               */\n\n              _proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {\n                switch (keysListItem.mediaKeySystemDomain) {\n                  // case KeySystems.PLAYREADY:\n                  // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n\n                  /*\n      if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n        // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n        var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n        if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n            challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n        } else {\n            throw 'Cannot find <Challenge> in key message';\n        }\n        var headerNames = keyMessageXml.getElementsByTagName('name');\n        var headerValues = keyMessageXml.getElementsByTagName('value');\n        if (headerNames.length !== headerValues.length) {\n            throw 'Mismatched header <name>/<value> pair in key message';\n        }\n        for (var i = 0; i < headerNames.length; i++) {\n            xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n        }\n      }\n      break;\n      */\n                  case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__[\"KeySystems\"].WIDEVINE:\n                    // For Widevine CDMs, the challenge is the keyMessage.\n                    return keyMessage;\n                }\n\n                throw new Error(\"unsupported key-system: \" + keysListItem.mediaKeySystemDomain);\n              };\n              /**\n               * @private\n               * @param keyMessage\n               * @param callback\n               */\n\n              _proto._requestLicense = function _requestLicense(keyMessage, callback) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"Requesting content license for key-system\");\n                var keysListItem = this._mediaKeysList[0];\n\n                if (!keysListItem) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Fatal error: Media is encrypted but no key-system access has been obtained yet\");\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_NO_ACCESS,\n                    fatal: true,\n                  });\n                  return;\n                }\n\n                try {\n                  var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n\n                  var _xhr = this._createLicenseXhr(_url, keyMessage, callback);\n\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"Sending license request to URL: \" + _url);\n\n                  var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);\n\n                  _xhr.send(challenge);\n                } catch (e) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"Failure requesting DRM license: \" + e);\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].KEY_SYSTEM_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n                    fatal: true,\n                  });\n                }\n              };\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                if (!this._emeEnabled) {\n                  return;\n                }\n\n                var media = data.media; // keep reference of media\n\n                this._media = media;\n                media.addEventListener(\"encrypted\", this._onMediaEncrypted);\n              };\n\n              _proto.onMediaDetached = function onMediaDetached() {\n                var media = this._media;\n                var mediaKeysList = this._mediaKeysList;\n\n                if (!media) {\n                  return;\n                }\n\n                media.removeEventListener(\"encrypted\", this._onMediaEncrypted);\n                this._media = null;\n                this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.\n\n                Promise.all(\n                  mediaKeysList.map(function (mediaKeysListItem) {\n                    if (mediaKeysListItem.mediaKeysSession) {\n                      return mediaKeysListItem.mediaKeysSession.close().catch(function () {\n                        // Ignore errors when closing the sessions. Closing a session that\n                        // generated no key requests will throw an error.\n                      });\n                    }\n                  })\n                )\n                  .then(function () {\n                    return media.setMediaKeys(null);\n                  })\n                  .catch(function () {\n                    // Ignore any failures while removing media keys from the video element.\n                  });\n              };\n\n              _proto.onManifestParsed = function onManifestParsed(event, data) {\n                if (!this._emeEnabled) {\n                  return;\n                }\n\n                var audioCodecs = data.levels\n                  .map(function (level) {\n                    return level.audioCodec;\n                  })\n                  .filter(function (audioCodec) {\n                    return !!audioCodec;\n                  });\n                var videoCodecs = data.levels\n                  .map(function (level) {\n                    return level.videoCodec;\n                  })\n                  .filter(function (videoCodec) {\n                    return !!videoCodec;\n                  });\n\n                this._attemptKeySystemAccess(_utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__[\"KeySystems\"].WIDEVINE, audioCodecs, videoCodecs);\n              };\n\n              _createClass(EMEController, [\n                {\n                  key: \"requestMediaKeySystemAccess\",\n                  get: function get() {\n                    if (!this._requestMediaKeySystemAccess) {\n                      throw new Error(\"No requestMediaKeySystemAccess function configured\");\n                    }\n\n                    return this._requestMediaKeySystemAccess;\n                  },\n                },\n              ]);\n\n              return EMEController;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = EMEController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/fps-controller.ts\":\n          /*!******************************************!*\\\n  !*** ./src/controller/fps-controller.ts ***!\n  \\******************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            var FPSController = /*#__PURE__*/ (function () {\n              // stream controller must be provided as a dependency!\n              function FPSController(CiderHls) {\n                this.CiderHls = void 0;\n                this.isVideoPlaybackQualityAvailable = false;\n                this.timer = void 0;\n                this.media = null;\n                this.lastTime = void 0;\n                this.lastDroppedFrames = 0;\n                this.lastDecodedFrames = 0;\n                this.streamController = void 0;\n                this.CiderHls = CiderHls;\n                this.registerListeners();\n              }\n\n              var _proto = FPSController.prototype;\n\n              _proto.setStreamController = function setStreamController(streamController) {\n                this.streamController = streamController;\n              };\n\n              _proto.registerListeners = function registerListeners() {\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching);\n              };\n\n              _proto.destroy = function destroy() {\n                if (this.timer) {\n                  clearInterval(this.timer);\n                }\n\n                this.unregisterListeners();\n                this.isVideoPlaybackQualityAvailable = false;\n                this.media = null;\n              };\n\n              _proto.onMediaAttaching = function onMediaAttaching(event, data) {\n                var config = this.CiderHls.config;\n\n                if (config.capLevelOnFPSDrop) {\n                  var media = data.media instanceof self.HTMLVideoElement ? data.media : null;\n                  this.media = media;\n\n                  if (media && typeof media.getVideoPlaybackQuality === \"function\") {\n                    this.isVideoPlaybackQualityAvailable = true;\n                  }\n\n                  self.clearInterval(this.timer);\n                  this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n                }\n              };\n\n              _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {\n                var currentTime = performance.now();\n\n                if (decodedFrames) {\n                  if (this.lastTime) {\n                    var currentPeriod = currentTime - this.lastTime;\n                    var currentDropped = droppedFrames - this.lastDroppedFrames;\n                    var currentDecoded = decodedFrames - this.lastDecodedFrames;\n                    var droppedFPS = (1000 * currentDropped) / currentPeriod;\n                    var CiderHls = this.CiderHls;\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FPS_DROP, {\n                      currentDropped: currentDropped,\n                      currentDecoded: currentDecoded,\n                      totalDroppedFrames: droppedFrames,\n                    });\n\n                    if (droppedFPS > 0) {\n                      // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n                      if (currentDropped > CiderHls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n                        var currentLevel = CiderHls.currentLevel;\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].warn(\"drop FPS ratio greater than max allowed value for currentLevel: \" + currentLevel);\n\n                        if (currentLevel > 0 && (CiderHls.autoLevelCapping === -1 || CiderHls.autoLevelCapping >= currentLevel)) {\n                          currentLevel = currentLevel - 1;\n                          CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FPS_DROP_LEVEL_CAPPING, {\n                            level: currentLevel,\n                            droppedLevel: CiderHls.currentLevel,\n                          });\n                          CiderHls.autoLevelCapping = currentLevel;\n                          this.streamController.nextLevelSwitch();\n                        }\n                      }\n                    }\n                  }\n\n                  this.lastTime = currentTime;\n                  this.lastDroppedFrames = droppedFrames;\n                  this.lastDecodedFrames = decodedFrames;\n                }\n              };\n\n              _proto.checkFPSInterval = function checkFPSInterval() {\n                var video = this.media;\n\n                if (video) {\n                  if (this.isVideoPlaybackQualityAvailable) {\n                    var videoPlaybackQuality = video.getVideoPlaybackQuality();\n                    this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n                  } else {\n                    // HTMLVideoElement doesn't include the webkit types\n                    this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n                  }\n                }\n              };\n\n              return FPSController;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = FPSController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/fragment-finders.ts\":\n          /*!********************************************!*\\\n  !*** ./src/controller/fragment-finders.ts ***!\n  \\********************************************/\n          /*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"findFragmentByPDT\", function () {\n              return findFragmentByPDT;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"findFragmentByPTS\", function () {\n              return findFragmentByPTS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"fragmentWithinToleranceTest\", function () {\n              return fragmentWithinToleranceTest;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"pdtWithinToleranceTest\", function () {\n              return pdtWithinToleranceTest;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"findFragWithCC\", function () {\n              return findFragWithCC;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ \"./src/utils/binary-search.ts\");\n\n            /**\n             * Returns first fragment whose endPdt value exceeds the given PDT.\n             * @param {Array<Fragment>} fragments - The array of candidate fragments\n             * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n             * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n             * @returns {*|null} fragment - The best matching fragment\n             */\n            function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {\n              if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(PDTValue)) {\n                return null;\n              } // if less than start\n\n              var startPDT = fragments[0].programDateTime;\n\n              if (PDTValue < (startPDT || 0)) {\n                return null;\n              }\n\n              var endPDT = fragments[fragments.length - 1].endProgramDateTime;\n\n              if (PDTValue >= (endPDT || 0)) {\n                return null;\n              }\n\n              maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n\n              for (var seg = 0; seg < fragments.length; ++seg) {\n                var frag = fragments[seg];\n\n                if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n                  return frag;\n                }\n              }\n\n              return null;\n            }\n            /**\n             * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n             * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n             * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n             * @param {*} fragPrevious - The last frag successfully appended\n             * @param {Array} fragments - The array of candidate fragments\n             * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n             * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n             * @returns {*} foundFrag - The best matching fragment\n             */\n\n            function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {\n              if (bufferEnd === void 0) {\n                bufferEnd = 0;\n              }\n\n              if (maxFragLookUpTolerance === void 0) {\n                maxFragLookUpTolerance = 0;\n              }\n\n              var fragNext = null;\n\n              if (fragPrevious) {\n                fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;\n              } else if (bufferEnd === 0 && fragments[0].start === 0) {\n                fragNext = fragments[0];\n              } // Prefer the next fragment if it's within tolerance\n\n              if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {\n                return fragNext;\n              } // We might be seeking past the tolerance so find the best match\n\n              var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__[\"default\"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n\n              if (foundFragment) {\n                return foundFragment;\n              } // If no match was found return the next fragment after fragPrevious, or null\n\n              return fragNext;\n            }\n            /**\n             * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n             * @param {*} candidate - The fragment to test\n             * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n             * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n             * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n             */\n\n            function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {\n              if (bufferEnd === void 0) {\n                bufferEnd = 0;\n              }\n\n              if (maxFragLookUpTolerance === void 0) {\n                maxFragLookUpTolerance = 0;\n              }\n\n              // offset should be within fragment boundary - config.maxFragLookUpTolerance\n              // this is to cope with situations like\n              // bufferEnd = 9.991\n              // frag[Ø] : [0,10]\n              // frag[1] : [10,20]\n              // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n              //              frag start               frag start+duration\n              //                  |-----------------------------|\n              //              <--->                         <--->\n              //  ...--------><-----------------------------><---------....\n              // previous frag         matching fragment         next frag\n              //  return -1             return 0                 return 1\n              // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n              // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n              var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n\n              if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n                return 1;\n              } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n                // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n                return -1;\n              }\n\n              return 0;\n            }\n            /**\n             * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n             * This function tests the candidate's program date time values, as represented in Unix time\n             * @param {*} candidate - The fragment to test\n             * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range\n             * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n             * @returns {boolean} True if contiguous, false otherwise\n             */\n\n            function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {\n              var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero\n\n              var endProgramDateTime = candidate.endProgramDateTime || 0;\n              return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n            }\n            function findFragWithCC(fragments, cc) {\n              return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__[\"default\"].search(fragments, function (candidate) {\n                if (candidate.cc < cc) {\n                  return 1;\n                } else if (candidate.cc > cc) {\n                  return -1;\n                } else {\n                  return 0;\n                }\n              });\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/controller/fragment-tracker.ts\":\n          /*!********************************************!*\\\n  !*** ./src/controller/fragment-tracker.ts ***!\n  \\********************************************/\n          /*! exports provided: FragmentState, FragmentTracker */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FragmentState\", function () {\n              return FragmentState;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FragmentTracker\", function () {\n              return FragmentTracker;\n            });\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n\n            var FragmentState;\n\n            (function (FragmentState) {\n              FragmentState[\"NOT_LOADED\"] = \"NOT_LOADED\";\n              FragmentState[\"BACKTRACKED\"] = \"BACKTRACKED\";\n              FragmentState[\"APPENDING\"] = \"APPENDING\";\n              FragmentState[\"PARTIAL\"] = \"PARTIAL\";\n              FragmentState[\"OK\"] = \"OK\";\n            })(FragmentState || (FragmentState = {}));\n\n            var FragmentTracker = /*#__PURE__*/ (function () {\n              function FragmentTracker(CiderHls) {\n                this.activeFragment = null;\n                this.activeParts = null;\n                this.fragments = Object.create(null);\n                this.timeRanges = Object.create(null);\n                this.bufferPadding = 0.2;\n                this.CiderHls = void 0;\n                this.CiderHls = CiderHls;\n\n                this._registerListeners();\n              }\n\n              var _proto = FragmentTracker.prototype;\n\n              _proto._registerListeners = function _registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_APPENDED, this.onBufferAppended, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_APPENDED, this.onBufferAppended, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n              };\n\n              _proto.destroy = function destroy() {\n                this._unregisterListeners(); // @ts-ignore\n\n                this.fragments = this.timeRanges = null;\n              };\n              /**\n               * Return a Fragment with an appended range that matches the position and levelType.\n               * If not found any Fragment, return null\n               */\n\n              _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {\n                if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__[\"PlaylistLevelType\"].MAIN) {\n                  var activeFragment = this.activeFragment,\n                    activeParts = this.activeParts;\n\n                  if (!activeFragment) {\n                    return null;\n                  }\n\n                  if (activeParts) {\n                    for (var i = activeParts.length; i--; ) {\n                      var activePart = activeParts[i];\n                      var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;\n\n                      if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {\n                        // 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.\n                        if (i > 9) {\n                          this.activeParts = activeParts.slice(i - 9);\n                        }\n\n                        return activePart;\n                      }\n                    }\n                  } else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {\n                    return activeFragment;\n                  }\n                }\n\n                return this.getBufferedFrag(position, levelType);\n              };\n              /**\n               * Return a buffered Fragment that matches the position and levelType.\n               * A buffered Fragment is one whose loading, parsing and appending is done (completed or \"partial\" meaning aborted).\n               * If not found any Fragment, return null\n               */\n\n              _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {\n                var fragments = this.fragments;\n                var keys = Object.keys(fragments);\n\n                for (var i = keys.length; i--; ) {\n                  var fragmentEntity = fragments[keys[i]];\n\n                  if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {\n                    var frag = fragmentEntity.body;\n\n                    if (frag.start <= position && position <= frag.end) {\n                      return frag;\n                    }\n                  }\n                }\n\n                return null;\n              };\n              /**\n               * Partial fragments effected by coded frame eviction will be removed\n               * The browser will unload parts of the buffer to free up memory for new buffer data\n               * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n               */\n\n              _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) {\n                var _this = this;\n\n                // Check if any flagged fragments have been unloaded\n                Object.keys(this.fragments).forEach(function (key) {\n                  var fragmentEntity = _this.fragments[key];\n\n                  if (!fragmentEntity) {\n                    return;\n                  }\n\n                  if (!fragmentEntity.buffered) {\n                    if (fragmentEntity.body.type === playlistType) {\n                      _this.removeFragment(fragmentEntity.body);\n                    }\n\n                    return;\n                  }\n\n                  var esData = fragmentEntity.range[elementaryStream];\n\n                  if (!esData) {\n                    return;\n                  }\n\n                  esData.time.some(function (time) {\n                    var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);\n\n                    if (isNotBuffered) {\n                      // Unregister partial fragment as it needs to load again to be reused\n                      _this.removeFragment(fragmentEntity.body);\n                    }\n\n                    return isNotBuffered;\n                  });\n                });\n              };\n              /**\n               * Checks if the fragment passed in is loaded in the buffer properly\n               * Partially loaded fragments will be registered as a partial fragment\n               */\n\n              _proto.detectPartialFragments = function detectPartialFragments(data) {\n                var _this2 = this;\n\n                var timeRanges = this.timeRanges;\n                var frag = data.frag,\n                  part = data.part;\n\n                if (!timeRanges || frag.sn === \"initSegment\") {\n                  return;\n                }\n\n                var fragKey = getFragmentKey(frag);\n                var fragmentEntity = this.fragments[fragKey];\n\n                if (!fragmentEntity) {\n                  return;\n                }\n\n                Object.keys(timeRanges).forEach(function (elementaryStream) {\n                  var streamInfo = frag.elementaryStreams[elementaryStream];\n\n                  if (!streamInfo) {\n                    return;\n                  }\n\n                  var timeRange = timeRanges[elementaryStream];\n                  var partial = part !== null || streamInfo.partial === true;\n                  fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);\n                });\n                fragmentEntity.backtrack = fragmentEntity.loaded = null;\n\n                if (Object.keys(fragmentEntity.range).length) {\n                  fragmentEntity.buffered = true;\n                } else {\n                  // remove fragment if nothing was appended\n                  this.removeFragment(fragmentEntity.body);\n                }\n              };\n\n              _proto.fragBuffered = function fragBuffered(frag) {\n                var fragKey = getFragmentKey(frag);\n                var fragmentEntity = this.fragments[fragKey];\n\n                if (fragmentEntity) {\n                  fragmentEntity.backtrack = fragmentEntity.loaded = null;\n                  fragmentEntity.buffered = true;\n                }\n              };\n\n              _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {\n                var buffered = {\n                  time: [],\n                  partial: partial,\n                };\n                var startPTS = part ? part.start : fragment.start;\n                var endPTS = part ? part.end : fragment.end;\n                var minEndPTS = fragment.minEndPTS || endPTS;\n                var maxStartPTS = fragment.maxStartPTS || startPTS;\n\n                for (var i = 0; i < timeRange.length; i++) {\n                  var startTime = timeRange.start(i) - this.bufferPadding;\n                  var endTime = timeRange.end(i) + this.bufferPadding;\n\n                  if (maxStartPTS >= startTime && minEndPTS <= endTime) {\n                    // Fragment is entirely contained in buffer\n                    // No need to check the other timeRange times since it's completely playable\n                    buffered.time.push({\n                      startPTS: Math.max(startPTS, timeRange.start(i)),\n                      endPTS: Math.min(endPTS, timeRange.end(i)),\n                    });\n                    break;\n                  } else if (startPTS < endTime && endPTS > startTime) {\n                    buffered.partial = true; // Check for intersection with buffer\n                    // Get playable sections of the fragment\n\n                    buffered.time.push({\n                      startPTS: Math.max(startPTS, timeRange.start(i)),\n                      endPTS: Math.min(endPTS, timeRange.end(i)),\n                    });\n                  } else if (endPTS <= startTime) {\n                    // No need to check the rest of the timeRange as it is in order\n                    break;\n                  }\n                }\n\n                return buffered;\n              };\n              /**\n               * Gets the partial fragment for a certain time\n               */\n\n              _proto.getPartialFragment = function getPartialFragment(time) {\n                var bestFragment = null;\n                var timePadding;\n                var startTime;\n                var endTime;\n                var bestOverlap = 0;\n                var bufferPadding = this.bufferPadding,\n                  fragments = this.fragments;\n                Object.keys(fragments).forEach(function (key) {\n                  var fragmentEntity = fragments[key];\n\n                  if (!fragmentEntity) {\n                    return;\n                  }\n\n                  if (isPartial(fragmentEntity)) {\n                    startTime = fragmentEntity.body.start - bufferPadding;\n                    endTime = fragmentEntity.body.end + bufferPadding;\n\n                    if (time >= startTime && time <= endTime) {\n                      // Use the fragment that has the most padding from start and end time\n                      timePadding = Math.min(time - startTime, endTime - time);\n\n                      if (bestOverlap <= timePadding) {\n                        bestFragment = fragmentEntity.body;\n                        bestOverlap = timePadding;\n                      }\n                    }\n                  }\n                });\n                return bestFragment;\n              };\n\n              _proto.getState = function getState(fragment) {\n                var fragKey = getFragmentKey(fragment);\n                var fragmentEntity = this.fragments[fragKey];\n\n                if (fragmentEntity) {\n                  if (!fragmentEntity.buffered) {\n                    if (fragmentEntity.backtrack) {\n                      return FragmentState.BACKTRACKED;\n                    }\n\n                    return FragmentState.APPENDING;\n                  } else if (isPartial(fragmentEntity)) {\n                    return FragmentState.PARTIAL;\n                  } else {\n                    return FragmentState.OK;\n                  }\n                }\n\n                return FragmentState.NOT_LOADED;\n              };\n\n              _proto.backtrack = function backtrack(frag, data) {\n                var fragKey = getFragmentKey(frag);\n                var fragmentEntity = this.fragments[fragKey];\n\n                if (!fragmentEntity || fragmentEntity.backtrack) {\n                  return null;\n                }\n\n                var backtrack = (fragmentEntity.backtrack = data ? data : fragmentEntity.loaded);\n                fragmentEntity.loaded = null;\n                return backtrack;\n              };\n\n              _proto.getBacktrackData = function getBacktrackData(fragment) {\n                var fragKey = getFragmentKey(fragment);\n                var fragmentEntity = this.fragments[fragKey];\n\n                if (fragmentEntity) {\n                  var _backtrack$payload;\n\n                  var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available\n\n                  if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) {\n                    return backtrack;\n                  } else {\n                    this.removeFragment(fragment);\n                  }\n                }\n\n                return null;\n              };\n\n              _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {\n                var startTime;\n                var endTime;\n\n                for (var i = 0; i < timeRange.length; i++) {\n                  startTime = timeRange.start(i) - this.bufferPadding;\n                  endTime = timeRange.end(i) + this.bufferPadding;\n\n                  if (startPTS >= startTime && endPTS <= endTime) {\n                    return true;\n                  }\n\n                  if (endPTS <= startTime) {\n                    // No need to check the rest of the timeRange as it is in order\n                    return false;\n                  }\n                }\n\n                return false;\n              };\n\n              _proto.onFragLoaded = function onFragLoaded(event, data) {\n                var frag = data.frag,\n                  part = data.part; // don't track initsegment (for which sn is not a number)\n                // don't track frags used for bitrateTest, they're irrelevant.\n                // don't track parts for memory efficiency\n\n                if (frag.sn === \"initSegment\" || frag.bitrateTest || part) {\n                  return;\n                }\n\n                var fragKey = getFragmentKey(frag);\n                this.fragments[fragKey] = {\n                  body: frag,\n                  loaded: data,\n                  backtrack: null,\n                  buffered: false,\n                  range: Object.create(null),\n                };\n              };\n\n              _proto.onBufferAppended = function onBufferAppended(event, data) {\n                var _this3 = this;\n\n                var frag = data.frag,\n                  part = data.part,\n                  timeRanges = data.timeRanges;\n\n                if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__[\"PlaylistLevelType\"].MAIN) {\n                  this.activeFragment = frag;\n\n                  if (part) {\n                    var activeParts = this.activeParts;\n\n                    if (!activeParts) {\n                      this.activeParts = activeParts = [];\n                    }\n\n                    activeParts.push(part);\n                  } else {\n                    this.activeParts = null;\n                  }\n                } // Store the latest timeRanges loaded in the buffer\n\n                this.timeRanges = timeRanges;\n                Object.keys(timeRanges).forEach(function (elementaryStream) {\n                  var timeRange = timeRanges[elementaryStream];\n\n                  _this3.detectEvictedFragments(elementaryStream, timeRange);\n\n                  if (!part) {\n                    for (var i = 0; i < timeRange.length; i++) {\n                      frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0);\n                    }\n                  }\n                });\n              };\n\n              _proto.onFragBuffered = function onFragBuffered(event, data) {\n                this.detectPartialFragments(data);\n              };\n\n              _proto.hasFragment = function hasFragment(fragment) {\n                var fragKey = getFragmentKey(fragment);\n                return !!this.fragments[fragKey];\n              };\n\n              _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) {\n                var _this4 = this;\n\n                Object.keys(this.fragments).forEach(function (key) {\n                  var fragmentEntity = _this4.fragments[key];\n\n                  if (!fragmentEntity) {\n                    return;\n                  }\n\n                  if (fragmentEntity.buffered) {\n                    var frag = fragmentEntity.body;\n\n                    if (frag.type === playlistType && frag.start < end && frag.end > start) {\n                      _this4.removeFragment(frag);\n                    }\n                  }\n                });\n              };\n\n              _proto.removeFragment = function removeFragment(fragment) {\n                var fragKey = getFragmentKey(fragment);\n                fragment.stats.loaded = 0;\n                fragment.clearElementaryStreamInfo();\n                delete this.fragments[fragKey];\n              };\n\n              _proto.removeAllFragments = function removeAllFragments() {\n                this.fragments = Object.create(null);\n                this.activeFragment = null;\n                this.activeParts = null;\n              };\n\n              return FragmentTracker;\n            })();\n\n            function isPartial(fragmentEntity) {\n              var _fragmentEntity$range, _fragmentEntity$range2;\n\n              return (\n                fragmentEntity.buffered &&\n                (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) ||\n                  ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial))\n              );\n            }\n\n            function getFragmentKey(fragment) {\n              return fragment.type + \"_\" + fragment.level + \"_\" + fragment.urlId + \"_\" + fragment.sn;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/controller/gap-controller.ts\":\n          /*!******************************************!*\\\n  !*** ./src/controller/gap-controller.ts ***!\n  \\******************************************/\n          /*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"STALL_MINIMUM_DURATION_MS\", function () {\n              return STALL_MINIMUM_DURATION_MS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"MAX_START_GAP_JUMP\", function () {\n              return MAX_START_GAP_JUMP;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"SKIP_BUFFER_HOLE_STEP_SECONDS\", function () {\n              return SKIP_BUFFER_HOLE_STEP_SECONDS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"SKIP_BUFFER_RANGE_START\", function () {\n              return SKIP_BUFFER_RANGE_START;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return GapController;\n            });\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            var STALL_MINIMUM_DURATION_MS = 250;\n            var MAX_START_GAP_JUMP = 2.0;\n            var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\n            var SKIP_BUFFER_RANGE_START = 0.05;\n\n            var GapController = /*#__PURE__*/ (function () {\n              function GapController(config, media, fragmentTracker, CiderHls) {\n                this.config = void 0;\n                this.media = void 0;\n                this.fragmentTracker = void 0;\n                this.CiderHls = void 0;\n                this.nudgeRetry = 0;\n                this.stallReported = false;\n                this.stalled = null;\n                this.moved = false;\n                this.seeking = false;\n                this.config = config;\n                this.media = media;\n                this.fragmentTracker = fragmentTracker;\n                this.CiderHls = CiderHls;\n              }\n\n              var _proto = GapController.prototype;\n\n              _proto.destroy = function destroy() {\n                // @ts-ignore\n                this.CiderHls = this.fragmentTracker = this.media = null;\n              };\n              /**\n               * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n               * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n               *\n               * @param {number} lastCurrentTime Previously read playhead position\n               */\n\n              _proto.poll = function poll(lastCurrentTime) {\n                var config = this.config,\n                  media = this.media,\n                  stalled = this.stalled;\n                var currentTime = media.currentTime,\n                  seeking = media.seeking;\n                var seeked = this.seeking && !seeking;\n                var beginSeek = !this.seeking && seeking;\n                this.seeking = seeking; // The playhead is moving, no-op\n\n                if (currentTime !== lastCurrentTime) {\n                  this.moved = true;\n\n                  if (stalled !== null) {\n                    // The playhead is now moving, but was previously stalled\n                    if (this.stallReported) {\n                      var _stalledDuration = self.performance.now() - stalled;\n\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"playback not stuck anymore @\" + currentTime + \", after \" + Math.round(_stalledDuration) + \"ms\");\n                      this.stallReported = false;\n                    }\n\n                    this.stalled = null;\n                    this.nudgeRetry = 0;\n                  }\n\n                  return;\n                } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n\n                if (beginSeek || seeked) {\n                  this.stalled = null;\n                } // The playhead should not be moving\n\n                if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__[\"BufferHelper\"].getBuffered(media).length) {\n                  return;\n                }\n\n                var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__[\"BufferHelper\"].bufferInfo(media, currentTime, 0);\n                var isBuffered = bufferInfo.len > 0;\n                var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer)\n\n                if (!isBuffered && !nextStart) {\n                  return;\n                }\n\n                if (seeking) {\n                  // Waiting for seeking in a buffered range to complete\n                  var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking\n\n                  var noBufferGap = !nextStart || (nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime));\n\n                  if (hasEnoughBuffer || noBufferGap) {\n                    return;\n                  } // Reset moved state when seeking to a point in or before a gap\n\n                  this.moved = false;\n                } // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n                // The addition poll gives the browser a chance to jump the gap for us\n\n                if (!this.moved && this.stalled !== null) {\n                  var _level$details;\n\n                  // Jump start gaps within jump threshold\n                  var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n                  // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n                  // that begins over 1 target duration after the video start position.\n\n                  var level = this.CiderHls.levels ? this.CiderHls.levels[this.CiderHls.currentLevel] : null;\n                  var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;\n                  var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;\n\n                  if (startJump > 0 && startJump <= maxStartGapJump) {\n                    this._trySkipBufferHole(null);\n\n                    return;\n                  }\n                } // Start tracking stall time\n\n                var tnow = self.performance.now();\n\n                if (stalled === null) {\n                  this.stalled = tnow;\n                  return;\n                }\n\n                var stalledDuration = tnow - stalled;\n\n                if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {\n                  // Report stalling after trying to fix\n                  this._reportStall(bufferInfo.len);\n                }\n\n                var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__[\"BufferHelper\"].bufferInfo(media, currentTime, config.maxBufferHole);\n\n                this._tryFixBufferStall(bufferedWithHoles, stalledDuration);\n              };\n              /**\n               * Detects and attempts to fix known buffer stalling issues.\n               * @param bufferInfo - The properties of the current buffer.\n               * @param stalledDurationMs - The amount of time CiderHls.js has been stalling for.\n               * @private\n               */\n\n              _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {\n                var config = this.config,\n                  fragmentTracker = this.fragmentTracker,\n                  media = this.media;\n                var currentTime = media.currentTime;\n                var partial = fragmentTracker.getPartialFragment(currentTime);\n\n                if (partial) {\n                  // Try to skip over the buffer hole caused by a partial fragment\n                  // This method isn't limited by the size of the gap between buffered ranges\n                  var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning\n                  // the branch below only executes when we don't handle a partial fragment\n\n                  if (targetTime) {\n                    return;\n                  }\n                } // if we haven't had to skip over a buffer hole of a partial fragment\n                // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n                // needs to cross some sort of threshold covering all source-buffers content\n                // to start playing properly.\n\n                if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Trying to nudge playhead over buffer-hole\"); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n                  // We only try to jump the hole if it's under the configured size\n                  // Reset stalled so to rearm watchdog timer\n\n                  this.stalled = null;\n\n                  this._tryNudgeBuffer();\n                }\n              };\n              /**\n               * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n               * @param bufferLen - The playhead distance from the end of the current buffer segment.\n               * @private\n               */\n\n              _proto._reportStall = function _reportStall(bufferLen) {\n                var CiderHls = this.CiderHls,\n                  media = this.media,\n                  stallReported = this.stallReported;\n\n                if (!stallReported) {\n                  // Report stalled error once\n                  this.stallReported = true;\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Playback stalling at @\" + media.currentTime + \" due to low buffer (buffer=\" + bufferLen + \")\");\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].BUFFER_STALLED_ERROR,\n                    fatal: false,\n                    buffer: bufferLen,\n                  });\n                }\n              };\n              /**\n               * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n               * @param partial - The partial fragment found at the current time (where playback is stalling).\n               * @private\n               */\n\n              _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {\n                var config = this.config,\n                  CiderHls = this.CiderHls,\n                  media = this.media;\n                var currentTime = media.currentTime;\n                var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments\n\n                var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__[\"BufferHelper\"].getBuffered(media);\n\n                for (var i = 0; i < buffered.length; i++) {\n                  var startTime = buffered.start(i);\n\n                  if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {\n                    var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"skipping hole, adjusting currentTime from \" + currentTime + \" to \" + targetTime);\n                    this.moved = true;\n                    this.stalled = null;\n                    media.currentTime = targetTime;\n\n                    if (partial) {\n                      CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, {\n                        type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                        details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].BUFFER_SEEK_OVER_HOLE,\n                        fatal: false,\n                        reason: \"fragment loaded with buffer holes, seeking from \" + currentTime + \" to \" + targetTime,\n                        frag: partial,\n                      });\n                    }\n\n                    return targetTime;\n                  }\n\n                  lastEndTime = buffered.end(i);\n                }\n\n                return 0;\n              };\n              /**\n               * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n               * @private\n               */\n\n              _proto._tryNudgeBuffer = function _tryNudgeBuffer() {\n                var config = this.config,\n                  CiderHls = this.CiderHls,\n                  media = this.media;\n                var currentTime = media.currentTime;\n                var nudgeRetry = (this.nudgeRetry || 0) + 1;\n                this.nudgeRetry = nudgeRetry;\n\n                if (nudgeRetry < config.nudgeMaxRetry) {\n                  var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Nudging 'currentTime' from \" + currentTime + \" to \" + targetTime);\n                  media.currentTime = targetTime;\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].BUFFER_NUDGE_ON_STALL,\n                    fatal: false,\n                  });\n                } else {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].error(\"Playhead still not moving while enough data buffered @\" + currentTime + \" after \" + config.nudgeMaxRetry + \" nudges\");\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].BUFFER_STALLED_ERROR,\n                    fatal: true,\n                  });\n                }\n              };\n\n              return GapController;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/controller/id3-track-controller.ts\":\n          /*!************************************************!*\\\n  !*** ./src/controller/id3-track-controller.ts ***!\n  \\************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ \"./src/utils/texttrack-utils.ts\");\n            /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ \"./src/demux/id3.ts\");\n\n            var MIN_CUE_DURATION = 0.25;\n\n            var ID3TrackController = /*#__PURE__*/ (function () {\n              function ID3TrackController(CiderHls) {\n                this.CiderHls = void 0;\n                this.id3Track = null;\n                this.media = null;\n                this.CiderHls = CiderHls;\n\n                this._registerListeners();\n              }\n\n              var _proto = ID3TrackController.prototype;\n\n              _proto.destroy = function destroy() {\n                this._unregisterListeners();\n              };\n\n              _proto._registerListeners = function _registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n              }; // Add ID3 metatadata text track.\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                this.media = data.media;\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                if (!this.id3Track) {\n                  return;\n                }\n\n                Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__[\"clearCurrentCues\"])(this.id3Track);\n                this.id3Track = null;\n                this.media = null;\n              };\n\n              _proto.getID3Track = function getID3Track(textTracks) {\n                if (!this.media) {\n                  return;\n                }\n\n                for (var i = 0; i < textTracks.length; i++) {\n                  var textTrack = textTracks[i];\n\n                  if (textTrack.kind === \"metadata\" && textTrack.label === \"id3\") {\n                    // send 'addtrack' when reusing the textTrack for metadata,\n                    // same as what we do for captions\n                    Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__[\"sendAddTrackEvent\"])(textTrack, this.media);\n                    return textTrack;\n                  }\n                }\n\n                return this.media.addTextTrack(\"metadata\", \"id3\");\n              };\n\n              _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {\n                if (!this.media) {\n                  return;\n                }\n\n                var fragment = data.frag;\n                var samples = data.samples; // create track dynamically\n\n                if (!this.id3Track) {\n                  this.id3Track = this.getID3Track(this.media.textTracks);\n                  this.id3Track.mode = \"hidden\";\n                } // Attempt to recreate Safari functionality by creating\n                // WebKitDataCue objects when available and store the decoded\n                // ID3 data in the value property of the cue\n\n                var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue;\n\n                for (var i = 0; i < samples.length; i++) {\n                  var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__[\"getID3Frames\"](samples[i].data);\n\n                  if (frames) {\n                    var startTime = samples[i].pts;\n                    var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end;\n                    var timeDiff = endTime - startTime;\n\n                    if (timeDiff <= 0) {\n                      endTime = startTime + MIN_CUE_DURATION;\n                    }\n\n                    for (var j = 0; j < frames.length; j++) {\n                      var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack\n\n                      if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__[\"isTimeStampFrame\"](frame)) {\n                        var cue = new Cue(startTime, endTime, \"\");\n                        cue.value = frame;\n                        this.id3Track.addCue(cue);\n                      }\n                    }\n                  }\n                }\n              };\n\n              _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {\n                var startOffset = _ref.startOffset,\n                  endOffset = _ref.endOffset,\n                  type = _ref.type;\n\n                if (!type || type === \"audio\") {\n                  // id3 cues come from parsed audio only remove cues when audio buffer is cleared\n                  var id3Track = this.id3Track;\n\n                  if (id3Track) {\n                    Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__[\"removeCuesInRange\"])(id3Track, startOffset, endOffset);\n                  }\n                }\n              };\n\n              return ID3TrackController;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = ID3TrackController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/latency-controller.ts\":\n          /*!**********************************************!*\\\n  !*** ./src/controller/latency-controller.ts ***!\n  \\**********************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return LatencyController;\n            });\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            var LatencyController = /*#__PURE__*/ (function () {\n              function LatencyController(CiderHls) {\n                var _this = this;\n\n                this.CiderHls = void 0;\n                this.config = void 0;\n                this.media = null;\n                this.levelDetails = null;\n                this.currentTime = 0;\n                this.stallCount = 0;\n                this._latency = null;\n\n                this.timeupdateHandler = function () {\n                  return _this.timeupdate();\n                };\n\n                this.CiderHls = CiderHls;\n                this.config = CiderHls.config;\n                this.registerListeners();\n              }\n\n              var _proto = LatencyController.prototype;\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners();\n                this.onMediaDetaching();\n                this.levelDetails = null; // @ts-ignore\n\n                this.CiderHls = this.timeupdateHandler = null;\n              };\n\n              _proto.registerListeners = function registerListeners() {\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_UPDATED, this.onLevelUpdated, this);\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached);\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching);\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading);\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_UPDATED, this.onLevelUpdated);\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, this.onError);\n              };\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                this.media = data.media;\n                this.media.addEventListener(\"timeupdate\", this.timeupdateHandler);\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                if (this.media) {\n                  this.media.removeEventListener(\"timeupdate\", this.timeupdateHandler);\n                  this.media = null;\n                }\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                this.levelDetails = null;\n                this._latency = null;\n                this.stallCount = 0;\n              };\n\n              _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {\n                var details = _ref.details;\n                this.levelDetails = details;\n\n                if (details.advanced) {\n                  this.timeupdate();\n                }\n\n                if (!details.live && this.media) {\n                  this.media.removeEventListener(\"timeupdate\", this.timeupdateHandler);\n                }\n              };\n\n              _proto.onError = function onError(event, data) {\n                if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__[\"ErrorDetails\"].BUFFER_STALLED_ERROR) {\n                  return;\n                }\n\n                this.stallCount++;\n                _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"[playback-rate-controller]: Stall detected, adjusting target latency\");\n              };\n\n              _proto.timeupdate = function timeupdate() {\n                var media = this.media,\n                  levelDetails = this.levelDetails;\n\n                if (!media || !levelDetails) {\n                  return;\n                }\n\n                this.currentTime = media.currentTime;\n                var latency = this.computeLatency();\n\n                if (latency === null) {\n                  return;\n                }\n\n                this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode\n\n                var _this$config = this.config,\n                  lowLatencyMode = _this$config.lowLatencyMode,\n                  maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;\n\n                if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {\n                  return;\n                }\n\n                var targetLatency = this.targetLatency;\n\n                if (targetLatency === null) {\n                  return;\n                }\n\n                var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency\n                // and more than one second from under-buffering.\n                // Playback further than one target duration from target can be considered DVR playback.\n\n                var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);\n                var inLiveRange = distanceFromTarget < liveMinLatencyDuration;\n\n                if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {\n                  var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));\n                  var rate = Math.round((2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled))) * 20) / 20;\n                  media.playbackRate = Math.min(max, Math.max(1, rate));\n                } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {\n                  media.playbackRate = 1;\n                }\n              };\n\n              _proto.estimateLiveEdge = function estimateLiveEdge() {\n                var levelDetails = this.levelDetails;\n\n                if (levelDetails === null) {\n                  return null;\n                }\n\n                return levelDetails.edge + levelDetails.age;\n              };\n\n              _proto.computeLatency = function computeLatency() {\n                var liveEdge = this.estimateLiveEdge();\n\n                if (liveEdge === null) {\n                  return null;\n                }\n\n                return liveEdge - this.currentTime;\n              };\n\n              _createClass(LatencyController, [\n                {\n                  key: \"latency\",\n                  get: function get() {\n                    return this._latency || 0;\n                  },\n                },\n                {\n                  key: \"maxLatency\",\n                  get: function get() {\n                    var config = this.config,\n                      levelDetails = this.levelDetails;\n\n                    if (config.liveMaxLatencyDuration !== undefined) {\n                      return config.liveMaxLatencyDuration;\n                    }\n\n                    return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;\n                  },\n                },\n                {\n                  key: \"targetLatency\",\n                  get: function get() {\n                    var levelDetails = this.levelDetails;\n\n                    if (levelDetails === null) {\n                      return null;\n                    }\n\n                    var holdBack = levelDetails.holdBack,\n                      partHoldBack = levelDetails.partHoldBack,\n                      targetduration = levelDetails.targetduration;\n                    var _this$config2 = this.config,\n                      liveSyncDuration = _this$config2.liveSyncDuration,\n                      liveSyncDurationCount = _this$config2.liveSyncDurationCount,\n                      lowLatencyMode = _this$config2.lowLatencyMode;\n                    var userConfig = this.CiderHls.userConfig;\n                    var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;\n\n                    if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {\n                      targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;\n                    }\n\n                    var maxLiveSyncOnStallIncrease = targetduration;\n                    var liveSyncOnStallIncrease = 1.0;\n                    return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);\n                  },\n                },\n                {\n                  key: \"liveSyncPosition\",\n                  get: function get() {\n                    var liveEdge = this.estimateLiveEdge();\n                    var targetLatency = this.targetLatency;\n                    var levelDetails = this.levelDetails;\n\n                    if (liveEdge === null || targetLatency === null || levelDetails === null) {\n                      return null;\n                    }\n\n                    var edge = levelDetails.edge;\n                    var syncPosition = liveEdge - targetLatency - this.edgeStalled;\n                    var min = edge - levelDetails.totalduration;\n                    var max = edge - ((this.config.lowLatencyMode && levelDetails.partTarget) || levelDetails.targetduration);\n                    return Math.min(Math.max(min, syncPosition), max);\n                  },\n                },\n                {\n                  key: \"drift\",\n                  get: function get() {\n                    var levelDetails = this.levelDetails;\n\n                    if (levelDetails === null) {\n                      return 1;\n                    }\n\n                    return levelDetails.drift;\n                  },\n                },\n                {\n                  key: \"edgeStalled\",\n                  get: function get() {\n                    var levelDetails = this.levelDetails;\n\n                    if (levelDetails === null) {\n                      return 0;\n                    }\n\n                    var maxLevelUpdateAge = ((this.config.lowLatencyMode && levelDetails.partTarget) || levelDetails.targetduration) * 3;\n                    return Math.max(levelDetails.age - maxLevelUpdateAge, 0);\n                  },\n                },\n                {\n                  key: \"forwardBufferLength\",\n                  get: function get() {\n                    var media = this.media,\n                      levelDetails = this.levelDetails;\n\n                    if (!media || !levelDetails) {\n                      return 0;\n                    }\n\n                    var bufferedRanges = media.buffered.length;\n                    return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime;\n                  },\n                },\n              ]);\n\n              return LatencyController;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/controller/level-controller.ts\":\n          /*!********************************************!*\\\n  !*** ./src/controller/level-controller.ts ***!\n  \\********************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return LevelController;\n            });\n            /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ \"./src/types/level.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ \"./src/utils/codecs.ts\");\n            /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ \"./src/controller/level-helper.ts\");\n            /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ \"./src/controller/base-playlist-controller.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            /*\n             * Level Controller\n             */\n\n            var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n\n            var LevelController = /*#__PURE__*/ (function (_BasePlaylistControll) {\n              _inheritsLoose(LevelController, _BasePlaylistControll);\n\n              function LevelController(CiderHls) {\n                var _this;\n\n                _this = _BasePlaylistControll.call(this, CiderHls, \"[level-controller]\") || this;\n                _this._levels = [];\n                _this._firstLevel = -1;\n                _this._startLevel = void 0;\n                _this.currentLevelIndex = -1;\n                _this.manualLevelIndex = -1;\n                _this.onParsedComplete = void 0;\n\n                _this._registerListeners();\n\n                return _this;\n              }\n\n              var _proto = LevelController.prototype;\n\n              _proto._registerListeners = function _registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADED, this.onManifestLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADED, this.onManifestLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.destroy = function destroy() {\n                this._unregisterListeners();\n\n                this.manualLevelIndex = -1;\n                this._levels.length = 0;\n\n                _BasePlaylistControll.prototype.destroy.call(this);\n              };\n\n              _proto.startLoad = function startLoad() {\n                var levels = this._levels; // clean up live level details to force reload them, and reset load errors\n\n                levels.forEach(function (level) {\n                  level.loadError = 0;\n                });\n\n                _BasePlaylistControll.prototype.startLoad.call(this);\n              };\n\n              _proto.onManifestLoaded = function onManifestLoaded(event, data) {\n                var levels = [];\n                var audioTracks = [];\n                var subtitleTracks = [];\n                var bitrateStart;\n                var levelSet = {};\n                var levelFromSet;\n                var resolutionFound = false;\n                var videoCodecFound = false;\n                var audioCodecFound = false; // regroup redundant levels together\n\n                data.levels.forEach(function (levelParsed) {\n                  var attributes = levelParsed.attrs;\n                  resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);\n                  videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;\n                  audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.\n                  // demuxer will autodetect codec and fallback to mpeg/audio\n\n                  if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf(\"mp4a.40.34\") !== -1) {\n                    levelParsed.audioCodec = undefined;\n                  }\n\n                  var levelKey = levelParsed.bitrate + \"-\" + levelParsed.attrs.RESOLUTION + \"-\" + levelParsed.attrs.CODECS;\n                  levelFromSet = levelSet[levelKey];\n\n                  if (!levelFromSet) {\n                    levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__[\"Level\"](levelParsed);\n                    levelSet[levelKey] = levelFromSet;\n                    levels.push(levelFromSet);\n                  } else {\n                    levelFromSet.url.push(levelParsed.url);\n                  }\n\n                  if (attributes) {\n                    if (attributes.AUDIO) {\n                      Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__[\"addGroupId\"])(levelFromSet, \"audio\", attributes.AUDIO);\n                    }\n\n                    if (attributes.SUBTITLES) {\n                      Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__[\"addGroupId\"])(levelFromSet, \"text\", attributes.SUBTITLES);\n                    }\n                  }\n                }); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled\n\n                if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n                  levels = levels.filter(function (_ref) {\n                    var videoCodec = _ref.videoCodec,\n                      width = _ref.width,\n                      height = _ref.height;\n                    return !!videoCodec || !!(width && height);\n                  });\n                } // only keep levels with supported audio/video codecs\n\n                levels = levels.filter(function (_ref2) {\n                  var audioCodec = _ref2.audioCodec,\n                    videoCodec = _ref2.videoCodec;\n                  return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__[\"isCodecSupportedInMp4\"])(audioCodec, \"audio\")) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__[\"isCodecSupportedInMp4\"])(videoCodec, \"video\"));\n                });\n\n                if (data.audioTracks) {\n                  audioTracks = data.audioTracks.filter(function (track) {\n                    return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__[\"isCodecSupportedInMp4\"])(track.audioCodec, \"audio\");\n                  }); // Assign ids after filtering as array indices by group-id\n\n                  Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__[\"assignTrackIdsByGroup\"])(audioTracks);\n                }\n\n                if (data.subtitles) {\n                  subtitleTracks = data.subtitles;\n                  Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__[\"assignTrackIdsByGroup\"])(subtitleTracks);\n                }\n\n                if (levels.length > 0) {\n                  // start bitrate is the first bitrate of the manifest\n                  bitrateStart = levels[0].bitrate; // sort level on bitrate\n\n                  levels.sort(function (a, b) {\n                    return a.bitrate - b.bitrate;\n                  });\n                  this._levels = levels; // find index of first level in sorted levels\n\n                  for (var i = 0; i < levels.length; i++) {\n                    if (levels[i].bitrate === bitrateStart) {\n                      this._firstLevel = i;\n                      this.log(\"manifest loaded, \" + levels.length + \" level(s) found, first bitrate: \" + bitrateStart);\n                      break;\n                    }\n                  } // Audio is only alternate if manifest include a URI along with the audio group tag,\n                  // and this is not an audio-only stream where levels contain audio-only\n\n                  var audioOnly = audioCodecFound && !videoCodecFound;\n                  var edata = {\n                    levels: levels,\n                    audioTracks: audioTracks,\n                    subtitleTracks: subtitleTracks,\n                    firstLevel: this._firstLevel,\n                    stats: data.stats,\n                    audio: audioCodecFound,\n                    video: videoCodecFound,\n                    altAudio:\n                      !audioOnly &&\n                      audioTracks.some(function (t) {\n                        return !!t.url;\n                      }),\n                  };\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED\n\n                  if (this.CiderHls.config.autoStartLoad || this.CiderHls.forceStartLoad) {\n                    this.CiderHls.startLoad(this.CiderHls.config.startPosition);\n                  }\n                } else {\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorTypes\"].MEDIA_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n                    fatal: true,\n                    url: data.url,\n                    reason: \"no level with compatible codecs found in manifest\",\n                  });\n                }\n              };\n\n              _proto.onError = function onError(event, data) {\n                _BasePlaylistControll.prototype.onError.call(this, event, data);\n\n                if (data.fatal) {\n                  return;\n                } // Switch to redundant level when track fails to load\n\n                var context = data.context;\n                var level = this._levels[this.currentLevelIndex];\n\n                if (\n                  context &&\n                  ((context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId]) ||\n                    (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId]))\n                ) {\n                  this.redundantFailover(this.currentLevelIndex);\n                  return;\n                }\n\n                var levelError = false;\n                var levelSwitch = true;\n                var levelIndex; // try to recover not fatal errors\n\n                switch (data.details) {\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].FRAG_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].FRAG_LOAD_TIMEOUT:\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].KEY_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].KEY_LOAD_TIMEOUT:\n                    if (data.frag) {\n                      var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries\n\n                      if (_level) {\n                        _level.fragmentError++;\n\n                        if (_level.fragmentError > this.CiderHls.config.fragLoadingMaxRetry) {\n                          levelIndex = data.frag.level;\n                        }\n                      } else {\n                        levelIndex = data.frag.level;\n                      }\n                    }\n\n                    break;\n\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].LEVEL_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].LEVEL_LOAD_TIMEOUT:\n                    // Do not perform level switch if an error occurred using delivery directives\n                    // Attempt to reload level without directives first\n                    if (context) {\n                      if (context.deliveryDirectives) {\n                        levelSwitch = false;\n                      }\n\n                      levelIndex = context.level;\n                    }\n\n                    levelError = true;\n                    break;\n\n                  case _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].REMUX_ALLOC_ERROR:\n                    levelIndex = data.level;\n                    levelError = true;\n                    break;\n                }\n\n                if (levelIndex !== undefined) {\n                  this.recoverLevel(data, levelIndex, levelError, levelSwitch);\n                }\n              };\n              /**\n               * Switch to a redundant stream if any available.\n               * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n               */\n\n              _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {\n                var errorDetails = errorEvent.details;\n                var level = this._levels[levelIndex];\n                level.loadError++;\n\n                if (levelError) {\n                  var retrying = this.retryLoadingOrFail(errorEvent);\n\n                  if (retrying) {\n                    // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n                    errorEvent.levelRetry = true;\n                  } else {\n                    this.currentLevelIndex = -1;\n                    return;\n                  }\n                }\n\n                if (levelSwitch) {\n                  var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels\n\n                  if (redundantLevels > 1 && level.loadError < redundantLevels) {\n                    errorEvent.levelRetry = true;\n                    this.redundantFailover(levelIndex);\n                  } else if (this.manualLevelIndex === -1) {\n                    // Search for available level in auto level selection mode, cycling from highest to lowest bitrate\n                    var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;\n\n                    if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) {\n                      this.warn(errorDetails + \": switch to \" + nextLevel);\n                      errorEvent.levelRetry = true;\n                      this.CiderHls.nextAutoLevel = nextLevel;\n                    }\n                  }\n                }\n              };\n\n              _proto.redundantFailover = function redundantFailover(levelIndex) {\n                var level = this._levels[levelIndex];\n                var redundantLevels = level.url.length;\n\n                if (redundantLevels > 1) {\n                  // Update the url id of all levels so that we stay on the same set of variants when level switching\n                  var newUrlId = (level.urlId + 1) % redundantLevels;\n                  this.warn(\"Switching to redundant URL-id \" + newUrlId);\n\n                  this._levels.forEach(function (level) {\n                    level.urlId = newUrlId;\n                  });\n\n                  this.level = levelIndex;\n                }\n              }; // reset errors on the successful load of a fragment\n\n              _proto.onFragLoaded = function onFragLoaded(event, _ref3) {\n                var frag = _ref3.frag;\n\n                if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN) {\n                  var level = this._levels[frag.level];\n\n                  if (level !== undefined) {\n                    level.fragmentError = 0;\n                    level.loadError = 0;\n                  }\n                }\n              };\n\n              _proto.onLevelLoaded = function onLevelLoaded(event, data) {\n                var _data$deliveryDirecti2;\n\n                var level = data.level,\n                  details = data.details;\n                var curLevel = this._levels[level];\n\n                if (!curLevel) {\n                  var _data$deliveryDirecti;\n\n                  this.warn(\"Invalid level index \" + level);\n\n                  if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {\n                    details.deltaUpdateFailed = true;\n                  }\n\n                  return;\n                } // only process level loaded events matching with expected level\n\n                if (level === this.currentLevelIndex) {\n                  // reset level load error counter on successful level loaded only if there is no issues with fragments\n                  if (curLevel.fragmentError === 0) {\n                    curLevel.loadError = 0;\n                    this.retryCount = 0;\n                  }\n\n                  this.playlistLoaded(level, data, curLevel.details);\n                } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {\n                  // received a delta playlist update that cannot be merged\n                  details.deltaUpdateFailed = true;\n                }\n              };\n\n              _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {\n                var currentLevel = this.CiderHls.levels[this.currentLevelIndex];\n\n                if (!currentLevel) {\n                  return;\n                }\n\n                if (currentLevel.audioGroupIds) {\n                  var urlId = -1;\n                  var audioGroupId = this.CiderHls.audioTracks[data.id].groupId;\n\n                  for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {\n                    if (currentLevel.audioGroupIds[i] === audioGroupId) {\n                      urlId = i;\n                      break;\n                    }\n                  }\n\n                  if (urlId !== currentLevel.urlId) {\n                    currentLevel.urlId = urlId;\n                    this.startLoad();\n                  }\n                }\n              };\n\n              _proto.loadPlaylist = function loadPlaylist(CiderHlsUrlParameters) {\n                var level = this.currentLevelIndex;\n                var currentLevel = this._levels[level];\n\n                if (this.canLoad && currentLevel && currentLevel.url.length > 0) {\n                  var id = currentLevel.urlId;\n                  var url = currentLevel.url[id];\n\n                  if (CiderHlsUrlParameters) {\n                    try {\n                      url = CiderHlsUrlParameters.addDirectives(url);\n                    } catch (error) {\n                      this.warn(\"Could not construct new URL with CiderHls Delivery Directives: \" + error);\n                    }\n                  }\n\n                  this.log(\"Attempt loading level index \" + level + (CiderHlsUrlParameters ? \" at sn \" + CiderHlsUrlParameters.msn + \" part \" + CiderHlsUrlParameters.part : \"\") + \" with URL-id \" + id + \" \" + url); // console.log('Current audio track group ID:', this.CiderHls.audioTracks[this.CiderHls.audioTrack].groupId);\n                  // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n                  this.clearTimer();\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_LOADING, {\n                    url: url,\n                    level: level,\n                    id: id,\n                    deliveryDirectives: CiderHlsUrlParameters || null,\n                  });\n                }\n              };\n\n              _proto.removeLevel = function removeLevel(levelIndex, urlId) {\n                var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {\n                  return id !== urlId;\n                };\n\n                var levels = this._levels\n                  .filter(function (level, index) {\n                    if (index !== levelIndex) {\n                      return true;\n                    }\n\n                    if (level.url.length > 1 && urlId !== undefined) {\n                      level.url = level.url.filter(filterLevelAndGroupByIdIndex);\n\n                      if (level.audioGroupIds) {\n                        level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);\n                      }\n\n                      if (level.textGroupIds) {\n                        level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);\n                      }\n\n                      level.urlId = 0;\n                      return true;\n                    }\n\n                    return false;\n                  })\n                  .map(function (level, index) {\n                    var details = level.details;\n\n                    if (details !== null && details !== void 0 && details.fragments) {\n                      details.fragments.forEach(function (fragment) {\n                        fragment.level = index;\n                      });\n                    }\n\n                    return level;\n                  });\n\n                this._levels = levels;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVELS_UPDATED, {\n                  levels: levels,\n                });\n              };\n\n              _createClass(LevelController, [\n                {\n                  key: \"levels\",\n                  get: function get() {\n                    if (this._levels.length === 0) {\n                      return null;\n                    }\n\n                    return this._levels;\n                  },\n                },\n                {\n                  key: \"level\",\n                  get: function get() {\n                    return this.currentLevelIndex;\n                  },\n                  set: function set(newLevel) {\n                    var _levels$newLevel;\n\n                    var levels = this._levels;\n\n                    if (levels.length === 0) {\n                      return;\n                    }\n\n                    if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {\n                      return;\n                    } // check if level idx is valid\n\n                    if (newLevel < 0 || newLevel >= levels.length) {\n                      // invalid level id given, trigger error\n                      var fatal = newLevel < 0;\n                      this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                        type: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorTypes\"].OTHER_ERROR,\n                        details: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].LEVEL_SWITCH_ERROR,\n                        level: newLevel,\n                        fatal: fatal,\n                        reason: \"invalid level idx\",\n                      });\n\n                      if (fatal) {\n                        return;\n                      }\n\n                      newLevel = Math.min(newLevel, levels.length - 1);\n                    } // stopping live reloading timer if any\n\n                    this.clearTimer();\n                    var lastLevelIndex = this.currentLevelIndex;\n                    var lastLevel = levels[lastLevelIndex];\n                    var level = levels[newLevel];\n                    this.log(\"switching to level \" + newLevel + \" from \" + lastLevelIndex);\n                    this.currentLevelIndex = newLevel;\n\n                    var levelSwitchingData = _extends({}, level, {\n                      level: newLevel,\n                      maxBitrate: level.maxBitrate,\n                      uri: level.uri,\n                      urlId: level.urlId,\n                    }); // @ts-ignore\n\n                    delete levelSwitchingData._urlId;\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level\n\n                    var levelDetails = level.details;\n\n                    if (!levelDetails || levelDetails.live) {\n                      // level not retrieved yet, or live playlist we need to (re)load it\n                      var CiderHlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);\n                      this.loadPlaylist(CiderHlsUrlParameters);\n                    }\n                  },\n                },\n                {\n                  key: \"manualLevel\",\n                  get: function get() {\n                    return this.manualLevelIndex;\n                  },\n                  set: function set(newLevel) {\n                    this.manualLevelIndex = newLevel;\n\n                    if (this._startLevel === undefined) {\n                      this._startLevel = newLevel;\n                    }\n\n                    if (newLevel !== -1) {\n                      this.level = newLevel;\n                    }\n                  },\n                },\n                {\n                  key: \"firstLevel\",\n                  get: function get() {\n                    return this._firstLevel;\n                  },\n                  set: function set(newLevel) {\n                    this._firstLevel = newLevel;\n                  },\n                },\n                {\n                  key: \"startLevel\",\n                  get: function get() {\n                    // CiderHls.startLevel takes precedence over config.startLevel\n                    // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n                    if (this._startLevel === undefined) {\n                      var configStartLevel = this.CiderHls.config.startLevel;\n\n                      if (configStartLevel !== undefined) {\n                        return configStartLevel;\n                      } else {\n                        return this._firstLevel;\n                      }\n                    } else {\n                      return this._startLevel;\n                    }\n                  },\n                  set: function set(newLevel) {\n                    this._startLevel = newLevel;\n                  },\n                },\n                {\n                  key: \"nextLoadLevel\",\n                  get: function get() {\n                    if (this.manualLevelIndex !== -1) {\n                      return this.manualLevelIndex;\n                    } else {\n                      return this.CiderHls.nextAutoLevel;\n                    }\n                  },\n                  set: function set(nextLevel) {\n                    this.level = nextLevel;\n\n                    if (this.manualLevelIndex === -1) {\n                      this.CiderHls.nextAutoLevel = nextLevel;\n                    }\n                  },\n                },\n              ]);\n\n              return LevelController;\n            })(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__[\"default\"]);\n\n            /***/\n          },\n\n        /***/ \"./src/controller/level-helper.ts\":\n          /*!****************************************!*\\\n  !*** ./src/controller/level-helper.ts ***!\n  \\****************************************/\n          /*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"addGroupId\", function () {\n              return addGroupId;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"assignTrackIdsByGroup\", function () {\n              return assignTrackIdsByGroup;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"updatePTS\", function () {\n              return updatePTS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"updateFragPTSDTS\", function () {\n              return updateFragPTSDTS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"mergeDetails\", function () {\n              return mergeDetails;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"mapPartIntersection\", function () {\n              return mapPartIntersection;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"mapFragmentIntersection\", function () {\n              return mapFragmentIntersection;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"adjustSliding\", function () {\n              return adjustSliding;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"addSliding\", function () {\n              return addSliding;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computeReloadInterval\", function () {\n              return computeReloadInterval;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getFragmentWithSN\", function () {\n              return getFragmentWithSN;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getPartWith\", function () {\n              return getPartWith;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            /**\n             * @module LevelHelper\n             * Providing methods dealing with playlist sliding and drift\n             * */\n\n            function addGroupId(level, type, id) {\n              switch (type) {\n                case \"audio\":\n                  if (!level.audioGroupIds) {\n                    level.audioGroupIds = [];\n                  }\n\n                  level.audioGroupIds.push(id);\n                  break;\n\n                case \"text\":\n                  if (!level.textGroupIds) {\n                    level.textGroupIds = [];\n                  }\n\n                  level.textGroupIds.push(id);\n                  break;\n              }\n            }\n            function assignTrackIdsByGroup(tracks) {\n              var groups = {};\n              tracks.forEach(function (track) {\n                var groupId = track.groupId || \"\";\n                track.id = groups[groupId] = groups[groupId] || 0;\n                groups[groupId]++;\n              });\n            }\n            function updatePTS(fragments, fromIdx, toIdx) {\n              var fragFrom = fragments[fromIdx];\n              var fragTo = fragments[toIdx];\n              updateFromToPTS(fragFrom, fragTo);\n            }\n\n            function updateFromToPTS(fragFrom, fragTo) {\n              var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]\n\n              if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(fragToPTS)) {\n                // update fragment duration.\n                // it helps to fix drifts between playlist reported duration and fragment real duration\n                var duration = 0;\n                var frag;\n\n                if (fragTo.sn > fragFrom.sn) {\n                  duration = fragToPTS - fragFrom.start;\n                  frag = fragFrom;\n                } else {\n                  duration = fragFrom.start - fragToPTS;\n                  frag = fragTo;\n                } // TODO? Drift can go either way, or the playlist could be completely accurate\n                // console.assert(duration > 0,\n                //   `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);\n\n                if (frag.duration !== duration) {\n                  frag.duration = duration;\n                } // we dont know startPTS[toIdx]\n              } else if (fragTo.sn > fragFrom.sn) {\n                var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS\n\n                if (contiguous && fragFrom.minEndPTS) {\n                  fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);\n                } else {\n                  fragTo.start = fragFrom.start + fragFrom.duration;\n                }\n              } else {\n                fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n              }\n            }\n\n            function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {\n              var parsedMediaDuration = endPTS - startPTS;\n\n              if (parsedMediaDuration <= 0) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].warn(\"Fragment should have a positive duration\", frag);\n                endPTS = startPTS + frag.duration;\n                endDTS = startDTS + frag.duration;\n              }\n\n              var maxStartPTS = startPTS;\n              var minEndPTS = endPTS;\n              var fragStartPts = frag.startPTS;\n              var fragEndPts = frag.endPTS;\n\n              if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(fragStartPts)) {\n                // delta PTS between audio and video\n                var deltaPTS = Math.abs(fragStartPts - startPTS);\n\n                if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(frag.deltaPTS)) {\n                  frag.deltaPTS = deltaPTS;\n                } else {\n                  frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n                }\n\n                maxStartPTS = Math.max(startPTS, fragStartPts);\n                startPTS = Math.min(startPTS, fragStartPts);\n                startDTS = Math.min(startDTS, frag.startDTS);\n                minEndPTS = Math.min(endPTS, fragEndPts);\n                endPTS = Math.max(endPTS, fragEndPts);\n                endDTS = Math.max(endDTS, frag.endDTS);\n              }\n\n              frag.duration = endPTS - startPTS;\n              var drift = startPTS - frag.start;\n              frag.appendedPTS = endPTS;\n              frag.start = frag.startPTS = startPTS;\n              frag.maxStartPTS = maxStartPTS;\n              frag.startDTS = startDTS;\n              frag.endPTS = endPTS;\n              frag.minEndPTS = minEndPTS;\n              frag.endDTS = endDTS;\n              var sn = frag.sn; // 'initSegment'\n              // exit if sn out of range\n\n              if (!details || sn < details.startSN || sn > details.endSN) {\n                return 0;\n              }\n\n              var i;\n              var fragIdx = sn - details.startSN;\n              var fragments = details.fragments; // update frag reference in fragments array\n              // rationale is that fragments array might not contain this frag object.\n              // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n              // if we don't update frag, we won't be able to propagate PTS info on the playlist\n              // resulting in invalid sliding computation\n\n              fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0\n\n              for (i = fragIdx; i > 0; i--) {\n                updateFromToPTS(fragments[i], fragments[i - 1]);\n              } // adjust fragment PTS/duration from seqnum to last frag\n\n              for (i = fragIdx; i < fragments.length - 1; i++) {\n                updateFromToPTS(fragments[i], fragments[i + 1]);\n              }\n\n              if (details.fragmentHint) {\n                updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);\n              }\n\n              details.PTSKnown = details.alignedSliding = true;\n              return drift;\n            }\n            function mergeDetails(oldDetails, newDetails) {\n              // Track the last initSegment processed. Initialize it to the last one on the timeline.\n              var currentInitSegment = null;\n              var oldFragments = oldDetails.fragments;\n\n              for (var i = oldFragments.length - 1; i >= 0; i--) {\n                var oldInit = oldFragments[i].initSegment;\n\n                if (oldInit) {\n                  currentInitSegment = oldInit;\n                  break;\n                }\n              }\n\n              if (oldDetails.fragmentHint) {\n                // prevent PTS and duration from being adjusted on the next hint\n                delete oldDetails.fragmentHint.endPTS;\n              } // check if old/new playlists have fragments in common\n              // loop through overlapping SN and update startPTS , cc, and duration if any found\n\n              var ccOffset = 0;\n              var PTSFrag;\n              mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {\n                if (oldFrag.relurl) {\n                  // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-CiderHls parts.\n                  // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end\n                  // of the playlist.\n                  ccOffset = oldFrag.cc - newFrag.cc;\n                }\n\n                if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(oldFrag.startPTS) && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(oldFrag.endPTS)) {\n                  newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n                  newFrag.startDTS = oldFrag.startDTS;\n                  newFrag.appendedPTS = oldFrag.appendedPTS;\n                  newFrag.maxStartPTS = oldFrag.maxStartPTS;\n                  newFrag.endPTS = oldFrag.endPTS;\n                  newFrag.endDTS = oldFrag.endDTS;\n                  newFrag.minEndPTS = oldFrag.minEndPTS;\n                  newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;\n\n                  if (newFrag.duration) {\n                    PTSFrag = newFrag;\n                  } // PTS is known when any segment has startPTS and endPTS\n\n                  newDetails.PTSKnown = newDetails.alignedSliding = true;\n                }\n\n                newFrag.elementaryStreams = oldFrag.elementaryStreams;\n                newFrag.loader = oldFrag.loader;\n                newFrag.stats = oldFrag.stats;\n                newFrag.urlId = oldFrag.urlId;\n\n                if (oldFrag.initSegment) {\n                  newFrag.initSegment = oldFrag.initSegment;\n                  currentInitSegment = oldFrag.initSegment;\n                }\n              });\n\n              if (currentInitSegment) {\n                var fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;\n                fragmentsToCheck.forEach(function (frag) {\n                  var _currentInitSegment;\n\n                  if (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) {\n                    frag.initSegment = currentInitSegment;\n                  }\n                });\n              }\n\n              if (newDetails.skippedSegments) {\n                newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {\n                  return !frag;\n                });\n\n                if (newDetails.deltaUpdateFailed) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].warn(\"[level-helper] Previous playlist missing segments skipped in delta playlist\");\n\n                  for (var _i = newDetails.skippedSegments; _i--; ) {\n                    newDetails.fragments.shift();\n                  }\n\n                  newDetails.startSN = newDetails.fragments[0].sn;\n                  newDetails.startCC = newDetails.fragments[0].cc;\n                }\n              }\n\n              var newFragments = newDetails.fragments;\n\n              if (ccOffset) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].warn(\"discontinuity sliding from playlist, take drift into account\");\n\n                for (var _i2 = 0; _i2 < newFragments.length; _i2++) {\n                  newFragments[_i2].cc += ccOffset;\n                }\n              }\n\n              if (newDetails.skippedSegments) {\n                newDetails.startCC = newDetails.fragments[0].cc;\n              } // Merge parts\n\n              mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {\n                newPart.elementaryStreams = oldPart.elementaryStreams;\n                newPart.stats = oldPart.stats;\n              }); // if at least one fragment contains PTS info, recompute PTS information for all fragments\n\n              if (PTSFrag) {\n                updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);\n              } else {\n                // ensure that delta is within oldFragments range\n                // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n                // in that case we also need to adjust start offset of all fragments\n                adjustSliding(oldDetails, newDetails);\n              }\n\n              if (newFragments.length) {\n                newDetails.totalduration = newDetails.edge - newFragments[0].start;\n              }\n\n              newDetails.driftStartTime = oldDetails.driftStartTime;\n              newDetails.driftStart = oldDetails.driftStart;\n              var advancedDateTime = newDetails.advancedDateTime;\n\n              if (newDetails.advanced && advancedDateTime) {\n                var edge = newDetails.edge;\n\n                if (!newDetails.driftStart) {\n                  newDetails.driftStartTime = advancedDateTime;\n                  newDetails.driftStart = edge;\n                }\n\n                newDetails.driftEndTime = advancedDateTime;\n                newDetails.driftEnd = edge;\n              } else {\n                newDetails.driftEndTime = oldDetails.driftEndTime;\n                newDetails.driftEnd = oldDetails.driftEnd;\n                newDetails.advancedDateTime = oldDetails.advancedDateTime;\n              }\n            }\n            function mapPartIntersection(oldParts, newParts, intersectionFn) {\n              if (oldParts && newParts) {\n                var delta = 0;\n\n                for (var i = 0, len = oldParts.length; i <= len; i++) {\n                  var _oldPart = oldParts[i];\n                  var _newPart = newParts[i + delta];\n\n                  if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {\n                    intersectionFn(_oldPart, _newPart);\n                  } else {\n                    delta--;\n                  }\n                }\n              }\n            }\n            function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {\n              var skippedSegments = newDetails.skippedSegments;\n              var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;\n              var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;\n              var delta = newDetails.startSN - oldDetails.startSN;\n              var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;\n              var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;\n\n              for (var i = start; i <= end; i++) {\n                var _oldFrag = oldFrags[delta + i];\n                var _newFrag = newFrags[i];\n\n                if (skippedSegments && !_newFrag && i < skippedSegments) {\n                  // Fill in skipped segments in delta playlist\n                  _newFrag = newDetails.fragments[i] = _oldFrag;\n                }\n\n                if (_oldFrag && _newFrag) {\n                  intersectionFn(_oldFrag, _newFrag);\n                }\n              }\n            }\n            function adjustSliding(oldDetails, newDetails) {\n              var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;\n              var oldFragments = oldDetails.fragments;\n\n              if (delta < 0 || delta >= oldFragments.length) {\n                return;\n              }\n\n              addSliding(newDetails, oldFragments[delta].start);\n            }\n            function addSliding(details, start) {\n              if (start) {\n                var fragments = details.fragments;\n\n                for (var i = details.skippedSegments; i < fragments.length; i++) {\n                  fragments[i].start += start;\n                }\n\n                if (details.fragmentHint) {\n                  details.fragmentHint.start += start;\n                }\n              }\n            }\n            function computeReloadInterval(newDetails, stats) {\n              var reloadInterval = 1000 * newDetails.levelTargetDuration;\n              var reloadIntervalAfterMiss = reloadInterval / 2;\n              var timeSinceLastModified = newDetails.age;\n              var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3;\n              var roundTrip = stats.loading.end - stats.loading.start;\n              var estimatedTimeUntilUpdate;\n              var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average';\n\n              if (newDetails.updated === false) {\n                if (useLastModified) {\n                  // estimate = 'miss round trip';\n                  // We should have had a hit so try again in the time it takes to get a response,\n                  // but no less than 1/3 second.\n                  var minRetry = 333 * newDetails.misses;\n                  estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry);\n                  newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate;\n                } else {\n                  // estimate = 'miss half average';\n                  // follow CiderHls Spec, If the client reloads a Playlist file and finds that it has not\n                  // changed then it MUST wait for a period of one-half the target\n                  // duration before retrying.\n                  estimatedTimeUntilUpdate = reloadIntervalAfterMiss;\n                }\n              } else if (useLastModified) {\n                // estimate = 'next modified date';\n                // Get the closest we've been to timeSinceLastModified on update\n                availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified);\n                newDetails.availabilityDelay = availabilityDelay;\n                estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified;\n              } else {\n                estimatedTimeUntilUpdate = reloadInterval - roundTrip;\n              } // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`,\n              //   '\\n  method', estimate,\n              //   '\\n  estimated time until update =>', estimatedTimeUntilUpdate,\n              //   '\\n  average target duration', reloadInterval,\n              //   '\\n  time since modified', timeSinceLastModified,\n              //   '\\n  time round trip', roundTrip,\n              //   '\\n  availability delay', availabilityDelay);\n\n              return Math.round(estimatedTimeUntilUpdate);\n            }\n            function getFragmentWithSN(level, sn, fragCurrent) {\n              if (!level || !level.details) {\n                return null;\n              }\n\n              var levelDetails = level.details;\n              var fragment = levelDetails.fragments[sn - levelDetails.startSN];\n\n              if (fragment) {\n                return fragment;\n              }\n\n              fragment = levelDetails.fragmentHint;\n\n              if (fragment && fragment.sn === sn) {\n                return fragment;\n              }\n\n              if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {\n                return fragCurrent;\n              }\n\n              return null;\n            }\n            function getPartWith(level, sn, partIndex) {\n              if (!level || !level.details) {\n                return null;\n              }\n\n              var partList = level.details.partList;\n\n              if (partList) {\n                for (var i = partList.length; i--; ) {\n                  var part = partList[i];\n\n                  if (part.index === partIndex && part.fragment.sn === sn) {\n                    return part;\n                  }\n                }\n              }\n\n              return null;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/controller/stream-controller.ts\":\n          /*!*********************************************!*\\\n  !*** ./src/controller/stream-controller.ts ***!\n  \\*********************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return StreamController;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ \"./src/controller/base-stream-controller.ts\");\n            /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ \"./src/is-supported.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ \"./src/controller/fragment-tracker.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ \"./src/loader/fragment.ts\");\n            /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ \"./src/demux/transmuxer-interface.ts\");\n            /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ \"./src/types/transmuxer.ts\");\n            /* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ \"./src/controller/gap-controller.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            var TICK_INTERVAL = 100; // how often to tick in ms\n\n            var StreamController = /*#__PURE__*/ (function (_BaseStreamController) {\n              _inheritsLoose(StreamController, _BaseStreamController);\n\n              function StreamController(CiderHls, fragmentTracker) {\n                var _this;\n\n                _this = _BaseStreamController.call(this, CiderHls, fragmentTracker, \"[stream-controller]\") || this;\n                _this.audioCodecSwap = false;\n                _this.gapController = null;\n                _this.level = -1;\n                _this._forceStartLoad = false;\n                _this.altAudio = false;\n                _this.audioOnly = false;\n                _this.fragPlaying = null;\n                _this.onvplaying = null;\n                _this.onvseeked = null;\n                _this.fragLastKbps = 0;\n                _this.stalled = false;\n                _this.couldBacktrack = false;\n                _this.audioCodecSwitch = false;\n                _this.videoBuffer = null;\n\n                _this._registerListeners();\n\n                return _this;\n              }\n\n              var _proto = StreamController.prototype;\n\n              _proto._registerListeners = function _registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].ERROR, this.onError, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_CREATED, this.onBufferCreated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_FLUSHED, this.onBufferFlushed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVELS_UPDATED, this.onLevelsUpdated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].ERROR, this.onError, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_CREATED, this.onBufferCreated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_FLUSHED, this.onBufferFlushed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVELS_UPDATED, this.onLevelsUpdated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_BUFFERED, this.onFragBuffered, this);\n              };\n\n              _proto.onHandlerDestroying = function onHandlerDestroying() {\n                this._unregisterListeners();\n\n                this.onMediaDetaching();\n              };\n\n              _proto.startLoad = function startLoad(startPosition) {\n                if (this.levels) {\n                  var lastCurrentTime = this.lastCurrentTime,\n                    CiderHls = this.CiderHls;\n                  this.stopLoad();\n                  this.setInterval(TICK_INTERVAL);\n                  this.level = -1;\n                  this.fragLoadError = 0;\n\n                  if (!this.startFragRequested) {\n                    // determine load level\n                    var startLevel = CiderHls.startLevel;\n\n                    if (startLevel === -1) {\n                      if (CiderHls.config.testBandwidth) {\n                        // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n                        startLevel = 0;\n                        this.bitrateTest = true;\n                      } else {\n                        startLevel = CiderHls.nextAutoLevel;\n                      }\n                    } // set new level to playlist loader : this will trigger start level load\n                    // CiderHls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n\n                    this.level = CiderHls.nextLoadLevel = startLevel;\n                    this.loadedmetadata = false;\n                  } // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n\n                  if (lastCurrentTime > 0 && startPosition === -1) {\n                    this.log(\"Override startPosition with lastCurrentTime @\" + lastCurrentTime.toFixed(3));\n                    startPosition = lastCurrentTime;\n                  }\n\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                  this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n                  this.tick();\n                } else {\n                  this._forceStartLoad = true;\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].STOPPED;\n                }\n              };\n\n              _proto.stopLoad = function stopLoad() {\n                this._forceStartLoad = false;\n\n                _BaseStreamController.prototype.stopLoad.call(this);\n              };\n\n              _proto.doTick = function doTick() {\n                switch (this.state) {\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE:\n                    this.doTickIdle();\n                    break;\n\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_LEVEL: {\n                    var _levels$level;\n\n                    var levels = this.levels,\n                      level = this.level;\n                    var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;\n\n                    if (details && (!details.live || this.levelLastLoaded === this.level)) {\n                      if (this.waitForCdnTuneIn(details)) {\n                        break;\n                      }\n\n                      this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                      break;\n                    }\n\n                    break;\n                  }\n\n                  case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].FRAG_LOADING_WAITING_RETRY:\n                    {\n                      var _this$media;\n\n                      var now = self.performance.now();\n                      var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n\n                      if (!retryDate || now >= retryDate || ((_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking)) {\n                        this.log(\"retryDate reached, switch back to IDLE state\");\n                        this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                      }\n                    }\n                    break;\n\n                  default:\n                    break;\n                } // check buffer\n                // check/update current fragment\n\n                this.onTickEnd();\n              };\n\n              _proto.onTickEnd = function onTickEnd() {\n                _BaseStreamController.prototype.onTickEnd.call(this);\n\n                this.checkBuffer();\n                this.checkFragmentChanged();\n              };\n\n              _proto.doTickIdle = function doTickIdle() {\n                var _frag$decryptdata, _frag$decryptdata2;\n\n                var CiderHls = this.CiderHls,\n                  levelLastLoaded = this.levelLastLoaded,\n                  levels = this.levels,\n                  media = this.media;\n                var config = CiderHls.config,\n                  level = CiderHls.nextLoadLevel; // if start level not parsed yet OR\n                // if video not attached AND start fragment already requested OR start frag prefetch not enabled\n                // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n\n                if (levelLastLoaded === null || (!media && (this.startFragRequested || !config.startFragPrefetch))) {\n                  return;\n                } // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n\n                if (this.altAudio && this.audioOnly) {\n                  return;\n                }\n\n                if (!levels || !levels[level]) {\n                  return;\n                }\n\n                var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment\n                // set next load level : this will trigger a playlist load if needed\n\n                this.level = CiderHls.nextLoadLevel = level;\n                var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval\n                // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n                // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n\n                if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_LEVEL || (levelDetails.live && this.levelLastLoaded !== level)) {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_LEVEL;\n                  return;\n                }\n\n                var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : media, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN);\n\n                if (bufferInfo === null) {\n                  return;\n                }\n\n                var bufferLen = bufferInfo.len; // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n\n                var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); // Stay idle if we are still with buffer margins\n\n                if (bufferLen >= maxBufLen) {\n                  return;\n                }\n\n                if (this._streamEnded(bufferInfo, levelDetails)) {\n                  var data = {};\n\n                  if (this.altAudio) {\n                    data.type = \"video\";\n                  }\n\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_EOS, data);\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].ENDED;\n                  return;\n                }\n\n                var targetBufferTime = bufferInfo.end;\n                var frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid backtracking after seeking or switching by loading an earlier segment in streams that could backtrack\n\n                if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== \"initSegment\") {\n                  var fragIdx = frag.sn - levelDetails.startSN;\n\n                  if (fragIdx > 1) {\n                    frag = levelDetails.fragments[fragIdx - 1];\n                    this.fragmentTracker.removeFragment(frag);\n                  }\n                } // Avoid loop loading by using nextLoadPosition set for backtracking\n\n                if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__[\"FragmentState\"].OK && this.nextLoadPosition > targetBufferTime) {\n                  // Cleanup the fragment tracker before trying to find the next unbuffered fragment\n                  var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].VIDEO;\n                  this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN);\n                  frag = this.getNextFragment(this.nextLoadPosition, levelDetails);\n                }\n\n                if (!frag) {\n                  return;\n                }\n\n                if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {\n                  frag = frag.initSegment;\n                } // We want to load the key if we're dealing with an identity key, because we will decrypt\n                // this content using the key we fetch. Other keys will be handled by the DRM CDM via EME.\n\n                if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === \"identity\" && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {\n                  this.loadKey(frag, levelDetails);\n                } else {\n                  this.loadFragment(frag, levelDetails, targetBufferTime);\n                }\n              };\n\n              _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {\n                var _this$media2;\n\n                // Check if fragment is not loaded\n                var fragState = this.fragmentTracker.getState(frag);\n                this.fragCurrent = frag; // Use data from loaded backtracked fragment if available\n\n                if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__[\"FragmentState\"].BACKTRACKED) {\n                  var data = this.fragmentTracker.getBacktrackData(frag);\n\n                  if (data) {\n                    this._handleFragmentLoadProgress(data);\n\n                    this._handleFragmentLoadComplete(data);\n\n                    return;\n                  } else {\n                    fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__[\"FragmentState\"].NOT_LOADED;\n                  }\n                }\n\n                if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__[\"FragmentState\"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__[\"FragmentState\"].PARTIAL) {\n                  if (frag.sn === \"initSegment\") {\n                    this._loadInitSegment(frag);\n                  } else if (this.bitrateTest) {\n                    frag.bitrateTest = true;\n                    this.log(\"Fragment \" + frag.sn + \" of level \" + frag.level + \" is being downloaded to test bitrate and will not be buffered\");\n\n                    this._loadBitrateTestFrag(frag);\n                  } else {\n                    this.startFragRequested = true;\n\n                    _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);\n                  }\n                } else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__[\"FragmentState\"].APPENDING) {\n                  // Lower the buffer size and try again\n                  if (this.reduceMaxBufferLength(frag.duration)) {\n                    this.fragmentTracker.removeFragment(frag);\n                  }\n                } else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {\n                  // Stop gap for bad tracker / buffer flush behavior\n                  this.fragmentTracker.removeAllFragments();\n                }\n              };\n\n              _proto.getAppendedFrag = function getAppendedFrag(position) {\n                var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN);\n\n                if (fragOrPart && \"fragment\" in fragOrPart) {\n                  return fragOrPart.fragment;\n                }\n\n                return fragOrPart;\n              };\n\n              _proto.getBufferedFrag = function getBufferedFrag(position) {\n                return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN);\n              };\n\n              _proto.followingBufferedFrag = function followingBufferedFrag(frag) {\n                if (frag) {\n                  // try to get range of next fragment (500ms after this range)\n                  return this.getBufferedFrag(frag.end + 0.5);\n                }\n\n                return null;\n              };\n              /*\n    on immediate level switch :\n     - pause playback if playing\n     - cancel any pending load request\n     - and trigger a buffer flush\n  */\n\n              _proto.immediateLevelSwitch = function immediateLevelSwitch() {\n                this.abortCurrentFrag();\n                this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n              };\n              /**\n               * try to switch ASAP without breaking video playback:\n               * in order to ensure smooth but quick level switching,\n               * we need to find the next flushable buffer range\n               * we should take into account new segment fetch time\n               */\n\n              _proto.nextLevelSwitch = function nextLevelSwitch() {\n                var levels = this.levels,\n                  media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)\n\n                if (media !== null && media !== void 0 && media.readyState) {\n                  var fetchdelay;\n                  var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n\n                  if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {\n                    // flush buffer preceding current fragment (flush until current fragment start offset)\n                    // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n                    this.flushMainBuffer(0, fragPlayingCurrent.start - 1);\n                  }\n\n                  if (!media.paused && levels) {\n                    // add a safety delay of 1s\n                    var nextLevelId = this.CiderHls.nextLoadLevel;\n                    var nextLevel = levels[nextLevelId];\n                    var fragLastKbps = this.fragLastKbps;\n\n                    if (fragLastKbps && this.fragCurrent) {\n                      fetchdelay = (this.fragCurrent.duration * nextLevel.maxBitrate) / (1000 * fragLastKbps) + 1;\n                    } else {\n                      fetchdelay = 0;\n                    }\n                  } else {\n                    fetchdelay = 0;\n                  } // this.log('fetchdelay:'+fetchdelay);\n                  // find buffer range that will be reached once new fragment will be fetched\n\n                  var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n\n                  if (bufferedFrag) {\n                    // we can flush buffer range following this one without stalling playback\n                    var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n\n                    if (nextBufferedFrag) {\n                      // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n                      this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.\n\n                      var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;\n                      var fragDuration = nextBufferedFrag.duration;\n                      var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));\n                      this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n                    }\n                  }\n                }\n              };\n\n              _proto.abortCurrentFrag = function abortCurrentFrag() {\n                var fragCurrent = this.fragCurrent;\n                this.fragCurrent = null;\n\n                if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {\n                  fragCurrent.loader.abort();\n                }\n\n                if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].KEY_LOADING) {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                }\n\n                this.nextLoadPosition = this.getLoadPosition();\n              };\n\n              _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {\n                _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? \"video\" : null);\n              };\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                _BaseStreamController.prototype.onMediaAttached.call(this, event, data);\n\n                var media = data.media;\n                this.onvplaying = this.onMediaPlaying.bind(this);\n                this.onvseeked = this.onMediaSeeked.bind(this);\n                media.addEventListener(\"playing\", this.onvplaying);\n                media.addEventListener(\"seeked\", this.onvseeked);\n                this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__[\"default\"](this.config, media, this.fragmentTracker, this.CiderHls);\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                var media = this.media;\n\n                if (media) {\n                  media.removeEventListener(\"playing\", this.onvplaying);\n                  media.removeEventListener(\"seeked\", this.onvseeked);\n                  this.onvplaying = this.onvseeked = null;\n                  this.videoBuffer = null;\n                }\n\n                this.fragPlaying = null;\n\n                if (this.gapController) {\n                  this.gapController.destroy();\n                  this.gapController = null;\n                }\n\n                _BaseStreamController.prototype.onMediaDetaching.call(this);\n              };\n\n              _proto.onMediaPlaying = function onMediaPlaying() {\n                // tick to speed up FRAG_CHANGED triggering\n                this.tick();\n              };\n\n              _proto.onMediaSeeked = function onMediaSeeked() {\n                var media = this.media;\n                var currentTime = media ? media.currentTime : null;\n\n                if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(currentTime)) {\n                  this.log(\"Media seeked to \" + currentTime.toFixed(3));\n                } // tick to speed up FRAG_CHANGED triggering\n\n                this.tick();\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                // reset buffer on manifest loading\n                this.log(\"Trigger BUFFER_RESET\");\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_RESET, undefined);\n                this.fragmentTracker.removeAllFragments();\n                this.couldBacktrack = this.stalled = false;\n                this.startPosition = this.lastCurrentTime = 0;\n                this.fragPlaying = null;\n              };\n\n              _proto.onManifestParsed = function onManifestParsed(event, data) {\n                var aac = false;\n                var heaac = false;\n                var codec;\n                data.levels.forEach(function (level) {\n                  // detect if we have different kind of audio codecs used amongst playlists\n                  codec = level.audioCodec;\n\n                  if (codec) {\n                    if (codec.indexOf(\"mp4a.40.2\") !== -1) {\n                      aac = true;\n                    }\n\n                    if (codec.indexOf(\"mp4a.40.5\") !== -1) {\n                      heaac = true;\n                    }\n                  }\n                });\n                this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__[\"changeTypeSupported\"])();\n\n                if (this.audioCodecSwitch) {\n                  this.log(\"Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC\");\n                }\n\n                this.levels = data.levels;\n                this.startFragRequested = false;\n              };\n\n              _proto.onLevelLoading = function onLevelLoading(event, data) {\n                var levels = this.levels;\n\n                if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE) {\n                  return;\n                }\n\n                var level = levels[data.level];\n\n                if (!level.details || (level.details.live && this.levelLastLoaded !== data.level) || this.waitForCdnTuneIn(level.details)) {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_LEVEL;\n                }\n              };\n\n              _proto.onLevelLoaded = function onLevelLoaded(event, data) {\n                var _curLevel$details;\n\n                var levels = this.levels;\n                var newLevelId = data.level;\n                var newDetails = data.details;\n                var duration = newDetails.totalduration;\n\n                if (!levels) {\n                  this.warn(\"Levels were reset while loading level \" + newLevelId);\n                  return;\n                }\n\n                this.log(\"Level \" + newLevelId + \" loaded [\" + newDetails.startSN + \",\" + newDetails.endSN + \"], cc [\" + newDetails.startCC + \", \" + newDetails.endCC + \"] duration:\" + duration);\n                var fragCurrent = this.fragCurrent;\n\n                if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].FRAG_LOADING_WAITING_RETRY)) {\n                  if (fragCurrent.level !== data.level && fragCurrent.loader) {\n                    this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                    fragCurrent.loader.abort();\n                  }\n                }\n\n                var curLevel = levels[newLevelId];\n                var sliding = 0;\n\n                if (newDetails.live || ((_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live)) {\n                  if (!newDetails.fragments[0]) {\n                    newDetails.deltaUpdateFailed = true;\n                  }\n\n                  if (newDetails.deltaUpdateFailed) {\n                    return;\n                  }\n\n                  sliding = this.alignPlaylists(newDetails, curLevel.details);\n                } // override level info\n\n                curLevel.details = newDetails;\n                this.levelLastLoaded = newLevelId;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVEL_UPDATED, {\n                  details: newDetails,\n                  level: newLevelId,\n                }); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment\n\n                if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_LEVEL) {\n                  if (this.waitForCdnTuneIn(newDetails)) {\n                    // Wait for Low-Latency CDN Tune-in\n                    return;\n                  }\n\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                }\n\n                if (!this.startFragRequested) {\n                  this.setStartPosition(newDetails, sliding);\n                } else if (newDetails.live) {\n                  this.synchronizeToLiveEdge(newDetails);\n                } // trigger handler right now\n\n                this.tick();\n              };\n\n              _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {\n                var _frag$initSegment;\n\n                var frag = data.frag,\n                  part = data.part,\n                  payload = data.payload;\n                var levels = this.levels;\n\n                if (!levels) {\n                  this.warn(\"Levels were reset while fragment load was in progress. Fragment \" + frag.sn + \" of level \" + frag.level + \" will not be buffered\");\n                  return;\n                }\n\n                var currentLevel = levels[frag.level];\n                var details = currentLevel.details;\n\n                if (!details) {\n                  this.warn(\"Dropping fragment \" + frag.sn + \" of level \" + frag.level + \" after level details were reset\");\n                  return;\n                }\n\n                var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n\n                var accurateTimeOffset = details.PTSKnown || !details.live;\n                var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;\n\n                var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments\n                // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);\n\n                var transmuxer = (this.transmuxer =\n                  this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__[\"default\"](this.CiderHls, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)));\n                var partIndex = part ? part.index : -1;\n                var partial = partIndex !== -1;\n                var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__[\"ChunkMetadata\"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);\n                var initPTS = this.initPTS[frag.cc];\n                transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);\n              };\n\n              _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {\n                // if any URL found on new audio track, it is an alternate audio track\n                var fromAltAudio = this.altAudio;\n                var altAudio = !!data.url;\n                var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n                // don't do anything if we switch to alt audio: audio stream controller is handling it.\n                // we will just have to change buffer scheduling on audioTrackSwitched\n\n                if (!altAudio) {\n                  if (this.mediaBuffer !== this.media) {\n                    this.log(\"Switching on main audio, use media.buffered to schedule main fragment loading\");\n                    this.mediaBuffer = this.media;\n                    var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n\n                    if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {\n                      this.log(\"Switching to main audio track, cancel main fragment load\");\n                      fragCurrent.loader.abort();\n                    } // destroy transmuxer to force init segment generation (following audio switch)\n\n                    this.resetTransmuxer(); // switch to IDLE state to load new fragment\n\n                    this.resetLoadingState();\n                  } else if (this.audioOnly) {\n                    // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off\n                    this.resetTransmuxer();\n                  }\n\n                  var CiderHls = this.CiderHls; // If switching from alt to main audio, flush all audio and trigger track switched\n\n                  if (fromAltAudio) {\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_FLUSHING, {\n                      startOffset: 0,\n                      endOffset: Number.POSITIVE_INFINITY,\n                      type: \"audio\",\n                    });\n                  }\n\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].AUDIO_TRACK_SWITCHED, {\n                    id: trackId,\n                  });\n                }\n              };\n\n              _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {\n                var trackId = data.id;\n                var altAudio = !!this.CiderHls.audioTracks[trackId].url;\n\n                if (altAudio) {\n                  var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n\n                  if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n                    this.log(\"Switching on alternate audio, use video.buffered to schedule main fragment loading\");\n                    this.mediaBuffer = videoBuffer;\n                  }\n                }\n\n                this.altAudio = altAudio;\n                this.tick();\n              };\n\n              _proto.onBufferCreated = function onBufferCreated(event, data) {\n                var tracks = data.tracks;\n                var mediaTrack;\n                var name;\n                var alternate = false;\n\n                for (var type in tracks) {\n                  var track = tracks[type];\n\n                  if (track.id === \"main\") {\n                    name = type;\n                    mediaTrack = track; // keep video source buffer reference\n\n                    if (type === \"video\") {\n                      var videoTrack = tracks[type];\n\n                      if (videoTrack) {\n                        this.videoBuffer = videoTrack.buffer;\n                      }\n                    }\n                  } else {\n                    alternate = true;\n                  }\n                }\n\n                if (alternate && mediaTrack) {\n                  this.log(\"Alternate track found, use \" + name + \".buffered to schedule main fragment loading\");\n                  this.mediaBuffer = mediaTrack.buffer;\n                } else {\n                  this.mediaBuffer = this.media;\n                }\n              };\n\n              _proto.onFragBuffered = function onFragBuffered(event, data) {\n                var frag = data.frag,\n                  part = data.part;\n\n                if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN) {\n                  return;\n                }\n\n                if (this.fragContextChanged(frag)) {\n                  // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n                  // Avoid setting state back to IDLE, since that will interfere with a level switch\n                  this.warn(\"Fragment \" + frag.sn + (part ? \" p: \" + part.index : \"\") + \" of level \" + frag.level + \" finished buffering, but was aborted. state: \" + this.state);\n\n                  if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSED) {\n                    this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                  }\n\n                  return;\n                }\n\n                var stats = part ? part.stats : frag.stats;\n                this.fragLastKbps = Math.round((8 * stats.total) / (stats.buffering.end - stats.loading.first));\n\n                if (frag.sn !== \"initSegment\") {\n                  this.fragPrevious = frag;\n                }\n\n                this.fragBufferedComplete(frag, part);\n              };\n\n              _proto.onError = function onError(event, data) {\n                switch (data.details) {\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].FRAG_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].FRAG_LOAD_TIMEOUT:\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].KEY_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].KEY_LOAD_TIMEOUT:\n                    this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN, data);\n                    break;\n\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].LEVEL_LOAD_ERROR:\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].LEVEL_LOAD_TIMEOUT:\n                    if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].ERROR) {\n                      if (data.fatal) {\n                        // if fatal error, stop processing\n                        this.warn(\"\" + data.details);\n                        this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].ERROR;\n                      } else {\n                        // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n                        if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].WAITING_LEVEL) {\n                          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                        }\n                      }\n                    }\n\n                    break;\n\n                  case _errors__WEBPACK_IMPORTED_MODULE_11__[\"ErrorDetails\"].BUFFER_FULL_ERROR:\n                    // if in appending state\n                    if (data.parent === \"main\" && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSED)) {\n                      var flushBuffer = true;\n                      var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n                      // reduce max buf len if current position is buffered\n\n                      if (bufferedInfo && bufferedInfo.len > 0.5) {\n                        flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);\n                      }\n\n                      if (flushBuffer) {\n                        // current position is not buffered, but browser is still complaining about buffer full error\n                        // this happens on IE/Edge, refer to https://github.com/video-dev/CiderHls.js/pull/708\n                        // in that case flush the whole buffer to recover\n                        this.warn(\"buffer full error also media.currentTime is not buffered, flush main\"); // flush main buffer\n\n                        this.immediateLevelSwitch();\n                      }\n\n                      this.resetLoadingState();\n                    }\n\n                    break;\n\n                  default:\n                    break;\n                }\n              }; // Checks the health of the buffer and attempts to resolve playback stalls.\n\n              _proto.checkBuffer = function checkBuffer() {\n                var media = this.media,\n                  gapController = this.gapController;\n\n                if (!media || !gapController || !media.readyState) {\n                  // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n                  return;\n                } // Check combined buffer\n\n                var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__[\"BufferHelper\"].getBuffered(media);\n\n                if (!this.loadedmetadata && buffered.length) {\n                  this.loadedmetadata = true;\n                  this.seekToStartPos();\n                } else {\n                  // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers\n                  gapController.poll(this.lastCurrentTime);\n                }\n\n                this.lastCurrentTime = media.currentTime;\n              };\n\n              _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {\n                this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n                // in that case, reset startFragRequested flag\n\n                if (!this.loadedmetadata) {\n                  this.startFragRequested = false;\n                  this.nextLoadPosition = this.startPosition;\n                }\n\n                this.tickImmediate();\n              };\n\n              _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {\n                var type = _ref.type;\n\n                if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO || (this.audioOnly && !this.altAudio)) {\n                  var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;\n                  this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN);\n                }\n              };\n\n              _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {\n                this.levels = data.levels;\n              };\n\n              _proto.swapAudioCodec = function swapAudioCodec() {\n                this.audioCodecSwap = !this.audioCodecSwap;\n              };\n              /**\n               * Seeks to the set startPosition if not equal to the mediaElement's current time.\n               * @private\n               */\n\n              _proto.seekToStartPos = function seekToStartPos() {\n                var media = this.media;\n                var currentTime = media.currentTime;\n                var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered\n                // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n\n                if (startPosition >= 0 && currentTime < startPosition) {\n                  if (media.seeking) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_12__[\"logger\"].log(\"could not seek to \" + startPosition + \", already seeking at \" + currentTime);\n                    return;\n                  }\n\n                  var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__[\"BufferHelper\"].getBuffered(media);\n                  var bufferStart = buffered.length ? buffered.start(0) : 0;\n                  var delta = bufferStart - startPosition;\n\n                  if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_12__[\"logger\"].log(\"adjusting start position by \" + delta + \" to match buffer start\");\n                    startPosition += delta;\n                    this.startPosition = startPosition;\n                  }\n\n                  this.log(\"seek to target start position \" + startPosition + \" from current time \" + currentTime);\n                  media.currentTime = startPosition;\n                }\n              };\n\n              _proto._getAudioCodec = function _getAudioCodec(currentLevel) {\n                var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n\n                if (this.audioCodecSwap && audioCodec) {\n                  this.log(\"Swapping audio codec\");\n\n                  if (audioCodec.indexOf(\"mp4a.40.5\") !== -1) {\n                    audioCodec = \"mp4a.40.2\";\n                  } else {\n                    audioCodec = \"mp4a.40.5\";\n                  }\n                }\n\n                return audioCodec;\n              };\n\n              _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) {\n                var _this2 = this;\n\n                this._doFragLoad(frag).then(function (data) {\n                  var CiderHls = _this2.CiderHls;\n\n                  if (!data || CiderHls.nextLoadLevel || _this2.fragContextChanged(frag)) {\n                    return;\n                  }\n\n                  _this2.fragLoadError = 0;\n                  _this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].IDLE;\n                  _this2.startFragRequested = false;\n                  _this2.bitrateTest = false;\n                  var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered\n\n                  stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_LOADED, data);\n                });\n              };\n\n              _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {\n                var _id3$samples;\n\n                var id = \"main\";\n                var CiderHls = this.CiderHls;\n                var remuxResult = transmuxResult.remuxResult,\n                  chunkMeta = transmuxResult.chunkMeta;\n                var context = this.getCurrentContext(chunkMeta);\n\n                if (!context) {\n                  this.warn(\"The loading context changed while buffering fragment \" + chunkMeta.sn + \" of level \" + chunkMeta.level + \". This chunk will not be buffered.\");\n                  this.resetLiveStartWhenNotLoaded(chunkMeta.level);\n                  return;\n                }\n\n                var frag = context.frag,\n                  part = context.part,\n                  level = context.level;\n                var video = remuxResult.video,\n                  text = remuxResult.text,\n                  id3 = remuxResult.id3,\n                  initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if CiderHls.js is playing an alternate audio track\n\n                var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n                // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n\n                if (this.fragContextChanged(frag)) {\n                  return;\n                }\n\n                this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSING;\n\n                if (initSegment) {\n                  if (initSegment.tracks) {\n                    this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);\n\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_PARSING_INIT_SEGMENT, {\n                      frag: frag,\n                      id: id,\n                      tracks: initSegment.tracks,\n                    });\n                  } // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038\n\n                  var initPTS = initSegment.initPTS;\n                  var timescale = initSegment.timescale;\n\n                  if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(initPTS)) {\n                    this.initPTS[frag.cc] = initPTS;\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].INIT_PTS_FOUND, {\n                      frag: frag,\n                      id: id,\n                      initPTS: initPTS,\n                      timescale: timescale,\n                    });\n                  }\n                } // Avoid buffering if backtracking this fragment\n\n                if (video && remuxResult.independent !== false) {\n                  if (level.details) {\n                    var startPTS = video.startPTS,\n                      endPTS = video.endPTS,\n                      startDTS = video.startDTS,\n                      endDTS = video.endDTS;\n\n                    if (part) {\n                      part.elementaryStreams[video.type] = {\n                        startPTS: startPTS,\n                        endPTS: endPTS,\n                        startDTS: startDTS,\n                        endDTS: endDTS,\n                      };\n                    } else {\n                      if (video.firstKeyFrame && video.independent) {\n                        this.couldBacktrack = true;\n                      }\n\n                      if (video.dropped && video.independent) {\n                        // Backtrack if dropped frames create a gap after currentTime\n                        var pos = this.getLoadPosition() + this.config.maxBufferHole;\n\n                        if (pos < startPTS) {\n                          this.backtrack(frag);\n                          return;\n                        } // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial\n\n                        frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);\n                      }\n                    }\n\n                    frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);\n                    this.bufferFragmentData(video, frag, part, chunkMeta);\n                  }\n                } else if (remuxResult.independent === false) {\n                  this.backtrack(frag);\n                  return;\n                }\n\n                if (audio) {\n                  var _startPTS = audio.startPTS,\n                    _endPTS = audio.endPTS,\n                    _startDTS = audio.startDTS,\n                    _endDTS = audio.endDTS;\n\n                  if (part) {\n                    part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO] = {\n                      startPTS: _startPTS,\n                      endPTS: _endPTS,\n                      startDTS: _startDTS,\n                      endDTS: _endDTS,\n                    };\n                  }\n\n                  frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__[\"ElementaryStreamTypes\"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);\n                  this.bufferFragmentData(audio, frag, part, chunkMeta);\n                }\n\n                if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {\n                  var emittedID3 = {\n                    frag: frag,\n                    id: id,\n                    samples: id3.samples,\n                  };\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_PARSING_METADATA, emittedID3);\n                }\n\n                if (text) {\n                  var emittedText = {\n                    frag: frag,\n                    id: id,\n                    samples: text.samples,\n                  };\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_PARSING_USERDATA, emittedText);\n                }\n              };\n\n              _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {\n                var _this3 = this;\n\n                if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].PARSING) {\n                  return;\n                }\n\n                this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main\n\n                if (this.altAudio && !this.audioOnly) {\n                  delete tracks.audio;\n                } // include levelCodec in audio and video tracks\n\n                var audio = tracks.audio,\n                  video = tracks.video,\n                  audiovideo = tracks.audiovideo;\n\n                if (audio) {\n                  var audioCodec = currentLevel.audioCodec;\n                  var ua = navigator.userAgent.toLowerCase();\n\n                  if (this.audioCodecSwitch) {\n                    if (audioCodec) {\n                      if (audioCodec.indexOf(\"mp4a.40.5\") !== -1) {\n                        audioCodec = \"mp4a.40.2\";\n                      } else {\n                        audioCodec = \"mp4a.40.5\";\n                      }\n                    } // In the case that AAC and HE-AAC audio codecs are signalled in manifest,\n                    // force HE-AAC, as it seems that most browsers prefers it.\n                    // don't force HE-AAC if mono stream, or in Firefox\n\n                    if (audio.metadata.channelCount !== 1 && ua.indexOf(\"firefox\") === -1) {\n                      audioCodec = \"mp4a.40.5\";\n                    }\n                  } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n\n                  if (ua.indexOf(\"android\") !== -1 && audio.container !== \"audio/mpeg\") {\n                    // Exclude mpeg audio\n                    audioCodec = \"mp4a.40.2\";\n                    this.log(\"Android: force audio codec to \" + audioCodec);\n                  }\n\n                  if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {\n                    this.log('Swapping manifest audio codec \"' + currentLevel.audioCodec + '\" for \"' + audioCodec + '\"');\n                  }\n\n                  audio.levelCodec = audioCodec;\n                  audio.id = \"main\";\n                  this.log(\"Init audio buffer, container:\" + audio.container + \", codecs[selected/level/parsed]=[\" + (audioCodec || \"\") + \"/\" + (currentLevel.audioCodec || \"\") + \"/\" + audio.codec + \"]\");\n                }\n\n                if (video) {\n                  video.levelCodec = currentLevel.videoCodec;\n                  video.id = \"main\";\n                  this.log(\"Init video buffer, container:\" + video.container + \", codecs[level/parsed]=[\" + (currentLevel.videoCodec || \"\") + \"/\" + video.codec + \"]\");\n                }\n\n                if (audiovideo) {\n                  this.log(\"Init audiovideo buffer, container:\" + audiovideo.container + \", codecs[level/parsed]=[\" + (currentLevel.attrs.CODECS || \"\") + \"/\" + audiovideo.codec + \"]\");\n                }\n\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController\n\n                Object.keys(tracks).forEach(function (trackName) {\n                  var track = tracks[trackName];\n                  var initSegment = track.initSegment;\n\n                  if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {\n                    _this3.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].BUFFER_APPENDING, {\n                      type: trackName,\n                      data: initSegment,\n                      frag: frag,\n                      part: null,\n                      chunkMeta: chunkMeta,\n                      parent: frag.type,\n                    });\n                  }\n                }); // trigger handler right now\n\n                this.tick();\n              };\n\n              _proto.backtrack = function backtrack(frag) {\n                this.couldBacktrack = true; // Causes findFragments to backtrack through fragments to find the keyframe\n\n                this.resetTransmuxer();\n                this.flushBufferGap(frag);\n                var data = this.fragmentTracker.backtrack(frag);\n                this.fragPrevious = null;\n                this.nextLoadPosition = frag.start;\n\n                if (data) {\n                  this.resetFragmentLoading(frag);\n                } else {\n                  // Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"State\"].BACKTRACKING;\n                }\n              };\n\n              _proto.checkFragmentChanged = function checkFragmentChanged() {\n                var video = this.media;\n                var fragPlayingCurrent = null;\n\n                if (video && video.readyState > 1 && video.seeking === false) {\n                  var currentTime = video.currentTime;\n                  /* if video element is in seeked state, currentTime can only increase.\n        (assuming that playback rate is positive ...)\n        As sometimes currentTime jumps back to zero after a\n        media decode error, check this, to avoid seeking back to\n        wrong position after a media decode error\n      */\n\n                  if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__[\"BufferHelper\"].isBuffered(video, currentTime)) {\n                    fragPlayingCurrent = this.getAppendedFrag(currentTime);\n                  } else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__[\"BufferHelper\"].isBuffered(video, currentTime + 0.1)) {\n                    /* ensure that FRAG_CHANGED event is triggered at startup,\n          when first video frame is displayed and playback is paused.\n          add a tolerance of 100ms, in case current position is not buffered,\n          check if current pos+100ms is buffered and use that buffer range\n          for FRAG_CHANGED event reporting */\n                    fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);\n                  }\n\n                  if (fragPlayingCurrent) {\n                    var fragPlaying = this.fragPlaying;\n                    var fragCurrentLevel = fragPlayingCurrent.level;\n\n                    if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {\n                      this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].FRAG_CHANGED, {\n                        frag: fragPlayingCurrent,\n                      });\n\n                      if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {\n                        this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].LEVEL_SWITCHED, {\n                          level: fragCurrentLevel,\n                        });\n                      }\n\n                      this.fragPlaying = fragPlayingCurrent;\n                    }\n                  }\n                }\n              };\n\n              _createClass(StreamController, [\n                {\n                  key: \"nextLevel\",\n                  get: function get() {\n                    var frag = this.nextBufferedFrag;\n\n                    if (frag) {\n                      return frag.level;\n                    } else {\n                      return -1;\n                    }\n                  },\n                },\n                {\n                  key: \"currentLevel\",\n                  get: function get() {\n                    var media = this.media;\n\n                    if (media) {\n                      var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n\n                      if (fragPlayingCurrent) {\n                        return fragPlayingCurrent.level;\n                      }\n                    }\n\n                    return -1;\n                  },\n                },\n                {\n                  key: \"nextBufferedFrag\",\n                  get: function get() {\n                    var media = this.media;\n\n                    if (media) {\n                      // first get end range of current fragment\n                      var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n                      return this.followingBufferedFrag(fragPlayingCurrent);\n                    } else {\n                      return null;\n                    }\n                  },\n                },\n                {\n                  key: \"forceStartLoad\",\n                  get: function get() {\n                    return this._forceStartLoad;\n                  },\n                },\n              ]);\n\n              return StreamController;\n            })(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__[\"default\"]);\n\n            /***/\n          },\n\n        /***/ \"./src/controller/subtitle-stream-controller.ts\":\n          /*!******************************************************!*\\\n  !*** ./src/controller/subtitle-stream-controller.ts ***!\n  \\******************************************************/\n          /*! exports provided: SubtitleStreamController */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"SubtitleStreamController\", function () {\n              return SubtitleStreamController;\n            });\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ \"./src/utils/buffer-helper.ts\");\n            /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment-finders */ \"./src/controller/fragment-finders.ts\");\n            /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/discontinuities */ \"./src/utils/discontinuities.ts\");\n            /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./level-helper */ \"./src/controller/level-helper.ts\");\n            /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fragment-tracker */ \"./src/controller/fragment-tracker.ts\");\n            /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./base-stream-controller */ \"./src/controller/base-stream-controller.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/level */ \"./src/types/level.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            var TICK_INTERVAL = 500; // how often to tick in ms\n\n            var SubtitleStreamController = /*#__PURE__*/ (function (_BaseStreamController) {\n              _inheritsLoose(SubtitleStreamController, _BaseStreamController);\n\n              function SubtitleStreamController(CiderHls, fragmentTracker) {\n                var _this;\n\n                _this = _BaseStreamController.call(this, CiderHls, fragmentTracker, \"[subtitle-stream-controller]\") || this;\n                _this.levels = [];\n                _this.currentTrackId = -1;\n                _this.tracksBuffered = [];\n                _this.mainDetails = null;\n\n                _this._registerListeners();\n\n                return _this;\n              }\n\n              var _proto = SubtitleStreamController.prototype;\n\n              _proto.onHandlerDestroying = function onHandlerDestroying() {\n                this._unregisterListeners();\n\n                this.mainDetails = null;\n              };\n\n              _proto._registerListeners = function _registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, this.onError, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_LOADED, this.onLevelLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, this.onError, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n              };\n\n              _proto.startLoad = function startLoad() {\n                this.stopLoad();\n                this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].IDLE;\n                this.setInterval(TICK_INTERVAL);\n                this.tick();\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                this.mainDetails = null;\n                this.fragmentTracker.removeAllFragments();\n              };\n\n              _proto.onLevelLoaded = function onLevelLoaded(event, data) {\n                this.mainDetails = data.details;\n              };\n\n              _proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) {\n                var frag = data.frag,\n                  success = data.success;\n                this.fragPrevious = frag;\n                this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].IDLE;\n\n                if (!success) {\n                  return;\n                }\n\n                var buffered = this.tracksBuffered[this.currentTrackId];\n\n                if (!buffered) {\n                  return;\n                } // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n                // so we can re-use the logic used to detect how much has been buffered\n\n                var timeRange;\n                var fragStart = frag.start;\n\n                for (var i = 0; i < buffered.length; i++) {\n                  if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n                    timeRange = buffered[i];\n                    break;\n                  }\n                }\n\n                var fragEnd = frag.start + frag.duration;\n\n                if (timeRange) {\n                  timeRange.end = fragEnd;\n                } else {\n                  timeRange = {\n                    start: fragStart,\n                    end: fragEnd,\n                  };\n                  buffered.push(timeRange);\n                }\n\n                this.fragmentTracker.fragBuffered(frag);\n              };\n\n              _proto.onBufferFlushing = function onBufferFlushing(event, data) {\n                var startOffset = data.startOffset,\n                  endOffset = data.endOffset;\n\n                if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {\n                  var currentTrackId = this.currentTrackId,\n                    levels = this.levels;\n\n                  if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {\n                    return;\n                  }\n\n                  var trackDetails = levels[currentTrackId].details;\n                  var targetDuration = trackDetails.targetduration;\n                  var endOffsetSubtitles = endOffset - targetDuration;\n\n                  if (endOffsetSubtitles <= 0) {\n                    return;\n                  }\n\n                  data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);\n                  this.tracksBuffered.forEach(function (buffered) {\n                    for (var i = 0; i < buffered.length; ) {\n                      if (buffered[i].end <= endOffsetSubtitles) {\n                        buffered.shift();\n                        continue;\n                      } else if (buffered[i].start < endOffsetSubtitles) {\n                        buffered[i].start = endOffsetSubtitles;\n                      } else {\n                        break;\n                      }\n\n                      i++;\n                    }\n                  });\n                  this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, _types_loader__WEBPACK_IMPORTED_MODULE_8__[\"PlaylistLevelType\"].SUBTITLE);\n                }\n              }; // If something goes wrong, proceed to next frag, if we were processing one.\n\n              _proto.onError = function onError(event, data) {\n                var _this$fragCurrent;\n\n                var frag = data.frag; // don't handle error not related to subtitle fragment\n\n                if (!frag || frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_8__[\"PlaylistLevelType\"].SUBTITLE) {\n                  return;\n                }\n\n                if ((_this$fragCurrent = this.fragCurrent) !== null && _this$fragCurrent !== void 0 && _this$fragCurrent.loader) {\n                  this.fragCurrent.loader.abort();\n                }\n\n                this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].IDLE;\n              }; // Got all new subtitle levels.\n\n              _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref) {\n                var _this2 = this;\n\n                var subtitleTracks = _ref.subtitleTracks;\n                this.tracksBuffered = [];\n                this.levels = subtitleTracks.map(function (mediaPlaylist) {\n                  return new _types_level__WEBPACK_IMPORTED_MODULE_9__[\"Level\"](mediaPlaylist);\n                });\n                this.fragmentTracker.removeAllFragments();\n                this.fragPrevious = null;\n                this.levels.forEach(function (level) {\n                  _this2.tracksBuffered[level.id] = [];\n                });\n                this.mediaBuffer = null;\n              };\n\n              _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {\n                this.currentTrackId = data.id;\n\n                if (!this.levels.length || this.currentTrackId === -1) {\n                  this.clearInterval();\n                  return;\n                } // Check if track has the necessary details to load fragments\n\n                var currentTrack = this.levels[this.currentTrackId];\n\n                if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {\n                  this.mediaBuffer = this.mediaBufferTimeRanges;\n                } else {\n                  this.mediaBuffer = null;\n                }\n\n                if (currentTrack) {\n                  this.setInterval(TICK_INTERVAL);\n                }\n              }; // Got a new set of subtitle fragments.\n\n              _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {\n                var _track$details;\n\n                var newDetails = data.details,\n                  trackId = data.id;\n                var currentTrackId = this.currentTrackId,\n                  levels = this.levels;\n\n                if (!levels.length) {\n                  return;\n                }\n\n                var track = levels[currentTrackId];\n\n                if (trackId >= levels.length || trackId !== currentTrackId || !track) {\n                  return;\n                }\n\n                this.mediaBuffer = this.mediaBufferTimeRanges;\n\n                if (newDetails.live || ((_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live)) {\n                  var mainDetails = this.mainDetails;\n\n                  if (newDetails.deltaUpdateFailed || !mainDetails) {\n                    return;\n                  }\n\n                  var mainSlidingStartFragment = mainDetails.fragments[0];\n\n                  if (!track.details) {\n                    if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {\n                      Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__[\"alignMediaPlaylistByPDT\"])(newDetails, mainDetails);\n                    } else if (mainSlidingStartFragment) {\n                      // line up live playlist with main so that fragments in range are loaded\n                      Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__[\"addSliding\"])(newDetails, mainSlidingStartFragment.start);\n                    }\n                  } else {\n                    var sliding = this.alignPlaylists(newDetails, track.details);\n\n                    if (sliding === 0 && mainSlidingStartFragment) {\n                      // realign with main when there is no overlap with last refresh\n                      Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__[\"addSliding\"])(newDetails, mainSlidingStartFragment.start);\n                    }\n                  }\n                }\n\n                track.details = newDetails;\n                this.levelLastLoaded = trackId; // trigger handler right now\n\n                this.tick(); // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload\n\n                if (newDetails.live && !this.fragCurrent && this.media && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].IDLE) {\n                  var foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__[\"findFragmentByPTS\"])(null, newDetails.fragments, this.media.currentTime, 0);\n\n                  if (!foundFrag) {\n                    this.warn(\"Subtitle playlist not aligned with playback\");\n                    track.details = undefined;\n                  }\n                }\n              };\n\n              _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {\n                var frag = fragLoadedData.frag,\n                  payload = fragLoadedData.payload;\n                var decryptData = frag.decryptdata;\n                var CiderHls = this.CiderHls;\n\n                if (this.fragContextChanged(frag)) {\n                  return;\n                } // check to see if the payload needs to be decrypted\n\n                if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === \"AES-128\") {\n                  var startTime = performance.now(); // decrypt the subtitles\n\n                  this.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {\n                    var endTime = performance.now();\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].FRAG_DECRYPTED, {\n                      frag: frag,\n                      payload: decryptedData,\n                      stats: {\n                        tstart: startTime,\n                        tdecrypt: endTime,\n                      },\n                    });\n                  });\n                }\n              };\n\n              _proto.doTick = function doTick() {\n                if (!this.media) {\n                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].IDLE;\n                  return;\n                }\n\n                if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].IDLE) {\n                  var _foundFrag;\n\n                  var currentTrackId = this.currentTrackId,\n                    levels = this.levels;\n\n                  if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {\n                    return;\n                  } // Expand range of subs loaded by one target-duration in either direction to make up for misaligned playlists\n\n                  var trackDetails = levels[currentTrackId].details;\n                  var targetDuration = trackDetails.targetduration;\n                  var config = this.config,\n                    media = this.media;\n                  var bufferedInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__[\"BufferHelper\"].bufferedInfo(this.mediaBufferTimeRanges, media.currentTime - targetDuration, config.maxBufferHole);\n                  var targetBufferTime = bufferedInfo.end,\n                    bufferLen = bufferedInfo.len;\n                  var maxBufLen = this.getMaxBufferLength() + targetDuration;\n\n                  if (bufferLen > maxBufLen) {\n                    return;\n                  }\n\n                  console.assert(trackDetails, \"Subtitle track details are defined on idle subtitle stream controller tick\");\n                  var fragments = trackDetails.fragments;\n                  var fragLen = fragments.length;\n                  var end = trackDetails.edge;\n                  var foundFrag;\n                  var fragPrevious = this.fragPrevious;\n\n                  if (targetBufferTime < end) {\n                    var maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n\n                    if (fragPrevious && trackDetails.hasProgramDateTime) {\n                      foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__[\"findFragmentByPDT\"])(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);\n                    }\n\n                    if (!foundFrag) {\n                      foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__[\"findFragmentByPTS\"])(fragPrevious, fragments, targetBufferTime, maxFragLookUpTolerance);\n\n                      if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {\n                        foundFrag = fragments[0];\n                      }\n                    }\n                  } else {\n                    foundFrag = fragments[fragLen - 1];\n                  }\n\n                  if ((_foundFrag = foundFrag) !== null && _foundFrag !== void 0 && _foundFrag.encrypted) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].log(\"Loading key for \" + foundFrag.sn);\n                    this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"State\"].KEY_LOADING;\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].KEY_LOADING, {\n                      frag: foundFrag,\n                    });\n                  } else if (foundFrag && this.fragmentTracker.getState(foundFrag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__[\"FragmentState\"].NOT_LOADED) {\n                    // only load if fragment is not loaded\n                    this.loadFragment(foundFrag, trackDetails, targetBufferTime);\n                  }\n                }\n              };\n\n              _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {\n                this.fragCurrent = frag;\n\n                _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);\n              };\n\n              _createClass(SubtitleStreamController, [\n                {\n                  key: \"mediaBufferTimeRanges\",\n                  get: function get() {\n                    return this.tracksBuffered[this.currentTrackId] || [];\n                  },\n                },\n              ]);\n\n              return SubtitleStreamController;\n            })(_base_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"default\"]);\n\n            /***/\n          },\n\n        /***/ \"./src/controller/subtitle-track-controller.ts\":\n          /*!*****************************************************!*\\\n  !*** ./src/controller/subtitle-track-controller.ts ***!\n  \\*****************************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ \"./src/utils/texttrack-utils.ts\");\n            /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ \"./src/controller/base-playlist-controller.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            var SubtitleTrackController = /*#__PURE__*/ (function (_BasePlaylistControll) {\n              _inheritsLoose(SubtitleTrackController, _BasePlaylistControll);\n\n              // Enable/disable subtitle display rendering\n              function SubtitleTrackController(CiderHls) {\n                var _this;\n\n                _this = _BasePlaylistControll.call(this, CiderHls, \"[subtitle-track-controller]\") || this;\n                _this.media = null;\n                _this.tracks = [];\n                _this.groupId = null;\n                _this.tracksInGroup = [];\n                _this.trackId = -1;\n                _this.selectDefaultTrack = true;\n                _this.queuedDefaultTrack = -1;\n\n                _this.trackChangeListener = function () {\n                  return _this.onTextTracksChanged();\n                };\n\n                _this.asyncPollTrackChange = function () {\n                  return _this.pollTrackChange(0);\n                };\n\n                _this.useTextTrackPolling = false;\n                _this.subtitlePollingInterval = -1;\n                _this.subtitleDisplay = true;\n\n                _this.registerListeners();\n\n                return _this;\n              }\n\n              var _proto = SubtitleTrackController.prototype;\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners();\n                this.tracks.length = 0;\n                this.tracksInGroup.length = 0;\n                this.trackChangeListener = this.asyncPollTrackChange = null;\n\n                _BasePlaylistControll.prototype.destroy.call(this);\n              };\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_SWITCHING, this.onLevelSwitching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, this.onError, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_ATTACHED, this.onMediaAttached, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].MANIFEST_PARSED, this.onManifestParsed, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].LEVEL_SWITCHING, this.onLevelSwitching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, this.onError, this);\n              }; // Listen for subtitle track change, then extract the current track ID.\n\n              _proto.onMediaAttached = function onMediaAttached(event, data) {\n                this.media = data.media;\n\n                if (!this.media) {\n                  return;\n                }\n\n                if (this.queuedDefaultTrack > -1) {\n                  this.subtitleTrack = this.queuedDefaultTrack;\n                  this.queuedDefaultTrack = -1;\n                }\n\n                this.useTextTrackPolling = !(this.media.textTracks && \"onchange\" in this.media.textTracks);\n\n                if (this.useTextTrackPolling) {\n                  this.pollTrackChange(500);\n                } else {\n                  this.media.textTracks.addEventListener(\"change\", this.asyncPollTrackChange);\n                }\n              };\n\n              _proto.pollTrackChange = function pollTrackChange(timeout) {\n                self.clearInterval(this.subtitlePollingInterval);\n                this.subtitlePollingInterval = self.setInterval(this.trackChangeListener, timeout);\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                if (!this.media) {\n                  return;\n                }\n\n                self.clearInterval(this.subtitlePollingInterval);\n\n                if (!this.useTextTrackPolling) {\n                  this.media.textTracks.removeEventListener(\"change\", this.asyncPollTrackChange);\n                }\n\n                if (this.trackId > -1) {\n                  this.queuedDefaultTrack = this.trackId;\n                }\n\n                var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks\n\n                textTracks.forEach(function (track) {\n                  Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__[\"clearCurrentCues\"])(track);\n                }); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n\n                this.subtitleTrack = -1;\n                this.media = null;\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                this.tracks = [];\n                this.groupId = null;\n                this.tracksInGroup = [];\n                this.trackId = -1;\n                this.selectDefaultTrack = true;\n              }; // Fired whenever a new manifest is loaded.\n\n              _proto.onManifestParsed = function onManifestParsed(event, data) {\n                this.tracks = data.subtitleTracks;\n              };\n\n              _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {\n                var id = data.id,\n                  details = data.details;\n                var trackId = this.trackId;\n                var currentTrack = this.tracksInGroup[trackId];\n\n                if (!currentTrack) {\n                  this.warn(\"Invalid subtitle track id \" + id);\n                  return;\n                }\n\n                var curDetails = currentTrack.details;\n                currentTrack.details = data.details;\n                this.log(\"subtitle track \" + id + \" loaded [\" + details.startSN + \"-\" + details.endSN + \"]\");\n\n                if (id === this.trackId) {\n                  this.retryCount = 0;\n                  this.playlistLoaded(id, data, curDetails);\n                }\n              };\n\n              _proto.onLevelLoading = function onLevelLoading(event, data) {\n                this.switchLevel(data.level);\n              };\n\n              _proto.onLevelSwitching = function onLevelSwitching(event, data) {\n                this.switchLevel(data.level);\n              };\n\n              _proto.switchLevel = function switchLevel(levelIndex) {\n                var levelInfo = this.CiderHls.levels[levelIndex];\n\n                if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.textGroupIds)) {\n                  return;\n                }\n\n                var textGroupId = levelInfo.textGroupIds[levelInfo.urlId];\n\n                if (this.groupId !== textGroupId) {\n                  var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;\n                  var subtitleTracks = this.tracks.filter(function (track) {\n                    return !textGroupId || track.groupId === textGroupId;\n                  });\n                  this.tracksInGroup = subtitleTracks;\n                  var initialTrackId = this.findTrackId(lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.name) || this.findTrackId();\n                  this.groupId = textGroupId;\n                  var subtitleTracksUpdated = {\n                    subtitleTracks: subtitleTracks,\n                  };\n                  this.log(\"Updating subtitle tracks, \" + subtitleTracks.length + ' track(s) found in \"' + textGroupId + '\" group-id');\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);\n\n                  if (initialTrackId !== -1) {\n                    this.setSubtitleTrack(initialTrackId, lastTrack);\n                  }\n                }\n              };\n\n              _proto.findTrackId = function findTrackId(name) {\n                var textTracks = this.tracksInGroup;\n\n                for (var i = 0; i < textTracks.length; i++) {\n                  var track = textTracks[i];\n\n                  if (!this.selectDefaultTrack || track.default) {\n                    if (!name || name === track.name) {\n                      return track.id;\n                    }\n                  }\n                }\n\n                return -1;\n              };\n\n              _proto.onError = function onError(event, data) {\n                _BasePlaylistControll.prototype.onError.call(this, event, data);\n\n                if (data.fatal || !data.context) {\n                  return;\n                }\n\n                if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__[\"PlaylistContextType\"].SUBTITLE_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {\n                  this.retryLoadingOrFail(data);\n                }\n              };\n              /** get alternate subtitle tracks list from playlist **/\n\n              _proto.loadPlaylist = function loadPlaylist(CiderHlsUrlParameters) {\n                var currentTrack = this.tracksInGroup[this.trackId];\n\n                if (this.shouldLoadTrack(currentTrack)) {\n                  var id = currentTrack.id;\n                  var groupId = currentTrack.groupId;\n                  var url = currentTrack.url;\n\n                  if (CiderHlsUrlParameters) {\n                    try {\n                      url = CiderHlsUrlParameters.addDirectives(url);\n                    } catch (error) {\n                      this.warn(\"Could not construct new URL with CiderHls Delivery Directives: \" + error);\n                    }\n                  }\n\n                  this.log(\"Loading subtitle playlist for id \" + id);\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_LOADING, {\n                    url: url,\n                    id: id,\n                    groupId: groupId,\n                    deliveryDirectives: CiderHlsUrlParameters || null,\n                  });\n                }\n              };\n              /**\n               * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n               * This operates on the DOM textTracks.\n               * A value of -1 will disable all subtitle tracks.\n               */\n\n              _proto.toggleTrackModes = function toggleTrackModes(newId) {\n                var _this2 = this;\n\n                var media = this.media,\n                  subtitleDisplay = this.subtitleDisplay,\n                  trackId = this.trackId;\n\n                if (!media) {\n                  return;\n                }\n\n                var textTracks = filterSubtitleTracks(media.textTracks);\n                var groupTracks = textTracks.filter(function (track) {\n                  return track.groupId === _this2.groupId;\n                });\n\n                if (newId === -1) {\n                  [].slice.call(textTracks).forEach(function (track) {\n                    track.mode = \"disabled\";\n                  });\n                } else {\n                  var oldTrack = groupTracks[trackId];\n\n                  if (oldTrack) {\n                    oldTrack.mode = \"disabled\";\n                  }\n                }\n\n                var nextTrack = groupTracks[newId];\n\n                if (nextTrack) {\n                  nextTrack.mode = subtitleDisplay ? \"showing\" : \"hidden\";\n                }\n              };\n              /**\n               * This method is responsible for validating the subtitle index and periodically reloading if live.\n               * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n               */\n\n              _proto.setSubtitleTrack = function setSubtitleTrack(newId, lastTrack) {\n                var _tracks$newId;\n\n                var tracks = this.tracksInGroup; // setting this.subtitleTrack will trigger internal logic\n                // if media has not been attached yet, it will fail\n                // we keep a reference to the default track id\n                // and we'll set subtitleTrack when onMediaAttached is triggered\n\n                if (!this.media) {\n                  this.queuedDefaultTrack = newId;\n                  return;\n                }\n\n                if (this.trackId !== newId) {\n                  this.toggleTrackModes(newId);\n                } // exit if track id as already set or invalid\n\n                if ((this.trackId === newId && (newId === -1 || ((_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details))) || newId < -1 || newId >= tracks.length) {\n                  return;\n                } // stopping live reloading timer if any\n\n                this.clearTimer();\n                var track = tracks[newId];\n                this.log(\"Switching to subtitle track \" + newId);\n                this.trackId = newId;\n\n                if (track) {\n                  var id = track.id,\n                    _track$groupId = track.groupId,\n                    groupId = _track$groupId === void 0 ? \"\" : _track$groupId,\n                    name = track.name,\n                    type = track.type,\n                    url = track.url;\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_SWITCH, {\n                    id: id,\n                    groupId: groupId,\n                    name: name,\n                    type: type,\n                    url: url,\n                  });\n                  var CiderHlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);\n                  this.loadPlaylist(CiderHlsUrlParameters);\n                } else {\n                  // switch to -1\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].SUBTITLE_TRACK_SWITCH, {\n                    id: newId,\n                  });\n                }\n              };\n\n              _proto.onTextTracksChanged = function onTextTracksChanged() {\n                if (!this.useTextTrackPolling) {\n                  self.clearInterval(this.subtitlePollingInterval);\n                } // Media is undefined when switching streams via loadSource()\n\n                if (!this.media || !this.CiderHls.config.renderTextTracksNatively) {\n                  return;\n                }\n\n                var trackId = -1;\n                var tracks = filterSubtitleTracks(this.media.textTracks);\n\n                for (var id = 0; id < tracks.length; id++) {\n                  if (tracks[id].mode === \"hidden\") {\n                    // Do not break in case there is a following track with showing.\n                    trackId = id;\n                  } else if (tracks[id].mode === \"showing\") {\n                    trackId = id;\n                    break;\n                  }\n                } // Setting current subtitleTrack will invoke code.\n\n                if (this.subtitleTrack !== trackId) {\n                  this.subtitleTrack = trackId;\n                }\n              };\n\n              _createClass(SubtitleTrackController, [\n                {\n                  key: \"subtitleTracks\",\n                  get: function get() {\n                    return this.tracksInGroup;\n                  },\n                  /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/\n                },\n                {\n                  key: \"subtitleTrack\",\n                  get: function get() {\n                    return this.trackId;\n                  },\n                  set: function set(newId) {\n                    this.selectDefaultTrack = false;\n                    var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;\n                    this.setSubtitleTrack(newId, lastTrack);\n                  },\n                },\n              ]);\n\n              return SubtitleTrackController;\n            })(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n\n            function filterSubtitleTracks(textTrackList) {\n              var tracks = [];\n\n              for (var i = 0; i < textTrackList.length; i++) {\n                var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it\n\n                if (track.kind === \"subtitles\" && track.label) {\n                  tracks.push(textTrackList[i]);\n                }\n              }\n\n              return tracks;\n            }\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = SubtitleTrackController;\n\n            /***/\n          },\n\n        /***/ \"./src/controller/timeline-controller.ts\":\n          /*!***********************************************!*\\\n  !*** ./src/controller/timeline-controller.ts ***!\n  \\***********************************************/\n          /*! exports provided: TimelineController */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"TimelineController\", function () {\n              return TimelineController;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/cea-608-parser */ \"./src/utils/cea-608-parser.ts\");\n            /* harmony import */ var _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/output-filter */ \"./src/utils/output-filter.ts\");\n            /* harmony import */ var _utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/webvtt-parser */ \"./src/utils/webvtt-parser.ts\");\n            /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/texttrack-utils */ \"./src/utils/texttrack-utils.ts\");\n            /* harmony import */ var _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/imsc1-ttml-parser */ \"./src/utils/imsc1-ttml-parser.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            var TimelineController = /*#__PURE__*/ (function () {\n              function TimelineController(CiderHls) {\n                this.CiderHls = void 0;\n                this.media = null;\n                this.config = void 0;\n                this.enabled = true;\n                this.Cues = void 0;\n                this.textTracks = [];\n                this.tracks = [];\n                this.initPTS = [];\n                this.timescale = [];\n                this.unparsedVttFrags = [];\n                this.captionsTracks = {};\n                this.nonNativeCaptionsTracks = {};\n                this.cea608Parser1 = void 0;\n                this.cea608Parser2 = void 0;\n                this.lastSn = -1;\n                this.lastPartIndex = -1;\n                this.prevCC = -1;\n                this.vttCCs = newVTTCCs();\n                this.captionsProperties = void 0;\n                this.CiderHls = CiderHls;\n                this.config = CiderHls.config;\n                this.Cues = CiderHls.config.cueHandler;\n                this.captionsProperties = {\n                  textTrack1: {\n                    label: this.config.captionsTextTrack1Label,\n                    languageCode: this.config.captionsTextTrack1LanguageCode,\n                  },\n                  textTrack2: {\n                    label: this.config.captionsTextTrack2Label,\n                    languageCode: this.config.captionsTextTrack2LanguageCode,\n                  },\n                  textTrack3: {\n                    label: this.config.captionsTextTrack3Label,\n                    languageCode: this.config.captionsTextTrack3LanguageCode,\n                  },\n                  textTrack4: {\n                    label: this.config.captionsTextTrack4Label,\n                    languageCode: this.config.captionsTextTrack4LanguageCode,\n                  },\n                };\n\n                if (this.config.enableCEA708Captions) {\n                  var channel1 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__[\"default\"](this, \"textTrack1\");\n                  var channel2 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__[\"default\"](this, \"textTrack2\");\n                  var channel3 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__[\"default\"](this, \"textTrack3\");\n                  var channel4 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__[\"default\"](this, \"textTrack4\");\n                  this.cea608Parser1 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__[\"default\"](1, channel1, channel2);\n                  this.cea608Parser2 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__[\"default\"](3, channel3, channel4);\n                }\n\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADED, this.onManifestLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADING, this.onFragLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_DECRYPTED, this.onFragDecrypted, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].INIT_PTS_FOUND, this.onInitPtsFound, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this);\n              }\n\n              var _proto = TimelineController.prototype;\n\n              _proto.destroy = function destroy() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_ATTACHING, this.onMediaAttaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MEDIA_DETACHING, this.onMediaDetaching, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADED, this.onManifestLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADING, this.onFragLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADED, this.onFragLoaded, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_DECRYPTED, this.onFragDecrypted, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].INIT_PTS_FOUND, this.onInitPtsFound, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].BUFFER_FLUSHING, this.onBufferFlushing, this); // @ts-ignore\n\n                this.CiderHls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;\n              };\n\n              _proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {\n                // skip cues which overlap more than 50% with previously parsed time ranges\n                var merged = false;\n\n                for (var i = cueRanges.length; i--; ) {\n                  var cueRange = cueRanges[i];\n                  var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n\n                  if (overlap >= 0) {\n                    cueRange[0] = Math.min(cueRange[0], startTime);\n                    cueRange[1] = Math.max(cueRange[1], endTime);\n                    merged = true;\n\n                    if (overlap / (endTime - startTime) > 0.5) {\n                      return;\n                    }\n                  }\n                }\n\n                if (!merged) {\n                  cueRanges.push([startTime, endTime]);\n                }\n\n                if (this.config.renderTextTracksNatively) {\n                  var track = this.captionsTracks[trackName];\n                  this.Cues.newCue(track, startTime, endTime, screen);\n                } else {\n                  var cues = this.Cues.newCue(null, startTime, endTime, screen);\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].CUES_PARSED, {\n                    type: \"captions\",\n                    cues: cues,\n                    track: trackName,\n                  });\n                }\n              }; // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n\n              _proto.onInitPtsFound = function onInitPtsFound(event, _ref) {\n                var _this = this;\n\n                var frag = _ref.frag,\n                  id = _ref.id,\n                  initPTS = _ref.initPTS,\n                  timescale = _ref.timescale;\n                var unparsedVttFrags = this.unparsedVttFrags;\n\n                if (id === \"main\") {\n                  this.initPTS[frag.cc] = initPTS;\n                  this.timescale[frag.cc] = timescale;\n                } // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n                // Parse any unparsed fragments upon receiving the initial PTS.\n\n                if (unparsedVttFrags.length) {\n                  this.unparsedVttFrags = [];\n                  unparsedVttFrags.forEach(function (frag) {\n                    _this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADED, frag);\n                  });\n                }\n              };\n\n              _proto.getExistingTrack = function getExistingTrack(trackName) {\n                var media = this.media;\n\n                if (media) {\n                  for (var i = 0; i < media.textTracks.length; i++) {\n                    var textTrack = media.textTracks[i];\n\n                    if (textTrack[trackName]) {\n                      return textTrack;\n                    }\n                  }\n                }\n\n                return null;\n              };\n\n              _proto.createCaptionsTrack = function createCaptionsTrack(trackName) {\n                if (this.config.renderTextTracksNatively) {\n                  this.createNativeTrack(trackName);\n                } else {\n                  this.createNonNativeTrack(trackName);\n                }\n              };\n\n              _proto.createNativeTrack = function createNativeTrack(trackName) {\n                if (this.captionsTracks[trackName]) {\n                  return;\n                }\n\n                var captionsProperties = this.captionsProperties,\n                  captionsTracks = this.captionsTracks,\n                  media = this.media;\n                var _captionsProperties$t = captionsProperties[trackName],\n                  label = _captionsProperties$t.label,\n                  languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.\n\n                var existingTrack = this.getExistingTrack(trackName);\n\n                if (!existingTrack) {\n                  var textTrack = this.createTextTrack(\"captions\", label, languageCode);\n\n                  if (textTrack) {\n                    // Set a special property on the track so we know it's managed by CiderHls.js\n                    textTrack[trackName] = true;\n                    captionsTracks[trackName] = textTrack;\n                  }\n                } else {\n                  captionsTracks[trackName] = existingTrack;\n                  Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"clearCurrentCues\"])(captionsTracks[trackName]);\n                  Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"sendAddTrackEvent\"])(captionsTracks[trackName], media);\n                }\n              };\n\n              _proto.createNonNativeTrack = function createNonNativeTrack(trackName) {\n                if (this.nonNativeCaptionsTracks[trackName]) {\n                  return;\n                } // Create a list of a single track for the provider to consume\n\n                var trackProperties = this.captionsProperties[trackName];\n\n                if (!trackProperties) {\n                  return;\n                }\n\n                var label = trackProperties.label;\n                var track = {\n                  _id: trackName,\n                  label: label,\n                  kind: \"captions\",\n                  default: trackProperties.media ? !!trackProperties.media.default : false,\n                  closedCaptions: trackProperties.media,\n                };\n                this.nonNativeCaptionsTracks[trackName] = track;\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].NON_NATIVE_TEXT_TRACKS_FOUND, {\n                  tracks: [track],\n                });\n              };\n\n              _proto.createTextTrack = function createTextTrack(kind, label, lang) {\n                var media = this.media;\n\n                if (!media) {\n                  return;\n                }\n\n                return media.addTextTrack(kind, label, lang);\n              };\n\n              _proto.onMediaAttaching = function onMediaAttaching(event, data) {\n                this.media = data.media;\n\n                this._cleanTracks();\n              };\n\n              _proto.onMediaDetaching = function onMediaDetaching() {\n                var captionsTracks = this.captionsTracks;\n                Object.keys(captionsTracks).forEach(function (trackName) {\n                  Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"clearCurrentCues\"])(captionsTracks[trackName]);\n                  delete captionsTracks[trackName];\n                });\n                this.nonNativeCaptionsTracks = {};\n              };\n\n              _proto.onManifestLoading = function onManifestLoading() {\n                this.lastSn = -1; // Detect discontinuity in fragment parsing\n\n                this.lastPartIndex = -1;\n                this.prevCC = -1;\n                this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests\n\n                this._cleanTracks();\n\n                this.tracks = [];\n                this.captionsTracks = {};\n                this.nonNativeCaptionsTracks = {};\n                this.textTracks = [];\n                this.unparsedVttFrags = this.unparsedVttFrags || [];\n                this.initPTS = [];\n                this.timescale = [];\n\n                if (this.cea608Parser1 && this.cea608Parser2) {\n                  this.cea608Parser1.reset();\n                  this.cea608Parser2.reset();\n                }\n              };\n\n              _proto._cleanTracks = function _cleanTracks() {\n                // clear outdated subtitles\n                var media = this.media;\n\n                if (!media) {\n                  return;\n                }\n\n                var textTracks = media.textTracks;\n\n                if (textTracks) {\n                  for (var i = 0; i < textTracks.length; i++) {\n                    Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"clearCurrentCues\"])(textTracks[i]);\n                  }\n                }\n              };\n\n              _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) {\n                var _this2 = this;\n\n                this.textTracks = [];\n                var tracks = data.subtitleTracks || [];\n                var hasIMSC1 = tracks.some(function (track) {\n                  return track.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__[\"IMSC1_CODEC\"];\n                });\n\n                if (this.config.enableWebVTT || (hasIMSC1 && this.config.enableIMSC1)) {\n                  var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;\n                  this.tracks = tracks || [];\n\n                  if (this.config.renderTextTracksNatively) {\n                    var inUseTracks = this.media ? this.media.textTracks : [];\n                    this.tracks.forEach(function (track, index) {\n                      var textTrack;\n\n                      if (index < inUseTracks.length) {\n                        var inUseTrack = null;\n\n                        for (var i = 0; i < inUseTracks.length; i++) {\n                          if (canReuseVttTextTrack(inUseTracks[i], track)) {\n                            inUseTrack = inUseTracks[i];\n                            break;\n                          }\n                        } // Reuse tracks with the same label, but do not reuse 608/708 tracks\n\n                        if (inUseTrack) {\n                          textTrack = inUseTrack;\n                        }\n                      }\n\n                      if (textTrack) {\n                        Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"clearCurrentCues\"])(textTrack);\n                      } else {\n                        textTrack = _this2.createTextTrack(\"subtitles\", track.name, track.lang);\n\n                        if (textTrack) {\n                          textTrack.mode = \"disabled\";\n                        }\n                      }\n\n                      if (textTrack) {\n                        textTrack.groupId = track.groupId;\n\n                        _this2.textTracks.push(textTrack);\n                      }\n                    });\n                  } else if (!sameTracks && this.tracks && this.tracks.length) {\n                    // Create a list of tracks for the provider to consume\n                    var tracksList = this.tracks.map(function (track) {\n                      return {\n                        label: track.name,\n                        kind: track.type.toLowerCase(),\n                        default: track.default,\n                        subtitleTrack: track,\n                      };\n                    });\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].NON_NATIVE_TEXT_TRACKS_FOUND, {\n                      tracks: tracksList,\n                    });\n                  }\n                }\n              };\n\n              _proto.onManifestLoaded = function onManifestLoaded(event, data) {\n                var _this3 = this;\n\n                if (this.config.enableCEA708Captions && data.captions) {\n                  data.captions.forEach(function (captionsTrack) {\n                    var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);\n\n                    if (!instreamIdMatch) {\n                      return;\n                    }\n\n                    var trackName = \"textTrack\" + instreamIdMatch[1];\n                    var trackProperties = _this3.captionsProperties[trackName];\n\n                    if (!trackProperties) {\n                      return;\n                    }\n\n                    trackProperties.label = captionsTrack.name;\n\n                    if (captionsTrack.lang) {\n                      // optional attribute\n                      trackProperties.languageCode = captionsTrack.lang;\n                    }\n\n                    trackProperties.media = captionsTrack;\n                  });\n                }\n              };\n\n              _proto.onFragLoading = function onFragLoading(event, data) {\n                var cea608Parser1 = this.cea608Parser1,\n                  cea608Parser2 = this.cea608Parser2,\n                  lastSn = this.lastSn,\n                  lastPartIndex = this.lastPartIndex;\n\n                if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n                  return;\n                } // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n\n                if (data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__[\"PlaylistLevelType\"].MAIN) {\n                  var _data$part$index, _data$part;\n\n                  var sn = data.frag.sn;\n                  var partIndex = (_data$part$index = data === null || data === void 0 ? void 0 : (_data$part = data.part) === null || _data$part === void 0 ? void 0 : _data$part.index) != null ? _data$part$index : -1;\n\n                  if (!(sn === lastSn + 1 || (sn === lastSn && partIndex === lastPartIndex + 1))) {\n                    cea608Parser1.reset();\n                    cea608Parser2.reset();\n                  }\n\n                  this.lastSn = sn;\n                  this.lastPartIndex = partIndex;\n                }\n              };\n\n              _proto.onFragLoaded = function onFragLoaded(event, data) {\n                var frag = data.frag,\n                  payload = data.payload;\n                var initPTS = this.initPTS,\n                  unparsedVttFrags = this.unparsedVttFrags;\n\n                if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__[\"PlaylistLevelType\"].SUBTITLE) {\n                  // If fragment is subtitle type, parse as WebVTT.\n                  if (payload.byteLength) {\n                    // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n                    if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(initPTS[frag.cc])) {\n                      unparsedVttFrags.push(data);\n\n                      if (initPTS.length) {\n                        // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.\n                        this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_FRAG_PROCESSED, {\n                          success: false,\n                          frag: frag,\n                          error: new Error(\"Missing initial subtitle PTS\"),\n                        });\n                      }\n\n                      return;\n                    }\n\n                    var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n\n                    if (decryptData == null || decryptData.key == null || decryptData.method !== \"AES-128\") {\n                      var trackPlaylistMedia = this.tracks[frag.level];\n                      var vttCCs = this.vttCCs;\n\n                      if (!vttCCs[frag.cc]) {\n                        vttCCs[frag.cc] = {\n                          start: frag.start,\n                          prevCC: this.prevCC,\n                          new: true,\n                        };\n                        this.prevCC = frag.cc;\n                      }\n\n                      if (trackPlaylistMedia && trackPlaylistMedia.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__[\"IMSC1_CODEC\"]) {\n                        this._parseIMSC1(frag, payload);\n                      } else {\n                        this._parseVTTs(frag, payload, vttCCs);\n                      }\n                    }\n                  } else {\n                    // In case there is no payload, finish unsuccessfully.\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_FRAG_PROCESSED, {\n                      success: false,\n                      frag: frag,\n                      error: new Error(\"Empty subtitle payload\"),\n                    });\n                  }\n                }\n              };\n\n              _proto._parseIMSC1 = function _parseIMSC1(frag, payload) {\n                var _this4 = this;\n\n                var CiderHls = this.CiderHls;\n                Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__[\"parseIMSC1\"])(\n                  payload,\n                  this.initPTS[frag.cc],\n                  this.timescale[frag.cc],\n                  function (cues) {\n                    _this4._appendCues(cues, frag.level);\n\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_FRAG_PROCESSED, {\n                      success: true,\n                      frag: frag,\n                    });\n                  },\n                  function (error) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_8__[\"logger\"].log(\"Failed to parse IMSC1: \" + error);\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_FRAG_PROCESSED, {\n                      success: false,\n                      frag: frag,\n                      error: error,\n                    });\n                  }\n                );\n              };\n\n              _proto._parseVTTs = function _parseVTTs(frag, payload, vttCCs) {\n                var _this5 = this;\n\n                var CiderHls = this.CiderHls; // Parse the WebVTT file contents.\n\n                Object(_utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__[\"parseWebVTT\"])(\n                  payload,\n                  this.initPTS[frag.cc],\n                  this.timescale[frag.cc],\n                  vttCCs,\n                  frag.cc,\n                  frag.start,\n                  function (cues) {\n                    _this5._appendCues(cues, frag.level);\n\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_FRAG_PROCESSED, {\n                      success: true,\n                      frag: frag,\n                    });\n                  },\n                  function (error) {\n                    _this5._fallbackToIMSC1(frag, payload); // Something went wrong while parsing. Trigger event with success false.\n\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_8__[\"logger\"].log(\"Failed to parse VTT cue: \" + error);\n                    CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_FRAG_PROCESSED, {\n                      success: false,\n                      frag: frag,\n                      error: error,\n                    });\n                  }\n                );\n              };\n\n              _proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) {\n                var _this6 = this;\n\n                // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result\n                var trackPlaylistMedia = this.tracks[frag.level];\n\n                if (!trackPlaylistMedia.textCodec) {\n                  Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__[\"parseIMSC1\"])(\n                    payload,\n                    this.initPTS[frag.cc],\n                    this.timescale[frag.cc],\n                    function () {\n                      trackPlaylistMedia.textCodec = _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__[\"IMSC1_CODEC\"];\n\n                      _this6._parseIMSC1(frag, payload);\n                    },\n                    function () {\n                      trackPlaylistMedia.textCodec = \"wvtt\";\n                    }\n                  );\n                }\n              };\n\n              _proto._appendCues = function _appendCues(cues, fragLevel) {\n                var CiderHls = this.CiderHls;\n\n                if (this.config.renderTextTracksNatively) {\n                  var textTrack = this.textTracks[fragLevel]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n                  // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n                  // and trying to access getCueById method of cues will throw an exception\n                  // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.\n\n                  if (textTrack.mode === \"disabled\") {\n                    return;\n                  }\n\n                  cues.forEach(function (cue) {\n                    return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"addCueToTrack\"])(textTrack, cue);\n                  });\n                } else {\n                  var currentTrack = this.tracks[fragLevel];\n                  var track = currentTrack.default ? \"default\" : \"subtitles\" + fragLevel;\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].CUES_PARSED, {\n                    type: \"subtitles\",\n                    cues: cues,\n                    track: track,\n                  });\n                }\n              };\n\n              _proto.onFragDecrypted = function onFragDecrypted(event, data) {\n                var frag = data.frag;\n\n                if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__[\"PlaylistLevelType\"].SUBTITLE) {\n                  if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(this.initPTS[frag.cc])) {\n                    this.unparsedVttFrags.push(data);\n                    return;\n                  }\n\n                  this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_LOADED, data);\n                }\n              };\n\n              _proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() {\n                this.tracks = [];\n                this.captionsTracks = {};\n              };\n\n              _proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) {\n                var cea608Parser1 = this.cea608Parser1,\n                  cea608Parser2 = this.cea608Parser2;\n\n                if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n                  return;\n                } // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n                // It will create the proper timestamps based on the PTS value\n\n                for (var i = 0; i < data.samples.length; i++) {\n                  var ccBytes = data.samples[i].bytes;\n\n                  if (ccBytes) {\n                    var ccdatas = this.extractCea608Data(ccBytes);\n                    cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);\n                    cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);\n                  }\n                }\n              };\n\n              _proto.onBufferFlushing = function onBufferFlushing(event, _ref2) {\n                var startOffset = _ref2.startOffset,\n                  endOffset = _ref2.endOffset,\n                  endOffsetSubtitles = _ref2.endOffsetSubtitles,\n                  type = _ref2.type;\n                var media = this.media;\n\n                if (!media || media.currentTime < endOffset) {\n                  return;\n                } // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed\n                // Forward cues are never removed because we can loose streamed 608 content from recent fragments\n\n                if (!type || type === \"video\") {\n                  var captionsTracks = this.captionsTracks;\n                  Object.keys(captionsTracks).forEach(function (trackName) {\n                    return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"removeCuesInRange\"])(captionsTracks[trackName], startOffset, endOffset);\n                  });\n                }\n\n                if (this.config.renderTextTracksNatively) {\n                  // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed\n                  if (startOffset === 0 && endOffsetSubtitles !== undefined) {\n                    var textTracks = this.textTracks;\n                    Object.keys(textTracks).forEach(function (trackName) {\n                      return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__[\"removeCuesInRange\"])(textTracks[trackName], startOffset, endOffsetSubtitles);\n                    });\n                  }\n                }\n              };\n\n              _proto.extractCea608Data = function extractCea608Data(byteArray) {\n                var count = byteArray[0] & 31;\n                var position = 2;\n                var actualCCBytes = [[], []];\n\n                for (var j = 0; j < count; j++) {\n                  var tmpByte = byteArray[position++];\n                  var ccbyte1 = 0x7f & byteArray[position++];\n                  var ccbyte2 = 0x7f & byteArray[position++];\n                  var ccValid = (4 & tmpByte) !== 0;\n                  var ccType = 3 & tmpByte;\n\n                  if (ccbyte1 === 0 && ccbyte2 === 0) {\n                    continue;\n                  }\n\n                  if (ccValid) {\n                    if (ccType === 0 || ccType === 1) {\n                      actualCCBytes[ccType].push(ccbyte1);\n                      actualCCBytes[ccType].push(ccbyte2);\n                    }\n                  }\n                }\n\n                return actualCCBytes;\n              };\n\n              return TimelineController;\n            })();\n\n            function canReuseVttTextTrack(inUseTrack, manifestTrack) {\n              return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);\n            }\n\n            function intersection(x1, x2, y1, y2) {\n              return Math.min(x2, y2) - Math.max(x1, y1);\n            }\n\n            function newVTTCCs() {\n              return {\n                ccOffset: 0,\n                presentationOffset: 0,\n                0: {\n                  start: 0,\n                  prevCC: -1,\n                  new: false,\n                },\n              };\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/crypt/aes-crypto.ts\":\n          /*!*********************************!*\\\n  !*** ./src/crypt/aes-crypto.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return AESCrypto;\n            });\n            var AESCrypto = /*#__PURE__*/ (function () {\n              function AESCrypto(subtle, iv) {\n                this.subtle = void 0;\n                this.aesIV = void 0;\n                this.subtle = subtle;\n                this.aesIV = iv;\n              }\n\n              var _proto = AESCrypto.prototype;\n\n              _proto.decrypt = function decrypt(data, key) {\n                return this.subtle.decrypt(\n                  {\n                    name: \"AES-CBC\",\n                    iv: this.aesIV,\n                  },\n                  key,\n                  data\n                );\n              };\n\n              return AESCrypto;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/crypt/aes-decryptor.ts\":\n          /*!************************************!*\\\n  !*** ./src/crypt/aes-decryptor.ts ***!\n  \\************************************/\n          /*! exports provided: removePadding, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"removePadding\", function () {\n              return removePadding;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return AESDecryptor;\n            });\n            /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ \"./src/utils/typed-array.ts\");\n            // PKCS7\n\n            function removePadding(array) {\n              var outputBytes = array.byteLength;\n              var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);\n\n              if (paddingBytes) {\n                return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__[\"sliceUint8\"])(array, 0, outputBytes - paddingBytes);\n              }\n\n              return array;\n            }\n\n            var AESDecryptor = /*#__PURE__*/ (function () {\n              function AESDecryptor() {\n                this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n                this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n                this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n                this.sBox = new Uint32Array(256);\n                this.invSBox = new Uint32Array(256);\n                this.key = new Uint32Array(0);\n                this.ksRows = 0;\n                this.keySize = 0;\n                this.keySchedule = void 0;\n                this.invKeySchedule = void 0;\n                this.initTable();\n              } // Using view.getUint32() also swaps the byte order.\n\n              var _proto = AESDecryptor.prototype;\n\n              _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {\n                var view = new DataView(arrayBuffer);\n                var newArray = new Uint32Array(4);\n\n                for (var i = 0; i < 4; i++) {\n                  newArray[i] = view.getUint32(i * 4);\n                }\n\n                return newArray;\n              };\n\n              _proto.initTable = function initTable() {\n                var sBox = this.sBox;\n                var invSBox = this.invSBox;\n                var subMix = this.subMix;\n                var subMix0 = subMix[0];\n                var subMix1 = subMix[1];\n                var subMix2 = subMix[2];\n                var subMix3 = subMix[3];\n                var invSubMix = this.invSubMix;\n                var invSubMix0 = invSubMix[0];\n                var invSubMix1 = invSubMix[1];\n                var invSubMix2 = invSubMix[2];\n                var invSubMix3 = invSubMix[3];\n                var d = new Uint32Array(256);\n                var x = 0;\n                var xi = 0;\n                var i = 0;\n\n                for (i = 0; i < 256; i++) {\n                  if (i < 128) {\n                    d[i] = i << 1;\n                  } else {\n                    d[i] = (i << 1) ^ 0x11b;\n                  }\n                }\n\n                for (i = 0; i < 256; i++) {\n                  var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n                  sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n                  sBox[x] = sx;\n                  invSBox[sx] = x; // Compute multiplication\n\n                  var x2 = d[x];\n                  var x4 = d[x2];\n                  var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables\n\n                  var t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n                  subMix0[x] = (t << 24) | (t >>> 8);\n                  subMix1[x] = (t << 16) | (t >>> 16);\n                  subMix2[x] = (t << 8) | (t >>> 24);\n                  subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables\n\n                  t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n                  invSubMix0[sx] = (t << 24) | (t >>> 8);\n                  invSubMix1[sx] = (t << 16) | (t >>> 16);\n                  invSubMix2[sx] = (t << 8) | (t >>> 24);\n                  invSubMix3[sx] = t; // Compute next counter\n\n                  if (!x) {\n                    x = xi = 1;\n                  } else {\n                    x = x2 ^ d[d[d[x8 ^ x2]]];\n                    xi ^= d[d[xi]];\n                  }\n                }\n              };\n\n              _proto.expandKey = function expandKey(keyBuffer) {\n                // convert keyBuffer to Uint32Array\n                var key = this.uint8ArrayToUint32Array_(keyBuffer);\n                var sameKey = true;\n                var offset = 0;\n\n                while (offset < key.length && sameKey) {\n                  sameKey = key[offset] === this.key[offset];\n                  offset++;\n                }\n\n                if (sameKey) {\n                  return;\n                }\n\n                this.key = key;\n                var keySize = (this.keySize = key.length);\n\n                if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n                  throw new Error(\"Invalid aes key size=\" + keySize);\n                }\n\n                var ksRows = (this.ksRows = (keySize + 6 + 1) * 4);\n                var ksRow;\n                var invKsRow;\n                var keySchedule = (this.keySchedule = new Uint32Array(ksRows));\n                var invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows));\n                var sbox = this.sBox;\n                var rcon = this.rcon;\n                var invSubMix = this.invSubMix;\n                var invSubMix0 = invSubMix[0];\n                var invSubMix1 = invSubMix[1];\n                var invSubMix2 = invSubMix[2];\n                var invSubMix3 = invSubMix[3];\n                var prev;\n                var t;\n\n                for (ksRow = 0; ksRow < ksRows; ksRow++) {\n                  if (ksRow < keySize) {\n                    prev = keySchedule[ksRow] = key[ksRow];\n                    continue;\n                  }\n\n                  t = prev;\n\n                  if (ksRow % keySize === 0) {\n                    // Rot word\n                    t = (t << 8) | (t >>> 24); // Sub word\n\n                    t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff]; // Mix Rcon\n\n                    t ^= rcon[(ksRow / keySize) | 0] << 24;\n                  } else if (keySize > 6 && ksRow % keySize === 4) {\n                    // Sub word\n                    t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n                  }\n\n                  keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n                }\n\n                for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n                  ksRow = ksRows - invKsRow;\n\n                  if (invKsRow & 3) {\n                    t = keySchedule[ksRow];\n                  } else {\n                    t = keySchedule[ksRow - 4];\n                  }\n\n                  if (invKsRow < 4 || ksRow <= 4) {\n                    invKeySchedule[invKsRow] = t;\n                  } else {\n                    invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];\n                  }\n\n                  invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n                }\n              }; // Adding this as a method greatly improves performance.\n\n              _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {\n                return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);\n              };\n\n              _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {\n                var nRounds = this.keySize + 6;\n                var invKeySchedule = this.invKeySchedule;\n                var invSBOX = this.invSBox;\n                var invSubMix = this.invSubMix;\n                var invSubMix0 = invSubMix[0];\n                var invSubMix1 = invSubMix[1];\n                var invSubMix2 = invSubMix[2];\n                var invSubMix3 = invSubMix[3];\n                var initVector = this.uint8ArrayToUint32Array_(aesIV);\n                var initVector0 = initVector[0];\n                var initVector1 = initVector[1];\n                var initVector2 = initVector[2];\n                var initVector3 = initVector[3];\n                var inputInt32 = new Int32Array(inputArrayBuffer);\n                var outputInt32 = new Int32Array(inputInt32.length);\n                var t0, t1, t2, t3;\n                var s0, s1, s2, s3;\n                var inputWords0, inputWords1, inputWords2, inputWords3;\n                var ksRow, i;\n                var swapWord = this.networkToHostOrderSwap;\n\n                while (offset < inputInt32.length) {\n                  inputWords0 = swapWord(inputInt32[offset]);\n                  inputWords1 = swapWord(inputInt32[offset + 1]);\n                  inputWords2 = swapWord(inputInt32[offset + 2]);\n                  inputWords3 = swapWord(inputInt32[offset + 3]);\n                  s0 = inputWords0 ^ invKeySchedule[0];\n                  s1 = inputWords3 ^ invKeySchedule[1];\n                  s2 = inputWords2 ^ invKeySchedule[2];\n                  s3 = inputWords1 ^ invKeySchedule[3];\n                  ksRow = 4; // Iterate through the rounds of decryption\n\n                  for (i = 1; i < nRounds; i++) {\n                    t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];\n                    t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n                    t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n                    t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state\n\n                    s0 = t0;\n                    s1 = t1;\n                    s2 = t2;\n                    s3 = t3;\n                    ksRow = ksRow + 4;\n                  } // Shift rows, sub bytes, add round key\n\n                  t0 = (invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];\n                  t1 = (invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n                  t2 = (invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n                  t3 = (invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write\n\n                  outputInt32[offset] = swapWord(t0 ^ initVector0);\n                  outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n                  outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n                  outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int\n\n                  initVector0 = inputWords0;\n                  initVector1 = inputWords1;\n                  initVector2 = inputWords2;\n                  initVector3 = inputWords3;\n                  offset = offset + 4;\n                }\n\n                return outputInt32.buffer;\n              };\n\n              return AESDecryptor;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/crypt/decrypter.ts\":\n          /*!********************************!*\\\n  !*** ./src/crypt/decrypter.ts ***!\n  \\********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return Decrypter;\n            });\n            /* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ \"./src/crypt/aes-crypto.ts\");\n            /* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ \"./src/crypt/fast-aes-key.ts\");\n            /* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ \"./src/crypt/aes-decryptor.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ \"./src/utils/typed-array.ts\");\n\n            var CHUNK_SIZE = 16; // 16 bytes, 128 bits\n\n            var Decrypter = /*#__PURE__*/ (function () {\n              function Decrypter(observer, config, _temp) {\n                var _ref = _temp === void 0 ? {} : _temp,\n                  _ref$removePKCS7Paddi = _ref.removePKCS7Padding,\n                  removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;\n\n                this.logEnabled = true;\n                this.observer = void 0;\n                this.config = void 0;\n                this.removePKCS7Padding = void 0;\n                this.subtle = null;\n                this.softwareDecrypter = null;\n                this.key = null;\n                this.fastAesKey = null;\n                this.remainderData = null;\n                this.currentIV = null;\n                this.currentResult = null;\n                this.observer = observer;\n                this.config = config;\n                this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding\n\n                if (removePKCS7Padding) {\n                  try {\n                    var browserCrypto = self.crypto;\n\n                    if (browserCrypto) {\n                      this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n                    }\n                  } catch (e) {\n                    /* no-op */\n                  }\n                }\n\n                if (this.subtle === null) {\n                  this.config.enableSoftwareAES = true;\n                }\n              }\n\n              var _proto = Decrypter.prototype;\n\n              _proto.destroy = function destroy() {\n                // @ts-ignore\n                this.observer = null;\n              };\n\n              _proto.isSync = function isSync() {\n                return this.config.enableSoftwareAES;\n              };\n\n              _proto.flush = function flush() {\n                var currentResult = this.currentResult;\n\n                if (!currentResult) {\n                  this.reset();\n                  return;\n                }\n\n                var data = new Uint8Array(currentResult);\n                this.reset();\n\n                if (this.removePKCS7Padding) {\n                  return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__[\"removePadding\"])(data);\n                }\n\n                return data;\n              };\n\n              _proto.reset = function reset() {\n                this.currentResult = null;\n                this.currentIV = null;\n                this.remainderData = null;\n\n                if (this.softwareDecrypter) {\n                  this.softwareDecrypter = null;\n                }\n              };\n\n              _proto.decrypt = function decrypt(data, key, iv, callback) {\n                if (this.config.enableSoftwareAES) {\n                  this.softwareDecrypt(new Uint8Array(data), key, iv);\n                  var decryptResult = this.flush();\n\n                  if (decryptResult) {\n                    callback(decryptResult.buffer);\n                  }\n                } else {\n                  this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback);\n                }\n              };\n\n              _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {\n                var currentIV = this.currentIV,\n                  currentResult = this.currentResult,\n                  remainderData = this.remainderData;\n                this.logOnce(\"JS AES decrypt\"); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call\n                // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached\n                // the end on flush(), but by that time we have already received all bytes for the segment.\n                // Progressive decryption does not work with WebCrypto\n\n                if (remainderData) {\n                  data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__[\"appendUint8Array\"])(remainderData, data);\n                  this.remainderData = null;\n                } // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)\n\n                var currentChunk = this.getValidChunk(data);\n\n                if (!currentChunk.length) {\n                  return null;\n                }\n\n                if (currentIV) {\n                  iv = currentIV;\n                }\n\n                var softwareDecrypter = this.softwareDecrypter;\n\n                if (!softwareDecrypter) {\n                  softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__[\"default\"]();\n                }\n\n                softwareDecrypter.expandKey(key);\n                var result = currentResult;\n                this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);\n                this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__[\"sliceUint8\"])(currentChunk, -16).buffer;\n\n                if (!result) {\n                  return null;\n                }\n\n                return result;\n              };\n\n              _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {\n                var _this = this;\n\n                var subtle = this.subtle;\n\n                if (this.key !== key || !this.fastAesKey) {\n                  this.key = key;\n                  this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__[\"default\"](subtle, key);\n                }\n\n                return this.fastAesKey\n                  .expandKey()\n                  .then(function (aesKey) {\n                    // decrypt using web crypto\n                    if (!subtle) {\n                      return Promise.reject(new Error(\"web crypto not initialized\"));\n                    }\n\n                    var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__[\"default\"](subtle, iv);\n                    return crypto.decrypt(data.buffer, aesKey);\n                  })\n                  .catch(function (err) {\n                    return _this.onWebCryptoError(err, data, key, iv);\n                  });\n              };\n\n              _proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"[decrypter.ts]: WebCrypto Error, disable WebCrypto API:\", err);\n                this.config.enableSoftwareAES = true;\n                this.logEnabled = true;\n                return this.softwareDecrypt(data, key, iv);\n              };\n\n              _proto.getValidChunk = function getValidChunk(data) {\n                var currentChunk = data;\n                var splitPoint = data.length - (data.length % CHUNK_SIZE);\n\n                if (splitPoint !== data.length) {\n                  currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__[\"sliceUint8\"])(data, 0, splitPoint);\n                  this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__[\"sliceUint8\"])(data, splitPoint);\n                }\n\n                return currentChunk;\n              };\n\n              _proto.logOnce = function logOnce(msg) {\n                if (!this.logEnabled) {\n                  return;\n                }\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].log(\"[decrypter.ts]: \" + msg);\n                this.logEnabled = false;\n              };\n\n              return Decrypter;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/crypt/fast-aes-key.ts\":\n          /*!***********************************!*\\\n  !*** ./src/crypt/fast-aes-key.ts ***!\n  \\***********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return FastAESKey;\n            });\n            var FastAESKey = /*#__PURE__*/ (function () {\n              function FastAESKey(subtle, key) {\n                this.subtle = void 0;\n                this.key = void 0;\n                this.subtle = subtle;\n                this.key = key;\n              }\n\n              var _proto = FastAESKey.prototype;\n\n              _proto.expandKey = function expandKey() {\n                return this.subtle.importKey(\n                  \"raw\",\n                  this.key,\n                  {\n                    name: \"AES-CBC\",\n                  },\n                  false,\n                  [\"encrypt\", \"decrypt\"]\n                );\n              };\n\n              return FastAESKey;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/demux/aacdemuxer.ts\":\n          /*!*********************************!*\\\n  !*** ./src/demux/aacdemuxer.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ \"./src/demux/base-audio-demuxer.ts\");\n            /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ \"./src/demux/adts.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ \"./src/demux/id3.ts\");\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            /**\n             * AAC demuxer\n             */\n\n            var AACDemuxer = /*#__PURE__*/ (function (_BaseAudioDemuxer) {\n              _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);\n\n              function AACDemuxer(observer, config) {\n                var _this;\n\n                _this = _BaseAudioDemuxer.call(this) || this;\n                _this.observer = void 0;\n                _this.config = void 0;\n                _this.observer = observer;\n                _this.config = config;\n                return _this;\n              }\n\n              var _proto = AACDemuxer.prototype;\n\n              _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {\n                _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);\n\n                this._audioTrack = {\n                  container: \"audio/adts\",\n                  type: \"audio\",\n                  id: 2,\n                  pid: -1,\n                  sequenceNumber: 0,\n                  isAAC: true,\n                  samples: [],\n                  manifestCodec: audioCodec,\n                  duration: duration,\n                  inputTimeScale: 90000,\n                  dropped: 0,\n                };\n              }; // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS\n\n              AACDemuxer.probe = function probe(data) {\n                if (!data) {\n                  return false;\n                } // Check for the ADTS sync word\n                // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n                // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n                // More info https://wiki.multimedia.cx/index.php?title=ADTS\n\n                var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__[\"getID3Data\"](data, 0) || [];\n                var offset = id3Data.length;\n\n                for (var length = data.length; offset < length; offset++) {\n                  if (_adts__WEBPACK_IMPORTED_MODULE_1__[\"probe\"](data, offset)) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"ADTS sync word found !\");\n                    return true;\n                  }\n                }\n\n                return false;\n              };\n\n              _proto.canParse = function canParse(data, offset) {\n                return _adts__WEBPACK_IMPORTED_MODULE_1__[\"canParse\"](data, offset);\n              };\n\n              _proto.appendFrame = function appendFrame(track, data, offset) {\n                _adts__WEBPACK_IMPORTED_MODULE_1__[\"initTrackConfig\"](track, this.observer, data, offset, track.manifestCodec);\n                var frame = _adts__WEBPACK_IMPORTED_MODULE_1__[\"appendFrame\"](track, data, offset, this.initPTS, this.frameIndex);\n\n                if (frame && frame.missing === 0) {\n                  return frame;\n                }\n              };\n\n              return AACDemuxer;\n            })(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__[\"default\"]);\n\n            AACDemuxer.minProbeByteLength = 9;\n            /* harmony default export */ __webpack_exports__[\"default\"] = AACDemuxer;\n\n            /***/\n          },\n\n        /***/ \"./src/demux/adts.ts\":\n          /*!***************************!*\\\n  !*** ./src/demux/adts.ts ***!\n  \\***************************/\n          /*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getAudioConfig\", function () {\n              return getAudioConfig;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isHeaderPattern\", function () {\n              return isHeaderPattern;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getHeaderLength\", function () {\n              return getHeaderLength;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getFullFrameLength\", function () {\n              return getFullFrameLength;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"canGetFrameLength\", function () {\n              return canGetFrameLength;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isHeader\", function () {\n              return isHeader;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"canParse\", function () {\n              return canParse;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"probe\", function () {\n              return probe;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"initTrackConfig\", function () {\n              return initTrackConfig;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getFrameDuration\", function () {\n              return getFrameDuration;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseFrameHeader\", function () {\n              return parseFrameHeader;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"appendFrame\", function () {\n              return appendFrame;\n            });\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /**\n             * ADTS parser helper\n             * @link https://wiki.multimedia.cx/index.php?title=ADTS\n             */\n\n            function getAudioConfig(observer, data, offset, audioCodec) {\n              var adtsObjectType;\n              var adtsExtensionSamplingIndex;\n              var adtsChanelConfig;\n              var config;\n              var userAgent = navigator.userAgent.toLowerCase();\n              var manifestCodec = audioCodec;\n              var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2\n\n              adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;\n              var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;\n\n              if (adtsSamplingIndex > adtsSampleingRates.length - 1) {\n                observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__[\"Events\"].ERROR, {\n                  type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                  details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_PARSING_ERROR,\n                  fatal: true,\n                  reason: \"invalid ADTS sampling index:\" + adtsSamplingIndex,\n                });\n                return;\n              }\n\n              adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3\n\n              adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;\n              _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].log(\"manifest codec:\" + audioCodec + \", ADTS type:\" + adtsObjectType + \", samplingIndex:\" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n\n              if (/firefox/i.test(userAgent)) {\n                if (adtsSamplingIndex >= 6) {\n                  adtsObjectType = 5;\n                  config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n                  // there is a factor 2 between frame sample rate and output sample rate\n                  // multiply frequency by 2 (see table below, equivalent to substract 3)\n\n                  adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n                } else {\n                  adtsObjectType = 2;\n                  config = new Array(2);\n                  adtsExtensionSamplingIndex = adtsSamplingIndex;\n                } // Android : always use AAC\n              } else if (userAgent.indexOf(\"android\") !== -1) {\n                adtsObjectType = 2;\n                config = new Array(2);\n                adtsExtensionSamplingIndex = adtsSamplingIndex;\n              } else {\n                /*  for other browsers (Chrome/Vivaldi/Opera ...)\n        always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n    */\n                adtsObjectType = 5;\n                config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n\n                if ((audioCodec && (audioCodec.indexOf(\"mp4a.40.29\") !== -1 || audioCodec.indexOf(\"mp4a.40.5\") !== -1)) || (!audioCodec && adtsSamplingIndex >= 6)) {\n                  // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n                  // there is a factor 2 between frame sample rate and output sample rate\n                  // multiply frequency by 2 (see table below, equivalent to substract 3)\n                  adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n                } else {\n                  // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n                  // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC.  This is not a problem with stereo.\n                  if ((audioCodec && audioCodec.indexOf(\"mp4a.40.2\") !== -1 && ((adtsSamplingIndex >= 6 && adtsChanelConfig === 1) || /vivaldi/i.test(userAgent))) || (!audioCodec && adtsChanelConfig === 1)) {\n                    adtsObjectType = 2;\n                    config = new Array(2);\n                  }\n\n                  adtsExtensionSamplingIndex = adtsSamplingIndex;\n                }\n              }\n              /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n      ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n    Audio Profile / Audio Object Type\n    0: Null\n    1: AAC Main\n    2: AAC LC (Low Complexity)\n    3: AAC SSR (Scalable Sample Rate)\n    4: AAC LTP (Long Term Prediction)\n    5: SBR (Spectral Band Replication)\n    6: AAC Scalable\n   sampling freq\n    0: 96000 Hz\n    1: 88200 Hz\n    2: 64000 Hz\n    3: 48000 Hz\n    4: 44100 Hz\n    5: 32000 Hz\n    6: 24000 Hz\n    7: 22050 Hz\n    8: 16000 Hz\n    9: 12000 Hz\n    10: 11025 Hz\n    11: 8000 Hz\n    12: 7350 Hz\n    13: Reserved\n    14: Reserved\n    15: frequency is written explictly\n    Channel Configurations\n    These are the channel configurations:\n    0: Defined in AOT Specifc Config\n    1: 1 channel: front-center\n    2: 2 channels: front-left, front-right\n  */\n              // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n\n              config[0] = adtsObjectType << 3; // samplingFrequencyIndex\n\n              config[0] |= (adtsSamplingIndex & 0x0e) >> 1;\n              config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration\n\n              config[1] |= adtsChanelConfig << 3;\n\n              if (adtsObjectType === 5) {\n                // adtsExtensionSampleingIndex\n                config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;\n                config[2] = (adtsExtensionSamplingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n                //    https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n\n                config[2] |= 2 << 2;\n                config[3] = 0;\n              }\n\n              return {\n                config: config,\n                samplerate: adtsSampleingRates[adtsSamplingIndex],\n                channelCount: adtsChanelConfig,\n                codec: \"mp4a.40.\" + adtsObjectType,\n                manifestCodec: manifestCodec,\n              };\n            }\n            function isHeaderPattern(data, offset) {\n              return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n            }\n            function getHeaderLength(data, offset) {\n              return data[offset + 1] & 0x01 ? 7 : 9;\n            }\n            function getFullFrameLength(data, offset) {\n              return ((data[offset + 3] & 0x03) << 11) | (data[offset + 4] << 3) | ((data[offset + 5] & 0xe0) >>> 5);\n            }\n            function canGetFrameLength(data, offset) {\n              return offset + 5 < data.length;\n            }\n            function isHeader(data, offset) {\n              // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n              // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n              // More info https://wiki.multimedia.cx/index.php?title=ADTS\n              return offset + 1 < data.length && isHeaderPattern(data, offset);\n            }\n            function canParse(data, offset) {\n              return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;\n            }\n            function probe(data, offset) {\n              // same as isHeader but we also check that ADTS frame follows last ADTS frame\n              // or end of data is reached\n              if (isHeader(data, offset)) {\n                // ADTS header Length\n                var headerLength = getHeaderLength(data, offset);\n\n                if (offset + headerLength >= data.length) {\n                  return false;\n                } // ADTS frame Length\n\n                var frameLength = getFullFrameLength(data, offset);\n\n                if (frameLength <= headerLength) {\n                  return false;\n                }\n\n                var newOffset = offset + frameLength;\n                return newOffset === data.length || isHeader(data, newOffset);\n              }\n\n              return false;\n            }\n            function initTrackConfig(track, observer, data, offset, audioCodec) {\n              if (!track.samplerate) {\n                var config = getAudioConfig(observer, data, offset, audioCodec);\n\n                if (!config) {\n                  return;\n                }\n\n                track.config = config.config;\n                track.samplerate = config.samplerate;\n                track.channelCount = config.channelCount;\n                track.codec = config.codec;\n                track.manifestCodec = config.manifestCodec;\n                _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].log(\"parsed codec:\" + track.codec + \", rate:\" + config.samplerate + \", channels:\" + config.channelCount);\n              }\n            }\n            function getFrameDuration(samplerate) {\n              return (1024 * 90000) / samplerate;\n            }\n            function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {\n              // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n              var headerLength = getHeaderLength(data, offset); // retrieve frame size\n\n              var frameLength = getFullFrameLength(data, offset);\n              frameLength -= headerLength;\n\n              if (frameLength > 0) {\n                var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n\n                return {\n                  headerLength: headerLength,\n                  frameLength: frameLength,\n                  stamp: stamp,\n                };\n              }\n            }\n            function appendFrame(track, data, offset, pts, frameIndex) {\n              var frameDuration = getFrameDuration(track.samplerate);\n              var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n\n              if (header) {\n                var frameLength = header.frameLength,\n                  headerLength = header.headerLength,\n                  stamp = header.stamp;\n                var length = headerLength + frameLength;\n                var missing = Math.max(0, offset + length - data.length); // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);\n\n                var unit;\n\n                if (missing) {\n                  unit = new Uint8Array(length - headerLength);\n                  unit.set(data.subarray(offset + headerLength, data.length), 0);\n                } else {\n                  unit = data.subarray(offset + headerLength, offset + length);\n                }\n\n                var sample = {\n                  unit: unit,\n                  pts: stamp,\n                };\n\n                if (!missing) {\n                  track.samples.push(sample);\n                }\n\n                return {\n                  sample: sample,\n                  length: length,\n                  missing: missing,\n                };\n              }\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/demux/base-audio-demuxer.ts\":\n          /*!*****************************************!*\\\n  !*** ./src/demux/base-audio-demuxer.ts ***!\n  \\*****************************************/\n          /*! exports provided: initPTSFn, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"initPTSFn\", function () {\n              return initPTSFn;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ \"./src/demux/id3.ts\");\n            /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ \"./src/demux/dummy-demuxed-track.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ \"./src/utils/typed-array.ts\");\n\n            var BaseAudioDemuxer = /*#__PURE__*/ (function () {\n              function BaseAudioDemuxer() {\n                this._audioTrack = void 0;\n                this._id3Track = void 0;\n                this.frameIndex = 0;\n                this.cachedData = null;\n                this.initPTS = null;\n              }\n\n              var _proto = BaseAudioDemuxer.prototype;\n\n              _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {\n                this._id3Track = {\n                  type: \"id3\",\n                  id: 3,\n                  pid: -1,\n                  inputTimeScale: 90000,\n                  sequenceNumber: 0,\n                  samples: [],\n                  dropped: 0,\n                };\n              };\n\n              _proto.resetTimeStamp = function resetTimeStamp() {};\n\n              _proto.resetContiguity = function resetContiguity() {};\n\n              _proto.canParse = function canParse(data, offset) {\n                return false;\n              };\n\n              _proto.appendFrame = function appendFrame(track, data, offset) {}; // feed incoming data to the front of the parsing pipeline\n\n              _proto.demux = function demux(data, timeOffset) {\n                if (this.cachedData) {\n                  data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__[\"appendUint8Array\"])(this.cachedData, data);\n                  this.cachedData = null;\n                }\n\n                var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__[\"getID3Data\"](data, 0);\n                var offset = id3Data ? id3Data.length : 0;\n                var lastDataIndex;\n                var pts;\n                var track = this._audioTrack;\n                var id3Track = this._id3Track;\n                var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__[\"getTimeStamp\"](id3Data) : undefined;\n                var length = data.length;\n\n                if (this.frameIndex === 0 || this.initPTS === null) {\n                  this.initPTS = initPTSFn(timestamp, timeOffset);\n                } // more expressive than alternative: id3Data?.length\n\n                if (id3Data && id3Data.length > 0) {\n                  id3Track.samples.push({\n                    pts: this.initPTS,\n                    dts: this.initPTS,\n                    data: id3Data,\n                  });\n                }\n\n                pts = this.initPTS;\n\n                while (offset < length) {\n                  if (this.canParse(data, offset)) {\n                    var frame = this.appendFrame(track, data, offset);\n\n                    if (frame) {\n                      this.frameIndex++;\n                      pts = frame.sample.pts;\n                      offset += frame.length;\n                      lastDataIndex = offset;\n                    } else {\n                      offset = length;\n                    }\n                  } else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__[\"canParse\"](data, offset)) {\n                    // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data\n                    id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__[\"getID3Data\"](data, offset);\n                    id3Track.samples.push({\n                      pts: pts,\n                      dts: pts,\n                      data: id3Data,\n                    });\n                    offset += id3Data.length;\n                    lastDataIndex = offset;\n                  } else {\n                    offset++;\n                  }\n\n                  if (offset === length && lastDataIndex !== length) {\n                    var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__[\"sliceUint8\"])(data, lastDataIndex);\n\n                    if (this.cachedData) {\n                      this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__[\"appendUint8Array\"])(this.cachedData, partialData);\n                    } else {\n                      this.cachedData = partialData;\n                    }\n                  }\n                }\n\n                return {\n                  audioTrack: track,\n                  avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__[\"dummyTrack\"])(),\n                  id3Track: id3Track,\n                  textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__[\"dummyTrack\"])(),\n                };\n              };\n\n              _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {\n                return Promise.reject(new Error(\"[\" + this + \"] This demuxer does not support Sample-AES decryption\"));\n              };\n\n              _proto.flush = function flush(timeOffset) {\n                // Parse cache in case of remaining frames.\n                var cachedData = this.cachedData;\n\n                if (cachedData) {\n                  this.cachedData = null;\n                  this.demux(cachedData, 0);\n                }\n\n                this.frameIndex = 0;\n                return {\n                  audioTrack: this._audioTrack,\n                  avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__[\"dummyTrack\"])(),\n                  id3Track: this._id3Track,\n                  textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__[\"dummyTrack\"])(),\n                };\n              };\n\n              _proto.destroy = function destroy() {};\n\n              return BaseAudioDemuxer;\n            })();\n            /**\n             * Initialize PTS\n             * <p>\n             *    use timestamp unless it is undefined, NaN or Infinity\n             * </p>\n             */\n\n            var initPTSFn = function initPTSFn(timestamp, timeOffset) {\n              return Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(timestamp) ? timestamp * 90 : timeOffset * 90000;\n            };\n            /* harmony default export */ __webpack_exports__[\"default\"] = BaseAudioDemuxer;\n\n            /***/\n          },\n\n        /***/ \"./src/demux/chunk-cache.ts\":\n          /*!**********************************!*\\\n  !*** ./src/demux/chunk-cache.ts ***!\n  \\**********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return ChunkCache;\n            });\n            var ChunkCache = /*#__PURE__*/ (function () {\n              function ChunkCache() {\n                this.chunks = [];\n                this.dataLength = 0;\n              }\n\n              var _proto = ChunkCache.prototype;\n\n              _proto.push = function push(chunk) {\n                this.chunks.push(chunk);\n                this.dataLength += chunk.length;\n              };\n\n              _proto.flush = function flush() {\n                var chunks = this.chunks,\n                  dataLength = this.dataLength;\n                var result;\n\n                if (!chunks.length) {\n                  return new Uint8Array(0);\n                } else if (chunks.length === 1) {\n                  result = chunks[0];\n                } else {\n                  result = concatUint8Arrays(chunks, dataLength);\n                }\n\n                this.reset();\n                return result;\n              };\n\n              _proto.reset = function reset() {\n                this.chunks.length = 0;\n                this.dataLength = 0;\n              };\n\n              return ChunkCache;\n            })();\n\n            function concatUint8Arrays(chunks, dataLength) {\n              var result = new Uint8Array(dataLength);\n              var offset = 0;\n\n              for (var i = 0; i < chunks.length; i++) {\n                var chunk = chunks[i];\n                result.set(chunk, offset);\n                offset += chunk.length;\n              }\n\n              return result;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/demux/dummy-demuxed-track.ts\":\n          /*!******************************************!*\\\n  !*** ./src/demux/dummy-demuxed-track.ts ***!\n  \\******************************************/\n          /*! exports provided: dummyTrack */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"dummyTrack\", function () {\n              return dummyTrack;\n            });\n            function dummyTrack() {\n              return {\n                type: \"\",\n                id: -1,\n                pid: -1,\n                inputTimeScale: 90000,\n                sequenceNumber: -1,\n                samples: [],\n                dropped: 0,\n              };\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/demux/exp-golomb.ts\":\n          /*!*********************************!*\\\n  !*** ./src/demux/exp-golomb.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /**\n             * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n             */\n\n            var ExpGolomb = /*#__PURE__*/ (function () {\n              function ExpGolomb(data) {\n                this.data = void 0;\n                this.bytesAvailable = void 0;\n                this.word = void 0;\n                this.bitsAvailable = void 0;\n                this.data = data; // the number of bytes left to examine in this.data\n\n                this.bytesAvailable = data.byteLength; // the current word being examined\n\n                this.word = 0; // :uint\n                // the number of bits left to examine in the current word\n\n                this.bitsAvailable = 0; // :uint\n              } // ():void\n\n              var _proto = ExpGolomb.prototype;\n\n              _proto.loadWord = function loadWord() {\n                var data = this.data;\n                var bytesAvailable = this.bytesAvailable;\n                var position = data.byteLength - bytesAvailable;\n                var workingBytes = new Uint8Array(4);\n                var availableBytes = Math.min(4, bytesAvailable);\n\n                if (availableBytes === 0) {\n                  throw new Error(\"no bytes available\");\n                }\n\n                workingBytes.set(data.subarray(position, position + availableBytes));\n                this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed\n\n                this.bitsAvailable = availableBytes * 8;\n                this.bytesAvailable -= availableBytes;\n              }; // (count:int):void\n\n              _proto.skipBits = function skipBits(count) {\n                var skipBytes; // :int\n\n                if (this.bitsAvailable > count) {\n                  this.word <<= count;\n                  this.bitsAvailable -= count;\n                } else {\n                  count -= this.bitsAvailable;\n                  skipBytes = count >> 3;\n                  count -= skipBytes >> 3;\n                  this.bytesAvailable -= skipBytes;\n                  this.loadWord();\n                  this.word <<= count;\n                  this.bitsAvailable -= count;\n                }\n              }; // (size:int):uint\n\n              _proto.readBits = function readBits(size) {\n                var bits = Math.min(this.bitsAvailable, size); // :uint\n\n                var valu = this.word >>> (32 - bits); // :uint\n\n                if (size > 32) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].error(\"Cannot read more than 32 bits at a time\");\n                }\n\n                this.bitsAvailable -= bits;\n\n                if (this.bitsAvailable > 0) {\n                  this.word <<= bits;\n                } else if (this.bytesAvailable > 0) {\n                  this.loadWord();\n                }\n\n                bits = size - bits;\n\n                if (bits > 0 && this.bitsAvailable) {\n                  return (valu << bits) | this.readBits(bits);\n                } else {\n                  return valu;\n                }\n              }; // ():uint\n\n              _proto.skipLZ = function skipLZ() {\n                var leadingZeroCount; // :uint\n\n                for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n                  if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n                    // the first bit of working word is 1\n                    this.word <<= leadingZeroCount;\n                    this.bitsAvailable -= leadingZeroCount;\n                    return leadingZeroCount;\n                  }\n                } // we exhausted word and still have not found a 1\n\n                this.loadWord();\n                return leadingZeroCount + this.skipLZ();\n              }; // ():void\n\n              _proto.skipUEG = function skipUEG() {\n                this.skipBits(1 + this.skipLZ());\n              }; // ():void\n\n              _proto.skipEG = function skipEG() {\n                this.skipBits(1 + this.skipLZ());\n              }; // ():uint\n\n              _proto.readUEG = function readUEG() {\n                var clz = this.skipLZ(); // :uint\n\n                return this.readBits(clz + 1) - 1;\n              }; // ():int\n\n              _proto.readEG = function readEG() {\n                var valu = this.readUEG(); // :int\n\n                if (0x01 & valu) {\n                  // the number is odd if the low order bit is set\n                  return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n                } else {\n                  return -1 * (valu >>> 1); // divide by two then make it negative\n                }\n              }; // Some convenience functions\n              // :Boolean\n\n              _proto.readBoolean = function readBoolean() {\n                return this.readBits(1) === 1;\n              }; // ():int\n\n              _proto.readUByte = function readUByte() {\n                return this.readBits(8);\n              }; // ():int\n\n              _proto.readUShort = function readUShort() {\n                return this.readBits(16);\n              }; // ():int\n\n              _proto.readUInt = function readUInt() {\n                return this.readBits(32);\n              };\n              /**\n               * Advance the ExpGolomb decoder past a scaling list. The scaling\n               * list is optionally transmitted as part of a sequence parameter\n               * set and is not relevant to transmuxing.\n               * @param count the number of entries in this scaling list\n               * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n               */\n\n              _proto.skipScalingList = function skipScalingList(count) {\n                var lastScale = 8;\n                var nextScale = 8;\n                var deltaScale;\n\n                for (var j = 0; j < count; j++) {\n                  if (nextScale !== 0) {\n                    deltaScale = this.readEG();\n                    nextScale = (lastScale + deltaScale + 256) % 256;\n                  }\n\n                  lastScale = nextScale === 0 ? lastScale : nextScale;\n                }\n              };\n              /**\n               * Read a sequence parameter set and return some interesting video\n               * properties. A sequence parameter set is the H264 metadata that\n               * describes the properties of upcoming video frames.\n               * @param data {Uint8Array} the bytes of a sequence parameter set\n               * @return {object} an object with configuration parsed from the\n               * sequence parameter set, including the dimensions of the\n               * associated video frames.\n               */\n\n              _proto.readSPS = function readSPS() {\n                var frameCropLeftOffset = 0;\n                var frameCropRightOffset = 0;\n                var frameCropTopOffset = 0;\n                var frameCropBottomOffset = 0;\n                var numRefFramesInPicOrderCntCycle;\n                var scalingListCount;\n                var i;\n                var readUByte = this.readUByte.bind(this);\n                var readBits = this.readBits.bind(this);\n                var readUEG = this.readUEG.bind(this);\n                var readBoolean = this.readBoolean.bind(this);\n                var skipBits = this.skipBits.bind(this);\n                var skipEG = this.skipEG.bind(this);\n                var skipUEG = this.skipUEG.bind(this);\n                var skipScalingList = this.skipScalingList.bind(this);\n                readUByte();\n                var profileIdc = readUByte(); // profile_idc\n\n                readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)\n\n                skipBits(3); // reserved_zero_3bits u(3),\n\n                readUByte(); // level_idc u(8)\n\n                skipUEG(); // seq_parameter_set_id\n                // some profiles have more optional data we don't need\n\n                if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {\n                  var chromaFormatIdc = readUEG();\n\n                  if (chromaFormatIdc === 3) {\n                    skipBits(1);\n                  } // separate_colour_plane_flag\n\n                  skipUEG(); // bit_depth_luma_minus8\n\n                  skipUEG(); // bit_depth_chroma_minus8\n\n                  skipBits(1); // qpprime_y_zero_transform_bypass_flag\n\n                  if (readBoolean()) {\n                    // seq_scaling_matrix_present_flag\n                    scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n\n                    for (i = 0; i < scalingListCount; i++) {\n                      if (readBoolean()) {\n                        // seq_scaling_list_present_flag[ i ]\n                        if (i < 6) {\n                          skipScalingList(16);\n                        } else {\n                          skipScalingList(64);\n                        }\n                      }\n                    }\n                  }\n                }\n\n                skipUEG(); // log2_max_frame_num_minus4\n\n                var picOrderCntType = readUEG();\n\n                if (picOrderCntType === 0) {\n                  readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n                } else if (picOrderCntType === 1) {\n                  skipBits(1); // delta_pic_order_always_zero_flag\n\n                  skipEG(); // offset_for_non_ref_pic\n\n                  skipEG(); // offset_for_top_to_bottom_field\n\n                  numRefFramesInPicOrderCntCycle = readUEG();\n\n                  for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n                    skipEG();\n                  } // offset_for_ref_frame[ i ]\n                }\n\n                skipUEG(); // max_num_ref_frames\n\n                skipBits(1); // gaps_in_frame_num_value_allowed_flag\n\n                var picWidthInMbsMinus1 = readUEG();\n                var picHeightInMapUnitsMinus1 = readUEG();\n                var frameMbsOnlyFlag = readBits(1);\n\n                if (frameMbsOnlyFlag === 0) {\n                  skipBits(1);\n                } // mb_adaptive_frame_field_flag\n\n                skipBits(1); // direct_8x8_inference_flag\n\n                if (readBoolean()) {\n                  // frame_cropping_flag\n                  frameCropLeftOffset = readUEG();\n                  frameCropRightOffset = readUEG();\n                  frameCropTopOffset = readUEG();\n                  frameCropBottomOffset = readUEG();\n                }\n\n                var pixelRatio = [1, 1];\n\n                if (readBoolean()) {\n                  // vui_parameters_present_flag\n                  if (readBoolean()) {\n                    // aspect_ratio_info_present_flag\n                    var aspectRatioIdc = readUByte();\n\n                    switch (aspectRatioIdc) {\n                      case 1:\n                        pixelRatio = [1, 1];\n                        break;\n\n                      case 2:\n                        pixelRatio = [12, 11];\n                        break;\n\n                      case 3:\n                        pixelRatio = [10, 11];\n                        break;\n\n                      case 4:\n                        pixelRatio = [16, 11];\n                        break;\n\n                      case 5:\n                        pixelRatio = [40, 33];\n                        break;\n\n                      case 6:\n                        pixelRatio = [24, 11];\n                        break;\n\n                      case 7:\n                        pixelRatio = [20, 11];\n                        break;\n\n                      case 8:\n                        pixelRatio = [32, 11];\n                        break;\n\n                      case 9:\n                        pixelRatio = [80, 33];\n                        break;\n\n                      case 10:\n                        pixelRatio = [18, 11];\n                        break;\n\n                      case 11:\n                        pixelRatio = [15, 11];\n                        break;\n\n                      case 12:\n                        pixelRatio = [64, 33];\n                        break;\n\n                      case 13:\n                        pixelRatio = [160, 99];\n                        break;\n\n                      case 14:\n                        pixelRatio = [4, 3];\n                        break;\n\n                      case 15:\n                        pixelRatio = [3, 2];\n                        break;\n\n                      case 16:\n                        pixelRatio = [2, 1];\n                        break;\n\n                      case 255: {\n                        pixelRatio = [(readUByte() << 8) | readUByte(), (readUByte() << 8) | readUByte()];\n                        break;\n                      }\n                    }\n                  }\n                }\n\n                return {\n                  width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),\n                  height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),\n                  pixelRatio: pixelRatio,\n                };\n              };\n\n              _proto.readSliceType = function readSliceType() {\n                // skip NALu type\n                this.readUByte(); // discard first_mb_in_slice\n\n                this.readUEG(); // return slice_type\n\n                return this.readUEG();\n              };\n\n              return ExpGolomb;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = ExpGolomb;\n\n            /***/\n          },\n\n        /***/ \"./src/demux/id3.ts\":\n          /*!**************************!*\\\n  !*** ./src/demux/id3.ts ***!\n  \\**************************/\n          /*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isHeader\", function () {\n              return isHeader;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFooter\", function () {\n              return isFooter;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getID3Data\", function () {\n              return getID3Data;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"canParse\", function () {\n              return canParse;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getTimeStamp\", function () {\n              return getTimeStamp;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isTimeStampFrame\", function () {\n              return isTimeStampFrame;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getID3Frames\", function () {\n              return getID3Frames;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"decodeFrame\", function () {\n              return decodeFrame;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"utf8ArrayToStr\", function () {\n              return utf8ArrayToStr;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"testables\", function () {\n              return testables;\n            });\n            // breaking up those two types in order to clarify what is happening in the decoding path.\n\n            /**\n             * Returns true if an ID3 header can be found at offset in data\n             * @param {Uint8Array} data - The data to search in\n             * @param {number} offset - The offset at which to start searching\n             * @return {boolean} - True if an ID3 header is found\n             */\n            var isHeader = function isHeader(data, offset) {\n              /*\n               * http://id3.org/id3v2.3.0\n               * [0]     = 'I'\n               * [1]     = 'D'\n               * [2]     = '3'\n               * [3,4]   = {Version}\n               * [5]     = {Flags}\n               * [6-9]   = {ID3 Size}\n               *\n               * An ID3v2 tag can be detected with the following pattern:\n               *  $49 44 33 yy yy xx zz zz zz zz\n               * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n               */\n              if (offset + 10 <= data.length) {\n                // look for 'ID3' identifier\n                if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {\n                  // check version is within range\n                  if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n                    // check size is within range\n                    if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n                      return true;\n                    }\n                  }\n                }\n              }\n\n              return false;\n            };\n            /**\n             * Returns true if an ID3 footer can be found at offset in data\n             * @param {Uint8Array} data - The data to search in\n             * @param {number} offset - The offset at which to start searching\n             * @return {boolean} - True if an ID3 footer is found\n             */\n\n            var isFooter = function isFooter(data, offset) {\n              /*\n               * The footer is a copy of the header, but with a different identifier\n               */\n              if (offset + 10 <= data.length) {\n                // look for '3DI' identifier\n                if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {\n                  // check version is within range\n                  if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n                    // check size is within range\n                    if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n                      return true;\n                    }\n                  }\n                }\n              }\n\n              return false;\n            };\n            /**\n             * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n             * @param {Uint8Array} data - The data to search in\n             * @param {number} offset - The offset at which to start searching\n             * @return {Uint8Array | undefined} - The block of data containing any ID3 tags found\n             * or *undefined* if no header is found at the starting offset\n             */\n\n            var getID3Data = function getID3Data(data, offset) {\n              var front = offset;\n              var length = 0;\n\n              while (isHeader(data, offset)) {\n                // ID3 header is 10 bytes\n                length += 10;\n                var size = readSize(data, offset + 6);\n                length += size;\n\n                if (isFooter(data, offset + 10)) {\n                  // ID3 footer is 10 bytes\n                  length += 10;\n                }\n\n                offset += length;\n              }\n\n              if (length > 0) {\n                return data.subarray(front, front + length);\n              }\n\n              return undefined;\n            };\n\n            var readSize = function readSize(data, offset) {\n              var size = 0;\n              size = (data[offset] & 0x7f) << 21;\n              size |= (data[offset + 1] & 0x7f) << 14;\n              size |= (data[offset + 2] & 0x7f) << 7;\n              size |= data[offset + 3] & 0x7f;\n              return size;\n            };\n\n            var canParse = function canParse(data, offset) {\n              return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;\n            };\n            /**\n             * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n             * @param {Uint8Array} data - Block of data containing one or more ID3 tags\n             * @return {number | undefined} - The timestamp\n             */\n\n            var getTimeStamp = function getTimeStamp(data) {\n              var frames = getID3Frames(data);\n\n              for (var i = 0; i < frames.length; i++) {\n                var frame = frames[i];\n\n                if (isTimeStampFrame(frame)) {\n                  return readTimeStamp(frame);\n                }\n              }\n\n              return undefined;\n            };\n            /**\n             * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n             * @param {ID3 frame} frame\n             */\n\n            var isTimeStampFrame = function isTimeStampFrame(frame) {\n              return frame && frame.key === \"PRIV\" && frame.info === \"com.apple.streaming.transportStreamTimestamp\";\n            };\n\n            var getFrameData = function getFrameData(data) {\n              /*\n  Frame ID       $xx xx xx xx (four characters)\n  Size           $xx xx xx xx\n  Flags          $xx xx\n  */\n              var type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n              var size = readSize(data, 4); // skip frame id, size, and flags\n\n              var offset = 10;\n              return {\n                type: type,\n                size: size,\n                data: data.subarray(offset, offset + size),\n              };\n            };\n            /**\n             * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n             * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n             * @return {ID3.Frame[]} - Array of ID3 frame objects\n             */\n\n            var getID3Frames = function getID3Frames(id3Data) {\n              var offset = 0;\n              var frames = [];\n\n              while (isHeader(id3Data, offset)) {\n                var size = readSize(id3Data, offset + 6); // skip past ID3 header\n\n                offset += 10;\n                var end = offset + size; // loop through frames in the ID3 tag\n\n                while (offset + 8 < end) {\n                  var frameData = getFrameData(id3Data.subarray(offset));\n                  var frame = decodeFrame(frameData);\n\n                  if (frame) {\n                    frames.push(frame);\n                  } // skip frame header and frame data\n\n                  offset += frameData.size + 10;\n                }\n\n                if (isFooter(id3Data, offset)) {\n                  offset += 10;\n                }\n              }\n\n              return frames;\n            };\n            var decodeFrame = function decodeFrame(frame) {\n              if (frame.type === \"PRIV\") {\n                return decodePrivFrame(frame);\n              } else if (frame.type[0] === \"W\") {\n                return decodeURLFrame(frame);\n              }\n\n              return decodeTextFrame(frame);\n            };\n\n            var decodePrivFrame = function decodePrivFrame(frame) {\n              /*\n  Format: <text string>\\0<binary data>\n  */\n              if (frame.size < 2) {\n                return undefined;\n              }\n\n              var owner = utf8ArrayToStr(frame.data, true);\n              var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n              return {\n                key: frame.type,\n                info: owner,\n                data: privateData.buffer,\n              };\n            };\n\n            var decodeTextFrame = function decodeTextFrame(frame) {\n              if (frame.size < 2) {\n                return undefined;\n              }\n\n              if (frame.type === \"TXXX\") {\n                /*\n    Format:\n    [0]   = {Text Encoding}\n    [1-?] = {Description}\\0{Value}\n    */\n                var index = 1;\n                var description = utf8ArrayToStr(frame.data.subarray(index), true);\n                index += description.length + 1;\n                var value = utf8ArrayToStr(frame.data.subarray(index));\n                return {\n                  key: frame.type,\n                  info: description,\n                  data: value,\n                };\n              }\n              /*\n  Format:\n  [0]   = {Text Encoding}\n  [1-?] = {Value}\n  */\n\n              var text = utf8ArrayToStr(frame.data.subarray(1));\n              return {\n                key: frame.type,\n                data: text,\n              };\n            };\n\n            var decodeURLFrame = function decodeURLFrame(frame) {\n              if (frame.type === \"WXXX\") {\n                /*\n    Format:\n    [0]   = {Text Encoding}\n    [1-?] = {Description}\\0{URL}\n    */\n                if (frame.size < 2) {\n                  return undefined;\n                }\n\n                var index = 1;\n                var description = utf8ArrayToStr(frame.data.subarray(index), true);\n                index += description.length + 1;\n                var value = utf8ArrayToStr(frame.data.subarray(index));\n                return {\n                  key: frame.type,\n                  info: description,\n                  data: value,\n                };\n              }\n              /*\n  Format:\n  [0-?] = {URL}\n  */\n\n              var url = utf8ArrayToStr(frame.data);\n              return {\n                key: frame.type,\n                data: url,\n              };\n            };\n\n            var readTimeStamp = function readTimeStamp(timeStampFrame) {\n              if (timeStampFrame.data.byteLength === 8) {\n                var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,\n                // with the upper 31 bits set to zero.\n\n                var pts33Bit = data[3] & 0x1;\n                var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];\n                timestamp /= 45;\n\n                if (pts33Bit) {\n                  timestamp += 47721858.84;\n                } // 2^32 / 90\n\n                return Math.round(timestamp);\n              }\n\n              return undefined;\n            }; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n            // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n\n            /* utf.js - UTF-8 <=> UTF-16 convertion\n             *\n             * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n             * Version: 1.0\n             * LastModified: Dec 25 1999\n             * This library is free.  You can redistribute it and/or modify it.\n             */\n\n            var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {\n              if (exitOnNull === void 0) {\n                exitOnNull = false;\n              }\n\n              var decoder = getTextDecoder();\n\n              if (decoder) {\n                var decoded = decoder.decode(array);\n\n                if (exitOnNull) {\n                  // grab up to the first null\n                  var idx = decoded.indexOf(\"\\0\");\n                  return idx !== -1 ? decoded.substring(0, idx) : decoded;\n                } // remove any null characters\n\n                return decoded.replace(/\\0/g, \"\");\n              }\n\n              var len = array.length;\n              var c;\n              var char2;\n              var char3;\n              var out = \"\";\n              var i = 0;\n\n              while (i < len) {\n                c = array[i++];\n\n                if (c === 0x00 && exitOnNull) {\n                  return out;\n                } else if (c === 0x00 || c === 0x03) {\n                  // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n                  continue;\n                }\n\n                switch (c >> 4) {\n                  case 0:\n                  case 1:\n                  case 2:\n                  case 3:\n                  case 4:\n                  case 5:\n                  case 6:\n                  case 7:\n                    // 0xxxxxxx\n                    out += String.fromCharCode(c);\n                    break;\n\n                  case 12:\n                  case 13:\n                    // 110x xxxx   10xx xxxx\n                    char2 = array[i++];\n                    out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));\n                    break;\n\n                  case 14:\n                    // 1110 xxxx  10xx xxxx  10xx xxxx\n                    char2 = array[i++];\n                    char3 = array[i++];\n                    out += String.fromCharCode(((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0));\n                    break;\n\n                  default:\n                }\n              }\n\n              return out;\n            };\n            var testables = {\n              decodeTextFrame: decodeTextFrame,\n            };\n            var decoder;\n\n            function getTextDecoder() {\n              if (!decoder && typeof self.TextDecoder !== \"undefined\") {\n                decoder = new self.TextDecoder(\"utf-8\");\n              }\n\n              return decoder;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/demux/mp3demuxer.ts\":\n          /*!*********************************!*\\\n  !*** ./src/demux/mp3demuxer.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ \"./src/demux/base-audio-demuxer.ts\");\n            /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ \"./src/demux/id3.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ \"./src/demux/mpegaudio.ts\");\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            /**\n             * MP3 demuxer\n             */\n\n            var MP3Demuxer = /*#__PURE__*/ (function (_BaseAudioDemuxer) {\n              _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);\n\n              function MP3Demuxer() {\n                return _BaseAudioDemuxer.apply(this, arguments) || this;\n              }\n\n              var _proto = MP3Demuxer.prototype;\n\n              _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {\n                _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);\n\n                this._audioTrack = {\n                  container: \"audio/mpeg\",\n                  type: \"audio\",\n                  id: 2,\n                  pid: -1,\n                  sequenceNumber: 0,\n                  isAAC: false,\n                  samples: [],\n                  manifestCodec: audioCodec,\n                  duration: duration,\n                  inputTimeScale: 90000,\n                  dropped: 0,\n                };\n              };\n\n              MP3Demuxer.probe = function probe(data) {\n                if (!data) {\n                  return false;\n                } // check if data contains ID3 timestamp and MPEG sync word\n                // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n                // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n                // More info http://www.mp3-tech.org/programmer/frame_header.html\n\n                var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__[\"getID3Data\"](data, 0) || [];\n                var offset = id3Data.length;\n\n                for (var length = data.length; offset < length; offset++) {\n                  if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__[\"probe\"](data, offset)) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].log(\"MPEG Audio sync word found !\");\n                    return true;\n                  }\n                }\n\n                return false;\n              };\n\n              _proto.canParse = function canParse(data, offset) {\n                return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__[\"canParse\"](data, offset);\n              };\n\n              _proto.appendFrame = function appendFrame(track, data, offset) {\n                if (this.initPTS === null) {\n                  return;\n                }\n\n                return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__[\"appendFrame\"](track, data, offset, this.initPTS, this.frameIndex);\n              };\n\n              return MP3Demuxer;\n            })(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__[\"default\"]);\n\n            MP3Demuxer.minProbeByteLength = 4;\n            /* harmony default export */ __webpack_exports__[\"default\"] = MP3Demuxer;\n\n            /***/\n          },\n\n        /***/ \"./src/demux/mp4demuxer.ts\":\n          /*!*********************************!*\\\n  !*** ./src/demux/mp4demuxer.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ \"./src/demux/dummy-demuxed-track.ts\");\n            /**\n             * MP4 demuxer\n             */\n\n            var MP4Demuxer = /*#__PURE__*/ (function () {\n              function MP4Demuxer(observer, config) {\n                this.remainderData = null;\n                this.config = void 0;\n                this.config = config;\n              }\n\n              var _proto = MP4Demuxer.prototype;\n\n              _proto.resetTimeStamp = function resetTimeStamp() {};\n\n              _proto.resetInitSegment = function resetInitSegment() {};\n\n              _proto.resetContiguity = function resetContiguity() {};\n\n              MP4Demuxer.probe = function probe(data) {\n                // ensure we find a moof box in the first 16 kB\n                return (\n                  Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__[\"findBox\"])(\n                    {\n                      data: data,\n                      start: 0,\n                      end: Math.min(data.length, 16384),\n                    },\n                    [\"moof\"]\n                  ).length > 0\n                );\n              };\n\n              _proto.demux = function demux(data) {\n                // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter\n                var avcSamples = data;\n                var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])();\n\n                if (this.config.progressive) {\n                  // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.\n                  // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee\n                  // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.\n                  if (this.remainderData) {\n                    avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__[\"appendUint8Array\"])(this.remainderData, data);\n                  }\n\n                  var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__[\"segmentValidRange\"])(avcSamples);\n                  this.remainderData = segmentedData.remainder;\n                  avcTrack.samples = segmentedData.valid || new Uint8Array();\n                } else {\n                  avcTrack.samples = avcSamples;\n                }\n\n                return {\n                  audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])(),\n                  avcTrack: avcTrack,\n                  id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])(),\n                  textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])(),\n                };\n              };\n\n              _proto.flush = function flush() {\n                var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])();\n                avcTrack.samples = this.remainderData || new Uint8Array();\n                this.remainderData = null;\n                return {\n                  audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])(),\n                  avcTrack: avcTrack,\n                  id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])(),\n                  textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__[\"dummyTrack\"])(),\n                };\n              };\n\n              _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {\n                return Promise.reject(new Error(\"The MP4 demuxer does not support SAMPLE-AES decryption\"));\n              };\n\n              _proto.destroy = function destroy() {};\n\n              return MP4Demuxer;\n            })();\n\n            MP4Demuxer.minProbeByteLength = 1024;\n            /* harmony default export */ __webpack_exports__[\"default\"] = MP4Demuxer;\n\n            /***/\n          },\n\n        /***/ \"./src/demux/mpegaudio.ts\":\n          /*!********************************!*\\\n  !*** ./src/demux/mpegaudio.ts ***!\n  \\********************************/\n          /*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"appendFrame\", function () {\n              return appendFrame;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseHeader\", function () {\n              return parseHeader;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isHeaderPattern\", function () {\n              return isHeaderPattern;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isHeader\", function () {\n              return isHeader;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"canParse\", function () {\n              return canParse;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"probe\", function () {\n              return probe;\n            });\n            /**\n             *  MPEG parser helper\n             */\n            var chromeVersion = null;\n            var BitratesMap = [\n              32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56,\n              64, 80, 96, 112, 128, 144, 160,\n            ];\n            var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];\n            var SamplesCoefficients = [\n              // MPEG 2.5\n              [\n                0, // Reserved\n                72, // Layer3\n                144, // Layer2\n                12, // Layer1\n              ], // Reserved\n              [\n                0, // Reserved\n                0, // Layer3\n                0, // Layer2\n                0, // Layer1\n              ], // MPEG 2\n              [\n                0, // Reserved\n                72, // Layer3\n                144, // Layer2\n                12, // Layer1\n              ], // MPEG 1\n              [\n                0, // Reserved\n                144, // Layer3\n                144, // Layer2\n                12, // Layer1\n              ],\n            ];\n            var BytesInSlot = [\n              0, // Reserved\n              1, // Layer3\n              1, // Layer2\n              4, // Layer1\n            ];\n            function appendFrame(track, data, offset, pts, frameIndex) {\n              // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n              if (offset + 24 > data.length) {\n                return;\n              }\n\n              var header = parseHeader(data, offset);\n\n              if (header && offset + header.frameLength <= data.length) {\n                var frameDuration = (header.samplesPerFrame * 90000) / header.sampleRate;\n                var stamp = pts + frameIndex * frameDuration;\n                var sample = {\n                  unit: data.subarray(offset, offset + header.frameLength),\n                  pts: stamp,\n                  dts: stamp,\n                };\n                track.config = [];\n                track.channelCount = header.channelCount;\n                track.samplerate = header.sampleRate;\n                track.samples.push(sample);\n                return {\n                  sample: sample,\n                  length: header.frameLength,\n                  missing: 0,\n                };\n              }\n            }\n            function parseHeader(data, offset) {\n              var mpegVersion = (data[offset + 1] >> 3) & 3;\n              var mpegLayer = (data[offset + 1] >> 1) & 3;\n              var bitRateIndex = (data[offset + 2] >> 4) & 15;\n              var sampleRateIndex = (data[offset + 2] >> 2) & 3;\n\n              if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {\n                var paddingBit = (data[offset + 2] >> 1) & 1;\n                var channelMode = data[offset + 3] >> 6;\n                var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;\n                var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;\n                var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;\n                var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];\n                var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n\n                var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];\n                var bytesInSlot = BytesInSlot[mpegLayer];\n                var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n                var frameLength = Math.floor((sampleCoefficient * bitRate) / sampleRate + paddingBit) * bytesInSlot;\n\n                if (chromeVersion === null) {\n                  var userAgent = navigator.userAgent || \"\";\n                  var result = userAgent.match(/Chrome\\/(\\d+)/i);\n                  chromeVersion = result ? parseInt(result[1]) : 0;\n                }\n\n                var needChromeFix = !!chromeVersion && chromeVersion <= 87;\n\n                if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {\n                  // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)\n                  data[offset + 3] = data[offset + 3] | 0x80;\n                }\n\n                return {\n                  sampleRate: sampleRate,\n                  channelCount: channelCount,\n                  frameLength: frameLength,\n                  samplesPerFrame: samplesPerFrame,\n                };\n              }\n            }\n            function isHeaderPattern(data, offset) {\n              return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n            }\n            function isHeader(data, offset) {\n              // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n              // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n              // More info http://www.mp3-tech.org/programmer/frame_header.html\n              return offset + 1 < data.length && isHeaderPattern(data, offset);\n            }\n            function canParse(data, offset) {\n              var headerSize = 4;\n              return isHeaderPattern(data, offset) && headerSize <= data.length - offset;\n            }\n            function probe(data, offset) {\n              // same as isHeader but we also check that MPEG frame follows last MPEG frame\n              // or end of data is reached\n              if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n                // MPEG header Length\n                var headerLength = 4; // MPEG frame Length\n\n                var header = parseHeader(data, offset);\n                var frameLength = headerLength;\n\n                if (header !== null && header !== void 0 && header.frameLength) {\n                  frameLength = header.frameLength;\n                }\n\n                var newOffset = offset + frameLength;\n                return newOffset === data.length || isHeader(data, newOffset);\n              }\n\n              return false;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/demux/sample-aes.ts\":\n          /*!*********************************!*\\\n  !*** ./src/demux/sample-aes.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ \"./src/crypt/decrypter.ts\");\n            /* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ \"./src/demux/tsdemuxer.ts\");\n            /**\n             * SAMPLE-AES decrypter\n             */\n\n            var SampleAesDecrypter = /*#__PURE__*/ (function () {\n              function SampleAesDecrypter(observer, config, keyData) {\n                this.keyData = void 0;\n                this.decrypter = void 0;\n                this.keyData = keyData;\n                this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__[\"default\"](observer, config, {\n                  removePKCS7Padding: false,\n                });\n              }\n\n              var _proto = SampleAesDecrypter.prototype;\n\n              _proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {\n                this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback);\n              }; // AAC - encrypt all full 16 bytes blocks starting from offset 16\n\n              _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {\n                var curUnit = samples[sampleIndex].unit;\n                var encryptedData = curUnit.subarray(16, curUnit.length - (curUnit.length % 16));\n                var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);\n                var localthis = this;\n                this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) {\n                  var decryptedData = new Uint8Array(decryptedBuffer);\n                  curUnit.set(decryptedData, 16);\n\n                  if (!sync) {\n                    localthis.decryptAacSamples(samples, sampleIndex + 1, callback);\n                  }\n                });\n              };\n\n              _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {\n                for (; ; sampleIndex++) {\n                  if (sampleIndex >= samples.length) {\n                    callback();\n                    return;\n                  }\n\n                  if (samples[sampleIndex].unit.length < 32) {\n                    continue;\n                  }\n\n                  var sync = this.decrypter.isSync();\n                  this.decryptAacSample(samples, sampleIndex, callback, sync);\n\n                  if (!sync) {\n                    return;\n                  }\n                }\n              }; // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n\n              _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {\n                var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n                var encryptedData = new Int8Array(encryptedDataLen);\n                var outputPos = 0;\n\n                for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n                  encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n                }\n\n                return encryptedData;\n              };\n\n              _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {\n                var uint8DecryptedData = new Uint8Array(decryptedData);\n                var inputPos = 0;\n\n                for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n                  decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);\n                }\n\n                return decodedData;\n              };\n\n              _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n                var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__[\"discardEPB\"])(curUnit.data);\n                var encryptedData = this.getAvcEncryptedData(decodedData);\n                var localthis = this;\n                this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) {\n                  curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer);\n\n                  if (!sync) {\n                    localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n                  }\n                });\n              };\n\n              _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {\n                if (samples instanceof Uint8Array) {\n                  throw new Error(\"Cannot decrypt samples of type Uint8Array\");\n                }\n\n                for (; ; sampleIndex++, unitIndex = 0) {\n                  if (sampleIndex >= samples.length) {\n                    callback();\n                    return;\n                  }\n\n                  var curUnits = samples[sampleIndex].units;\n\n                  for (; ; unitIndex++) {\n                    if (unitIndex >= curUnits.length) {\n                      break;\n                    }\n\n                    var curUnit = curUnits[unitIndex];\n\n                    if (curUnit.data.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {\n                      continue;\n                    }\n\n                    var sync = this.decrypter.isSync();\n                    this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);\n\n                    if (!sync) {\n                      return;\n                    }\n                  }\n                }\n              };\n\n              return SampleAesDecrypter;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = SampleAesDecrypter;\n\n            /***/\n          },\n\n        /***/ \"./src/demux/transmuxer-interface.ts\":\n          /*!*******************************************!*\\\n  !*** ./src/demux/transmuxer-interface.ts ***!\n  \\*******************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return TransmuxerInterface;\n            });\n            /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ \"./node_modules/webworkify-webpack/index.js\");\n            /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ \"./src/demux/transmuxer.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ \"./src/utils/mediasource-helper.ts\");\n            /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\");\n            /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/ __webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);\n\n            var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__[\"getMediaSource\"])() || {\n              isTypeSupported: function isTypeSupported() {\n                return false;\n              },\n            };\n\n            var TransmuxerInterface = /*#__PURE__*/ (function () {\n              function TransmuxerInterface(CiderHls, id, onTransmuxComplete, onFlush) {\n                var _this = this;\n\n                this.CiderHls = void 0;\n                this.id = void 0;\n                this.observer = void 0;\n                this.frag = null;\n                this.part = null;\n                this.worker = void 0;\n                this.onwmsg = void 0;\n                this.transmuxer = null;\n                this.onTransmuxComplete = void 0;\n                this.onFlush = void 0;\n                this.CiderHls = CiderHls;\n                this.id = id;\n                this.onTransmuxComplete = onTransmuxComplete;\n                this.onFlush = onFlush;\n                var config = CiderHls.config;\n\n                var forwardMessage = function forwardMessage(ev, data) {\n                  data = data || {};\n                  data.frag = _this.frag;\n                  data.id = _this.id;\n                  CiderHls.trigger(ev, data);\n                }; // forward events to main thread\n\n                this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__[\"EventEmitter\"]();\n                this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_DECRYPTED, forwardMessage);\n                this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, forwardMessage);\n                var typeSupported = {\n                  mp4: MediaSource.isTypeSupported(\"video/mp4\"),\n                  mpeg: MediaSource.isTypeSupported(\"audio/mpeg\"),\n                  mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n                }; // navigator.vendor is not always available in Web Worker\n                // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n\n                var vendor = navigator.vendor;\n\n                if (config.enableWorker && typeof Worker !== \"undefined\") {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].log(\"demuxing in webworker\");\n                  var worker;\n\n                  try {\n                    worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/ /*! ../demux/transmuxer-worker.ts */ \"./src/demux/transmuxer-worker.ts\");\n                    this.onwmsg = this.onWorkerMessage.bind(this);\n                    worker.addEventListener(\"message\", this.onwmsg);\n\n                    worker.onerror = function (event) {\n                      CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                        type: _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorTypes\"].OTHER_ERROR,\n                        details: _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorDetails\"].INTERNAL_EXCEPTION,\n                        fatal: true,\n                        event: \"demuxerWorker\",\n                        error: new Error(event.message + \"  (\" + event.filename + \":\" + event.lineno + \")\"),\n                      });\n                    };\n\n                    worker.postMessage({\n                      cmd: \"init\",\n                      typeSupported: typeSupported,\n                      vendor: vendor,\n                      id: id,\n                      config: JSON.stringify(config),\n                    });\n                  } catch (err) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Error in worker:\", err);\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].error(\"Error while initializing DemuxerWorker, fallback to inline\");\n\n                    if (worker) {\n                      // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n                      self.URL.revokeObjectURL(worker.objectURL);\n                    }\n\n                    this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__[\"default\"](this.observer, typeSupported, config, vendor, id);\n                    this.worker = null;\n                  }\n                } else {\n                  this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__[\"default\"](this.observer, typeSupported, config, vendor, id);\n                }\n              }\n\n              var _proto = TransmuxerInterface.prototype;\n\n              _proto.destroy = function destroy() {\n                var w = this.worker;\n\n                if (w) {\n                  w.removeEventListener(\"message\", this.onwmsg);\n                  w.terminate();\n                  this.worker = null;\n                } else {\n                  var transmuxer = this.transmuxer;\n\n                  if (transmuxer) {\n                    transmuxer.destroy();\n                    this.transmuxer = null;\n                  }\n                }\n\n                var observer = this.observer;\n\n                if (observer) {\n                  observer.removeAllListeners();\n                } // @ts-ignore\n\n                this.observer = null;\n              };\n\n              _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {\n                var _this2 = this;\n\n                chunkMeta.transmuxing.start = self.performance.now();\n                var transmuxer = this.transmuxer,\n                  worker = this.worker;\n                var timeOffset = part ? part.start : frag.start;\n                var decryptdata = frag.decryptdata;\n                var lastFrag = this.frag;\n                var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n                var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);\n                var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;\n                var partDiff = this.part ? chunkMeta.part - this.part.index : 1;\n                var contiguous = !trackSwitch && (snDiff === 1 || (snDiff === 0 && partDiff === 1));\n                var now = self.performance.now();\n\n                if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {\n                  frag.stats.parsing.start = now;\n                }\n\n                if (part && (partDiff || !contiguous)) {\n                  part.stats.parsing.start = now;\n                }\n\n                var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__[\"TransmuxState\"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset);\n\n                if (!contiguous || discontinuity) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].log(\n                    \"[transmuxer-interface, \" +\n                      frag.type +\n                      \"]: Starting new transmux session for sn: \" +\n                      chunkMeta.sn +\n                      \" p: \" +\n                      chunkMeta.part +\n                      \" level: \" +\n                      chunkMeta.level +\n                      \" id: \" +\n                      chunkMeta.id +\n                      \"\\n        discontinuity: \" +\n                      discontinuity +\n                      \"\\n        trackSwitch: \" +\n                      trackSwitch +\n                      \"\\n        contiguous: \" +\n                      contiguous +\n                      \"\\n        accurateTimeOffset: \" +\n                      accurateTimeOffset +\n                      \"\\n        timeOffset: \" +\n                      timeOffset\n                  );\n                  var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__[\"TransmuxConfig\"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);\n                  this.configureTransmuxer(config);\n                }\n\n                this.frag = frag;\n                this.part = part; // Frags with sn of 'initSegment' are not transmuxed\n\n                if (worker) {\n                  // post fragment payload as transferable objects for ArrayBuffer (no copy)\n                  worker.postMessage(\n                    {\n                      cmd: \"demux\",\n                      data: data,\n                      decryptdata: decryptdata,\n                      chunkMeta: chunkMeta,\n                      state: state,\n                    },\n                    data instanceof ArrayBuffer ? [data] : []\n                  );\n                } else if (transmuxer) {\n                  var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);\n\n                  if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__[\"isPromise\"])(_transmuxResult)) {\n                    _transmuxResult.then(function (data) {\n                      _this2.handleTransmuxComplete(data);\n                    });\n                  } else {\n                    this.handleTransmuxComplete(_transmuxResult);\n                  }\n                }\n              };\n\n              _proto.flush = function flush(chunkMeta) {\n                var _this3 = this;\n\n                chunkMeta.transmuxing.start = self.performance.now();\n                var transmuxer = this.transmuxer,\n                  worker = this.worker;\n\n                if (worker) {\n                  worker.postMessage({\n                    cmd: \"flush\",\n                    chunkMeta: chunkMeta,\n                  });\n                } else if (transmuxer) {\n                  var _transmuxResult2 = transmuxer.flush(chunkMeta);\n\n                  if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__[\"isPromise\"])(_transmuxResult2)) {\n                    _transmuxResult2.then(function (data) {\n                      _this3.handleFlushResult(data, chunkMeta);\n                    });\n                  } else {\n                    this.handleFlushResult(_transmuxResult2, chunkMeta);\n                  }\n                }\n              };\n\n              _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {\n                var _this4 = this;\n\n                results.forEach(function (result) {\n                  _this4.handleTransmuxComplete(result);\n                });\n                this.onFlush(chunkMeta);\n              };\n\n              _proto.onWorkerMessage = function onWorkerMessage(ev) {\n                var data = ev.data;\n                var CiderHls = this.CiderHls;\n\n                switch (data.event) {\n                  case \"init\": {\n                    // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n                    self.URL.revokeObjectURL(this.worker.objectURL);\n                    break;\n                  }\n\n                  case \"transmuxComplete\": {\n                    this.handleTransmuxComplete(data.data);\n                    break;\n                  }\n\n                  case \"flush\": {\n                    this.onFlush(data.data);\n                    break;\n                  }\n\n                  /* falls through */\n\n                  default: {\n                    data.data = data.data || {};\n                    data.data.frag = this.frag;\n                    data.data.id = this.id;\n                    CiderHls.trigger(data.event, data.data);\n                    break;\n                  }\n                }\n              };\n\n              _proto.configureTransmuxer = function configureTransmuxer(config) {\n                var worker = this.worker,\n                  transmuxer = this.transmuxer;\n\n                if (worker) {\n                  worker.postMessage({\n                    cmd: \"configure\",\n                    config: config,\n                  });\n                } else if (transmuxer) {\n                  transmuxer.configure(config);\n                }\n              };\n\n              _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {\n                result.chunkMeta.transmuxing.end = self.performance.now();\n                this.onTransmuxComplete(result);\n              };\n\n              return TransmuxerInterface;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/demux/transmuxer-worker.ts\":\n          /*!****************************************!*\\\n  !*** ./src/demux/transmuxer-worker.ts ***!\n  \\****************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return TransmuxerWorker;\n            });\n            /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ \"./src/demux/transmuxer.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\");\n            /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/ __webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);\n\n            function TransmuxerWorker(self) {\n              var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__[\"EventEmitter\"]();\n\n              var forwardMessage = function forwardMessage(ev, data) {\n                self.postMessage({\n                  event: ev,\n                  data: data,\n                });\n              }; // forward events to main thread\n\n              observer.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].FRAG_DECRYPTED, forwardMessage);\n              observer.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, forwardMessage);\n              self.addEventListener(\"message\", function (ev) {\n                var data = ev.data;\n\n                switch (data.cmd) {\n                  case \"init\": {\n                    var config = JSON.parse(data.config);\n                    self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__[\"default\"](observer, data.typeSupported, config, data.vendor, data.id);\n                    Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"enableLogs\"])(config.debug);\n                    forwardMessage(\"init\", null);\n                    break;\n                  }\n\n                  case \"configure\": {\n                    self.transmuxer.configure(data.config);\n                    break;\n                  }\n\n                  case \"demux\": {\n                    var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);\n\n                    if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__[\"isPromise\"])(transmuxResult)) {\n                      transmuxResult.then(function (data) {\n                        emitTransmuxComplete(self, data);\n                      });\n                    } else {\n                      emitTransmuxComplete(self, transmuxResult);\n                    }\n\n                    break;\n                  }\n\n                  case \"flush\": {\n                    var id = data.chunkMeta;\n\n                    var _transmuxResult = self.transmuxer.flush(id);\n\n                    if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__[\"isPromise\"])(_transmuxResult)) {\n                      _transmuxResult.then(function (results) {\n                        handleFlushResult(self, results, id);\n                      });\n                    } else {\n                      handleFlushResult(self, _transmuxResult, id);\n                    }\n\n                    break;\n                  }\n\n                  default:\n                    break;\n                }\n              });\n            }\n\n            function emitTransmuxComplete(self, transmuxResult) {\n              if (isEmptyResult(transmuxResult.remuxResult)) {\n                return;\n              }\n\n              var transferable = [];\n              var _transmuxResult$remux = transmuxResult.remuxResult,\n                audio = _transmuxResult$remux.audio,\n                video = _transmuxResult$remux.video;\n\n              if (audio) {\n                addToTransferable(transferable, audio);\n              }\n\n              if (video) {\n                addToTransferable(transferable, video);\n              }\n\n              self.postMessage(\n                {\n                  event: \"transmuxComplete\",\n                  data: transmuxResult,\n                },\n                transferable\n              );\n            } // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)\n            // in order to minimize message passing overhead\n\n            function addToTransferable(transferable, track) {\n              if (track.data1) {\n                transferable.push(track.data1.buffer);\n              }\n\n              if (track.data2) {\n                transferable.push(track.data2.buffer);\n              }\n            }\n\n            function handleFlushResult(self, results, chunkMeta) {\n              results.forEach(function (result) {\n                emitTransmuxComplete(self, result);\n              });\n              self.postMessage({\n                event: \"flush\",\n                data: chunkMeta,\n              });\n            }\n\n            function isEmptyResult(remuxResult) {\n              return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/demux/transmuxer.ts\":\n          /*!*********************************!*\\\n  !*** ./src/demux/transmuxer.ts ***!\n  \\*********************************/\n          /*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return Transmuxer;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isPromise\", function () {\n              return isPromise;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"TransmuxConfig\", function () {\n              return TransmuxConfig;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"TransmuxState\", function () {\n              return TransmuxState;\n            });\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ \"./src/crypt/decrypter.ts\");\n            /* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ \"./src/demux/aacdemuxer.ts\");\n            /* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ \"./src/demux/mp4demuxer.ts\");\n            /* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ \"./src/demux/tsdemuxer.ts\");\n            /* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ \"./src/demux/mp3demuxer.ts\");\n            /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ \"./src/remux/mp4-remuxer.ts\");\n            /* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ \"./src/remux/passthrough-remuxer.ts\");\n            /* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ \"./src/demux/chunk-cache.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            var now; // performance.now() not available on WebWorker, at least on Safari Desktop\n\n            try {\n              now = self.performance.now.bind(self.performance);\n            } catch (err) {\n              _utils_logger__WEBPACK_IMPORTED_MODULE_11__[\"logger\"].debug(\"Unable to use Performance API on this environment\");\n              now = self.Date.now;\n            }\n\n            var muxConfig = [\n              {\n                demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__[\"default\"],\n                remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__[\"default\"],\n              },\n              {\n                demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__[\"default\"],\n                remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__[\"default\"],\n              },\n              {\n                demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__[\"default\"],\n                remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__[\"default\"],\n              },\n              {\n                demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__[\"default\"],\n                remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__[\"default\"],\n              },\n            ];\n            var minProbeByteLength = 1024;\n            muxConfig.forEach(function (_ref) {\n              var demux = _ref.demux;\n              minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength);\n            });\n\n            var Transmuxer = /*#__PURE__*/ (function () {\n              function Transmuxer(observer, typeSupported, config, vendor, id) {\n                this.observer = void 0;\n                this.typeSupported = void 0;\n                this.config = void 0;\n                this.vendor = void 0;\n                this.id = void 0;\n                this.demuxer = void 0;\n                this.remuxer = void 0;\n                this.decrypter = void 0;\n                this.probe = void 0;\n                this.decryptionPromise = null;\n                this.transmuxConfig = void 0;\n                this.currentTransmuxState = void 0;\n                this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__[\"default\"]();\n                this.observer = observer;\n                this.typeSupported = typeSupported;\n                this.config = config;\n                this.vendor = vendor;\n                this.id = id;\n              }\n\n              var _proto = Transmuxer.prototype;\n\n              _proto.configure = function configure(transmuxConfig) {\n                this.transmuxConfig = transmuxConfig;\n\n                if (this.decrypter) {\n                  this.decrypter.reset();\n                }\n              };\n\n              _proto.push = function push(data, decryptdata, chunkMeta, state) {\n                var _this = this;\n\n                var stats = chunkMeta.transmuxing;\n                stats.executeStart = now();\n                var uintData = new Uint8Array(data);\n                var cache = this.cache,\n                  config = this.config,\n                  currentTransmuxState = this.currentTransmuxState,\n                  transmuxConfig = this.transmuxConfig;\n\n                if (state) {\n                  this.currentTransmuxState = state;\n                }\n\n                var keyData = getEncryptionType(uintData, decryptdata);\n\n                if (keyData && keyData.method === \"AES-128\") {\n                  var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not\n\n                  if (config.enableSoftwareAES) {\n                    // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n                    // data is handled in the flush() call\n                    var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);\n\n                    if (!decryptedData) {\n                      stats.executeEnd = now();\n                      return emptyResult(chunkMeta);\n                    }\n\n                    uintData = new Uint8Array(decryptedData);\n                  } else {\n                    this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {\n                      // Calling push here is important; if flush() is called while this is still resolving, this ensures that\n                      // the decrypted data has been transmuxed\n                      var result = _this.push(decryptedData, null, chunkMeta);\n\n                      _this.decryptionPromise = null;\n                      return result;\n                    });\n                    return this.decryptionPromise;\n                  }\n                }\n\n                var _ref2 = state || currentTransmuxState,\n                  contiguous = _ref2.contiguous,\n                  discontinuity = _ref2.discontinuity,\n                  trackSwitch = _ref2.trackSwitch,\n                  accurateTimeOffset = _ref2.accurateTimeOffset,\n                  timeOffset = _ref2.timeOffset;\n\n                var audioCodec = transmuxConfig.audioCodec,\n                  videoCodec = transmuxConfig.videoCodec,\n                  defaultInitPts = transmuxConfig.defaultInitPts,\n                  duration = transmuxConfig.duration,\n                  initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe\n\n                if (discontinuity || trackSwitch) {\n                  this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);\n                }\n\n                if (discontinuity) {\n                  this.resetInitialTimestamp(defaultInitPts);\n                }\n\n                if (!contiguous) {\n                  this.resetContiguity();\n                }\n\n                if (this.needsProbing(uintData, discontinuity, trackSwitch)) {\n                  if (cache.dataLength) {\n                    var cachedData = cache.flush();\n                    uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__[\"appendUint8Array\"])(cachedData, uintData);\n                  }\n\n                  this.configureTransmuxer(uintData, transmuxConfig);\n                }\n\n                var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);\n                var currentState = this.currentTransmuxState;\n                currentState.contiguous = true;\n                currentState.discontinuity = false;\n                currentState.trackSwitch = false;\n                stats.executeEnd = now();\n                return result;\n              }; // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)\n\n              _proto.flush = function flush(chunkMeta) {\n                var _this2 = this;\n\n                var stats = chunkMeta.transmuxing;\n                stats.executeStart = now();\n                var decrypter = this.decrypter,\n                  cache = this.cache,\n                  currentTransmuxState = this.currentTransmuxState,\n                  decryptionPromise = this.decryptionPromise;\n\n                if (decryptionPromise) {\n                  // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore\n                  // only flushing is required for async decryption\n                  return decryptionPromise.then(function () {\n                    return _this2.flush(chunkMeta);\n                  });\n                }\n\n                var transmuxResults = [];\n                var timeOffset = currentTransmuxState.timeOffset;\n\n                if (decrypter) {\n                  // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults\n                  // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,\n                  // or for progressive downloads with small segments)\n                  var decryptedData = decrypter.flush();\n\n                  if (decryptedData) {\n                    // Push always returns a TransmuxerResult if decryptdata is null\n                    transmuxResults.push(this.push(decryptedData, null, chunkMeta));\n                  }\n                }\n\n                var bytesSeen = cache.dataLength;\n                cache.reset();\n                var demuxer = this.demuxer,\n                  remuxer = this.remuxer;\n\n                if (!demuxer || !remuxer) {\n                  // If probing failed, and each demuxer saw enough bytes to be able to probe, then CiderHls.js has been given content its not able to handle\n                  if (bytesSeen >= minProbeByteLength) {\n                    this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].MEDIA_ERROR,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_PARSING_ERROR,\n                      fatal: true,\n                      reason: \"no demux matching with content found\",\n                    });\n                  }\n\n                  stats.executeEnd = now();\n                  return [emptyResult(chunkMeta)];\n                }\n\n                var demuxResultOrPromise = demuxer.flush(timeOffset);\n\n                if (isPromise(demuxResultOrPromise)) {\n                  // Decrypt final SAMPLE-AES samples\n                  return demuxResultOrPromise.then(function (demuxResult) {\n                    _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);\n\n                    return transmuxResults;\n                  });\n                }\n\n                this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);\n                return transmuxResults;\n              };\n\n              _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {\n                var audioTrack = demuxResult.audioTrack,\n                  avcTrack = demuxResult.avcTrack,\n                  id3Track = demuxResult.id3Track,\n                  textTrack = demuxResult.textTrack;\n                var _this$currentTransmux = this.currentTransmuxState,\n                  accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,\n                  timeOffset = _this$currentTransmux.timeOffset;\n                _utils_logger__WEBPACK_IMPORTED_MODULE_11__[\"logger\"].log(\"[transmuxer.ts]: Flushed fragment \" + chunkMeta.sn + (chunkMeta.part > -1 ? \" p: \" + chunkMeta.part : \"\") + \" of level \" + chunkMeta.level);\n                var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);\n                transmuxResults.push({\n                  remuxResult: remuxResult,\n                  chunkMeta: chunkMeta,\n                });\n                chunkMeta.transmuxing.executeEnd = now();\n              };\n\n              _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {\n                var demuxer = this.demuxer,\n                  remuxer = this.remuxer;\n\n                if (!demuxer || !remuxer) {\n                  return;\n                }\n\n                demuxer.resetTimeStamp(defaultInitPts);\n                remuxer.resetTimeStamp(defaultInitPts);\n              };\n\n              _proto.resetContiguity = function resetContiguity() {\n                var demuxer = this.demuxer,\n                  remuxer = this.remuxer;\n\n                if (!demuxer || !remuxer) {\n                  return;\n                }\n\n                demuxer.resetContiguity();\n                remuxer.resetNextTimestamp();\n              };\n\n              _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) {\n                var demuxer = this.demuxer,\n                  remuxer = this.remuxer;\n\n                if (!demuxer || !remuxer) {\n                  return;\n                }\n\n                demuxer.resetInitSegment(audioCodec, videoCodec, duration);\n                remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);\n              };\n\n              _proto.destroy = function destroy() {\n                if (this.demuxer) {\n                  this.demuxer.destroy();\n                  this.demuxer = undefined;\n                }\n\n                if (this.remuxer) {\n                  this.remuxer.destroy();\n                  this.remuxer = undefined;\n                }\n              };\n\n              _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {\n                var result;\n\n                if (keyData && keyData.method === \"SAMPLE-AES\") {\n                  result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);\n                } else {\n                  result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);\n                }\n\n                return result;\n              };\n\n              _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {\n                var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),\n                  audioTrack = _demux.audioTrack,\n                  avcTrack = _demux.avcTrack,\n                  id3Track = _demux.id3Track,\n                  textTrack = _demux.textTrack;\n\n                var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);\n                return {\n                  remuxResult: remuxResult,\n                  chunkMeta: chunkMeta,\n                };\n              };\n\n              _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {\n                var _this3 = this;\n\n                return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {\n                  var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);\n\n                  return {\n                    remuxResult: remuxResult,\n                    chunkMeta: chunkMeta,\n                  };\n                });\n              };\n\n              _proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {\n                var config = this.config,\n                  observer = this.observer,\n                  typeSupported = this.typeSupported,\n                  vendor = this.vendor;\n                var audioCodec = transmuxConfig.audioCodec,\n                  defaultInitPts = transmuxConfig.defaultInitPts,\n                  duration = transmuxConfig.duration,\n                  initSegmentData = transmuxConfig.initSegmentData,\n                  videoCodec = transmuxConfig.videoCodec; // probe for content type\n\n                var mux;\n\n                for (var i = 0, len = muxConfig.length; i < len; i++) {\n                  if (muxConfig[i].demux.probe(data)) {\n                    mux = muxConfig[i];\n                    break;\n                  }\n                }\n\n                if (!mux) {\n                  // If probing previous configs fail, use mp4 passthrough\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_11__[\"logger\"].warn(\"Failed to find demuxer by probing frag, treating as mp4 passthrough\");\n                  mux = {\n                    demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__[\"default\"],\n                    remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__[\"default\"],\n                  };\n                } // so let's check that current remuxer and demuxer are still valid\n\n                var demuxer = this.demuxer;\n                var remuxer = this.remuxer;\n                var Remuxer = mux.remux;\n                var Demuxer = mux.demux;\n\n                if (!remuxer || !(remuxer instanceof Remuxer)) {\n                  this.remuxer = new Remuxer(observer, config, typeSupported, vendor);\n                }\n\n                if (!demuxer || !(demuxer instanceof Demuxer)) {\n                  this.demuxer = new Demuxer(observer, config, typeSupported);\n                  this.probe = Demuxer.probe;\n                } // Ensure that muxers are always initialized with an initSegment\n\n                this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);\n                this.resetInitialTimestamp(defaultInitPts);\n              };\n\n              _proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {\n                // in case of continuity change, or track switch\n                // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n                return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;\n              };\n\n              _proto.getDecrypter = function getDecrypter() {\n                var decrypter = this.decrypter;\n\n                if (!decrypter) {\n                  decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__[\"default\"](this.observer, this.config);\n                }\n\n                return decrypter;\n              };\n\n              return Transmuxer;\n            })();\n\n            function getEncryptionType(data, decryptData) {\n              var encryptionType = null;\n\n              if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {\n                encryptionType = decryptData;\n              }\n\n              return encryptionType;\n            }\n\n            var emptyResult = function emptyResult(chunkMeta) {\n              return {\n                remuxResult: {},\n                chunkMeta: chunkMeta,\n              };\n            };\n\n            function isPromise(p) {\n              return \"then\" in p && p.then instanceof Function;\n            }\n            var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {\n              this.audioCodec = void 0;\n              this.videoCodec = void 0;\n              this.initSegmentData = void 0;\n              this.duration = void 0;\n              this.defaultInitPts = void 0;\n              this.audioCodec = audioCodec;\n              this.videoCodec = videoCodec;\n              this.initSegmentData = initSegmentData;\n              this.duration = duration;\n              this.defaultInitPts = defaultInitPts;\n            };\n            var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) {\n              this.discontinuity = void 0;\n              this.contiguous = void 0;\n              this.accurateTimeOffset = void 0;\n              this.trackSwitch = void 0;\n              this.timeOffset = void 0;\n              this.discontinuity = discontinuity;\n              this.contiguous = contiguous;\n              this.accurateTimeOffset = accurateTimeOffset;\n              this.trackSwitch = trackSwitch;\n              this.timeOffset = timeOffset;\n            };\n\n            /***/\n          },\n\n        /***/ \"./src/demux/tsdemuxer.ts\":\n          /*!********************************!*\\\n  !*** ./src/demux/tsdemuxer.ts ***!\n  \\********************************/\n          /*! exports provided: discardEPB, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"discardEPB\", function () {\n              return discardEPB;\n            });\n            /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ \"./src/demux/adts.ts\");\n            /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ \"./src/demux/mpegaudio.ts\");\n            /* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ \"./src/demux/exp-golomb.ts\");\n            /* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ \"./src/demux/id3.ts\");\n            /* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ \"./src/demux/sample-aes.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /**\n             * highly optimized TS demuxer:\n             * parse PAT, PMT\n             * extract PES packet from audio and video PIDs\n             * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n             * trigger the remuxer upon parsing completion\n             * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n             * it also controls the remuxing process :\n             * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n             */\n\n            // We are using fixed track IDs for driving the MP4 remuxer\n            // instead of following the TS PIDs.\n            // There is no reason not to do this and some browsers/SourceBuffer-demuxers\n            // may not like if there are TrackID \"switches\"\n            // See https://github.com/video-dev/CiderHls.js/issues/1331\n            // Here we are mapping our internal track types to constant MP4 track IDs\n            // With MSE currently one can only have one track of each, and we are muxing\n            // whatever video/audio rendition in them.\n            var RemuxerTrackIdConfig = {\n              video: 1,\n              audio: 2,\n              id3: 3,\n              text: 4,\n            };\n\n            var TSDemuxer = /*#__PURE__*/ (function () {\n              function TSDemuxer(observer, config, typeSupported) {\n                this.observer = void 0;\n                this.config = void 0;\n                this.typeSupported = void 0;\n                this.sampleAes = null;\n                this.pmtParsed = false;\n                this.audioCodec = void 0;\n                this.videoCodec = void 0;\n                this._duration = 0;\n                this.aacLastPTS = null;\n                this._initPTS = null;\n                this._initDTS = null;\n                this._pmtId = -1;\n                this._avcTrack = void 0;\n                this._audioTrack = void 0;\n                this._id3Track = void 0;\n                this._txtTrack = void 0;\n                this.aacOverFlow = null;\n                this.avcSample = null;\n                this.remainderData = null;\n                this.observer = observer;\n                this.config = config;\n                this.typeSupported = typeSupported;\n              }\n\n              TSDemuxer.probe = function probe(data) {\n                var syncOffset = TSDemuxer.syncOffset(data);\n\n                if (syncOffset < 0) {\n                  return false;\n                } else {\n                  if (syncOffset) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(\"MPEG2-TS detected but first sync word found @ offset \" + syncOffset + \", junk ahead ?\");\n                  }\n\n                  return true;\n                }\n              };\n\n              TSDemuxer.syncOffset = function syncOffset(data) {\n                // scan 1000 first bytes\n                var scanwindow = Math.min(1000, data.length - 3 * 188);\n                var i = 0;\n\n                while (i < scanwindow) {\n                  // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n                  if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {\n                    return i;\n                  } else {\n                    i++;\n                  }\n                }\n\n                return -1;\n              };\n              /**\n               * Creates a track model internal to demuxer used to drive remuxing input\n               *\n               * @param type 'audio' | 'video' | 'id3' | 'text'\n               * @param duration\n               * @return TSDemuxer's internal track model\n               */\n\n              TSDemuxer.createTrack = function createTrack(type, duration) {\n                return {\n                  container: type === \"video\" || type === \"audio\" ? \"video/mp2t\" : undefined,\n                  type: type,\n                  id: RemuxerTrackIdConfig[type],\n                  pid: -1,\n                  inputTimeScale: 90000,\n                  sequenceNumber: 0,\n                  samples: [],\n                  dropped: 0,\n                  duration: type === \"audio\" ? duration : undefined,\n                };\n              };\n              /**\n               * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n               * Resets all internal track instances of the demuxer.\n               */\n\n              var _proto = TSDemuxer.prototype;\n\n              _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {\n                this.pmtParsed = false;\n                this._pmtId = -1;\n                this._avcTrack = TSDemuxer.createTrack(\"video\", duration);\n                this._audioTrack = TSDemuxer.createTrack(\"audio\", duration);\n                this._id3Track = TSDemuxer.createTrack(\"id3\", duration);\n                this._txtTrack = TSDemuxer.createTrack(\"text\", duration);\n                this._audioTrack.isAAC = true; // flush any partial content\n\n                this.aacOverFlow = null;\n                this.aacLastPTS = null;\n                this.avcSample = null;\n                this.audioCodec = audioCodec;\n                this.videoCodec = videoCodec;\n                this._duration = duration;\n              };\n\n              _proto.resetTimeStamp = function resetTimeStamp() {};\n\n              _proto.resetContiguity = function resetContiguity() {\n                var _audioTrack = this._audioTrack,\n                  _avcTrack = this._avcTrack,\n                  _id3Track = this._id3Track;\n\n                if (_audioTrack) {\n                  _audioTrack.pesData = null;\n                }\n\n                if (_avcTrack) {\n                  _avcTrack.pesData = null;\n                }\n\n                if (_id3Track) {\n                  _id3Track.pesData = null;\n                }\n\n                this.aacOverFlow = null;\n                this.aacLastPTS = null;\n              };\n\n              _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {\n                if (isSampleAes === void 0) {\n                  isSampleAes = false;\n                }\n\n                if (flush === void 0) {\n                  flush = false;\n                }\n\n                if (!isSampleAes) {\n                  this.sampleAes = null;\n                }\n\n                var pes;\n                var avcTrack = this._avcTrack;\n                var audioTrack = this._audioTrack;\n                var id3Track = this._id3Track;\n                var avcId = avcTrack.pid;\n                var avcData = avcTrack.pesData;\n                var audioId = audioTrack.pid;\n                var id3Id = id3Track.pid;\n                var audioData = audioTrack.pesData;\n                var id3Data = id3Track.pesData;\n                var unknownPIDs = false;\n                var pmtParsed = this.pmtParsed;\n                var pmtId = this._pmtId;\n                var len = data.length;\n\n                if (this.remainderData) {\n                  data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__[\"appendUint8Array\"])(this.remainderData, data);\n                  len = data.length;\n                  this.remainderData = null;\n                }\n\n                if (len < 188 && !flush) {\n                  this.remainderData = data;\n                  return {\n                    audioTrack: audioTrack,\n                    avcTrack: avcTrack,\n                    id3Track: id3Track,\n                    textTrack: this._txtTrack,\n                  };\n                }\n\n                var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));\n                len -= (len + syncOffset) % 188;\n\n                if (len < data.byteLength && !flush) {\n                  this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);\n                } // loop through TS packets\n\n                for (var start = syncOffset; start < len; start += 188) {\n                  if (data[start] === 0x47) {\n                    var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]\n\n                    var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n                    var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n\n                    var offset = void 0;\n\n                    if (atf > 1) {\n                      offset = start + 5 + data[start + 4]; // continue if there is only adaptation field\n\n                      if (offset === start + 188) {\n                        continue;\n                      }\n                    } else {\n                      offset = start + 4;\n                    }\n\n                    switch (pid) {\n                      case avcId:\n                        if (stt) {\n                          if (avcData && (pes = parsePES(avcData))) {\n                            this.parseAVCPES(pes, false);\n                          }\n\n                          avcData = {\n                            data: [],\n                            size: 0,\n                          };\n                        }\n\n                        if (avcData) {\n                          avcData.data.push(data.subarray(offset, start + 188));\n                          avcData.size += start + 188 - offset;\n                        }\n\n                        break;\n\n                      case audioId:\n                        if (stt) {\n                          if (audioData && (pes = parsePES(audioData))) {\n                            if (audioTrack.isAAC) {\n                              this.parseAACPES(pes);\n                            } else {\n                              this.parseMPEGPES(pes);\n                            }\n                          }\n\n                          audioData = {\n                            data: [],\n                            size: 0,\n                          };\n                        }\n\n                        if (audioData) {\n                          audioData.data.push(data.subarray(offset, start + 188));\n                          audioData.size += start + 188 - offset;\n                        }\n\n                        break;\n\n                      case id3Id:\n                        if (stt) {\n                          if (id3Data && (pes = parsePES(id3Data))) {\n                            this.parseID3PES(pes);\n                          }\n\n                          id3Data = {\n                            data: [],\n                            size: 0,\n                          };\n                        }\n\n                        if (id3Data) {\n                          id3Data.data.push(data.subarray(offset, start + 188));\n                          id3Data.size += start + 188 - offset;\n                        }\n\n                        break;\n\n                      case 0:\n                        if (stt) {\n                          offset += data[offset] + 1;\n                        }\n\n                        pmtId = this._pmtId = parsePAT(data, offset);\n                        break;\n\n                      case pmtId: {\n                        if (stt) {\n                          offset += data[offset] + 1;\n                        }\n\n                        var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT\n                        // this is to avoid resetting the PID to -1 in case\n                        // track PID transiently disappears from the stream\n                        // this could happen in case of transient missing audio samples for example\n                        // NOTE this is only the PID of the track as found in TS,\n                        // but we are not using this for MP4 track IDs.\n\n                        avcId = parsedPIDs.avc;\n\n                        if (avcId > 0) {\n                          avcTrack.pid = avcId;\n                        }\n\n                        audioId = parsedPIDs.audio;\n\n                        if (audioId > 0) {\n                          audioTrack.pid = audioId;\n                          audioTrack.isAAC = parsedPIDs.isAAC;\n                        }\n\n                        id3Id = parsedPIDs.id3;\n\n                        if (id3Id > 0) {\n                          id3Track.pid = id3Id;\n                        }\n\n                        if (unknownPIDs && !pmtParsed) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].log(\"reparse from beginning\");\n                          unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0\n\n                          start = syncOffset - 188;\n                        }\n\n                        pmtParsed = this.pmtParsed = true;\n                        break;\n                      }\n\n                      case 17:\n                      case 0x1fff:\n                        break;\n\n                      default:\n                        unknownPIDs = true;\n                        break;\n                    }\n                  } else {\n                    this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].ERROR, {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_8__[\"ErrorTypes\"].MEDIA_ERROR,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_8__[\"ErrorDetails\"].FRAG_PARSING_ERROR,\n                      fatal: false,\n                      reason: \"TS packet did not start with 0x47\",\n                    });\n                  }\n                }\n\n                avcTrack.pesData = avcData;\n                audioTrack.pesData = audioData;\n                id3Track.pesData = id3Data;\n                var demuxResult = {\n                  audioTrack: audioTrack,\n                  avcTrack: avcTrack,\n                  id3Track: id3Track,\n                  textTrack: this._txtTrack,\n                };\n\n                if (flush) {\n                  this.extractRemainingSamples(demuxResult);\n                }\n\n                return demuxResult;\n              };\n\n              _proto.flush = function flush() {\n                var remainderData = this.remainderData;\n                this.remainderData = null;\n                var result;\n\n                if (remainderData) {\n                  result = this.demux(remainderData, -1, false, true);\n                } else {\n                  result = {\n                    audioTrack: this._audioTrack,\n                    avcTrack: this._avcTrack,\n                    textTrack: this._txtTrack,\n                    id3Track: this._id3Track,\n                  };\n                }\n\n                this.extractRemainingSamples(result);\n\n                if (this.sampleAes) {\n                  return this.decrypt(result, this.sampleAes);\n                }\n\n                return result;\n              };\n\n              _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {\n                var audioTrack = demuxResult.audioTrack,\n                  avcTrack = demuxResult.avcTrack,\n                  id3Track = demuxResult.id3Track;\n                var avcData = avcTrack.pesData;\n                var audioData = audioTrack.pesData;\n                var id3Data = id3Track.pesData; // try to parse last PES packets\n\n                var pes;\n\n                if (avcData && (pes = parsePES(avcData))) {\n                  this.parseAVCPES(pes, true);\n                  avcTrack.pesData = null;\n                } else {\n                  // either avcData null or PES truncated, keep it for next frag parsing\n                  avcTrack.pesData = avcData;\n                }\n\n                if (audioData && (pes = parsePES(audioData))) {\n                  if (audioTrack.isAAC) {\n                    this.parseAACPES(pes);\n                  } else {\n                    this.parseMPEGPES(pes);\n                  }\n\n                  audioTrack.pesData = null;\n                } else {\n                  if (audioData !== null && audioData !== void 0 && audioData.size) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].log(\"last AAC PES packet truncated,might overlap between fragments\");\n                  } // either audioData null or PES truncated, keep it for next frag parsing\n\n                  audioTrack.pesData = audioData;\n                }\n\n                if (id3Data && (pes = parsePES(id3Data))) {\n                  this.parseID3PES(pes);\n                  id3Track.pesData = null;\n                } else {\n                  // either id3Data null or PES truncated, keep it for next frag parsing\n                  id3Track.pesData = id3Data;\n                }\n              };\n\n              _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {\n                var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);\n                var sampleAes = (this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__[\"default\"](this.observer, this.config, keyData));\n                return this.decrypt(demuxResult, sampleAes);\n              };\n\n              _proto.decrypt = function decrypt(demuxResult, sampleAes) {\n                return new Promise(function (resolve) {\n                  var audioTrack = demuxResult.audioTrack,\n                    avcTrack = demuxResult.avcTrack;\n\n                  if (audioTrack.samples && audioTrack.isAAC) {\n                    sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {\n                      if (avcTrack.samples) {\n                        sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {\n                          resolve(demuxResult);\n                        });\n                      } else {\n                        resolve(demuxResult);\n                      }\n                    });\n                  } else if (avcTrack.samples) {\n                    sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {\n                      resolve(demuxResult);\n                    });\n                  }\n                });\n              };\n\n              _proto.destroy = function destroy() {\n                this._initPTS = this._initDTS = null;\n                this._duration = 0;\n              };\n\n              _proto.parseAVCPES = function parseAVCPES(pes, last) {\n                var _this = this;\n\n                var track = this._avcTrack;\n                var units = this.parseAVCNALu(pes.data);\n                var debug = false;\n                var avcSample = this.avcSample;\n                var push;\n                var spsfound = false; // free pes.data to save up some memory\n\n                pes.data = null; // if new NAL units found and last sample still there, let's push ...\n                // this helps parsing streams with missing AUD (only do this if AUD never found)\n\n                if (avcSample && units.length && !track.audFound) {\n                  pushAccessUnit(avcSample, track);\n                  avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, \"\");\n                }\n\n                units.forEach(function (unit) {\n                  switch (unit.type) {\n                    // NDR\n                    case 1: {\n                      push = true;\n\n                      if (!avcSample) {\n                        avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, \"\");\n                      }\n\n                      if (debug) {\n                        avcSample.debug += \"NDR \";\n                      }\n\n                      avcSample.frame = true;\n                      var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n\n                      if (spsfound && data.length > 4) {\n                        // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n                        var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__[\"default\"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n                        // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n                        // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n                        // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n                        // if (sliceType === 2 || sliceType === 7) {\n\n                        if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n                          avcSample.key = true;\n                        }\n                      }\n\n                      break; // IDR\n                    }\n\n                    case 5:\n                      push = true; // handle PES not starting with AUD\n\n                      if (!avcSample) {\n                        avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, \"\");\n                      }\n\n                      if (debug) {\n                        avcSample.debug += \"IDR \";\n                      }\n\n                      avcSample.key = true;\n                      avcSample.frame = true;\n                      break;\n                    // SEI\n\n                    case 6: {\n                      push = true;\n\n                      if (debug && avcSample) {\n                        avcSample.debug += \"SEI \";\n                      }\n\n                      var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__[\"default\"](discardEPB(unit.data)); // skip frameType\n\n                      expGolombDecoder.readUByte();\n                      var payloadType = 0;\n                      var payloadSize = 0;\n                      var endOfCaptions = false;\n                      var b = 0;\n\n                      while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n                        payloadType = 0;\n\n                        do {\n                          b = expGolombDecoder.readUByte();\n                          payloadType += b;\n                        } while (b === 0xff); // Parse payload size.\n\n                        payloadSize = 0;\n\n                        do {\n                          b = expGolombDecoder.readUByte();\n                          payloadSize += b;\n                        } while (b === 0xff); // TODO: there can be more than one payload in an SEI packet...\n                        // TODO: need to read type and size in a while loop to get them all\n\n                        if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n                          endOfCaptions = true;\n                          var countryCode = expGolombDecoder.readUByte();\n\n                          if (countryCode === 181) {\n                            var providerCode = expGolombDecoder.readUShort();\n\n                            if (providerCode === 49) {\n                              var userStructure = expGolombDecoder.readUInt();\n\n                              if (userStructure === 0x47413934) {\n                                var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet\n\n                                if (userDataType === 3) {\n                                  var firstByte = expGolombDecoder.readUByte();\n                                  var secondByte = expGolombDecoder.readUByte();\n                                  var totalCCs = 31 & firstByte;\n                                  var byteArray = [firstByte, secondByte];\n\n                                  for (var i = 0; i < totalCCs; i++) {\n                                    // 3 bytes per CC\n                                    byteArray.push(expGolombDecoder.readUByte());\n                                    byteArray.push(expGolombDecoder.readUByte());\n                                    byteArray.push(expGolombDecoder.readUByte());\n                                  }\n\n                                  insertSampleInOrder(_this._txtTrack.samples, {\n                                    type: 3,\n                                    pts: pes.pts,\n                                    bytes: byteArray,\n                                  });\n                                }\n                              }\n                            }\n                          }\n                        } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {\n                          endOfCaptions = true;\n\n                          if (payloadSize > 16) {\n                            var uuidStrArray = [];\n\n                            for (var _i = 0; _i < 16; _i++) {\n                              uuidStrArray.push(expGolombDecoder.readUByte().toString(16));\n\n                              if (_i === 3 || _i === 5 || _i === 7 || _i === 9) {\n                                uuidStrArray.push(\"-\");\n                              }\n                            }\n\n                            var length = payloadSize - 16;\n                            var userDataPayloadBytes = new Uint8Array(length);\n\n                            for (var _i2 = 0; _i2 < length; _i2++) {\n                              userDataPayloadBytes[_i2] = expGolombDecoder.readUByte();\n                            }\n\n                            insertSampleInOrder(_this._txtTrack.samples, {\n                              pts: pes.pts,\n                              payloadType: payloadType,\n                              uuid: uuidStrArray.join(\"\"),\n                              userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__[\"utf8ArrayToStr\"])(userDataPayloadBytes),\n                              userDataBytes: userDataPayloadBytes,\n                            });\n                          }\n                        } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n                          for (var _i3 = 0; _i3 < payloadSize; _i3++) {\n                            expGolombDecoder.readUByte();\n                          }\n                        }\n                      }\n\n                      break; // SPS\n                    }\n\n                    case 7:\n                      push = true;\n                      spsfound = true;\n\n                      if (debug && avcSample) {\n                        avcSample.debug += \"SPS \";\n                      }\n\n                      if (!track.sps) {\n                        var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__[\"default\"](unit.data);\n\n                        var config = _expGolombDecoder.readSPS();\n\n                        track.width = config.width;\n                        track.height = config.height;\n                        track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.\n\n                        track.sps = [unit.data];\n                        track.duration = _this._duration;\n                        var codecarray = unit.data.subarray(1, 4);\n                        var codecstring = \"avc1.\";\n\n                        for (var _i4 = 0; _i4 < 3; _i4++) {\n                          var h = codecarray[_i4].toString(16);\n\n                          if (h.length < 2) {\n                            h = \"0\" + h;\n                          }\n\n                          codecstring += h;\n                        }\n\n                        track.codec = codecstring;\n                      }\n\n                      break;\n                    // PPS\n\n                    case 8:\n                      push = true;\n\n                      if (debug && avcSample) {\n                        avcSample.debug += \"PPS \";\n                      }\n\n                      if (!track.pps) {\n                        // TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.\n                        track.pps = [unit.data];\n                      }\n\n                      break;\n                    // AUD\n\n                    case 9:\n                      push = false;\n                      track.audFound = true;\n\n                      if (avcSample) {\n                        pushAccessUnit(avcSample, track);\n                      }\n\n                      avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? \"AUD \" : \"\");\n                      break;\n                    // Filler Data\n\n                    case 12:\n                      push = false;\n                      break;\n\n                    default:\n                      push = false;\n\n                      if (avcSample) {\n                        avcSample.debug += \"unknown NAL \" + unit.type + \" \";\n                      }\n\n                      break;\n                  }\n\n                  if (avcSample && push) {\n                    var _units = avcSample.units;\n\n                    _units.push(unit);\n                  }\n                }); // if last PES packet, push samples\n\n                if (last && avcSample) {\n                  pushAccessUnit(avcSample, track);\n                  this.avcSample = null;\n                }\n              };\n\n              _proto.getLastNalUnit = function getLastNalUnit() {\n                var _avcSample;\n\n                var avcSample = this.avcSample;\n                var lastUnit; // try to fallback to previous sample if current one is empty\n\n                if (!avcSample || avcSample.units.length === 0) {\n                  var samples = this._avcTrack.samples;\n                  avcSample = samples[samples.length - 1];\n                }\n\n                if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {\n                  var units = avcSample.units;\n                  lastUnit = units[units.length - 1];\n                }\n\n                return lastUnit;\n              };\n\n              _proto.parseAVCNALu = function parseAVCNALu(array) {\n                var len = array.byteLength;\n                var track = this._avcTrack;\n                var state = track.naluState || 0;\n                var lastState = state;\n                var units = [];\n                var i = 0;\n                var value;\n                var overflow;\n                var unitType;\n                var lastUnitStart = -1;\n                var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array));\n\n                if (state === -1) {\n                  // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n                  lastUnitStart = 0; // NALu type is value read from offset 0\n\n                  lastUnitType = array[0] & 0x1f;\n                  state = 0;\n                  i = 1;\n                }\n\n                while (i < len) {\n                  value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n\n                  if (!state) {\n                    state = value ? 0 : 1;\n                    continue;\n                  }\n\n                  if (state === 1) {\n                    state = value ? 0 : 2;\n                    continue;\n                  } // here we have state either equal to 2 or 3\n\n                  if (!value) {\n                    state = 3;\n                  } else if (value === 1) {\n                    if (lastUnitStart >= 0) {\n                      var unit = {\n                        data: array.subarray(lastUnitStart, i - state - 1),\n                        type: lastUnitType,\n                      }; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n\n                      units.push(unit);\n                    } else {\n                      // lastUnitStart is undefined => this is the first start code found in this PES packet\n                      // first check if start code delimiter is overlapping between 2 PES packets,\n                      // ie it started in last packet (lastState not zero)\n                      // and ended at the beginning of this PES packet (i <= 4 - lastState)\n                      var lastUnit = this.getLastNalUnit();\n\n                      if (lastUnit) {\n                        if (lastState && i <= 4 - lastState) {\n                          // start delimiter overlapping between PES packets\n                          // strip start delimiter bytes from the end of last NAL unit\n                          // check if lastUnit had a state different from zero\n                          if (lastUnit.state) {\n                            // strip last bytes\n                            lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);\n                          }\n                        } // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n\n                        overflow = i - state - 1;\n\n                        if (overflow > 0) {\n                          // logger.log('first NALU found with overflow:' + overflow);\n                          var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n                          tmp.set(lastUnit.data, 0);\n                          tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n                          lastUnit.data = tmp;\n                          lastUnit.state = 0;\n                        }\n                      }\n                    } // check if we can read unit type\n\n                    if (i < len) {\n                      unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n\n                      lastUnitStart = i;\n                      lastUnitType = unitType;\n                      state = 0;\n                    } else {\n                      // not enough byte to read unit type. let's read it on next PES parsing\n                      state = -1;\n                    }\n                  } else {\n                    state = 0;\n                  }\n                }\n\n                if (lastUnitStart >= 0 && state >= 0) {\n                  var _unit = {\n                    data: array.subarray(lastUnitStart, len),\n                    type: lastUnitType,\n                    state: state,\n                  };\n                  units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n                } // no NALu found\n\n                if (units.length === 0) {\n                  // append pes.data to previous NAL unit\n                  var _lastUnit = this.getLastNalUnit();\n\n                  if (_lastUnit) {\n                    var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);\n\n                    _tmp.set(_lastUnit.data, 0);\n\n                    _tmp.set(array, _lastUnit.data.byteLength);\n\n                    _lastUnit.data = _tmp;\n                  }\n                }\n\n                track.naluState = state;\n                return units;\n              };\n\n              _proto.parseAACPES = function parseAACPES(pes) {\n                var startOffset = 0;\n                var track = this._audioTrack;\n                var aacOverFlow = this.aacOverFlow;\n                var data = pes.data;\n\n                if (aacOverFlow) {\n                  this.aacOverFlow = null;\n                  var sampleLength = aacOverFlow.sample.unit.byteLength;\n                  var frameMissingBytes = Math.min(aacOverFlow.missing, sampleLength);\n                  var frameOverflowBytes = sampleLength - frameMissingBytes;\n                  aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);\n                  track.samples.push(aacOverFlow.sample); // logger.log(`AAC: append overflowing ${frameOverflowBytes} bytes to beginning of new PES`);\n\n                  startOffset = aacOverFlow.missing;\n                } // look for ADTS header (0xFFFx)\n\n                var offset;\n                var len;\n\n                for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n                  if (_adts__WEBPACK_IMPORTED_MODULE_0__[\"isHeader\"](data, offset)) {\n                    break;\n                  }\n                } // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n\n                if (offset !== startOffset) {\n                  var reason;\n                  var fatal;\n\n                  if (offset < len - 1) {\n                    reason = \"AAC PES did not start with ADTS header,offset:\" + offset;\n                    fatal = false;\n                  } else {\n                    reason = \"no ADTS header found in AAC PES\";\n                    fatal = true;\n                  }\n\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(\"parsing error:\" + reason);\n                  this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_8__[\"ErrorTypes\"].MEDIA_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_8__[\"ErrorDetails\"].FRAG_PARSING_ERROR,\n                    fatal: fatal,\n                    reason: reason,\n                  });\n\n                  if (fatal) {\n                    return;\n                  }\n                }\n\n                _adts__WEBPACK_IMPORTED_MODULE_0__[\"initTrackConfig\"](track, this.observer, data, offset, this.audioCodec);\n                var pts;\n\n                if (pes.pts !== undefined) {\n                  pts = pes.pts;\n                } else if (aacOverFlow) {\n                  // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n                  // first sample PTS should be equal to last sample PTS + frameDuration\n                  var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__[\"getFrameDuration\"](track.samplerate);\n                  pts = aacOverFlow.sample.pts + frameDuration;\n                } else {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(\"[tsdemuxer]: AAC PES unknown PTS\");\n                  return;\n                } // scan for aac samples\n\n                var frameIndex = 0;\n\n                while (offset < len) {\n                  if (_adts__WEBPACK_IMPORTED_MODULE_0__[\"isHeader\"](data, offset)) {\n                    if (offset + 5 < len) {\n                      var frame = _adts__WEBPACK_IMPORTED_MODULE_0__[\"appendFrame\"](track, data, offset, pts, frameIndex);\n\n                      if (frame) {\n                        if (frame.missing) {\n                          this.aacOverFlow = frame;\n                        } else {\n                          offset += frame.length;\n                          frameIndex++;\n                          continue;\n                        }\n                      }\n                    } // We are at an ADTS header, but do not have enough data for a frame\n                    // Remaining data will be added to aacOverFlow\n\n                    break;\n                  } else {\n                    // nothing found, keep looking\n                    offset++;\n                  }\n                }\n              };\n\n              _proto.parseMPEGPES = function parseMPEGPES(pes) {\n                var data = pes.data;\n                var length = data.length;\n                var frameIndex = 0;\n                var offset = 0;\n                var pts = pes.pts;\n\n                if (pts === undefined) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(\"[tsdemuxer]: MPEG PES unknown PTS\");\n                  return;\n                }\n\n                while (offset < length) {\n                  if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__[\"isHeader\"](data, offset)) {\n                    var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__[\"appendFrame\"](this._audioTrack, data, offset, pts, frameIndex);\n\n                    if (frame) {\n                      offset += frame.length;\n                      frameIndex++;\n                    } else {\n                      // logger.log('Unable to parse Mpeg audio frame');\n                      break;\n                    }\n                  } else {\n                    // nothing found, keep looking\n                    offset++;\n                  }\n                }\n              };\n\n              _proto.parseID3PES = function parseID3PES(pes) {\n                if (pes.pts === undefined) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(\"[tsdemuxer]: ID3 PES unknown PTS\");\n                  return;\n                }\n\n                this._id3Track.samples.push(pes);\n              };\n\n              return TSDemuxer;\n            })();\n\n            TSDemuxer.minProbeByteLength = 188;\n\n            function createAVCSample(key, pts, dts, debug) {\n              return {\n                key: key,\n                frame: false,\n                pts: pts,\n                dts: dts,\n                units: [],\n                debug: debug,\n                length: 0,\n              };\n            }\n\n            function parsePAT(data, offset) {\n              // skip the PSI header and parse the first PMT entry\n              return ((data[offset + 10] & 0x1f) << 8) | data[offset + 11]; // logger.log('PMT PID:'  + this._pmtId);\n            }\n\n            function parsePMT(data, offset, mpegSupported, isSampleAes) {\n              var result = {\n                audio: -1,\n                avc: -1,\n                id3: -1,\n                isAAC: true,\n              };\n              var sectionLength = ((data[offset + 1] & 0x0f) << 8) | data[offset + 2];\n              var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how\n              // long the program info descriptors are\n\n              var programInfoLength = ((data[offset + 10] & 0x0f) << 8) | data[offset + 11]; // advance the offset to the first entry in the mapping table\n\n              offset += 12 + programInfoLength;\n\n              while (offset < tableEnd) {\n                var pid = ((data[offset + 1] & 0x1f) << 8) | data[offset + 2];\n\n                switch (data[offset]) {\n                  case 0xcf:\n                    // SAMPLE-AES AAC\n                    if (!isSampleAes) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].log(\"ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream\");\n                      break;\n                    }\n\n                  /* falls through */\n\n                  case 0x0f:\n                    // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n                    // logger.log('AAC PID:'  + pid);\n                    if (result.audio === -1) {\n                      result.audio = pid;\n                    }\n\n                    break;\n                  // Packetized metadata (ID3)\n\n                  case 0x15:\n                    // logger.log('ID3 PID:'  + pid);\n                    if (result.id3 === -1) {\n                      result.id3 = pid;\n                    }\n\n                    break;\n\n                  case 0xdb:\n                    // SAMPLE-AES AVC\n                    if (!isSampleAes) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].log(\"H.264 with AES-128-CBC slice encryption found in unencrypted stream\");\n                      break;\n                    }\n\n                  /* falls through */\n\n                  case 0x1b:\n                    // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n                    // logger.log('AVC PID:'  + pid);\n                    if (result.avc === -1) {\n                      result.avc = pid;\n                    }\n\n                    break;\n                  // ISO/IEC 11172-3 (MPEG-1 audio)\n                  // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n\n                  case 0x03:\n                  case 0x04:\n                    // logger.log('MPEG PID:'  + pid);\n                    if (!mpegSupported) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].log(\"MPEG audio found, not supported in this browser\");\n                    } else if (result.audio === -1) {\n                      result.audio = pid;\n                      result.isAAC = false;\n                    }\n\n                    break;\n\n                  case 0x24:\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(\"Unsupported HEVC stream type found\");\n                    break;\n\n                  default:\n                    // logger.log('unknown stream type:' + data[offset]);\n                    break;\n                } // move to the next table entry\n                // skip past the elementary stream descriptors, if present\n\n                offset += (((data[offset + 3] & 0x0f) << 8) | data[offset + 4]) + 5;\n              }\n\n              return result;\n            }\n\n            function parsePES(stream) {\n              var i = 0;\n              var frag;\n              var pesLen;\n              var pesHdrLen;\n              var pesPts;\n              var pesDts;\n              var data = stream.data; // safety check\n\n              if (!stream || stream.size === 0) {\n                return null;\n              } // we might need up to 19 bytes to read PES header\n              // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n              // usually only one merge is needed (and this is rare ...)\n\n              while (data[0].length < 19 && data.length > 1) {\n                var newData = new Uint8Array(data[0].length + data[1].length);\n                newData.set(data[0]);\n                newData.set(data[1], data[0].length);\n                data[0] = newData;\n                data.splice(1, 1);\n              } // retrieve PTS/DTS from first fragment\n\n              frag = data[0];\n              var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n\n              if (pesPrefix === 1) {\n                pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n                // minus 6 : PES header size\n\n                if (pesLen && pesLen > stream.size - 6) {\n                  return null;\n                }\n\n                var pesFlags = frag[7];\n\n                if (pesFlags & 0xc0) {\n                  /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n          as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n          as Bitwise operators treat their operands as a sequence of 32 bits */\n                  pesPts =\n                    (frag[9] & 0x0e) * 536870912 + // 1 << 29\n                    (frag[10] & 0xff) * 4194304 + // 1 << 22\n                    (frag[11] & 0xfe) * 16384 + // 1 << 14\n                    (frag[12] & 0xff) * 128 + // 1 << 7\n                    (frag[13] & 0xfe) / 2;\n\n                  if (pesFlags & 0x40) {\n                    pesDts =\n                      (frag[14] & 0x0e) * 536870912 + // 1 << 29\n                      (frag[15] & 0xff) * 4194304 + // 1 << 22\n                      (frag[16] & 0xfe) * 16384 + // 1 << 14\n                      (frag[17] & 0xff) * 128 + // 1 << 7\n                      (frag[18] & 0xfe) / 2;\n\n                    if (pesPts - pesDts > 60 * 90000) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].warn(Math.round((pesPts - pesDts) / 90000) + \"s delta between PTS and DTS, align them\");\n                      pesPts = pesDts;\n                    }\n                  } else {\n                    pesDts = pesPts;\n                  }\n                }\n\n                pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n\n                var payloadStartOffset = pesHdrLen + 9;\n\n                if (stream.size <= payloadStartOffset) {\n                  return null;\n                }\n\n                stream.size -= payloadStartOffset; // reassemble PES packet\n\n                var pesData = new Uint8Array(stream.size);\n\n                for (var j = 0, dataLen = data.length; j < dataLen; j++) {\n                  frag = data[j];\n                  var len = frag.byteLength;\n\n                  if (payloadStartOffset) {\n                    if (payloadStartOffset > len) {\n                      // trim full frag if PES header bigger than frag\n                      payloadStartOffset -= len;\n                      continue;\n                    } else {\n                      // trim partial frag if PES header smaller than frag\n                      frag = frag.subarray(payloadStartOffset);\n                      len -= payloadStartOffset;\n                      payloadStartOffset = 0;\n                    }\n                  }\n\n                  pesData.set(frag, i);\n                  i += len;\n                }\n\n                if (pesLen) {\n                  // payload size : remove PES header + PES extension\n                  pesLen -= pesHdrLen + 3;\n                }\n\n                return {\n                  data: pesData,\n                  pts: pesPts,\n                  dts: pesDts,\n                  len: pesLen,\n                };\n              }\n\n              return null;\n            }\n\n            function pushAccessUnit(avcSample, avcTrack) {\n              if (avcSample.units.length && avcSample.frame) {\n                // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n                if (avcSample.pts === undefined) {\n                  var samples = avcTrack.samples;\n                  var nbSamples = samples.length;\n\n                  if (nbSamples) {\n                    var lastSample = samples[nbSamples - 1];\n                    avcSample.pts = lastSample.pts;\n                    avcSample.dts = lastSample.dts;\n                  } else {\n                    // dropping samples, no timestamp found\n                    avcTrack.dropped++;\n                    return;\n                  }\n                }\n\n                avcTrack.samples.push(avcSample);\n              }\n\n              if (avcSample.debug.length) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_7__[\"logger\"].log(avcSample.pts + \"/\" + avcSample.dts + \":\" + avcSample.debug);\n              }\n            }\n\n            function insertSampleInOrder(arr, data) {\n              var len = arr.length;\n\n              if (len > 0) {\n                if (data.pts >= arr[len - 1].pts) {\n                  arr.push(data);\n                } else {\n                  for (var pos = len - 1; pos >= 0; pos--) {\n                    if (data.pts < arr[pos].pts) {\n                      arr.splice(pos, 0, data);\n                      break;\n                    }\n                  }\n                }\n              } else {\n                arr.push(data);\n              }\n            }\n            /**\n             * remove Emulation Prevention bytes from a RBSP\n             */\n\n            function discardEPB(data) {\n              var length = data.byteLength;\n              var EPBPositions = [];\n              var i = 1; // Find all `Emulation Prevention Bytes`\n\n              while (i < length - 2) {\n                if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n                  EPBPositions.push(i + 2);\n                  i += 2;\n                } else {\n                  i++;\n                }\n              } // If no Emulation Prevention Bytes were found just return the original\n              // array\n\n              if (EPBPositions.length === 0) {\n                return data;\n              } // Create a new array to hold the NAL unit data\n\n              var newLength = length - EPBPositions.length;\n              var newData = new Uint8Array(newLength);\n              var sourceIndex = 0;\n\n              for (i = 0; i < newLength; sourceIndex++, i++) {\n                if (sourceIndex === EPBPositions[0]) {\n                  // Skip this byte\n                  sourceIndex++; // Remove this position index\n\n                  EPBPositions.shift();\n                }\n\n                newData[i] = data[sourceIndex];\n              }\n\n              return newData;\n            }\n            /* harmony default export */ __webpack_exports__[\"default\"] = TSDemuxer;\n\n            /***/\n          },\n\n        /***/ \"./src/errors.ts\":\n          /*!***********************!*\\\n  !*** ./src/errors.ts ***!\n  \\***********************/\n          /*! exports provided: ErrorTypes, ErrorDetails */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ErrorTypes\", function () {\n              return ErrorTypes;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ErrorDetails\", function () {\n              return ErrorDetails;\n            });\n            var ErrorTypes;\n            /**\n             * @enum {ErrorDetails}\n             * @typedef {string} ErrorDetail\n             */\n\n            (function (ErrorTypes) {\n              ErrorTypes[\"NETWORK_ERROR\"] = \"networkError\";\n              ErrorTypes[\"MEDIA_ERROR\"] = \"mediaError\";\n              ErrorTypes[\"KEY_SYSTEM_ERROR\"] = \"keySystemError\";\n              ErrorTypes[\"MUX_ERROR\"] = \"muxError\";\n              ErrorTypes[\"OTHER_ERROR\"] = \"otherError\";\n            })(ErrorTypes || (ErrorTypes = {}));\n\n            var ErrorDetails;\n\n            (function (ErrorDetails) {\n              ErrorDetails[\"KEY_SYSTEM_NO_KEYS\"] = \"keySystemNoKeys\";\n              ErrorDetails[\"KEY_SYSTEM_NO_ACCESS\"] = \"keySystemNoAccess\";\n              ErrorDetails[\"KEY_SYSTEM_NO_SESSION\"] = \"keySystemNoSession\";\n              ErrorDetails[\"KEY_SYSTEM_LICENSE_REQUEST_FAILED\"] = \"keySystemLicenseRequestFailed\";\n              ErrorDetails[\"KEY_SYSTEM_NO_INIT_DATA\"] = \"keySystemNoInitData\";\n              ErrorDetails[\"MANIFEST_LOAD_ERROR\"] = \"manifestLoadError\";\n              ErrorDetails[\"MANIFEST_LOAD_TIMEOUT\"] = \"manifestLoadTimeOut\";\n              ErrorDetails[\"MANIFEST_PARSING_ERROR\"] = \"manifestParsingError\";\n              ErrorDetails[\"MANIFEST_INCOMPATIBLE_CODECS_ERROR\"] = \"manifestIncompatibleCodecsError\";\n              ErrorDetails[\"LEVEL_EMPTY_ERROR\"] = \"levelEmptyError\";\n              ErrorDetails[\"LEVEL_LOAD_ERROR\"] = \"levelLoadError\";\n              ErrorDetails[\"LEVEL_LOAD_TIMEOUT\"] = \"levelLoadTimeOut\";\n              ErrorDetails[\"LEVEL_SWITCH_ERROR\"] = \"levelSwitchError\";\n              ErrorDetails[\"AUDIO_TRACK_LOAD_ERROR\"] = \"audioTrackLoadError\";\n              ErrorDetails[\"AUDIO_TRACK_LOAD_TIMEOUT\"] = \"audioTrackLoadTimeOut\";\n              ErrorDetails[\"SUBTITLE_LOAD_ERROR\"] = \"subtitleTrackLoadError\";\n              ErrorDetails[\"SUBTITLE_TRACK_LOAD_TIMEOUT\"] = \"subtitleTrackLoadTimeOut\";\n              ErrorDetails[\"FRAG_LOAD_ERROR\"] = \"fragLoadError\";\n              ErrorDetails[\"FRAG_LOAD_TIMEOUT\"] = \"fragLoadTimeOut\";\n              ErrorDetails[\"FRAG_DECRYPT_ERROR\"] = \"fragDecryptError\";\n              ErrorDetails[\"FRAG_PARSING_ERROR\"] = \"fragParsingError\";\n              ErrorDetails[\"REMUX_ALLOC_ERROR\"] = \"remuxAllocError\";\n              ErrorDetails[\"KEY_LOAD_ERROR\"] = \"keyLoadError\";\n              ErrorDetails[\"KEY_LOAD_TIMEOUT\"] = \"keyLoadTimeOut\";\n              ErrorDetails[\"BUFFER_ADD_CODEC_ERROR\"] = \"bufferAddCodecError\";\n              ErrorDetails[\"BUFFER_INCOMPATIBLE_CODECS_ERROR\"] = \"bufferIncompatibleCodecsError\";\n              ErrorDetails[\"BUFFER_APPEND_ERROR\"] = \"bufferAppendError\";\n              ErrorDetails[\"BUFFER_APPENDING_ERROR\"] = \"bufferAppendingError\";\n              ErrorDetails[\"BUFFER_STALLED_ERROR\"] = \"bufferStalledError\";\n              ErrorDetails[\"BUFFER_FULL_ERROR\"] = \"bufferFullError\";\n              ErrorDetails[\"BUFFER_SEEK_OVER_HOLE\"] = \"bufferSeekOverHole\";\n              ErrorDetails[\"BUFFER_NUDGE_ON_STALL\"] = \"bufferNudgeOnStall\";\n              ErrorDetails[\"INTERNAL_EXCEPTION\"] = \"internalException\";\n              ErrorDetails[\"INTERNAL_ABORTED\"] = \"aborted\";\n              ErrorDetails[\"UNKNOWN\"] = \"unknown\";\n            })(ErrorDetails || (ErrorDetails = {}));\n\n            /***/\n          },\n\n        /***/ \"./src/events.ts\":\n          /*!***********************!*\\\n  !*** ./src/events.ts ***!\n  \\***********************/\n          /*! exports provided: Events */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Events\", function () {\n              return Events;\n            });\n            /**\n             * @readonly\n             * @enum {string}\n             */\n            var Events;\n\n            (function (Events) {\n              Events[\"MEDIA_ATTACHING\"] = \"CiderHlsMediaAttaching\";\n              Events[\"MEDIA_ATTACHED\"] = \"CiderHlsMediaAttached\";\n              Events[\"MEDIA_DETACHING\"] = \"CiderHlsMediaDetaching\";\n              Events[\"MEDIA_DETACHED\"] = \"CiderHlsMediaDetached\";\n              Events[\"BUFFER_RESET\"] = \"CiderHlsBufferReset\";\n              Events[\"BUFFER_CODECS\"] = \"CiderHlsBufferCodecs\";\n              Events[\"BUFFER_CREATED\"] = \"CiderHlsBufferCreated\";\n              Events[\"BUFFER_APPENDING\"] = \"CiderHlsBufferAppending\";\n              Events[\"BUFFER_APPENDED\"] = \"CiderHlsBufferAppended\";\n              Events[\"BUFFER_EOS\"] = \"CiderHlsBufferEos\";\n              Events[\"BUFFER_FLUSHING\"] = \"CiderHlsBufferFlushing\";\n              Events[\"BUFFER_FLUSHED\"] = \"CiderHlsBufferFlushed\";\n              Events[\"MANIFEST_LOADING\"] = \"CiderHlsManifestLoading\";\n              Events[\"MANIFEST_LOADED\"] = \"CiderHlsManifestLoaded\";\n              Events[\"MANIFEST_PARSED\"] = \"CiderHlsManifestParsed\";\n              Events[\"LEVEL_SWITCHING\"] = \"CiderHlsLevelSwitching\";\n              Events[\"LEVEL_SWITCHED\"] = \"CiderHlsLevelSwitched\";\n              Events[\"LEVEL_LOADING\"] = \"CiderHlsLevelLoading\";\n              Events[\"LEVEL_LOADED\"] = \"CiderHlsLevelLoaded\";\n              Events[\"LEVEL_UPDATED\"] = \"CiderHlsLevelUpdated\";\n              Events[\"LEVEL_PTS_UPDATED\"] = \"CiderHlsLevelPtsUpdated\";\n              Events[\"LEVELS_UPDATED\"] = \"CiderHlsLevelsUpdated\";\n              Events[\"AUDIO_TRACKS_UPDATED\"] = \"CiderHlsAudioTracksUpdated\";\n              Events[\"AUDIO_TRACK_SWITCHING\"] = \"CiderHlsAudioTrackSwitching\";\n              Events[\"AUDIO_TRACK_SWITCHED\"] = \"CiderHlsAudioTrackSwitched\";\n              Events[\"AUDIO_TRACK_LOADING\"] = \"CiderHlsAudioTrackLoading\";\n              Events[\"AUDIO_TRACK_LOADED\"] = \"CiderHlsAudioTrackLoaded\";\n              Events[\"SUBTITLE_TRACKS_UPDATED\"] = \"CiderHlsSubtitleTracksUpdated\";\n              Events[\"SUBTITLE_TRACKS_CLEARED\"] = \"CiderHlsSubtitleTracksCleared\";\n              Events[\"SUBTITLE_TRACK_SWITCH\"] = \"CiderHlsSubtitleTrackSwitch\";\n              Events[\"SUBTITLE_TRACK_LOADING\"] = \"CiderHlsSubtitleTrackLoading\";\n              Events[\"SUBTITLE_TRACK_LOADED\"] = \"CiderHlsSubtitleTrackLoaded\";\n              Events[\"SUBTITLE_FRAG_PROCESSED\"] = \"CiderHlsSubtitleFragProcessed\";\n              Events[\"CUES_PARSED\"] = \"CiderHlsCuesParsed\";\n              Events[\"NON_NATIVE_TEXT_TRACKS_FOUND\"] = \"CiderHlsNonNativeTextTracksFound\";\n              Events[\"INIT_PTS_FOUND\"] = \"CiderHlsInitPtsFound\";\n              Events[\"FRAG_LOADING\"] = \"CiderHlsFragLoading\";\n              Events[\"FRAG_LOAD_EMERGENCY_ABORTED\"] = \"CiderHlsFragLoadEmergencyAborted\";\n              Events[\"FRAG_LOADED\"] = \"CiderHlsFragLoaded\";\n              Events[\"FRAG_DECRYPTED\"] = \"CiderHlsFragDecrypted\";\n              Events[\"FRAG_PARSING_INIT_SEGMENT\"] = \"CiderHlsFragParsingInitSegment\";\n              Events[\"FRAG_PARSING_USERDATA\"] = \"CiderHlsFragParsingUserdata\";\n              Events[\"FRAG_PARSING_METADATA\"] = \"CiderHlsFragParsingMetadata\";\n              Events[\"FRAG_PARSED\"] = \"CiderHlsFragParsed\";\n              Events[\"FRAG_BUFFERED\"] = \"CiderHlsFragBuffered\";\n              Events[\"FRAG_CHANGED\"] = \"CiderHlsFragChanged\";\n              Events[\"FPS_DROP\"] = \"CiderHlsFpsDrop\";\n              Events[\"FPS_DROP_LEVEL_CAPPING\"] = \"CiderHlsFpsDropLevelCapping\";\n              Events[\"ERROR\"] = \"CiderHlsError\";\n              Events[\"DESTROYING\"] = \"CiderHlsDestroying\";\n              Events[\"KEY_LOADING\"] = \"CiderHlsKeyLoading\";\n              Events[\"KEY_LOADED\"] = \"CiderHlsKeyLoaded\";\n              Events[\"LIVE_BACK_BUFFER_REACHED\"] = \"CiderHlsLiveBackBufferReached\";\n              Events[\"BACK_BUFFER_REACHED\"] = \"CiderHlsBackBufferReached\";\n            })(Events || (Events = {}));\n\n            /***/\n          },\n\n        /***/ \"./src/CiderHls.ts\":\n          /*!********************!*\\\n  !*** ./src/CiderHls.ts ***!\n  \\********************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return CiderHls;\n            });\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ \"./node_modules/url-toolkit/src/url-toolkit.js\");\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);\n            /* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ \"./src/loader/playlist-loader.ts\");\n            /* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ \"./src/loader/key-loader.ts\");\n            /* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ \"./src/controller/id3-track-controller.ts\");\n            /* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ \"./src/controller/latency-controller.ts\");\n            /* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ \"./src/controller/level-controller.ts\");\n            /* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ \"./src/controller/fragment-tracker.ts\");\n            /* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ \"./src/controller/stream-controller.ts\");\n            /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ \"./src/is-supported.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ \"./src/config.ts\");\n            /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\");\n            /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/ __webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__);\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ \"./src/errors.ts\");\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            /**\n             * @module CiderHls\n             * @class\n             * @constructor\n             */\n            var CiderHls = /*#__PURE__*/ (function () {\n              CiderHls.isSupported = function isSupported() {\n                return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__[\"isSupported\"])();\n              };\n\n              /**\n               * Creates an instance of an CiderHls client that can attach to exactly one `HTMLMediaElement`.\n               *\n               * @constructs CiderHls\n               * @param {CiderHlsConfig} config\n               */\n              function CiderHls(userConfig) {\n                if (userConfig === void 0) {\n                  userConfig = {};\n                }\n\n                this.config = void 0;\n                this.userConfig = void 0;\n                this.coreComponents = void 0;\n                this.networkControllers = void 0;\n                this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__[\"EventEmitter\"]();\n                this._autoLevelCapping = void 0;\n                this.abrController = void 0;\n                this.bufferController = void 0;\n                this.capLevelController = void 0;\n                this.latencyController = void 0;\n                this.levelController = void 0;\n                this.streamController = void 0;\n                this.audioTrackController = void 0;\n                this.subtitleTrackController = void 0;\n                this.emeController = void 0;\n                this.cmcdController = void 0;\n                this._media = null;\n                this.url = null;\n                var config = (this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__[\"mergeConfig\"])(CiderHls.DefaultConfig, userConfig));\n                this.userConfig = userConfig;\n                Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"enableLogs\"])(config.debug);\n                this._autoLevelCapping = -1;\n\n                if (config.progressive) {\n                  Object(_config__WEBPACK_IMPORTED_MODULE_10__[\"enableStreamingMode\"])(config);\n                } // core controllers and network loaders\n\n                var ConfigAbrController = config.abrController,\n                  ConfigBufferController = config.bufferController,\n                  ConfigCapLevelController = config.capLevelController,\n                  ConfigFpsController = config.fpsController;\n                var abrController = (this.abrController = new ConfigAbrController(this));\n                var bufferController = (this.bufferController = new ConfigBufferController(this));\n                var capLevelController = (this.capLevelController = new ConfigCapLevelController(this));\n                var fpsController = new ConfigFpsController(this);\n                var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__[\"default\"](this);\n                var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__[\"default\"](this);\n                var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__[\"default\"](this); // network controllers\n\n                var levelController = (this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__[\"default\"](this)); // FragmentTracker must be defined before StreamController because the order of event handling is important\n\n                var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__[\"FragmentTracker\"](this);\n                var streamController = (this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__[\"default\"](this, fragmentTracker)); // Cap level controller uses streamController to flush the buffer\n\n                capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped\n\n                fpsController.setStreamController(streamController);\n                var networkControllers = [levelController, streamController];\n                this.networkControllers = networkControllers;\n                var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];\n                this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);\n                this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before  because the order of event handling is important\n\n                this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);\n                this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);\n                this.createController(config.timelineController, null, coreComponents);\n                this.emeController = this.createController(config.emeController, null, coreComponents);\n                this.cmcdController = this.createController(config.cmcdController, null, coreComponents);\n                this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__[\"default\"], null, coreComponents);\n                this.coreComponents = coreComponents;\n              }\n\n              var _proto = CiderHls.prototype;\n\n              _proto.createController = function createController(ControllerClass, fragmentTracker, components) {\n                if (ControllerClass) {\n                  var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);\n\n                  if (components) {\n                    components.push(controllerInstance);\n                  }\n\n                  return controllerInstance;\n                }\n\n                return null;\n              }; // Delegate the EventEmitter through the public API of CiderHls.js\n\n              _proto.on = function on(event, listener, context) {\n                if (context === void 0) {\n                  context = this;\n                }\n\n                this._emitter.on(event, listener, context);\n              };\n\n              _proto.once = function once(event, listener, context) {\n                if (context === void 0) {\n                  context = this;\n                }\n\n                this._emitter.once(event, listener, context);\n              };\n\n              _proto.removeAllListeners = function removeAllListeners(event) {\n                this._emitter.removeAllListeners(event);\n              };\n\n              _proto.off = function off(event, listener, context, once) {\n                if (context === void 0) {\n                  context = this;\n                }\n\n                this._emitter.off(event, listener, context, once);\n              };\n\n              _proto.listeners = function listeners(event) {\n                return this._emitter.listeners(event);\n              };\n\n              _proto.emit = function emit(event, name, eventObject) {\n                return this._emitter.emit(event, name, eventObject);\n              };\n\n              _proto.trigger = function trigger(event, eventObject) {\n                if (this.config.debug) {\n                  return this.emit(event, event, eventObject);\n                } else {\n                  try {\n                    return this.emit(event, event, eventObject);\n                  } catch (e) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].error(\"An internal error happened while handling event \" + event + '. Error message: \"' + e.message + '\". Here is a stacktrace:', e);\n                    this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__[\"Events\"].ERROR, {\n                      type: _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorTypes\"].OTHER_ERROR,\n                      details: _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"].INTERNAL_EXCEPTION,\n                      fatal: false,\n                      event: event,\n                      error: e,\n                    });\n                  }\n                }\n\n                return false;\n              };\n\n              _proto.listenerCount = function listenerCount(event) {\n                return this._emitter.listenerCount(event);\n              };\n              /**\n               * Dispose of the instance\n               */\n\n              _proto.destroy = function destroy() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"destroy\");\n                this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__[\"Events\"].DESTROYING, undefined);\n                this.detachMedia();\n                this.removeAllListeners();\n                this._autoLevelCapping = -1;\n                this.url = null;\n                this.networkControllers.forEach(function (component) {\n                  return component.destroy();\n                });\n                this.networkControllers.length = 0;\n                this.coreComponents.forEach(function (component) {\n                  return component.destroy();\n                });\n                this.coreComponents.length = 0;\n              };\n              /**\n               * Attaches CiderHls.js to a media element\n               * @param {HTMLMediaElement} media\n               */\n\n              _proto.attachMedia = function attachMedia(media) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"attachMedia\");\n                this._media = media;\n                this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__[\"Events\"].MEDIA_ATTACHING, {\n                  media: media,\n                });\n              };\n              /**\n               * Detach CiderHls.js from the media\n               */\n\n              _proto.detachMedia = function detachMedia() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"detachMedia\");\n                this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__[\"Events\"].MEDIA_DETACHING, undefined);\n                this._media = null;\n              };\n              /**\n               * Set the source URL. Can be relative or absolute.\n               * @param {string} url\n               */\n\n              _proto.loadSource = function loadSource(url) {\n                this.stopLoad();\n                var media = this.media;\n                var loadedSource = this.url;\n                var loadingSource = (this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__[\"buildAbsoluteURL\"](self.location.href, url, {\n                  alwaysNormalize: true,\n                }));\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"loadSource:\" + loadingSource);\n\n                if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) {\n                  this.detachMedia();\n                  this.attachMedia(media);\n                } // when attaching to a source URL, trigger a playlist load\n\n                this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__[\"Events\"].MANIFEST_LOADING, {\n                  url: url,\n                });\n              };\n              /**\n               * Start loading data from the stream source.\n               * Depending on default config, client starts loading automatically when a source is set.\n               *\n               * @param {number} startPosition Set the start position to stream from\n               * @default -1 None (from earliest point)\n               */\n\n              _proto.startLoad = function startLoad(startPosition) {\n                if (startPosition === void 0) {\n                  startPosition = -1;\n                }\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"startLoad(\" + startPosition + \")\");\n                this.networkControllers.forEach(function (controller) {\n                  controller.startLoad(startPosition);\n                });\n              };\n              /**\n               * Stop loading of any stream data.\n               */\n\n              _proto.stopLoad = function stopLoad() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"stopLoad\");\n                this.networkControllers.forEach(function (controller) {\n                  controller.stopLoad();\n                });\n              };\n              /**\n               * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n               */\n\n              _proto.swapAudioCodec = function swapAudioCodec() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"swapAudioCodec\");\n                this.streamController.swapAudioCodec();\n              };\n              /**\n               * When the media-element fails, this allows to detach and then re-attach it\n               * as one call (convenience method).\n               *\n               * Automatic recovery of media-errors by this process is configurable.\n               */\n\n              _proto.recoverMediaError = function recoverMediaError() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"recoverMediaError\");\n                var media = this._media;\n                this.detachMedia();\n\n                if (media) {\n                  this.attachMedia(media);\n                }\n              };\n\n              _proto.removeLevel = function removeLevel(levelIndex, urlId) {\n                if (urlId === void 0) {\n                  urlId = 0;\n                }\n\n                this.levelController.removeLevel(levelIndex, urlId);\n              };\n              /**\n               * @type {Level[]}\n               */\n\n              _createClass(\n                CiderHls,\n                [\n                  {\n                    key: \"levels\",\n                    get: function get() {\n                      var levels = this.levelController.levels;\n                      return levels ? levels : [];\n                    },\n                    /**\n                     * Index of quality level currently played\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"currentLevel\",\n                    get: function get() {\n                      return this.streamController.currentLevel;\n                    },\n                    /**\n                     * Set quality level index immediately .\n                     * This will flush the current buffer to replace the quality asap.\n                     * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n                     * @type {number} -1 for automatic level selection\n                     */\n                    set: function set(newLevel) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"set currentLevel:\" + newLevel);\n                      this.loadLevel = newLevel;\n                      this.abrController.clearTimer();\n                      this.streamController.immediateLevelSwitch();\n                    },\n                    /**\n                     * Index of next quality level loaded as scheduled by stream controller.\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"nextLevel\",\n                    get: function get() {\n                      return this.streamController.nextLevel;\n                    },\n                    /**\n                     * Set quality level index for next loaded data.\n                     * This will switch the video quality asap, without interrupting playback.\n                     * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n                     * @type {number} -1 for automatic level selection\n                     */\n                    set: function set(newLevel) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"set nextLevel:\" + newLevel);\n                      this.levelController.manualLevel = newLevel;\n                      this.streamController.nextLevelSwitch();\n                    },\n                    /**\n                     * Return the quality level of the currently or last (of none is loaded currently) segment\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"loadLevel\",\n                    get: function get() {\n                      return this.levelController.level;\n                    },\n                    /**\n                     * Set quality level index for next loaded data in a conservative way.\n                     * This will switch the quality without flushing, but interrupt current loading.\n                     * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n                     * @type {number} newLevel -1 for automatic level selection\n                     */\n                    set: function set(newLevel) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"set loadLevel:\" + newLevel);\n                      this.levelController.manualLevel = newLevel;\n                    },\n                    /**\n                     * get next quality level loaded\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"nextLoadLevel\",\n                    get: function get() {\n                      return this.levelController.nextLoadLevel;\n                    },\n                    /**\n                     * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n                     * Same as `loadLevel` but will wait for next switch (until current loading is done).\n                     * @type {number} level\n                     */\n                    set: function set(level) {\n                      this.levelController.nextLoadLevel = level;\n                    },\n                    /**\n                     * Return \"first level\": like a default level, if not set,\n                     * falls back to index of first level referenced in manifest\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"firstLevel\",\n                    get: function get() {\n                      return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n                    },\n                    /**\n                     * Sets \"first-level\", see getter.\n                     * @type {number}\n                     */\n                    set: function set(newLevel) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"set firstLevel:\" + newLevel);\n                      this.levelController.firstLevel = newLevel;\n                    },\n                    /**\n                     * Return start level (level of first fragment that will be played back)\n                     * if not overrided by user, first level appearing in manifest will be used as start level\n                     * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n                     * (determined from download of first segment)\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"startLevel\",\n                    get: function get() {\n                      return this.levelController.startLevel;\n                    },\n                    /**\n                     * set  start level (level of first fragment that will be played back)\n                     * if not overrided by user, first level appearing in manifest will be used as start level\n                     * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n                     * (determined from download of first segment)\n                     * @type {number} newLevel\n                     */\n                    set: function set(newLevel) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"set startLevel:\" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n\n                      if (newLevel !== -1) {\n                        newLevel = Math.max(newLevel, this.minAutoLevel);\n                      }\n\n                      this.levelController.startLevel = newLevel;\n                    },\n                    /**\n                     * Get the current setting for capLevelToPlayerSize\n                     *\n                     * @type {boolean}\n                     */\n                  },\n                  {\n                    key: \"capLevelToPlayerSize\",\n                    get: function get() {\n                      return this.config.capLevelToPlayerSize;\n                    },\n                    /**\n                     * set  dynamically set capLevelToPlayerSize against (`CapLevelController`)\n                     *\n                     * @type {boolean}\n                     */\n                    set: function set(shouldStartCapping) {\n                      var newCapLevelToPlayerSize = !!shouldStartCapping;\n\n                      if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n                        if (newCapLevelToPlayerSize) {\n                          this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n                        } else {\n                          this.capLevelController.stopCapping();\n                          this.autoLevelCapping = -1;\n                          this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n                        }\n\n                        this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n                      }\n                    },\n                    /**\n                     * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"autoLevelCapping\",\n                    get: function get() {\n                      return this._autoLevelCapping;\n                    },\n                    /**\n                     * get bandwidth estimate\n                     * @type {number}\n                     */\n                    set:\n                      /**\n                       * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n                       * @type {number}\n                       */\n                      function set(newLevel) {\n                        if (this._autoLevelCapping !== newLevel) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_9__[\"logger\"].log(\"set autoLevelCapping:\" + newLevel);\n                          this._autoLevelCapping = newLevel;\n                        }\n                      },\n                    /**\n                     * True when automatic level selection enabled\n                     * @type {boolean}\n                     */\n                  },\n                  {\n                    key: \"bandwidthEstimate\",\n                    get: function get() {\n                      var bwEstimator = this.abrController.bwEstimator;\n\n                      if (!bwEstimator) {\n                        return NaN;\n                      }\n\n                      return bwEstimator.getEstimate();\n                    },\n                  },\n                  {\n                    key: \"autoLevelEnabled\",\n                    get: function get() {\n                      return this.levelController.manualLevel === -1;\n                    },\n                    /**\n                     * Level set manually (if any)\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"manualLevel\",\n                    get: function get() {\n                      return this.levelController.manualLevel;\n                    },\n                    /**\n                     * min level selectable in auto mode according to config.minAutoBitrate\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"minAutoLevel\",\n                    get: function get() {\n                      var levels = this.levels,\n                        minAutoBitrate = this.config.minAutoBitrate;\n                      if (!levels) return 0;\n                      var len = levels.length;\n\n                      for (var i = 0; i < len; i++) {\n                        if (levels[i].maxBitrate > minAutoBitrate) {\n                          return i;\n                        }\n                      }\n\n                      return 0;\n                    },\n                    /**\n                     * max level selectable in auto mode according to autoLevelCapping\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"maxAutoLevel\",\n                    get: function get() {\n                      var levels = this.levels,\n                        autoLevelCapping = this.autoLevelCapping;\n                      var maxAutoLevel;\n\n                      if (autoLevelCapping === -1 && levels && levels.length) {\n                        maxAutoLevel = levels.length - 1;\n                      } else {\n                        maxAutoLevel = autoLevelCapping;\n                      }\n\n                      return maxAutoLevel;\n                    },\n                    /**\n                     * next automatically selected quality level\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"nextAutoLevel\",\n                    get: function get() {\n                      // ensure next auto level is between  min and max auto level\n                      return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);\n                    },\n                    /**\n                     * this setter is used to force next auto level.\n                     * this is useful to force a switch down in auto mode:\n                     * in case of load error on level N, CiderHls.js can set nextAutoLevel to N-1 for example)\n                     * forced value is valid for one fragment. upon succesful frag loading at forced level,\n                     * this value will be resetted to -1 by ABR controller.\n                     * @type {number}\n                     */\n                    set: function set(nextLevel) {\n                      this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);\n                    },\n                    /**\n                     * @type {AudioTrack[]}\n                     */\n                  },\n                  {\n                    key: \"audioTracks\",\n                    get: function get() {\n                      var audioTrackController = this.audioTrackController;\n                      return audioTrackController ? audioTrackController.audioTracks : [];\n                    },\n                    /**\n                     * index of the selected audio track (index in audio track lists)\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"audioTrack\",\n                    get: function get() {\n                      var audioTrackController = this.audioTrackController;\n                      return audioTrackController ? audioTrackController.audioTrack : -1;\n                    },\n                    /**\n                     * selects an audio track, based on its index in audio track lists\n                     * @type {number}\n                     */\n                    set: function set(audioTrackId) {\n                      var audioTrackController = this.audioTrackController;\n\n                      if (audioTrackController) {\n                        audioTrackController.audioTrack = audioTrackId;\n                      }\n                    },\n                    /**\n                     * get alternate subtitle tracks list from playlist\n                     * @type {MediaPlaylist[]}\n                     */\n                  },\n                  {\n                    key: \"subtitleTracks\",\n                    get: function get() {\n                      var subtitleTrackController = this.subtitleTrackController;\n                      return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n                    },\n                    /**\n                     * index of the selected subtitle track (index in subtitle track lists)\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"subtitleTrack\",\n                    get: function get() {\n                      var subtitleTrackController = this.subtitleTrackController;\n                      return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n                    },\n                    set:\n                      /**\n                       * select an subtitle track, based on its index in subtitle track lists\n                       * @type {number}\n                       */\n                      function set(subtitleTrackId) {\n                        var subtitleTrackController = this.subtitleTrackController;\n\n                        if (subtitleTrackController) {\n                          subtitleTrackController.subtitleTrack = subtitleTrackId;\n                        }\n                      },\n                    /**\n                     * @type {boolean}\n                     */\n                  },\n                  {\n                    key: \"media\",\n                    get: function get() {\n                      return this._media;\n                    },\n                  },\n                  {\n                    key: \"subtitleDisplay\",\n                    get: function get() {\n                      var subtitleTrackController = this.subtitleTrackController;\n                      return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n                    },\n                    /**\n                     * Enable/disable subtitle display rendering\n                     * @type {boolean}\n                     */\n                    set: function set(value) {\n                      var subtitleTrackController = this.subtitleTrackController;\n\n                      if (subtitleTrackController) {\n                        subtitleTrackController.subtitleDisplay = value;\n                      }\n                    },\n                    /**\n                     * get mode for Low-Latency CiderHls loading\n                     * @type {boolean}\n                     */\n                  },\n                  {\n                    key: \"lowLatencyMode\",\n                    get: function get() {\n                      return this.config.lowLatencyMode;\n                    },\n                    /**\n                     * Enable/disable Low-Latency CiderHls part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.\n                     * @type {boolean}\n                     */\n                    set: function set(mode) {\n                      this.config.lowLatencyMode = mode;\n                    },\n                    /**\n                     * position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```CiderHls.config.liveSyncDuration```)\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"liveSyncPosition\",\n                    get: function get() {\n                      return this.latencyController.liveSyncPosition;\n                    },\n                    /**\n                     * estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)\n                     * returns 0 before first playlist is loaded\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"latency\",\n                    get: function get() {\n                      return this.latencyController.latency;\n                    },\n                    /**\n                     * maximum distance from the edge before the player seeks forward to ```CiderHls.liveSyncPosition```\n                     * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```\n                     * returns 0 before first playlist is loaded\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"maxLatency\",\n                    get: function get() {\n                      return this.latencyController.maxLatency;\n                    },\n                    /**\n                     * target distance from the edge as calculated by the latency controller\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"targetLatency\",\n                    get: function get() {\n                      return this.latencyController.targetLatency;\n                    },\n                    /**\n                     * the rate at which the edge of the current live playlist is advancing or 1 if there is none\n                     * @type {number}\n                     */\n                  },\n                  {\n                    key: \"drift\",\n                    get: function get() {\n                      return this.latencyController.drift;\n                    },\n                    /**\n                     * set to true when startLoad is called before MANIFEST_PARSED event\n                     * @type {boolean}\n                     */\n                  },\n                  {\n                    key: \"forceStartLoad\",\n                    get: function get() {\n                      return this.streamController.forceStartLoad;\n                    },\n                  },\n                ],\n                [\n                  {\n                    key: \"version\",\n                    get: function get() {\n                      return \"1.1.2\";\n                    },\n                  },\n                  {\n                    key: \"Events\",\n                    get: function get() {\n                      return _events__WEBPACK_IMPORTED_MODULE_12__[\"Events\"];\n                    },\n                  },\n                  {\n                    key: \"ErrorTypes\",\n                    get: function get() {\n                      return _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorTypes\"];\n                    },\n                  },\n                  {\n                    key: \"ErrorDetails\",\n                    get: function get() {\n                      return _errors__WEBPACK_IMPORTED_MODULE_13__[\"ErrorDetails\"];\n                    },\n                  },\n                  {\n                    key: \"DefaultConfig\",\n                    get: function get() {\n                      if (!CiderHls.defaultConfig) {\n                        return _config__WEBPACK_IMPORTED_MODULE_10__[\"CiderHlsDefaultConfig\"];\n                      }\n\n                      return CiderHls.defaultConfig;\n                    },\n                    /**\n                     * @type {CiderHlsConfig}\n                     */\n                    set: function set(defaultConfig) {\n                      CiderHls.defaultConfig = defaultConfig;\n                    },\n                  },\n                ]\n              );\n\n              return CiderHls;\n            })();\n\n            CiderHls.defaultConfig = void 0;\n\n            /***/\n          },\n\n        /***/ \"./src/is-supported.ts\":\n          /*!*****************************!*\\\n  !*** ./src/is-supported.ts ***!\n  \\*****************************/\n          /*! exports provided: isSupported, changeTypeSupported */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isSupported\", function () {\n              return isSupported;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"changeTypeSupported\", function () {\n              return changeTypeSupported;\n            });\n            /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ \"./src/utils/mediasource-helper.ts\");\n\n            function getSourceBuffer() {\n              return self.SourceBuffer || self.WebKitSourceBuffer;\n            }\n\n            function isSupported() {\n              var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__[\"getMediaSource\"])();\n\n              if (!mediaSource) {\n                return false;\n              }\n\n              var sourceBuffer = getSourceBuffer();\n              var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === \"function\" && mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"'); // if SourceBuffer is exposed ensure its API is valid\n              // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n\n              var sourceBufferValidAPI = !sourceBuffer || (sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === \"function\" && typeof sourceBuffer.prototype.remove === \"function\");\n              return !!isTypeSupported && !!sourceBufferValidAPI;\n            }\n            function changeTypeSupported() {\n              var _sourceBuffer$prototy;\n\n              var sourceBuffer = getSourceBuffer();\n              return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === \"function\";\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/loader/fragment-loader.ts\":\n          /*!***************************************!*\\\n  !*** ./src/loader/fragment-loader.ts ***!\n  \\***************************************/\n          /*! exports provided: default, LoadError */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return FragmentLoader;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"LoadError\", function () {\n              return LoadError;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _wrapNativeSuper(Class) {\n              var _cache = typeof Map === \"function\" ? new Map() : undefined;\n              _wrapNativeSuper = function _wrapNativeSuper(Class) {\n                if (Class === null || !_isNativeFunction(Class)) return Class;\n                if (typeof Class !== \"function\") {\n                  throw new TypeError(\"Super expression must either be null or a function\");\n                }\n                if (typeof _cache !== \"undefined\") {\n                  if (_cache.has(Class)) return _cache.get(Class);\n                  _cache.set(Class, Wrapper);\n                }\n                function Wrapper() {\n                  return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n                }\n                Wrapper.prototype = Object.create(Class.prototype, {\n                  constructor: {\n                    value: Wrapper,\n                    enumerable: false,\n                    writable: true,\n                    configurable: true,\n                  },\n                });\n                return _setPrototypeOf(Wrapper, Class);\n              };\n              return _wrapNativeSuper(Class);\n            }\n\n            function _construct(Parent, args, Class) {\n              if (_isNativeReflectConstruct()) {\n                _construct = Reflect.construct;\n              } else {\n                _construct = function _construct(Parent, args, Class) {\n                  var a = [null];\n                  a.push.apply(a, args);\n                  var Constructor = Function.bind.apply(Parent, a);\n                  var instance = new Constructor();\n                  if (Class) _setPrototypeOf(instance, Class.prototype);\n                  return instance;\n                };\n              }\n              return _construct.apply(null, arguments);\n            }\n\n            function _isNativeReflectConstruct() {\n              if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n              if (Reflect.construct.sham) return false;\n              if (typeof Proxy === \"function\") return true;\n              try {\n                Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n                return true;\n              } catch (e) {\n                return false;\n              }\n            }\n\n            function _isNativeFunction(fn) {\n              return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            function _getPrototypeOf(o) {\n              _getPrototypeOf = Object.setPrototypeOf\n                ? Object.getPrototypeOf\n                : function _getPrototypeOf(o) {\n                    return o.__proto__ || Object.getPrototypeOf(o);\n                  };\n              return _getPrototypeOf(o);\n            }\n\n            var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb\n\n            var FragmentLoader = /*#__PURE__*/ (function () {\n              function FragmentLoader(config) {\n                this.config = void 0;\n                this.loader = null;\n                this.partLoadTimeout = -1;\n                this.config = config;\n              }\n\n              var _proto = FragmentLoader.prototype;\n\n              _proto.destroy = function destroy() {\n                if (this.loader) {\n                  this.loader.destroy();\n                  this.loader = null;\n                }\n              };\n\n              _proto.abort = function abort() {\n                if (this.loader) {\n                  // Abort the loader for current fragment. Only one may load at any given time\n                  this.loader.abort();\n                }\n              };\n\n              _proto.load = function load(frag, _onProgress) {\n                var _this = this;\n\n                var url = frag.url;\n\n                if (!url) {\n                  return Promise.reject(\n                    new LoadError(\n                      {\n                        type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                        details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_LOAD_ERROR,\n                        fatal: false,\n                        frag: frag,\n                        networkDetails: null,\n                      },\n                      \"Fragment does not have a \" + (url ? \"part list\" : \"url\")\n                    )\n                  );\n                }\n\n                this.abort();\n                var config = this.config;\n                var FragmentILoader = config.fLoader;\n                var DefaultILoader = config.loader;\n                return new Promise(function (resolve, reject) {\n                  if (_this.loader) {\n                    _this.loader.destroy();\n                  }\n\n                  var loader = (_this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config));\n                  var loaderContext = createLoaderContext(frag);\n                  var loaderConfig = {\n                    timeout: config.fragLoadingTimeOut,\n                    maxRetry: 0,\n                    retryDelay: 0,\n                    maxRetryDelay: config.fragLoadingMaxRetryTimeout,\n                    highWaterMark: MIN_CHUNK_SIZE,\n                  }; // Assign frag stats to the loader's stats reference\n\n                  frag.stats = loader.stats;\n                  loader.load(loaderContext, loaderConfig, {\n                    onSuccess: function onSuccess(response, stats, context, networkDetails) {\n                      _this.resetLoader(frag, loader);\n\n                      resolve({\n                        frag: frag,\n                        part: null,\n                        payload: response.data,\n                        networkDetails: networkDetails,\n                      });\n                    },\n                    onError: function onError(response, context, networkDetails) {\n                      _this.resetLoader(frag, loader);\n\n                      reject(\n                        new LoadError({\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_LOAD_ERROR,\n                          fatal: false,\n                          frag: frag,\n                          response: response,\n                          networkDetails: networkDetails,\n                        })\n                      );\n                    },\n                    onAbort: function onAbort(stats, context, networkDetails) {\n                      _this.resetLoader(frag, loader);\n\n                      reject(\n                        new LoadError({\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].INTERNAL_ABORTED,\n                          fatal: false,\n                          frag: frag,\n                          networkDetails: networkDetails,\n                        })\n                      );\n                    },\n                    onTimeout: function onTimeout(response, context, networkDetails) {\n                      _this.resetLoader(frag, loader);\n\n                      reject(\n                        new LoadError({\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_LOAD_TIMEOUT,\n                          fatal: false,\n                          frag: frag,\n                          networkDetails: networkDetails,\n                        })\n                      );\n                    },\n                    onProgress: function onProgress(stats, context, data, networkDetails) {\n                      if (_onProgress) {\n                        _onProgress({\n                          frag: frag,\n                          part: null,\n                          payload: data,\n                          networkDetails: networkDetails,\n                        });\n                      }\n                    },\n                  });\n                });\n              };\n\n              _proto.loadPart = function loadPart(frag, part, onProgress) {\n                var _this2 = this;\n\n                this.abort();\n                var config = this.config;\n                var FragmentILoader = config.fLoader;\n                var DefaultILoader = config.loader;\n                return new Promise(function (resolve, reject) {\n                  if (_this2.loader) {\n                    _this2.loader.destroy();\n                  }\n\n                  var loader = (_this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config));\n                  var loaderContext = createLoaderContext(frag, part);\n                  var loaderConfig = {\n                    timeout: config.fragLoadingTimeOut,\n                    maxRetry: 0,\n                    retryDelay: 0,\n                    maxRetryDelay: config.fragLoadingMaxRetryTimeout,\n                    highWaterMark: MIN_CHUNK_SIZE,\n                  }; // Assign part stats to the loader's stats reference\n\n                  part.stats = loader.stats;\n                  loader.load(loaderContext, loaderConfig, {\n                    onSuccess: function onSuccess(response, stats, context, networkDetails) {\n                      _this2.resetLoader(frag, loader);\n\n                      _this2.updateStatsFromPart(frag, part);\n\n                      var partLoadedData = {\n                        frag: frag,\n                        part: part,\n                        payload: response.data,\n                        networkDetails: networkDetails,\n                      };\n                      onProgress(partLoadedData);\n                      resolve(partLoadedData);\n                    },\n                    onError: function onError(response, context, networkDetails) {\n                      _this2.resetLoader(frag, loader);\n\n                      reject(\n                        new LoadError({\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_LOAD_ERROR,\n                          fatal: false,\n                          frag: frag,\n                          part: part,\n                          response: response,\n                          networkDetails: networkDetails,\n                        })\n                      );\n                    },\n                    onAbort: function onAbort(stats, context, networkDetails) {\n                      frag.stats.aborted = part.stats.aborted;\n\n                      _this2.resetLoader(frag, loader);\n\n                      reject(\n                        new LoadError({\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].INTERNAL_ABORTED,\n                          fatal: false,\n                          frag: frag,\n                          part: part,\n                          networkDetails: networkDetails,\n                        })\n                      );\n                    },\n                    onTimeout: function onTimeout(response, context, networkDetails) {\n                      _this2.resetLoader(frag, loader);\n\n                      reject(\n                        new LoadError({\n                          type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].FRAG_LOAD_TIMEOUT,\n                          fatal: false,\n                          frag: frag,\n                          part: part,\n                          networkDetails: networkDetails,\n                        })\n                      );\n                    },\n                  });\n                });\n              };\n\n              _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {\n                var fragStats = frag.stats;\n                var partStats = part.stats;\n                var partTotal = partStats.total;\n                fragStats.loaded += partStats.loaded;\n\n                if (partTotal) {\n                  var estTotalParts = Math.round(frag.duration / part.duration);\n                  var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);\n                  var estRemainingParts = estTotalParts - estLoadedParts;\n                  var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);\n                  fragStats.total = fragStats.loaded + estRemainingBytes;\n                } else {\n                  fragStats.total = Math.max(fragStats.loaded, fragStats.total);\n                }\n\n                var fragLoading = fragStats.loading;\n                var partLoading = partStats.loading;\n\n                if (fragLoading.start) {\n                  // add to fragment loader latency\n                  fragLoading.first += partLoading.first - partLoading.start;\n                } else {\n                  fragLoading.start = partLoading.start;\n                  fragLoading.first = partLoading.first;\n                }\n\n                fragLoading.end = partLoading.end;\n              };\n\n              _proto.resetLoader = function resetLoader(frag, loader) {\n                frag.loader = null;\n\n                if (this.loader === loader) {\n                  self.clearTimeout(this.partLoadTimeout);\n                  this.loader = null;\n                }\n\n                loader.destroy();\n              };\n\n              return FragmentLoader;\n            })();\n\n            function createLoaderContext(frag, part) {\n              if (part === void 0) {\n                part = null;\n              }\n\n              var segment = part || frag;\n              var loaderContext = {\n                frag: frag,\n                part: part,\n                responseType: \"arraybuffer\",\n                url: segment.url,\n                headers: {},\n                rangeStart: 0,\n                rangeEnd: 0,\n              };\n              var start = segment.byteRangeStartOffset;\n              var end = segment.byteRangeEndOffset;\n\n              if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(start) && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(end)) {\n                loaderContext.rangeStart = start;\n                loaderContext.rangeEnd = end;\n              }\n\n              return loaderContext;\n            }\n\n            var LoadError = /*#__PURE__*/ (function (_Error) {\n              _inheritsLoose(LoadError, _Error);\n\n              function LoadError(data) {\n                var _this3;\n\n                for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n                  params[_key - 1] = arguments[_key];\n                }\n\n                _this3 = _Error.call.apply(_Error, [this].concat(params)) || this;\n                _this3.data = void 0;\n                _this3.data = data;\n                return _this3;\n              }\n\n              return LoadError;\n            })(/*#__PURE__*/ _wrapNativeSuper(Error));\n\n            /***/\n          },\n\n        /***/ \"./src/loader/fragment.ts\":\n          /*!********************************!*\\\n  !*** ./src/loader/fragment.ts ***!\n  \\********************************/\n          /*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ElementaryStreamTypes\", function () {\n              return ElementaryStreamTypes;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"BaseSegment\", function () {\n              return BaseSegment;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Fragment\", function () {\n              return Fragment;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Part\", function () {\n              return Part;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ \"./node_modules/url-toolkit/src/url-toolkit.js\");\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ \"./src/loader/level-key.ts\");\n            /* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ \"./src/loader/load-stats.ts\");\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            var ElementaryStreamTypes;\n\n            (function (ElementaryStreamTypes) {\n              ElementaryStreamTypes[\"AUDIO\"] = \"audio\";\n              ElementaryStreamTypes[\"VIDEO\"] = \"video\";\n              ElementaryStreamTypes[\"AUDIOVIDEO\"] = \"audiovideo\";\n            })(ElementaryStreamTypes || (ElementaryStreamTypes = {}));\n\n            var BaseSegment = /*#__PURE__*/ (function () {\n              // baseurl is the URL to the playlist\n              // relurl is the portion of the URL that comes from inside the playlist.\n              // Holds the types of data this fragment supports\n              function BaseSegment(baseurl) {\n                var _this$elementaryStrea;\n\n                this._byteRange = null;\n                this._url = null;\n                this.baseurl = void 0;\n                this.relurl = void 0;\n                this.elementaryStreams = ((_this$elementaryStrea = {}), (_this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null), (_this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null), (_this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null), _this$elementaryStrea);\n                this.baseurl = baseurl;\n              } // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n\n              var _proto = BaseSegment.prototype;\n\n              _proto.setByteRange = function setByteRange(value, previous) {\n                var params = value.split(\"@\", 2);\n                var byteRange = [];\n\n                if (params.length === 1) {\n                  byteRange[0] = previous ? previous.byteRangeEndOffset : 0;\n                } else {\n                  byteRange[0] = parseInt(params[1]);\n                }\n\n                byteRange[1] = parseInt(params[0]) + byteRange[0];\n                this._byteRange = byteRange;\n              };\n\n              _createClass(BaseSegment, [\n                {\n                  key: \"byteRange\",\n                  get: function get() {\n                    if (!this._byteRange) {\n                      return [];\n                    }\n\n                    return this._byteRange;\n                  },\n                },\n                {\n                  key: \"byteRangeStartOffset\",\n                  get: function get() {\n                    return this.byteRange[0];\n                  },\n                },\n                {\n                  key: \"byteRangeEndOffset\",\n                  get: function get() {\n                    return this.byteRange[1];\n                  },\n                },\n                {\n                  key: \"url\",\n                  get: function get() {\n                    if (!this._url && this.baseurl && this.relurl) {\n                      this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__[\"buildAbsoluteURL\"])(this.baseurl, this.relurl, {\n                        alwaysNormalize: true,\n                      });\n                    }\n\n                    return this._url || \"\";\n                  },\n                  set: function set(value) {\n                    this._url = value;\n                  },\n                },\n              ]);\n\n              return BaseSegment;\n            })();\n            var Fragment = /*#__PURE__*/ (function (_BaseSegment) {\n              _inheritsLoose(Fragment, _BaseSegment);\n\n              // EXTINF has to be present for a m38 to be considered valid\n              // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n              // levelkey is the EXT-X-KEY that applies to this segment for decryption\n              // core difference from the private field _decryptdata is the lack of the initialized IV\n              // _decryptdata will set the IV for this segment based on the segment number in the fragment\n              // A string representing the fragment type\n              // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading\n              // The level/track index to which the fragment belongs\n              // The continuity counter of the fragment\n              // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n              // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n              // The latest Presentation Time Stamp (PTS) appended to the buffer.\n              // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n              // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n              // The start time of the fragment, as listed in the manifest. Updated after transmux complete.\n              // Set by `updateFragPTSDTS` in level-helper\n              // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n              // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n              // Load/parse timing information\n              // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered\n              // #EXTINF  segment title\n              // The Media Initialization Section for this segment\n              function Fragment(type, baseurl) {\n                var _this;\n\n                _this = _BaseSegment.call(this, baseurl) || this;\n                _this._decryptdata = null;\n                _this.rawProgramDateTime = null;\n                _this.programDateTime = null;\n                _this.tagList = [];\n                _this.duration = 0;\n                _this.sn = 0;\n                _this.levelkey = void 0;\n                _this.type = void 0;\n                _this.loader = null;\n                _this.level = -1;\n                _this.cc = 0;\n                _this.startPTS = void 0;\n                _this.endPTS = void 0;\n                _this.appendedPTS = void 0;\n                _this.startDTS = void 0;\n                _this.endDTS = void 0;\n                _this.start = 0;\n                _this.deltaPTS = void 0;\n                _this.maxStartPTS = void 0;\n                _this.minEndPTS = void 0;\n                _this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__[\"LoadStats\"]();\n                _this.urlId = 0;\n                _this.data = void 0;\n                _this.bitrateTest = false;\n                _this.title = null;\n                _this.initSegment = null;\n                _this.type = type;\n                return _this;\n              }\n\n              var _proto2 = Fragment.prototype;\n\n              /**\n               * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n               * @param {number} segmentNumber - segment number to generate IV with\n               * @returns {Uint8Array}\n               */\n              _proto2.createInitializationVector = function createInitializationVector(segmentNumber) {\n                var uint8View = new Uint8Array(16);\n\n                for (var i = 12; i < 16; i++) {\n                  uint8View[i] = (segmentNumber >> (8 * (15 - i))) & 0xff;\n                }\n\n                return uint8View;\n              };\n              /**\n               * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data\n               * @param levelkey - a playlist's encryption info\n               * @param segmentNumber - the fragment's segment number\n               * @returns {LevelKey} - an object to be applied as a fragment's decryptdata\n               */\n\n              _proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {\n                var decryptdata = levelkey;\n\n                if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === \"AES-128\" && levelkey.uri && !levelkey.iv) {\n                  decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__[\"LevelKey\"].fromURI(levelkey.uri);\n                  decryptdata.method = levelkey.method;\n                  decryptdata.iv = this.createInitializationVector(segmentNumber);\n                  decryptdata.keyFormat = \"identity\";\n                }\n\n                return decryptdata;\n              };\n\n              _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {\n                if (partial === void 0) {\n                  partial = false;\n                }\n\n                var elementaryStreams = this.elementaryStreams;\n                var info = elementaryStreams[type];\n\n                if (!info) {\n                  elementaryStreams[type] = {\n                    startPTS: startPTS,\n                    endPTS: endPTS,\n                    startDTS: startDTS,\n                    endDTS: endDTS,\n                    partial: partial,\n                  };\n                  return;\n                }\n\n                info.startPTS = Math.min(info.startPTS, startPTS);\n                info.endPTS = Math.max(info.endPTS, endPTS);\n                info.startDTS = Math.min(info.startDTS, startDTS);\n                info.endDTS = Math.max(info.endDTS, endDTS);\n              };\n\n              _proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {\n                var elementaryStreams = this.elementaryStreams;\n                elementaryStreams[ElementaryStreamTypes.AUDIO] = null;\n                elementaryStreams[ElementaryStreamTypes.VIDEO] = null;\n                elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;\n              };\n\n              _createClass(Fragment, [\n                {\n                  key: \"decryptdata\",\n                  get: function get() {\n                    if (!this.levelkey && !this._decryptdata) {\n                      return null;\n                    }\n\n                    if (!this._decryptdata && this.levelkey) {\n                      var sn = this.sn;\n\n                      if (typeof sn !== \"number\") {\n                        // We are fetching decryption data for a initialization segment\n                        // If the segment was encrypted with AES-128\n                        // It must have an IV defined. We cannot substitute the Segment Number in.\n                        if (this.levelkey && this.levelkey.method === \"AES-128\" && !this.levelkey.iv) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn('missing IV for initialization segment with method=\"' + this.levelkey.method + '\" - compliance issue');\n                        }\n                        /*\n          Be converted to a Number.\n          'initSegment' will become NaN.\n          NaN, which when converted through ToInt32() -> +0.\n          ---\n          Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n          */\n\n                        sn = 0;\n                      }\n\n                      this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);\n                    }\n\n                    return this._decryptdata;\n                  },\n                },\n                {\n                  key: \"end\",\n                  get: function get() {\n                    return this.start + this.duration;\n                  },\n                },\n                {\n                  key: \"endProgramDateTime\",\n                  get: function get() {\n                    if (this.programDateTime === null) {\n                      return null;\n                    }\n\n                    if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(this.programDateTime)) {\n                      return null;\n                    }\n\n                    var duration = !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(this.duration) ? 0 : this.duration;\n                    return this.programDateTime + duration * 1000;\n                  },\n                },\n                {\n                  key: \"encrypted\",\n                  get: function get() {\n                    var _this$decryptdata;\n\n                    // At the m3u8-parser level we need to add support for manifest signalled keyformats\n                    // when we want the fragment to start reporting that it is encrypted.\n                    // Currently, keyFormat will only be set for identity keys\n                    if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {\n                      return true;\n                    }\n\n                    return false;\n                  },\n                },\n              ]);\n\n              return Fragment;\n            })(BaseSegment);\n            var Part = /*#__PURE__*/ (function (_BaseSegment2) {\n              _inheritsLoose(Part, _BaseSegment2);\n\n              function Part(partAttrs, frag, baseurl, index, previous) {\n                var _this2;\n\n                _this2 = _BaseSegment2.call(this, baseurl) || this;\n                _this2.fragOffset = 0;\n                _this2.duration = 0;\n                _this2.gap = false;\n                _this2.independent = false;\n                _this2.relurl = void 0;\n                _this2.fragment = void 0;\n                _this2.index = void 0;\n                _this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__[\"LoadStats\"]();\n                _this2.duration = partAttrs.decimalFloatingPoint(\"DURATION\");\n                _this2.gap = partAttrs.bool(\"GAP\");\n                _this2.independent = partAttrs.bool(\"INDEPENDENT\");\n                _this2.relurl = partAttrs.enumeratedString(\"URI\");\n                _this2.fragment = frag;\n                _this2.index = index;\n                var byteRange = partAttrs.enumeratedString(\"BYTERANGE\");\n\n                if (byteRange) {\n                  _this2.setByteRange(byteRange, previous);\n                }\n\n                if (previous) {\n                  _this2.fragOffset = previous.fragOffset + previous.duration;\n                }\n\n                return _this2;\n              }\n\n              _createClass(Part, [\n                {\n                  key: \"start\",\n                  get: function get() {\n                    return this.fragment.start + this.fragOffset;\n                  },\n                },\n                {\n                  key: \"end\",\n                  get: function get() {\n                    return this.start + this.duration;\n                  },\n                },\n                {\n                  key: \"loaded\",\n                  get: function get() {\n                    var elementaryStreams = this.elementaryStreams;\n                    return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);\n                  },\n                },\n              ]);\n\n              return Part;\n            })(BaseSegment);\n\n            /***/\n          },\n\n        /***/ \"./src/loader/key-loader.ts\":\n          /*!**********************************!*\\\n  !*** ./src/loader/key-loader.ts ***!\n  \\**********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return KeyLoader;\n            });\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /*\n             * Decrypt key Loader\n             */\n\n            var KeyLoader = /*#__PURE__*/ (function () {\n              function KeyLoader(CiderHls) {\n                this.CiderHls = void 0;\n                this.loaders = {};\n                this.decryptkey = null;\n                this.decrypturl = null;\n                this.CiderHls = CiderHls;\n\n                this._registerListeners();\n              }\n\n              var _proto = KeyLoader.prototype;\n\n              _proto._registerListeners = function _registerListeners() {\n                this.CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].KEY_LOADING, this.onKeyLoading, this);\n              };\n\n              _proto._unregisterListeners = function _unregisterListeners() {\n                this.CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].KEY_LOADING, this.onKeyLoading);\n              };\n\n              _proto.destroy = function destroy() {\n                this._unregisterListeners();\n\n                for (var loaderName in this.loaders) {\n                  var loader = this.loaders[loaderName];\n\n                  if (loader) {\n                    loader.destroy();\n                  }\n                }\n\n                this.loaders = {};\n              };\n\n              _proto.onKeyLoading = function onKeyLoading(event, data) {\n                var frag = data.frag;\n                var type = frag.type;\n                var loader = this.loaders[type];\n\n                if (!frag.decryptdata) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"Missing decryption data on fragment in onKeyLoading\");\n                  return;\n                } // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved\n\n                var uri = frag.decryptdata.uri;\n\n                if (uri !== this.decrypturl || this.decryptkey === null) {\n                  var config = this.CiderHls.config;\n\n                  if (loader) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"abort previous key loader for type:\" + type);\n                    loader.abort();\n                  }\n\n                  if (!uri) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].warn(\"key uri is falsy\");\n                    return;\n                  }\n\n                  var Loader = config.loader;\n                  var fragLoader = (frag.loader = this.loaders[type] = new Loader(config));\n                  this.decrypturl = uri;\n                  this.decryptkey = null;\n                  var loaderContext = {\n                    url: uri,\n                    frag: frag,\n                    responseType: \"arraybuffer\",\n                  }; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n                  // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n                  // this will also align retry logic with fragment-loader\n\n                  var loaderConfig = {\n                    timeout: config.fragLoadingTimeOut,\n                    maxRetry: 0,\n                    retryDelay: config.fragLoadingRetryDelay,\n                    maxRetryDelay: config.fragLoadingMaxRetryTimeout,\n                    highWaterMark: 0,\n                  };\n                  var loaderCallbacks = {\n                    onSuccess: this.loadsuccess.bind(this),\n                    onError: this.loaderror.bind(this),\n                    onTimeout: this.loadtimeout.bind(this),\n                  };\n                  fragLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n                } else if (this.decryptkey) {\n                  // Return the key if it's already been loaded\n                  frag.decryptdata.key = this.decryptkey;\n                  this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].KEY_LOADED, {\n                    frag: frag,\n                  });\n                }\n              };\n\n              _proto.loadsuccess = function loadsuccess(response, stats, context) {\n                var frag = context.frag;\n\n                if (!frag.decryptdata) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__[\"logger\"].error(\"after key load, decryptdata unset\");\n                  return;\n                }\n\n                this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success\n\n                frag.loader = null;\n                delete this.loaders[frag.type];\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].KEY_LOADED, {\n                  frag: frag,\n                });\n              };\n\n              _proto.loaderror = function loaderror(response, context) {\n                var frag = context.frag;\n                var loader = frag.loader;\n\n                if (loader) {\n                  loader.abort();\n                }\n\n                delete this.loaders[frag.type];\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                  type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                  details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_LOAD_ERROR,\n                  fatal: false,\n                  frag: frag,\n                  response: response,\n                });\n              };\n\n              _proto.loadtimeout = function loadtimeout(stats, context) {\n                var frag = context.frag;\n                var loader = frag.loader;\n\n                if (loader) {\n                  loader.abort();\n                }\n\n                delete this.loaders[frag.type];\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__[\"Events\"].ERROR, {\n                  type: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorTypes\"].NETWORK_ERROR,\n                  details: _errors__WEBPACK_IMPORTED_MODULE_1__[\"ErrorDetails\"].KEY_LOAD_TIMEOUT,\n                  fatal: false,\n                  frag: frag,\n                });\n              };\n\n              return KeyLoader;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/loader/level-details.ts\":\n          /*!*************************************!*\\\n  !*** ./src/loader/level-details.ts ***!\n  \\*************************************/\n          /*! exports provided: LevelDetails */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"LevelDetails\", function () {\n              return LevelDetails;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            var DEFAULT_TARGET_DURATION = 10;\n            var LevelDetails = /*#__PURE__*/ (function () {\n              // Manifest reload synchronization\n              function LevelDetails(baseUrl) {\n                this.PTSKnown = false;\n                this.alignedSliding = false;\n                this.averagetargetduration = void 0;\n                this.endCC = 0;\n                this.endSN = 0;\n                this.fragments = void 0;\n                this.fragmentHint = void 0;\n                this.partList = null;\n                this.live = true;\n                this.ageHeader = 0;\n                this.advancedDateTime = void 0;\n                this.updated = true;\n                this.advanced = true;\n                this.availabilityDelay = void 0;\n                this.misses = 0;\n                this.needSidxRanges = false;\n                this.startCC = 0;\n                this.startSN = 0;\n                this.startTimeOffset = null;\n                this.targetduration = 0;\n                this.totalduration = 0;\n                this.type = null;\n                this.url = void 0;\n                this.m3u8 = \"\";\n                this.version = null;\n                this.canBlockReload = false;\n                this.canSkipUntil = 0;\n                this.canSkipDateRanges = false;\n                this.skippedSegments = 0;\n                this.recentlyRemovedDateranges = void 0;\n                this.partHoldBack = 0;\n                this.holdBack = 0;\n                this.partTarget = 0;\n                this.preloadHint = void 0;\n                this.renditionReports = void 0;\n                this.tuneInGoal = 0;\n                this.deltaUpdateFailed = void 0;\n                this.driftStartTime = 0;\n                this.driftEndTime = 0;\n                this.driftStart = 0;\n                this.driftEnd = 0;\n                this.fragments = [];\n                this.url = baseUrl;\n              }\n\n              var _proto = LevelDetails.prototype;\n\n              _proto.reloaded = function reloaded(previous) {\n                if (!previous) {\n                  this.advanced = true;\n                  this.updated = true;\n                  return;\n                }\n\n                var partSnDiff = this.lastPartSn - previous.lastPartSn;\n                var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;\n                this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;\n                this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || (partSnDiff === 0 && partIndexDiff > 0);\n\n                if (this.updated || this.advanced) {\n                  this.misses = Math.floor(previous.misses * 0.6);\n                } else {\n                  this.misses = previous.misses + 1;\n                }\n\n                this.availabilityDelay = previous.availabilityDelay;\n              };\n\n              _createClass(LevelDetails, [\n                {\n                  key: \"hasProgramDateTime\",\n                  get: function get() {\n                    if (this.fragments.length) {\n                      return Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(this.fragments[this.fragments.length - 1].programDateTime);\n                    }\n\n                    return false;\n                  },\n                },\n                {\n                  key: \"levelTargetDuration\",\n                  get: function get() {\n                    return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;\n                  },\n                },\n                {\n                  key: \"drift\",\n                  get: function get() {\n                    var runTime = this.driftEndTime - this.driftStartTime;\n\n                    if (runTime > 0) {\n                      var runDuration = this.driftEnd - this.driftStart;\n                      return (runDuration * 1000) / runTime;\n                    }\n\n                    return 1;\n                  },\n                },\n                {\n                  key: \"edge\",\n                  get: function get() {\n                    return this.partEnd || this.fragmentEnd;\n                  },\n                },\n                {\n                  key: \"partEnd\",\n                  get: function get() {\n                    var _this$partList;\n\n                    if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {\n                      return this.partList[this.partList.length - 1].end;\n                    }\n\n                    return this.fragmentEnd;\n                  },\n                },\n                {\n                  key: \"fragmentEnd\",\n                  get: function get() {\n                    var _this$fragments;\n\n                    if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {\n                      return this.fragments[this.fragments.length - 1].end;\n                    }\n\n                    return 0;\n                  },\n                },\n                {\n                  key: \"age\",\n                  get: function get() {\n                    if (this.advancedDateTime) {\n                      return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;\n                    }\n\n                    return 0;\n                  },\n                },\n                {\n                  key: \"lastPartIndex\",\n                  get: function get() {\n                    var _this$partList2;\n\n                    if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {\n                      return this.partList[this.partList.length - 1].index;\n                    }\n\n                    return -1;\n                  },\n                },\n                {\n                  key: \"lastPartSn\",\n                  get: function get() {\n                    var _this$partList3;\n\n                    if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {\n                      return this.partList[this.partList.length - 1].fragment.sn;\n                    }\n\n                    return this.endSN;\n                  },\n                },\n              ]);\n\n              return LevelDetails;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/loader/level-key.ts\":\n          /*!*********************************!*\\\n  !*** ./src/loader/level-key.ts ***!\n  \\*********************************/\n          /*! exports provided: LevelKey */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"LevelKey\", function () {\n              return LevelKey;\n            });\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ \"./node_modules/url-toolkit/src/url-toolkit.js\");\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            var LevelKey = /*#__PURE__*/ (function () {\n              LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {\n                return new LevelKey(baseUrl, relativeUrl);\n              };\n\n              LevelKey.fromURI = function fromURI(uri) {\n                return new LevelKey(uri);\n              };\n\n              function LevelKey(absoluteOrBaseURI, relativeURL) {\n                this._uri = null;\n                this.method = null;\n                this.keyFormat = null;\n                this.keyFormatVersions = null;\n                this.keyID = null;\n                this.key = null;\n                this.iv = null;\n\n                if (relativeURL) {\n                  this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__[\"buildAbsoluteURL\"])(absoluteOrBaseURI, relativeURL, {\n                    alwaysNormalize: true,\n                  });\n                } else {\n                  this._uri = absoluteOrBaseURI;\n                }\n              }\n\n              _createClass(LevelKey, [\n                {\n                  key: \"uri\",\n                  get: function get() {\n                    return this._uri;\n                  },\n                },\n              ]);\n\n              return LevelKey;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/loader/load-stats.ts\":\n          /*!**********************************!*\\\n  !*** ./src/loader/load-stats.ts ***!\n  \\**********************************/\n          /*! exports provided: LoadStats */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"LoadStats\", function () {\n              return LoadStats;\n            });\n            var LoadStats = function LoadStats() {\n              this.aborted = false;\n              this.loaded = 0;\n              this.retry = 0;\n              this.total = 0;\n              this.chunkCount = 0;\n              this.bwEstimate = 0;\n              this.loading = {\n                start: 0,\n                first: 0,\n                end: 0,\n              };\n              this.parsing = {\n                start: 0,\n                end: 0,\n              };\n              this.buffering = {\n                start: 0,\n                first: 0,\n                end: 0,\n              };\n            };\n\n            /***/\n          },\n\n        /***/ \"./src/loader/m3u8-parser.ts\":\n          /*!***********************************!*\\\n  !*** ./src/loader/m3u8-parser.ts ***!\n  \\***********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return M3U8Parser;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ \"./node_modules/url-toolkit/src/url-toolkit.js\");\n            /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);\n            /* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ \"./src/loader/fragment.ts\");\n            /* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ \"./src/loader/level-details.ts\");\n            /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ \"./src/loader/level-key.ts\");\n            /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ \"./src/utils/attr-list.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ \"./src/utils/codecs.ts\");\n\n            // https://regex101.com is your friend\n            var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\r\\n]*)(?:[\\r\\n](?:#[^\\r\\n]*)?)*([^\\r\\n]+)|#EXT-X-SESSION-DATA:([^\\r\\n]*)[\\r\\n]+/g;\n            var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n            var LEVEL_PLAYLIST_REGEX_FAST = new RegExp(\n              [\n                /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n                /(?!#) *(\\S[\\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n                /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n                /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n                /#.*/.source, // All other non-segment oriented tags will match with all groups empty\n              ].join(\"|\"),\n              \"g\"\n            );\n            var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp(\n              [\n                /#(EXTM3U)/.source,\n                /#EXT-X-(PLAYLIST-TYPE):(.+)/.source,\n                /#EXT-X-(MEDIA-SEQUENCE): *(\\d+)/.source,\n                /#EXT-X-(SKIP):(.+)/.source,\n                /#EXT-X-(TARGETDURATION): *(\\d+)/.source,\n                /#EXT-X-(KEY):(.+)/.source,\n                /#EXT-X-(START):(.+)/.source,\n                /#EXT-X-(ENDLIST)/.source,\n                /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\\d+)/.source,\n                /#EXT-X-(DIS)CONTINUITY/.source,\n                /#EXT-X-(VERSION):(\\d+)/.source,\n                /#EXT-X-(MAP):(.+)/.source,\n                /#EXT-X-(SERVER-CONTROL):(.+)/.source,\n                /#EXT-X-(PART-INF):(.+)/.source,\n                /#EXT-X-(GAP)/.source,\n                /#EXT-X-(BITRATE):\\s*(\\d+)/.source,\n                /#EXT-X-(PART):(.+)/.source,\n                /#EXT-X-(PRELOAD-HINT):(.+)/.source,\n                /#EXT-X-(RENDITION-REPORT):(.+)/.source,\n                /(#)([^:]*):(.*)/.source,\n                /(#)(.*)(?:.*)\\r?\\n?/.source,\n              ].join(\"|\")\n            );\n            var MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\n            function isMP4Url(url) {\n              var _URLToolkit$parseURL$, _URLToolkit$parseURL;\n\n              return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__[\"parseURL\"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : \"\");\n            }\n\n            var M3U8Parser = /*#__PURE__*/ (function () {\n              function M3U8Parser() {}\n\n              M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {\n                for (var i = 0; i < groups.length; i++) {\n                  var group = groups[i];\n\n                  if (group.id === mediaGroupId) {\n                    return group;\n                  }\n                }\n              };\n\n              M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {\n                // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n                var avcdata = codec.split(\".\");\n\n                if (avcdata.length > 2) {\n                  var result = avcdata.shift() + \".\";\n                  result += parseInt(avcdata.shift()).toString(16);\n                  result += (\"000\" + parseInt(avcdata.shift()).toString(16)).substr(-4);\n                  return result;\n                }\n\n                return codec;\n              };\n\n              M3U8Parser.resolve = function resolve(url, baseUrl) {\n                return url_toolkit__WEBPACK_IMPORTED_MODULE_1__[\"buildAbsoluteURL\"](baseUrl, url, {\n                  alwaysNormalize: true,\n                });\n              };\n\n              M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {\n                var levels = [];\n                var sessionData = {};\n                var hasSessionData = false;\n                MASTER_PLAYLIST_REGEX.lastIndex = 0;\n                var result;\n\n                while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n                  if (result[1]) {\n                    // '#EXT-X-STREAM-INF' is found, parse level tag  in group 1\n                    var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](result[1]);\n                    var level = {\n                      attrs: attrs,\n                      bitrate: attrs.decimalInteger(\"AVERAGE-BANDWIDTH\") || attrs.decimalInteger(\"BANDWIDTH\"),\n                      name: attrs.NAME,\n                      url: M3U8Parser.resolve(result[2], baseurl),\n                    };\n                    var resolution = attrs.decimalResolution(\"RESOLUTION\");\n\n                    if (resolution) {\n                      level.width = resolution.width;\n                      level.height = resolution.height;\n                    }\n\n                    setCodecs(\n                      (attrs.CODECS || \"\").split(/[ ,]+/).filter(function (c) {\n                        return c;\n                      }),\n                      level\n                    );\n\n                    if (level.videoCodec && level.videoCodec.indexOf(\"avc1\") !== -1) {\n                      level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n                    }\n\n                    levels.push(level);\n                  } else if (result[3]) {\n                    // '#EXT-X-SESSION-DATA' is found, parse session data in group 3\n                    var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](result[3]);\n\n                    if (sessionAttrs[\"DATA-ID\"]) {\n                      hasSessionData = true;\n                      sessionData[sessionAttrs[\"DATA-ID\"]] = sessionAttrs;\n                    }\n                  }\n                }\n                if (levels && levels.length > 0) {\n                  levels = levels.sort(function (a, b) {\n                    return a.bitrate - b.bitrate;\n                  });\n                }\n                return {\n                  levels: levels,\n                  sessionData: hasSessionData ? sessionData : null,\n                };\n              };\n\n              M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {\n                if (groups === void 0) {\n                  groups = [];\n                }\n\n                var result;\n                var medias = [];\n                var id = 0;\n                MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n\n                while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n                  var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](result[1]);\n\n                  if (attrs.TYPE === type) {\n                    var media = {\n                      attrs: attrs,\n                      bitrate: 0,\n                      id: id++,\n                      groupId: attrs[\"GROUP-ID\"],\n                      instreamId: attrs[\"INSTREAM-ID\"],\n                      name: attrs.NAME || attrs.LANGUAGE || \"\",\n                      type: type,\n                      default: attrs.bool(\"DEFAULT\"),\n                      autoselect: attrs.bool(\"AUTOSELECT\"),\n                      forced: attrs.bool(\"FORCED\"),\n                      lang: attrs.LANGUAGE,\n                      url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : \"\",\n                    };\n\n                    if (groups.length) {\n                      // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track\n                      // If we don't find the track signalled, lets use the first audio groups codec we have\n                      // Acting as a best guess\n                      var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];\n                      assignCodec(media, groupCodec, \"audioCodec\");\n                      assignCodec(media, groupCodec, \"textCodec\");\n                    }\n\n                    medias.push(media);\n                  }\n                }\n\n                return medias;\n              };\n\n              M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {\n                var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__[\"LevelDetails\"](baseurl);\n                var fragments = level.fragments; // The most recent init segment seen (applies to all subsequent segments)\n\n                var currentInitSegment = null;\n                var currentSN = 0;\n                var currentPart = 0;\n                var totalduration = 0;\n                var discontinuityCounter = 0;\n                var prevFrag = null;\n                var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__[\"Fragment\"](type, baseurl);\n                var result;\n                var i;\n                var levelkey;\n                var firstPdtIndex = -1;\n                var createNextFrag = false;\n                LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n                level.m3u8 = string;\n\n                while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n                  if (createNextFrag) {\n                    createNextFrag = false;\n                    frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__[\"Fragment\"](type, baseurl); // setup the next fragment for part loading\n\n                    frag.start = totalduration;\n                    frag.sn = currentSN;\n                    frag.cc = discontinuityCounter;\n                    frag.level = id;\n\n                    if (currentInitSegment) {\n                      frag.initSegment = currentInitSegment;\n                      frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n                    }\n                  }\n\n                  var duration = result[1];\n\n                  if (duration) {\n                    // INF\n                    frag.duration = parseFloat(duration); // avoid sliced strings    https://github.com/video-dev/CiderHls.js/issues/939\n\n                    var title = (\" \" + result[2]).slice(1);\n                    frag.title = title || null;\n                    frag.tagList.push(title ? [\"INF\", duration, title] : [\"INF\", duration]);\n                  } else if (result[3]) {\n                    // url\n                    if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(frag.duration)) {\n                      frag.start = totalduration;\n\n                      if (levelkey) {\n                        frag.levelkey = levelkey;\n                      }\n\n                      frag.sn = currentSN;\n                      frag.level = id;\n                      frag.cc = discontinuityCounter;\n                      frag.urlId = levelUrlId;\n                      fragments.push(frag); // avoid sliced strings    https://github.com/video-dev/CiderHls.js/issues/939\n\n                      frag.relurl = (\" \" + result[3]).slice(1);\n                      assignProgramDateTime(frag, prevFrag);\n                      prevFrag = frag;\n                      totalduration += frag.duration;\n                      currentSN++;\n                      currentPart = 0;\n                      createNextFrag = true;\n                    }\n                  } else if (result[4]) {\n                    // X-BYTERANGE\n                    var data = (\" \" + result[4]).slice(1);\n\n                    if (prevFrag) {\n                      frag.setByteRange(data, prevFrag);\n                    } else {\n                      frag.setByteRange(data);\n                    }\n                  } else if (result[5]) {\n                    // PROGRAM-DATE-TIME\n                    // avoid sliced strings    https://github.com/video-dev/CiderHls.js/issues/939\n                    frag.rawProgramDateTime = (\" \" + result[5]).slice(1);\n                    frag.tagList.push([\"PROGRAM-DATE-TIME\", frag.rawProgramDateTime]);\n\n                    if (firstPdtIndex === -1) {\n                      firstPdtIndex = fragments.length;\n                    }\n                  } else {\n                    result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n\n                    if (!result) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].warn(\"No matches on slow regex match for level playlist!\");\n                      continue;\n                    }\n\n                    for (i = 1; i < result.length; i++) {\n                      if (typeof result[i] !== \"undefined\") {\n                        break;\n                      }\n                    } // avoid sliced strings    https://github.com/video-dev/CiderHls.js/issues/939\n\n                    var tag = (\" \" + result[i]).slice(1);\n                    var value1 = (\" \" + result[i + 1]).slice(1);\n                    var value2 = result[i + 2] ? (\" \" + result[i + 2]).slice(1) : \"\";\n\n                    switch (tag) {\n                      case \"PLAYLIST-TYPE\":\n                        level.type = value1.toUpperCase();\n                        break;\n\n                      case \"MEDIA-SEQUENCE\":\n                        currentSN = level.startSN = parseInt(value1);\n                        break;\n\n                      case \"SKIP\": {\n                        var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        var skippedSegments = skipAttrs.decimalInteger(\"SKIPPED-SEGMENTS\");\n\n                        if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(skippedSegments)) {\n                          level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`\n\n                          for (var _i = skippedSegments; _i--; ) {\n                            fragments.unshift(null);\n                          }\n\n                          currentSN += skippedSegments;\n                        }\n\n                        var recentlyRemovedDateranges = skipAttrs.enumeratedString(\"RECENTLY-REMOVED-DATERANGES\");\n\n                        if (recentlyRemovedDateranges) {\n                          level.recentlyRemovedDateranges = recentlyRemovedDateranges.split(\"\\t\");\n                        }\n\n                        break;\n                      }\n\n                      case \"TARGETDURATION\":\n                        level.targetduration = parseFloat(value1);\n                        break;\n\n                      case \"VERSION\":\n                        level.version = parseInt(value1);\n                        break;\n\n                      case \"EXTM3U\":\n                        break;\n\n                      case \"ENDLIST\":\n                        level.live = false;\n                        break;\n\n                      case \"#\":\n                        if (value1 || value2) {\n                          frag.tagList.push(value2 ? [value1, value2] : [value1]);\n                        }\n\n                        break;\n\n                      case \"DIS\":\n                        discontinuityCounter++;\n\n                      /* falls through */\n\n                      case \"GAP\":\n                        frag.tagList.push([tag]);\n                        break;\n\n                      case \"BITRATE\":\n                        frag.tagList.push([tag, value1]);\n                        break;\n\n                      case \"DISCONTINUITY-SEQ\":\n                        discontinuityCounter = parseInt(value1);\n                        break;\n\n                      case \"KEY\": {\n                        var _keyAttrs$enumeratedS;\n\n                        // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n                        var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        var decryptmethod = keyAttrs.enumeratedString(\"METHOD\");\n                        var decrypturi = keyAttrs.URI;\n                        var decryptiv = keyAttrs.hexadecimalInteger(\"IV\");\n                        var decryptkeyformatversions = keyAttrs.enumeratedString(\"KEYFORMATVERSIONS\");\n                        var decryptkeyid = keyAttrs.enumeratedString(\"KEYID\"); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n\n                        var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString(\"KEYFORMAT\")) != null ? _keyAttrs$enumeratedS : \"identity\";\n                        var unsupportedKnownKeyformatsInManifest = [\n                          \"com.apple.streamingkeydelivery\",\n                          \"com.microsoft.playready\",\n                          \"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed\", // widevine (v2)\n                          \"com.widevine\", // earlier widevine (v1)\n                        ];\n\n                        if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].warn(\"Keyformat \" + decryptkeyformat + \" is not supported from the manifest\");\n                          continue;\n                        } else if (decryptkeyformat !== \"identity\") {\n                          // We are supposed to skip keys we don't understand.\n                          // As we currently only officially support identity keys\n                          // from the manifest we shouldn't save any other key.\n                          continue;\n                        } // TODO: multiple keys can be defined on a fragment, and we need to support this\n                        // for clients that support both playready and widevine\n\n                        if (decryptmethod) {\n                          // TODO: need to determine if the level key is actually a relative URL\n                          // if it isn't, then we should instead construct the LevelKey using fromURI.\n                          levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__[\"LevelKey\"].fromURL(baseurl, decrypturi);\n\n                          if (decrypturi && [\"AES-128\", \"SAMPLE-AES\", \"SAMPLE-AES-CENC\"].indexOf(decryptmethod) >= 0) {\n                            levelkey.method = decryptmethod;\n                            levelkey.keyFormat = decryptkeyformat;\n\n                            if (decryptkeyid) {\n                              levelkey.keyID = decryptkeyid;\n                            }\n\n                            if (decryptkeyformatversions) {\n                              levelkey.keyFormatVersions = decryptkeyformatversions;\n                            } // Initialization Vector (IV)\n\n                            levelkey.iv = decryptiv;\n                          }\n                        }\n\n                        break;\n                      }\n\n                      case \"START\": {\n                        var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        var startTimeOffset = startAttrs.decimalFloatingPoint(\"TIME-OFFSET\"); // TIME-OFFSET can be 0\n\n                        if (Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(startTimeOffset)) {\n                          level.startTimeOffset = startTimeOffset;\n                        }\n\n                        break;\n                      }\n\n                      case \"MAP\": {\n                        var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        frag.relurl = mapAttrs.URI;\n\n                        if (mapAttrs.BYTERANGE) {\n                          frag.setByteRange(mapAttrs.BYTERANGE);\n                        }\n\n                        frag.level = id;\n                        frag.sn = \"initSegment\";\n\n                        if (levelkey) {\n                          frag.levelkey = levelkey;\n                        }\n\n                        frag.initSegment = null;\n                        currentInitSegment = frag;\n                        createNextFrag = true;\n                        break;\n                      }\n\n                      case \"SERVER-CONTROL\": {\n                        var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        level.canBlockReload = serverControlAttrs.bool(\"CAN-BLOCK-RELOAD\");\n                        level.canSkipUntil = serverControlAttrs.optionalFloat(\"CAN-SKIP-UNTIL\", 0);\n                        level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool(\"CAN-SKIP-DATERANGES\");\n                        level.partHoldBack = serverControlAttrs.optionalFloat(\"PART-HOLD-BACK\", 0);\n                        level.holdBack = serverControlAttrs.optionalFloat(\"HOLD-BACK\", 0);\n                        break;\n                      }\n\n                      case \"PART-INF\": {\n                        var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        level.partTarget = partInfAttrs.decimalFloatingPoint(\"PART-TARGET\");\n                        break;\n                      }\n\n                      case \"PART\": {\n                        var partList = level.partList;\n\n                        if (!partList) {\n                          partList = level.partList = [];\n                        }\n\n                        var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;\n                        var index = currentPart++;\n                        var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__[\"Part\"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1), frag, baseurl, index, previousFragmentPart);\n                        partList.push(part);\n                        frag.duration += part.duration;\n                        break;\n                      }\n\n                      case \"PRELOAD-HINT\": {\n                        var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        level.preloadHint = preloadHintAttrs;\n                        break;\n                      }\n\n                      case \"RENDITION-REPORT\": {\n                        var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__[\"AttrList\"](value1);\n                        level.renditionReports = level.renditionReports || [];\n                        level.renditionReports.push(renditionReportAttrs);\n                        break;\n                      }\n\n                      default:\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].warn(\"line parsed but not handled: \" + result);\n                        break;\n                    }\n                  }\n                }\n\n                if (prevFrag && !prevFrag.relurl) {\n                  fragments.pop();\n                  totalduration -= prevFrag.duration;\n\n                  if (level.partList) {\n                    level.fragmentHint = prevFrag;\n                  }\n                } else if (level.partList) {\n                  assignProgramDateTime(frag, prevFrag);\n                  frag.cc = discontinuityCounter;\n                  level.fragmentHint = frag;\n                }\n\n                var fragmentLength = fragments.length;\n                var firstFragment = fragments[0];\n                var lastFragment = fragments[fragmentLength - 1];\n                totalduration += level.skippedSegments * level.targetduration;\n\n                if (totalduration > 0 && fragmentLength && lastFragment) {\n                  level.averagetargetduration = totalduration / fragmentLength;\n                  var lastSn = lastFragment.sn;\n                  level.endSN = lastSn !== \"initSegment\" ? lastSn : 0;\n\n                  if (firstFragment) {\n                    level.startCC = firstFragment.cc;\n\n                    if (!firstFragment.initSegment) {\n                      // this is a bit lurky but CiderHls really has no other way to tell us\n                      // if the fragments are TS or MP4, except if we download them :/\n                      // but this is to be able to handle SIDX.\n                      if (\n                        level.fragments.every(function (frag) {\n                          return frag.relurl && isMP4Url(frag.relurl);\n                        })\n                      ) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_6__[\"logger\"].warn(\"MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX\");\n                        frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__[\"Fragment\"](type, baseurl);\n                        frag.relurl = lastFragment.relurl;\n                        frag.level = id;\n                        frag.sn = \"initSegment\";\n                        firstFragment.initSegment = frag;\n                        level.needSidxRanges = true;\n                      }\n                    }\n                  }\n                } else {\n                  level.endSN = 0;\n                  level.startCC = 0;\n                }\n\n                if (level.fragmentHint) {\n                  totalduration += level.fragmentHint.duration;\n                }\n\n                level.totalduration = totalduration;\n                level.endCC = discontinuityCounter;\n                /**\n                 * Backfill any missing PDT values\n                 * \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n                 * one or more Media Segment URIs, the client SHOULD extrapolate\n                 * backward from that tag (using EXTINF durations and/or media\n                 * timestamps) to associate dates with those segments.\"\n                 * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n                 * computed.\n                 */\n\n                if (firstPdtIndex > 0) {\n                  backfillProgramDateTimes(fragments, firstPdtIndex);\n                }\n\n                return level;\n              };\n\n              return M3U8Parser;\n            })();\n\n            function setCodecs(codecs, level) {\n              [\"video\", \"audio\", \"text\"].forEach(function (type) {\n                var filtered = codecs.filter(function (codec) {\n                  return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__[\"isCodecType\"])(codec, type);\n                });\n\n                if (filtered.length) {\n                  var preferred = filtered.filter(function (codec) {\n                    return codec.lastIndexOf(\"avc1\", 0) === 0 || codec.lastIndexOf(\"mp4a\", 0) === 0;\n                  });\n                  level[type + \"Codec\"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list\n\n                  codecs = codecs.filter(function (codec) {\n                    return filtered.indexOf(codec) === -1;\n                  });\n                }\n              });\n              level.unknownCodecs = codecs;\n            }\n\n            function assignCodec(media, groupItem, codecProperty) {\n              var codecValue = groupItem[codecProperty];\n\n              if (codecValue) {\n                media[codecProperty] = codecValue;\n              }\n            }\n\n            function backfillProgramDateTimes(fragments, firstPdtIndex) {\n              var fragPrev = fragments[firstPdtIndex];\n\n              for (var i = firstPdtIndex; i--; ) {\n                var frag = fragments[i]; // Exit on delta-playlist skipped segments\n\n                if (!frag) {\n                  return;\n                }\n\n                frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;\n                fragPrev = frag;\n              }\n            }\n\n            function assignProgramDateTime(frag, prevFrag) {\n              if (frag.rawProgramDateTime) {\n                frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n              } else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {\n                frag.programDateTime = prevFrag.endProgramDateTime;\n              }\n\n              if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(frag.programDateTime)) {\n                frag.programDateTime = null;\n                frag.rawProgramDateTime = null;\n              }\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/loader/playlist-loader.ts\":\n          /*!***************************************!*\\\n  !*** ./src/loader/playlist-loader.ts ***!\n  \\***************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ \"./src/loader/m3u8-parser.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ \"./src/utils/attr-list.ts\");\n\n            /**\n             * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n             *\n             * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n             *\n             * Uses loader(s) set in config to do actual internal loading of resource tasks.\n             *\n             * @module\n             *\n             */\n\n            function mapContextToLevelType(context) {\n              var type = context.type;\n\n              switch (type) {\n                case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK:\n                  return _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO;\n\n                case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK:\n                  return _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].SUBTITLE;\n\n                default:\n                  return _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].MAIN;\n              }\n            }\n\n            function getResponseUrl(response, context) {\n              var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)\n              // data-uri mode also not supported (but no need to detect redirection)\n\n              if (url === undefined || url.indexOf(\"data:\") === 0) {\n                // fallback to initial URL\n                url = context.url;\n              }\n\n              return url;\n            }\n\n            var PlaylistLoader = /*#__PURE__*/ (function () {\n              function PlaylistLoader(CiderHls) {\n                this.CiderHls = void 0;\n                this.loaders = Object.create(null);\n                this.CiderHls = CiderHls;\n                this.registerListeners();\n              }\n\n              var _proto = PlaylistLoader.prototype;\n\n              _proto.registerListeners = function registerListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n                CiderHls.on(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n              };\n\n              _proto.unregisterListeners = function unregisterListeners() {\n                var CiderHls = this.CiderHls;\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADING, this.onManifestLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_LOADING, this.onLevelLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n                CiderHls.off(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n              };\n              /**\n               * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n               */\n\n              _proto.createInternalLoader = function createInternalLoader(context) {\n                var config = this.CiderHls.config;\n                var PLoader = config.pLoader;\n                var Loader = config.loader;\n                var InternalLoader = PLoader || Loader;\n                var loader = new InternalLoader(config);\n                context.loader = loader;\n                this.loaders[context.type] = loader;\n                return loader;\n              };\n\n              _proto.getInternalLoader = function getInternalLoader(context) {\n                return this.loaders[context.type];\n              };\n\n              _proto.resetInternalLoader = function resetInternalLoader(contextType) {\n                if (this.loaders[contextType]) {\n                  delete this.loaders[contextType];\n                }\n              };\n              /**\n               * Call `destroy` on all internal loader instances mapped (one per context type)\n               */\n\n              _proto.destroyInternalLoaders = function destroyInternalLoaders() {\n                for (var contextType in this.loaders) {\n                  var loader = this.loaders[contextType];\n\n                  if (loader) {\n                    loader.destroy();\n                  }\n\n                  this.resetInternalLoader(contextType);\n                }\n              };\n\n              _proto.destroy = function destroy() {\n                this.unregisterListeners();\n                this.destroyInternalLoaders();\n              };\n\n              _proto.onManifestLoading = function onManifestLoading(event, data) {\n                var url = data.url;\n                this.load({\n                  id: null,\n                  groupId: null,\n                  level: 0,\n                  responseType: \"text\",\n                  type: _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].MANIFEST,\n                  url: url,\n                  deliveryDirectives: null,\n                });\n              };\n\n              _proto.onLevelLoading = function onLevelLoading(event, data) {\n                var id = data.id,\n                  level = data.level,\n                  url = data.url,\n                  deliveryDirectives = data.deliveryDirectives;\n                this.load({\n                  id: id,\n                  groupId: null,\n                  level: level,\n                  responseType: \"text\",\n                  type: _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].LEVEL,\n                  url: url,\n                  deliveryDirectives: deliveryDirectives,\n                });\n              };\n\n              _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {\n                var id = data.id,\n                  groupId = data.groupId,\n                  url = data.url,\n                  deliveryDirectives = data.deliveryDirectives;\n                this.load({\n                  id: id,\n                  groupId: groupId,\n                  level: null,\n                  responseType: \"text\",\n                  type: _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK,\n                  url: url,\n                  deliveryDirectives: deliveryDirectives,\n                });\n              };\n\n              _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {\n                var id = data.id,\n                  groupId = data.groupId,\n                  url = data.url,\n                  deliveryDirectives = data.deliveryDirectives;\n                this.load({\n                  id: id,\n                  groupId: groupId,\n                  level: null,\n                  responseType: \"text\",\n                  type: _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK,\n                  url: url,\n                  deliveryDirectives: deliveryDirectives,\n                });\n              };\n\n              _proto.load = function load(context) {\n                var _context$deliveryDire;\n\n                var config = this.CiderHls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n                // Check if a loader for this context already exists\n\n                var loader = this.getInternalLoader(context);\n\n                if (loader) {\n                  var loaderContext = loader.context;\n\n                  if (loaderContext && loaderContext.url === context.url) {\n                    // same URL can't overlap\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].trace(\"[playlist-loader]: playlist request ongoing\");\n                    return;\n                  }\n\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].log(\"[playlist-loader]: aborting previous loader for type: \" + context.type);\n                  loader.abort();\n                }\n\n                var maxRetry;\n                var timeout;\n                var retryDelay;\n                var maxRetryDelay; // apply different configs for retries depending on\n                // context (manifest, level, audio/subs playlist)\n\n                switch (context.type) {\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].MANIFEST:\n                    maxRetry = config.manifestLoadingMaxRetry;\n                    timeout = config.manifestLoadingTimeOut;\n                    retryDelay = config.manifestLoadingRetryDelay;\n                    maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n                    break;\n\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].LEVEL:\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK:\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK:\n                    // Manage retries in Level/Track Controller\n                    maxRetry = 0;\n                    timeout = config.levelLoadingTimeOut;\n                    break;\n\n                  default:\n                    maxRetry = config.levelLoadingMaxRetry;\n                    timeout = config.levelLoadingTimeOut;\n                    retryDelay = config.levelLoadingRetryDelay;\n                    maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n                    break;\n                }\n\n                loader = this.createInternalLoader(context); // Override level/track timeout for LL-CiderHls requests\n                // (the default of 10000ms is counter productive to blocking playlist reload requests)\n\n                if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {\n                  var levelDetails;\n\n                  if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].LEVEL && context.level !== null) {\n                    levelDetails = this.CiderHls.levels[context.level].details;\n                  } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK && context.id !== null) {\n                    levelDetails = this.CiderHls.audioTracks[context.id].details;\n                  } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK && context.id !== null) {\n                    levelDetails = this.CiderHls.subtitleTracks[context.id].details;\n                  }\n\n                  if (levelDetails) {\n                    var partTarget = levelDetails.partTarget;\n                    var targetDuration = levelDetails.targetduration;\n\n                    if (partTarget && targetDuration) {\n                      timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);\n                    }\n                  }\n                }\n\n                var loaderConfig = {\n                  timeout: timeout,\n                  maxRetry: maxRetry,\n                  retryDelay: retryDelay,\n                  maxRetryDelay: maxRetryDelay,\n                  highWaterMark: 0,\n                };\n                var loaderCallbacks = {\n                  onSuccess: this.loadsuccess.bind(this),\n                  onError: this.loaderror.bind(this),\n                  onTimeout: this.loadtimeout.bind(this),\n                }; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);\n\n                loader.load(context, loaderConfig, loaderCallbacks);\n              };\n\n              _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {\n                if (networkDetails === void 0) {\n                  networkDetails = null;\n                }\n\n                if (context.isSidxRequest) {\n                  this.handleSidxRequest(response, context);\n                  this.handlePlaylistLoaded(response, stats, context, networkDetails);\n                  return;\n                }\n\n                this.resetInternalLoader(context.type);\n                var string = response.data; // Validate if it is an M3U8 at all\n\n                if (string.indexOf(\"#EXTM3U\") !== 0) {\n                  this.handleManifestParsingError(response, context, \"no EXTM3U delimiter\", networkDetails);\n                  return;\n                }\n\n                stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n\n                if (string.indexOf(\"#EXTINF:\") > 0 || string.indexOf(\"#EXT-X-TARGETDURATION:\") > 0) {\n                  this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n                } else {\n                  this.handleMasterPlaylist(response, stats, context, networkDetails);\n                }\n              };\n\n              _proto.loaderror = function loaderror(response, context, networkDetails) {\n                if (networkDetails === void 0) {\n                  networkDetails = null;\n                }\n\n                this.handleNetworkError(context, networkDetails, false, response);\n              };\n\n              _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {\n                if (networkDetails === void 0) {\n                  networkDetails = null;\n                }\n\n                this.handleNetworkError(context, networkDetails, true);\n              };\n\n              _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {\n                var CiderHls = this.CiderHls;\n                var string = response.data;\n                var url = getResponseUrl(response, context);\n\n                var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__[\"default\"].parseMasterPlaylist(string, url),\n                  levels = _M3U8Parser$parseMast.levels,\n                  sessionData = _M3U8Parser$parseMast.sessionData;\n\n                if (!levels.length) {\n                  this.handleManifestParsingError(response, context, \"no level found in manifest\", networkDetails);\n                  return;\n                } // multi level playlist, parse level info\n\n                var audioGroups = levels.map(function (level) {\n                  return {\n                    id: level.attrs.AUDIO,\n                    audioCodec: level.audioCodec,\n                  };\n                });\n                var subtitleGroups = levels.map(function (level) {\n                  return {\n                    id: level.attrs.SUBTITLES,\n                    textCodec: level.textCodec,\n                  };\n                });\n                var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__[\"default\"].parseMasterPlaylistMedia(string, url, \"AUDIO\", audioGroups);\n                var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__[\"default\"].parseMasterPlaylistMedia(string, url, \"SUBTITLES\", subtitleGroups);\n                var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__[\"default\"].parseMasterPlaylistMedia(string, url, \"CLOSED-CAPTIONS\");\n\n                if (audioTracks.length) {\n                  // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n                  var embeddedAudioFound = audioTracks.some(function (audioTrack) {\n                    return !audioTrack.url;\n                  }); // if no embedded audio track defined, but audio codec signaled in quality level,\n                  // we need to signal this main audio track this could happen with playlists with\n                  // alt audio rendition in which quality levels (main)\n                  // contains both audio+video. but with mixed audio track not signaled\n\n                  if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].log(\"[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one\");\n                    audioTracks.unshift({\n                      type: \"main\",\n                      name: \"main\",\n                      default: false,\n                      autoselect: false,\n                      forced: false,\n                      id: -1,\n                      attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__[\"AttrList\"]({}),\n                      bitrate: 0,\n                      url: \"\",\n                    });\n                  }\n                }\n\n                CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADED, {\n                  levels: levels,\n                  audioTracks: audioTracks,\n                  subtitles: subtitles,\n                  captions: captions,\n                  url: url,\n                  stats: stats,\n                  networkDetails: networkDetails,\n                  sessionData: sessionData,\n                });\n              };\n\n              _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {\n                var CiderHls = this.CiderHls;\n                var id = context.id,\n                  level = context.level,\n                  type = context.type;\n                var url = getResponseUrl(response, context);\n                var levelUrlId = Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(id) ? id : 0;\n                var levelId = Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(level) ? level : levelUrlId;\n                var levelType = mapContextToLevelType(context);\n                var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__[\"default\"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n                if (!levelDetails.fragments.length) {\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorTypes\"].NETWORK_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].LEVEL_EMPTY_ERROR,\n                    fatal: false,\n                    url: url,\n                    reason: \"no fragments found in level\",\n                    level: typeof context.level === \"number\" ? context.level : undefined,\n                  });\n                  return;\n                } // We have done our first request (Manifest-type) and receive\n                // not a master playlist but a chunk-list (track/level)\n                // We fire the manifest-loaded event anyway with the parsed level-details\n                // by creating a single-level structure for it.\n\n                if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].MANIFEST) {\n                  var singleLevel = {\n                    attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__[\"AttrList\"]({}),\n                    bitrate: 0,\n                    details: levelDetails,\n                    name: \"\",\n                    url: url,\n                  };\n                  CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].MANIFEST_LOADED, {\n                    levels: [singleLevel],\n                    audioTracks: [],\n                    url: url,\n                    stats: stats,\n                    networkDetails: networkDetails,\n                    sessionData: null,\n                  });\n                } // save parsing time\n\n                stats.parsing.end = performance.now(); // in case we need SIDX ranges\n                // return early after calling load for\n                // the SIDX box.\n\n                if (levelDetails.needSidxRanges) {\n                  var _levelDetails$fragmen;\n\n                  var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url;\n                  this.load({\n                    url: sidxUrl,\n                    isSidxRequest: true,\n                    type: type,\n                    level: level,\n                    levelDetails: levelDetails,\n                    id: id,\n                    groupId: null,\n                    rangeStart: 0,\n                    rangeEnd: 2048,\n                    responseType: \"arraybuffer\",\n                    deliveryDirectives: null,\n                  });\n                  return;\n                } // extend the context with the new levelDetails property\n\n                context.levelDetails = levelDetails;\n                this.handlePlaylistLoaded(response, stats, context, networkDetails);\n              };\n\n              _proto.handleSidxRequest = function handleSidxRequest(response, context) {\n                var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__[\"parseSegmentIndex\"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return\n\n                if (!sidxInfo) {\n                  return;\n                }\n\n                var sidxReferences = sidxInfo.references;\n                var levelDetails = context.levelDetails;\n                sidxReferences.forEach(function (segmentRef, index) {\n                  var segRefInfo = segmentRef.info;\n                  var frag = levelDetails.fragments[index];\n\n                  if (frag.byteRange.length === 0) {\n                    frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + \"@\" + String(segRefInfo.start));\n                  }\n\n                  if (frag.initSegment) {\n                    frag.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + \"@0\");\n                  }\n                });\n              };\n\n              _proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, {\n                  type: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorTypes\"].NETWORK_ERROR,\n                  details: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].MANIFEST_PARSING_ERROR,\n                  fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].MANIFEST,\n                  url: response.url,\n                  reason: reason,\n                  response: response,\n                  context: context,\n                  networkDetails: networkDetails,\n                });\n              };\n\n              _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {\n                if (timeout === void 0) {\n                  timeout = false;\n                }\n\n                _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"[playlist-loader]: A network \" + (timeout ? \"timeout\" : \"error\") + \" occurred while loading \" + context.type + \" level: \" + context.level + \" id: \" + context.id + ' group-id: \"' + context.groupId + '\"');\n                var details = _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].UNKNOWN;\n                var fatal = false;\n                var loader = this.getInternalLoader(context);\n\n                switch (context.type) {\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].MANIFEST:\n                    details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].MANIFEST_LOAD_ERROR;\n                    fatal = true;\n                    break;\n\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].LEVEL:\n                    details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].LEVEL_LOAD_ERROR;\n                    fatal = false;\n                    break;\n\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK:\n                    details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].AUDIO_TRACK_LOAD_ERROR;\n                    fatal = false;\n                    break;\n\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK:\n                    details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorDetails\"].SUBTITLE_LOAD_ERROR;\n                    fatal = false;\n                    break;\n                }\n\n                if (loader) {\n                  this.resetInternalLoader(context.type);\n                }\n\n                var errorData = {\n                  type: _errors__WEBPACK_IMPORTED_MODULE_2__[\"ErrorTypes\"].NETWORK_ERROR,\n                  details: details,\n                  fatal: fatal,\n                  url: context.url,\n                  loader: loader,\n                  context: context,\n                  networkDetails: networkDetails,\n                };\n\n                if (response) {\n                  errorData.response = response;\n                }\n\n                this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].ERROR, errorData);\n              };\n\n              _proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {\n                var type = context.type,\n                  level = context.level,\n                  id = context.id,\n                  groupId = context.groupId,\n                  loader = context.loader,\n                  levelDetails = context.levelDetails,\n                  deliveryDirectives = context.deliveryDirectives;\n\n                if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {\n                  this.handleManifestParsingError(response, context, \"invalid target duration\", networkDetails);\n                  return;\n                }\n\n                if (!loader) {\n                  return;\n                }\n\n                if (levelDetails.live) {\n                  if (loader.getCacheAge) {\n                    levelDetails.ageHeader = loader.getCacheAge() || 0;\n                  }\n\n                  if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {\n                    levelDetails.ageHeader = 0;\n                  }\n                }\n\n                switch (type) {\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].MANIFEST:\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].LEVEL:\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].LEVEL_LOADED, {\n                      details: levelDetails,\n                      level: level || 0,\n                      id: id || 0,\n                      stats: stats,\n                      networkDetails: networkDetails,\n                      deliveryDirectives: deliveryDirectives,\n                    });\n                    break;\n\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].AUDIO_TRACK:\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].AUDIO_TRACK_LOADED, {\n                      details: levelDetails,\n                      id: id || 0,\n                      groupId: groupId || \"\",\n                      stats: stats,\n                      networkDetails: networkDetails,\n                      deliveryDirectives: deliveryDirectives,\n                    });\n                    break;\n\n                  case _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistContextType\"].SUBTITLE_TRACK:\n                    this.CiderHls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__[\"Events\"].SUBTITLE_TRACK_LOADED, {\n                      details: levelDetails,\n                      id: id || 0,\n                      groupId: groupId || \"\",\n                      stats: stats,\n                      networkDetails: networkDetails,\n                      deliveryDirectives: deliveryDirectives,\n                    });\n                    break;\n                }\n              };\n\n              return PlaylistLoader;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = PlaylistLoader;\n\n            /***/\n          },\n\n        /***/ \"./src/polyfills/number.ts\":\n          /*!*********************************!*\\\n  !*** ./src/polyfills/number.ts ***!\n  \\*********************************/\n          /*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFiniteNumber\", function () {\n              return isFiniteNumber;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"MAX_SAFE_INTEGER\", function () {\n              return MAX_SAFE_INTEGER;\n            });\n            var isFiniteNumber =\n              Number.isFinite ||\n              function (value) {\n                return typeof value === \"number\" && isFinite(value);\n              };\n            var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n\n            /***/\n          },\n\n        /***/ \"./src/remux/aac-helper.ts\":\n          /*!*********************************!*\\\n  !*** ./src/remux/aac-helper.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /**\n             *  AAC helper\n             */\n            var AAC = /*#__PURE__*/ (function () {\n              function AAC() {}\n\n              AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {\n                switch (codec) {\n                  case \"mp4a.40.2\":\n                    if (channelCount === 1) {\n                      return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n                    } else if (channelCount === 2) {\n                      return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n                    } else if (channelCount === 3) {\n                      return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n                    } else if (channelCount === 4) {\n                      return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n                    } else if (channelCount === 5) {\n                      return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n                    } else if (channelCount === 6) {\n                      return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);\n                    }\n\n                    break;\n                  // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n\n                  default:\n                    if (channelCount === 1) {\n                      // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n                      return new Uint8Array([\n                        0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n                        0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e,\n                      ]);\n                    } else if (channelCount === 2) {\n                      // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n                      return new Uint8Array([\n                        0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n                        0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e,\n                      ]);\n                    } else if (channelCount === 3) {\n                      // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n                      return new Uint8Array([\n                        0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n                        0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e,\n                      ]);\n                    }\n\n                    break;\n                }\n\n                return undefined;\n              };\n\n              return AAC;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = AAC;\n\n            /***/\n          },\n\n        /***/ \"./src/remux/mp4-generator.ts\":\n          /*!************************************!*\\\n  !*** ./src/remux/mp4-generator.ts ***!\n  \\************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /**\n             * Generate MP4 Box\n             */\n            var UINT32_MAX = Math.pow(2, 32) - 1;\n\n            var MP4 = /*#__PURE__*/ (function () {\n              function MP4() {}\n\n              MP4.init = function init() {\n                MP4.types = {\n                  avc1: [],\n                  // codingname\n                  avcC: [],\n                  btrt: [],\n                  dinf: [],\n                  dref: [],\n                  esds: [],\n                  ftyp: [],\n                  hdlr: [],\n                  mdat: [],\n                  mdhd: [],\n                  mdia: [],\n                  mfhd: [],\n                  minf: [],\n                  moof: [],\n                  moov: [],\n                  mp4a: [],\n                  \".mp3\": [],\n                  mvex: [],\n                  mvhd: [],\n                  pasp: [],\n                  sdtp: [],\n                  stbl: [],\n                  stco: [],\n                  stsc: [],\n                  stsd: [],\n                  stsz: [],\n                  stts: [],\n                  tfdt: [],\n                  tfhd: [],\n                  traf: [],\n                  trak: [],\n                  trun: [],\n                  trex: [],\n                  tkhd: [],\n                  vmhd: [],\n                  smhd: [],\n                };\n                var i;\n\n                for (i in MP4.types) {\n                  if (MP4.types.hasOwnProperty(i)) {\n                    MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];\n                  }\n                }\n\n                var videoHdlr = new Uint8Array([\n                  0x00, // version 0\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // pre_defined\n                  0x76,\n                  0x69,\n                  0x64,\n                  0x65, // handler_type: 'vide'\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x56,\n                  0x69,\n                  0x64,\n                  0x65,\n                  0x6f,\n                  0x48,\n                  0x61,\n                  0x6e,\n                  0x64,\n                  0x6c,\n                  0x65,\n                  0x72,\n                  0x00, // name: 'VideoHandler'\n                ]);\n                var audioHdlr = new Uint8Array([\n                  0x00, // version 0\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // pre_defined\n                  0x73,\n                  0x6f,\n                  0x75,\n                  0x6e, // handler_type: 'soun'\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x53,\n                  0x6f,\n                  0x75,\n                  0x6e,\n                  0x64,\n                  0x48,\n                  0x61,\n                  0x6e,\n                  0x64,\n                  0x6c,\n                  0x65,\n                  0x72,\n                  0x00, // name: 'SoundHandler'\n                ]);\n                MP4.HDLR_TYPES = {\n                  video: videoHdlr,\n                  audio: audioHdlr,\n                };\n                var dref = new Uint8Array([\n                  0x00, // version 0\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x01, // entry_count\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x0c, // entry_size\n                  0x75,\n                  0x72,\n                  0x6c,\n                  0x20, // 'url' type\n                  0x00, // version 0\n                  0x00,\n                  0x00,\n                  0x01, // entry_flags\n                ]);\n                var stco = new Uint8Array([\n                  0x00, // version\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // entry_count\n                ]);\n                MP4.STTS = MP4.STSC = MP4.STCO = stco;\n                MP4.STSZ = new Uint8Array([\n                  0x00, // version\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // sample_size\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // sample_count\n                ]);\n                MP4.VMHD = new Uint8Array([\n                  0x00, // version\n                  0x00,\n                  0x00,\n                  0x01, // flags\n                  0x00,\n                  0x00, // graphicsmode\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // opcolor\n                ]);\n                MP4.SMHD = new Uint8Array([\n                  0x00, // version\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00, // balance\n                  0x00,\n                  0x00, // reserved\n                ]);\n                MP4.STSD = new Uint8Array([\n                  0x00, // version 0\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x01,\n                ]); // entry_count\n\n                var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n\n                var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n\n                var minorVersion = new Uint8Array([0, 0, 0, 1]);\n                MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n                MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n              };\n\n              MP4.box = function box(type) {\n                var size = 8;\n\n                for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n                  payload[_key - 1] = arguments[_key];\n                }\n\n                var i = payload.length;\n                var len = i; // calculate the total size we need to allocate\n\n                while (i--) {\n                  size += payload[i].byteLength;\n                }\n\n                var result = new Uint8Array(size);\n                result[0] = (size >> 24) & 0xff;\n                result[1] = (size >> 16) & 0xff;\n                result[2] = (size >> 8) & 0xff;\n                result[3] = size & 0xff;\n                result.set(type, 4); // copy the payload into the result\n\n                for (i = 0, size = 8; i < len; i++) {\n                  // copy payload[i] array @ offset size\n                  result.set(payload[i], size);\n                  size += payload[i].byteLength;\n                }\n\n                return result;\n              };\n\n              MP4.hdlr = function hdlr(type) {\n                return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n              };\n\n              MP4.mdat = function mdat(data) {\n                return MP4.box(MP4.types.mdat, data);\n              };\n\n              MP4.mdhd = function mdhd(timescale, duration) {\n                duration *= timescale;\n                var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n                var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n                return MP4.box(\n                  MP4.types.mdhd,\n                  new Uint8Array([\n                    0x01, // version 1\n                    0x00,\n                    0x00,\n                    0x00, // flags\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x02, // creation_time\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x03, // modification_time\n                    (timescale >> 24) & 0xff,\n                    (timescale >> 16) & 0xff,\n                    (timescale >> 8) & 0xff,\n                    timescale & 0xff, // timescale\n                    upperWordDuration >> 24,\n                    (upperWordDuration >> 16) & 0xff,\n                    (upperWordDuration >> 8) & 0xff,\n                    upperWordDuration & 0xff,\n                    lowerWordDuration >> 24,\n                    (lowerWordDuration >> 16) & 0xff,\n                    (lowerWordDuration >> 8) & 0xff,\n                    lowerWordDuration & 0xff,\n                    0x55,\n                    0xc4, // 'und' language (undetermined)\n                    0x00,\n                    0x00,\n                  ])\n                );\n              };\n\n              MP4.mdia = function mdia(track) {\n                return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));\n              };\n\n              MP4.mfhd = function mfhd(sequenceNumber) {\n                return MP4.box(\n                  MP4.types.mfhd,\n                  new Uint8Array([\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // flags\n                    sequenceNumber >> 24,\n                    (sequenceNumber >> 16) & 0xff,\n                    (sequenceNumber >> 8) & 0xff,\n                    sequenceNumber & 0xff, // sequence_number\n                  ])\n                );\n              };\n\n              MP4.minf = function minf(track) {\n                if (track.type === \"audio\") {\n                  return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n                } else {\n                  return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n                }\n              };\n\n              MP4.moof = function moof(sn, baseMediaDecodeTime, track) {\n                return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));\n              };\n              /**\n               * @param tracks... (optional) {array} the tracks associated with this movie\n               */\n\n              MP4.moov = function moov(tracks) {\n                var i = tracks.length;\n                var boxes = [];\n\n                while (i--) {\n                  boxes[i] = MP4.trak(tracks[i]);\n                }\n\n                return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));\n              };\n\n              MP4.mvex = function mvex(tracks) {\n                var i = tracks.length;\n                var boxes = [];\n\n                while (i--) {\n                  boxes[i] = MP4.trex(tracks[i]);\n                }\n\n                return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n              };\n\n              MP4.mvhd = function mvhd(timescale, duration) {\n                duration *= timescale;\n                var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n                var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n                var bytes = new Uint8Array([\n                  0x01, // version 1\n                  0x00,\n                  0x00,\n                  0x00, // flags\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x02, // creation_time\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x03, // modification_time\n                  (timescale >> 24) & 0xff,\n                  (timescale >> 16) & 0xff,\n                  (timescale >> 8) & 0xff,\n                  timescale & 0xff, // timescale\n                  upperWordDuration >> 24,\n                  (upperWordDuration >> 16) & 0xff,\n                  (upperWordDuration >> 8) & 0xff,\n                  upperWordDuration & 0xff,\n                  lowerWordDuration >> 24,\n                  (lowerWordDuration >> 16) & 0xff,\n                  (lowerWordDuration >> 8) & 0xff,\n                  lowerWordDuration & 0xff,\n                  0x00,\n                  0x01,\n                  0x00,\n                  0x00, // 1.0 rate\n                  0x01,\n                  0x00, // 1.0 volume\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // reserved\n                  0x00,\n                  0x01,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x01,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x40,\n                  0x00,\n                  0x00,\n                  0x00, // transformation: unity matrix\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00,\n                  0x00, // pre_defined\n                  0xff,\n                  0xff,\n                  0xff,\n                  0xff, // next_track_ID\n                ]);\n                return MP4.box(MP4.types.mvhd, bytes);\n              };\n\n              MP4.sdtp = function sdtp(track) {\n                var samples = track.samples || [];\n                var bytes = new Uint8Array(4 + samples.length);\n                var i;\n                var flags; // leave the full box header (4 bytes) all zero\n                // write the sample table\n\n                for (i = 0; i < samples.length; i++) {\n                  flags = samples[i].flags;\n                  bytes[i + 4] = (flags.dependsOn << 4) | (flags.isDependedOn << 2) | flags.hasRedundancy;\n                }\n\n                return MP4.box(MP4.types.sdtp, bytes);\n              };\n\n              MP4.stbl = function stbl(track) {\n                return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));\n              };\n\n              MP4.avc1 = function avc1(track) {\n                var sps = [];\n                var pps = [];\n                var i;\n                var data;\n                var len; // assemble the SPSs\n\n                for (i = 0; i < track.sps.length; i++) {\n                  data = track.sps[i];\n                  len = data.byteLength;\n                  sps.push((len >>> 8) & 0xff);\n                  sps.push(len & 0xff); // SPS\n\n                  sps = sps.concat(Array.prototype.slice.call(data));\n                } // assemble the PPSs\n\n                for (i = 0; i < track.pps.length; i++) {\n                  data = track.pps[i];\n                  len = data.byteLength;\n                  pps.push((len >>> 8) & 0xff);\n                  pps.push(len & 0xff);\n                  pps = pps.concat(Array.prototype.slice.call(data));\n                }\n\n                var avcc = MP4.box(\n                  MP4.types.avcC,\n                  new Uint8Array(\n                    [\n                      0x01, // version\n                      sps[3], // profile\n                      sps[4], // profile compat\n                      sps[5], // level\n                      0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n                      0xe0 | track.sps.length, // 3bit reserved (111) + numOfSequenceParameterSets\n                    ]\n                      .concat(sps)\n                      .concat([\n                        track.pps.length, // numOfPictureParameterSets\n                      ])\n                      .concat(pps)\n                  )\n                ); // \"PPS\"\n\n                var width = track.width;\n                var height = track.height;\n                var hSpacing = track.pixelRatio[0];\n                var vSpacing = track.pixelRatio[1];\n                return MP4.box(\n                  MP4.types.avc1,\n                  new Uint8Array([\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x01, // data_reference_index\n                    0x00,\n                    0x00, // pre_defined\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // pre_defined\n                    (width >> 8) & 0xff,\n                    width & 0xff, // width\n                    (height >> 8) & 0xff,\n                    height & 0xff, // height\n                    0x00,\n                    0x48,\n                    0x00,\n                    0x00, // horizresolution\n                    0x00,\n                    0x48,\n                    0x00,\n                    0x00, // vertresolution\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x01, // frame_count\n                    0x12,\n                    0x64,\n                    0x61,\n                    0x69,\n                    0x6c, // dailymotion/CiderHls.js\n                    0x79,\n                    0x6d,\n                    0x6f,\n                    0x74,\n                    0x69,\n                    0x6f,\n                    0x6e,\n                    0x2f,\n                    0x68,\n                    0x6c,\n                    0x73,\n                    0x2e,\n                    0x6a,\n                    0x73,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // compressorname\n                    0x00,\n                    0x18, // depth = 24\n                    0x11,\n                    0x11,\n                  ]), // pre_defined = -1\n                  avcc,\n                  MP4.box(\n                    MP4.types.btrt,\n                    new Uint8Array([\n                      0x00,\n                      0x1c,\n                      0x9c,\n                      0x80, // bufferSizeDB\n                      0x00,\n                      0x2d,\n                      0xc6,\n                      0xc0, // maxBitrate\n                      0x00,\n                      0x2d,\n                      0xc6,\n                      0xc0,\n                    ])\n                  ), // avgBitrate\n                  MP4.box(\n                    MP4.types.pasp,\n                    new Uint8Array([\n                      hSpacing >> 24, // hSpacing\n                      (hSpacing >> 16) & 0xff,\n                      (hSpacing >> 8) & 0xff,\n                      hSpacing & 0xff,\n                      vSpacing >> 24, // vSpacing\n                      (vSpacing >> 16) & 0xff,\n                      (vSpacing >> 8) & 0xff,\n                      vSpacing & 0xff,\n                    ])\n                  )\n                );\n              };\n\n              MP4.esds = function esds(track) {\n                var configlen = track.config.length;\n                return new Uint8Array(\n                  [\n                    0x00, // version 0\n                    0x00,\n                    0x00,\n                    0x00, // flags\n                    0x03, // descriptor_type\n                    0x17 + configlen, // length\n                    0x00,\n                    0x01, // es_id\n                    0x00, // stream_priority\n                    0x04, // descriptor_type\n                    0x0f + configlen, // length\n                    0x40, // codec : mpeg4_audio\n                    0x15, // stream_type\n                    0x00,\n                    0x00,\n                    0x00, // buffer_size\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // maxBitrate\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // avgBitrate\n                    0x05, // descriptor_type\n                  ]\n                    .concat([configlen])\n                    .concat(track.config)\n                    .concat([0x06, 0x01, 0x02])\n                ); // GASpecificConfig)); // length + audio config descriptor\n              };\n\n              MP4.mp4a = function mp4a(track) {\n                var samplerate = track.samplerate;\n                return MP4.box(\n                  MP4.types.mp4a,\n                  new Uint8Array([\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x01, // data_reference_index\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    track.channelCount, // channelcount\n                    0x00,\n                    0x10, // sampleSize:16bits\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved2\n                    (samplerate >> 8) & 0xff,\n                    samplerate & 0xff, //\n                    0x00,\n                    0x00,\n                  ]),\n                  MP4.box(MP4.types.esds, MP4.esds(track))\n                );\n              };\n\n              MP4.mp3 = function mp3(track) {\n                var samplerate = track.samplerate;\n                return MP4.box(\n                  MP4.types[\".mp3\"],\n                  new Uint8Array([\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x01, // data_reference_index\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    track.channelCount, // channelcount\n                    0x00,\n                    0x10, // sampleSize:16bits\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved2\n                    (samplerate >> 8) & 0xff,\n                    samplerate & 0xff, //\n                    0x00,\n                    0x00,\n                  ])\n                );\n              };\n\n              MP4.stsd = function stsd(track) {\n                if (track.type === \"audio\") {\n                  if (!track.isAAC && track.codec === \"mp3\") {\n                    return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n                  }\n\n                  return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n                } else {\n                  return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n                }\n              };\n\n              MP4.tkhd = function tkhd(track) {\n                var id = track.id;\n                var duration = track.duration * track.timescale;\n                var width = track.width;\n                var height = track.height;\n                var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n                var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n                return MP4.box(\n                  MP4.types.tkhd,\n                  new Uint8Array([\n                    0x01, // version 1\n                    0x00,\n                    0x00,\n                    0x07, // flags\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x02, // creation_time\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x03, // modification_time\n                    (id >> 24) & 0xff,\n                    (id >> 16) & 0xff,\n                    (id >> 8) & 0xff,\n                    id & 0xff, // track_ID\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    upperWordDuration >> 24,\n                    (upperWordDuration >> 16) & 0xff,\n                    (upperWordDuration >> 8) & 0xff,\n                    upperWordDuration & 0xff,\n                    lowerWordDuration >> 24,\n                    (lowerWordDuration >> 16) & 0xff,\n                    (lowerWordDuration >> 8) & 0xff,\n                    lowerWordDuration & 0xff,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x00, // layer\n                    0x00,\n                    0x00, // alternate_group\n                    0x00,\n                    0x00, // non-audio track volume\n                    0x00,\n                    0x00, // reserved\n                    0x00,\n                    0x01,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x01,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x40,\n                    0x00,\n                    0x00,\n                    0x00, // transformation: unity matrix\n                    (width >> 8) & 0xff,\n                    width & 0xff,\n                    0x00,\n                    0x00, // width\n                    (height >> 8) & 0xff,\n                    height & 0xff,\n                    0x00,\n                    0x00, // height\n                  ])\n                );\n              };\n\n              MP4.traf = function traf(track, baseMediaDecodeTime) {\n                var sampleDependencyTable = MP4.sdtp(track);\n                var id = track.id;\n                var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n                var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n                return MP4.box(\n                  MP4.types.traf,\n                  MP4.box(\n                    MP4.types.tfhd,\n                    new Uint8Array([\n                      0x00, // version 0\n                      0x00,\n                      0x00,\n                      0x00, // flags\n                      id >> 24,\n                      (id >> 16) & 0xff,\n                      (id >> 8) & 0xff,\n                      id & 0xff, // track_ID\n                    ])\n                  ),\n                  MP4.box(\n                    MP4.types.tfdt,\n                    new Uint8Array([\n                      0x01, // version 1\n                      0x00,\n                      0x00,\n                      0x00, // flags\n                      upperWordBaseMediaDecodeTime >> 24,\n                      (upperWordBaseMediaDecodeTime >> 16) & 0xff,\n                      (upperWordBaseMediaDecodeTime >> 8) & 0xff,\n                      upperWordBaseMediaDecodeTime & 0xff,\n                      lowerWordBaseMediaDecodeTime >> 24,\n                      (lowerWordBaseMediaDecodeTime >> 16) & 0xff,\n                      (lowerWordBaseMediaDecodeTime >> 8) & 0xff,\n                      lowerWordBaseMediaDecodeTime & 0xff,\n                    ])\n                  ),\n                  MP4.trun(\n                    track,\n                    sampleDependencyTable.length +\n                      16 + // tfhd\n                      20 + // tfdt\n                      8 + // traf header\n                      16 + // mfhd\n                      8 + // moof header\n                      8\n                  ), // mdat header\n                  sampleDependencyTable\n                );\n              };\n              /**\n               * Generate a track box.\n               * @param track {object} a track definition\n               * @return {Uint8Array} the track box\n               */\n\n              MP4.trak = function trak(track) {\n                track.duration = track.duration || 0xffffffff;\n                return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n              };\n\n              MP4.trex = function trex(track) {\n                var id = track.id;\n                return MP4.box(\n                  MP4.types.trex,\n                  new Uint8Array([\n                    0x00, // version 0\n                    0x00,\n                    0x00,\n                    0x00, // flags\n                    id >> 24,\n                    (id >> 16) & 0xff,\n                    (id >> 8) & 0xff,\n                    id & 0xff, // track_ID\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x01, // default_sample_description_index\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // default_sample_duration\n                    0x00,\n                    0x00,\n                    0x00,\n                    0x00, // default_sample_size\n                    0x00,\n                    0x01,\n                    0x00,\n                    0x01, // default_sample_flags\n                  ])\n                );\n              };\n\n              MP4.trun = function trun(track, offset) {\n                var samples = track.samples || [];\n                var len = samples.length;\n                var arraylen = 12 + 16 * len;\n                var array = new Uint8Array(arraylen);\n                var i;\n                var sample;\n                var duration;\n                var size;\n                var flags;\n                var cts;\n                offset += 8 + arraylen;\n                array.set(\n                  [\n                    0x00, // version 0\n                    0x00,\n                    0x0f,\n                    0x01, // flags\n                    (len >>> 24) & 0xff,\n                    (len >>> 16) & 0xff,\n                    (len >>> 8) & 0xff,\n                    len & 0xff, // sample_count\n                    (offset >>> 24) & 0xff,\n                    (offset >>> 16) & 0xff,\n                    (offset >>> 8) & 0xff,\n                    offset & 0xff, // data_offset\n                  ],\n                  0\n                );\n\n                for (i = 0; i < len; i++) {\n                  sample = samples[i];\n                  duration = sample.duration;\n                  size = sample.size;\n                  flags = sample.flags;\n                  cts = sample.cts;\n                  array.set(\n                    [\n                      (duration >>> 24) & 0xff,\n                      (duration >>> 16) & 0xff,\n                      (duration >>> 8) & 0xff,\n                      duration & 0xff, // sample_duration\n                      (size >>> 24) & 0xff,\n                      (size >>> 16) & 0xff,\n                      (size >>> 8) & 0xff,\n                      size & 0xff, // sample_size\n                      (flags.isLeading << 2) | flags.dependsOn,\n                      (flags.isDependedOn << 6) | (flags.hasRedundancy << 4) | (flags.paddingValue << 1) | flags.isNonSync,\n                      flags.degradPrio & (0xf0 << 8),\n                      flags.degradPrio & 0x0f, // sample_flags\n                      (cts >>> 24) & 0xff,\n                      (cts >>> 16) & 0xff,\n                      (cts >>> 8) & 0xff,\n                      cts & 0xff, // sample_composition_time_offset\n                    ],\n                    12 + 16 * i\n                  );\n                }\n\n                return MP4.box(MP4.types.trun, array);\n              };\n\n              MP4.initSegment = function initSegment(tracks) {\n                if (!MP4.types) {\n                  MP4.init();\n                }\n\n                var movie = MP4.moov(tracks);\n                var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n                result.set(MP4.FTYP);\n                result.set(movie, MP4.FTYP.byteLength);\n                return result;\n              };\n\n              return MP4;\n            })();\n\n            MP4.types = void 0;\n            MP4.HDLR_TYPES = void 0;\n            MP4.STTS = void 0;\n            MP4.STSC = void 0;\n            MP4.STCO = void 0;\n            MP4.STSZ = void 0;\n            MP4.VMHD = void 0;\n            MP4.SMHD = void 0;\n            MP4.STSD = void 0;\n            MP4.FTYP = void 0;\n            MP4.DINF = void 0;\n            /* harmony default export */ __webpack_exports__[\"default\"] = MP4;\n\n            /***/\n          },\n\n        /***/ \"./src/remux/mp4-remuxer.ts\":\n          /*!**********************************!*\\\n  !*** ./src/remux/mp4-remuxer.ts ***!\n  \\**********************************/\n          /*! exports provided: default, normalizePts */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return MP4Remuxer;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"normalizePts\", function () {\n              return normalizePts;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ \"./src/remux/aac-helper.ts\");\n            /* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ \"./src/remux/mp4-generator.ts\");\n            /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ \"./src/events.ts\");\n            /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ \"./src/errors.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ \"./src/types/loader.ts\");\n            /* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ \"./src/utils/timescale-conversion.ts\");\n\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds\n\n            var AAC_SAMPLES_PER_FRAME = 1024;\n            var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;\n            var chromeVersion = null;\n            var safariWebkitVersion = null;\n            var requiresPositiveDts = false;\n\n            var MP4Remuxer = /*#__PURE__*/ (function () {\n              function MP4Remuxer(observer, config, typeSupported, vendor) {\n                if (vendor === void 0) {\n                  vendor = \"\";\n                }\n\n                this.observer = void 0;\n                this.config = void 0;\n                this.typeSupported = void 0;\n                this.ISGenerated = false;\n                this._initPTS = void 0;\n                this._initDTS = void 0;\n                this.nextAvcDts = null;\n                this.nextAudioPts = null;\n                this.isAudioContiguous = false;\n                this.isVideoContiguous = false;\n                this.observer = observer;\n                this.config = config;\n                this.typeSupported = typeSupported;\n                this.ISGenerated = false;\n\n                if (chromeVersion === null) {\n                  var userAgent = navigator.userAgent || \"\";\n                  var result = userAgent.match(/Chrome\\/(\\d+)/i);\n                  chromeVersion = result ? parseInt(result[1]) : 0;\n                }\n\n                if (safariWebkitVersion === null) {\n                  var _result = navigator.userAgent.match(/Safari\\/(\\d+)/i);\n\n                  safariWebkitVersion = _result ? parseInt(_result[1]) : 0;\n                }\n\n                requiresPositiveDts = (!!chromeVersion && chromeVersion < 75) || (!!safariWebkitVersion && safariWebkitVersion < 600);\n              }\n\n              var _proto = MP4Remuxer.prototype;\n\n              _proto.destroy = function destroy() {};\n\n              _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].log(\"[mp4-remuxer]: initPTS & initDTS reset\");\n                this._initPTS = this._initDTS = defaultTimeStamp;\n              };\n\n              _proto.resetNextTimestamp = function resetNextTimestamp() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].log(\"[mp4-remuxer]: reset next timestamp\");\n                this.isVideoContiguous = false;\n                this.isAudioContiguous = false;\n              };\n\n              _proto.resetInitSegment = function resetInitSegment() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].log(\"[mp4-remuxer]: ISGenerated flag reset\");\n                this.ISGenerated = false;\n              };\n\n              _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {\n                var rolloverDetected = false;\n                var startPTS = videoSamples.reduce(function (minPTS, sample) {\n                  var delta = sample.pts - minPTS;\n\n                  if (delta < -4294967296) {\n                    // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n                    rolloverDetected = true;\n                    return normalizePts(minPTS, sample.pts);\n                  } else if (delta > 0) {\n                    return minPTS;\n                  } else {\n                    return sample.pts;\n                  }\n                }, videoSamples[0].pts);\n\n                if (rolloverDetected) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].debug(\"PTS rollover detected\");\n                }\n\n                return startPTS;\n              };\n\n              _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {\n                var video;\n                var audio;\n                var initSegment;\n                var text;\n                var id3;\n                var independent;\n                var audioTimeOffset = timeOffset;\n                var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.\n                // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the \"pid\"\n                // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.\n                // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),\n                // then we can remux one track without waiting for the other.\n\n                var hasAudio = audioTrack.pid > -1;\n                var hasVideo = videoTrack.pid > -1;\n                var length = videoTrack.samples.length;\n                var enoughAudioSamples = audioTrack.samples.length > 0;\n                var enoughVideoSamples = length > 1;\n                var canRemuxAvc = ((!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples)) || this.ISGenerated || flush;\n\n                if (canRemuxAvc) {\n                  if (!this.ISGenerated) {\n                    initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);\n                  }\n\n                  var isVideoContiguous = this.isVideoContiguous;\n                  var firstKeyFrameIndex = -1;\n\n                  if (enoughVideoSamples) {\n                    firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);\n\n                    if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {\n                      independent = true;\n\n                      if (firstKeyFrameIndex > 0) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"[mp4-remuxer]: Dropped \" + firstKeyFrameIndex + \" out of \" + length + \" video samples due to a missing keyframe\");\n                        var startPTS = this.getVideoStartPts(videoTrack.samples);\n                        videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);\n                        videoTrack.dropped += firstKeyFrameIndex;\n                        videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000);\n                      } else if (firstKeyFrameIndex === -1) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"[mp4-remuxer]: No keyframe found out of \" + length + \" video samples\");\n                        independent = false;\n                      }\n                    }\n                  }\n\n                  if (this.ISGenerated) {\n                    if (enoughAudioSamples && enoughVideoSamples) {\n                      // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n                      // if first audio DTS is not aligned with first video DTS then we need to take that into account\n                      // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n                      // drift between audio and video streams\n                      var _startPTS = this.getVideoStartPts(videoTrack.samples);\n\n                      var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;\n\n                      var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n                      audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n                      videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n                    } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.\n\n                    if (enoughAudioSamples) {\n                      // if initSegment was generated without audio samples, regenerate it again\n                      if (!audioTrack.samplerate) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"[mp4-remuxer]: regenerate InitSegment as audio detected\");\n                        initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);\n                      }\n\n                      audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__[\"PlaylistLevelType\"].AUDIO ? videoTimeOffset : undefined);\n\n                      if (enoughVideoSamples) {\n                        var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again\n\n                        if (!videoTrack.inputTimeScale) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"[mp4-remuxer]: regenerate InitSegment as video detected\");\n                          initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);\n                        }\n\n                        video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);\n                      }\n                    } else if (enoughVideoSamples) {\n                      video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);\n                    }\n\n                    if (video) {\n                      video.firstKeyFrame = firstKeyFrameIndex;\n                      video.independent = firstKeyFrameIndex !== -1;\n                    }\n                  }\n                } // Allow ID3 and text to remux, even if more audio/video samples are required\n\n                if (this.ISGenerated) {\n                  if (id3Track.samples.length) {\n                    id3 = this.remuxID3(id3Track, timeOffset);\n                  }\n\n                  if (textTrack.samples.length) {\n                    text = this.remuxText(textTrack, timeOffset);\n                  }\n                }\n\n                return {\n                  audio: audio,\n                  video: video,\n                  initSegment: initSegment,\n                  independent: independent,\n                  text: text,\n                  id3: id3,\n                };\n              };\n\n              _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {\n                var audioSamples = audioTrack.samples;\n                var videoSamples = videoTrack.samples;\n                var typeSupported = this.typeSupported;\n                var tracks = {};\n                var computePTSDTS = !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(this._initPTS);\n                var container = \"audio/mp4\";\n                var initPTS;\n                var initDTS;\n                var timescale;\n\n                if (computePTSDTS) {\n                  initPTS = initDTS = Infinity;\n                }\n\n                if (audioTrack.config && audioSamples.length) {\n                  // let's use audio sampling rate as MP4 time scale.\n                  // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n                  // using audio sampling rate here helps having an integer MP4 frame duration\n                  // this avoids potential rounding issue and AV sync issue\n                  audioTrack.timescale = audioTrack.samplerate;\n\n                  if (!audioTrack.isAAC) {\n                    if (typeSupported.mpeg) {\n                      // Chrome and Safari\n                      container = \"audio/mpeg\";\n                      audioTrack.codec = \"\";\n                    } else if (typeSupported.mp3) {\n                      // Firefox\n                      audioTrack.codec = \"mp3\";\n                    }\n                  }\n\n                  tracks.audio = {\n                    id: \"audio\",\n                    container: container,\n                    codec: audioTrack.codec,\n                    initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__[\"default\"].initSegment([audioTrack]),\n                    metadata: {\n                      channelCount: audioTrack.channelCount,\n                    },\n                  };\n\n                  if (computePTSDTS) {\n                    timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS\n\n                    initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);\n                  }\n                }\n\n                if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n                  // let's use input time scale as MP4 video timescale\n                  // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n                  videoTrack.timescale = videoTrack.inputTimeScale;\n                  tracks.video = {\n                    id: \"main\",\n                    container: \"video/mp4\",\n                    codec: videoTrack.codec,\n                    initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__[\"default\"].initSegment([videoTrack]),\n                    metadata: {\n                      width: videoTrack.width,\n                      height: videoTrack.height,\n                    },\n                  };\n\n                  if (computePTSDTS) {\n                    timescale = videoTrack.inputTimeScale;\n                    var startPTS = this.getVideoStartPts(videoSamples);\n                    var startOffset = Math.round(timescale * timeOffset);\n                    initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);\n                    initPTS = Math.min(initPTS, startPTS - startOffset);\n                  }\n                }\n\n                if (Object.keys(tracks).length) {\n                  this.ISGenerated = true;\n\n                  if (computePTSDTS) {\n                    this._initPTS = initPTS;\n                    this._initDTS = initDTS;\n                  }\n\n                  return {\n                    tracks: tracks,\n                    initPTS: initPTS,\n                    timescale: timescale,\n                  };\n                }\n              };\n\n              _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {\n                var timeScale = track.inputTimeScale;\n                var inputSamples = track.samples;\n                var outputSamples = [];\n                var nbSamples = inputSamples.length;\n                var initPTS = this._initPTS;\n                var nextAvcDts = this.nextAvcDts;\n                var offset = 8;\n                var mp4SampleDuration;\n                var firstDTS;\n                var lastDTS;\n                var minPTS = Number.POSITIVE_INFINITY;\n                var maxPTS = Number.NEGATIVE_INFINITY;\n                var ptsDtsShift = 0;\n                var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n\n                if (!contiguous || nextAvcDts === null) {\n                  var pts = timeOffset * timeScale;\n                  var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset\n\n                  nextAvcDts = pts - cts;\n                } // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n                // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n\n                for (var i = 0; i < nbSamples; i++) {\n                  var sample = inputSamples[i];\n                  sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);\n                  sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);\n\n                  if (sample.dts > sample.pts) {\n                    var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2;\n                    ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);\n                  }\n\n                  if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n                    sortSamples = true;\n                  }\n                } // sort video samples by DTS then PTS then demux id order\n\n                if (sortSamples) {\n                  inputSamples.sort(function (a, b) {\n                    var deltadts = a.dts - b.dts;\n                    var deltapts = a.pts - b.pts;\n                    return deltadts || deltapts;\n                  });\n                } // Get first/last DTS\n\n                firstDTS = inputSamples[0].dts;\n                lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples\n                // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n                // set this constant duration as being the avg delta between consecutive DTS.\n\n                var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds\n\n                if (ptsDtsShift < 0) {\n                  if (ptsDtsShift < averageSampleDuration * -2) {\n                    // Fix for \"CNN special report, with CC\" in test-streams (including Safari browser)\n                    // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"PTS < DTS detected in video samples, offsetting DTS from PTS by \" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(-averageSampleDuration, true) + \" ms\");\n                    var lastDts = ptsDtsShift;\n\n                    for (var _i = 0; _i < nbSamples; _i++) {\n                      inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);\n                      inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);\n                    }\n                  } else {\n                    // Fix for \"Custom IV with bad PTS DTS\" in test-streams\n                    // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"PTS < DTS detected in video samples, shifting DTS by \" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(ptsDtsShift, true) + \" ms to overcome this issue\");\n\n                    for (var _i2 = 0; _i2 < nbSamples; _i2++) {\n                      inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;\n                    }\n                  }\n\n                  firstDTS = inputSamples[0].dts;\n                } // if fragment are contiguous, detect hole/overlapping between fragments\n\n                if (contiguous) {\n                  // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n                  var delta = firstDTS - nextAvcDts;\n                  var foundHole = delta > averageSampleDuration;\n                  var foundOverlap = delta < -1;\n\n                  if (foundHole || foundOverlap) {\n                    if (foundHole) {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"AVC: \" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(delta, true) + \" ms (\" + delta + \"dts) hole between fragments detected, filling it\");\n                    } else {\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"AVC: \" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(-delta, true) + \" ms (\" + delta + \"dts) overlapping between fragments detected\");\n                    }\n\n                    firstDTS = nextAvcDts;\n                    var firstPTS = inputSamples[0].pts - delta;\n                    inputSamples[0].dts = firstDTS;\n                    inputSamples[0].pts = firstPTS;\n                    _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].log(\n                      \"Video: First PTS/DTS adjusted: \" +\n                        Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(firstPTS, true) +\n                        \"/\" +\n                        Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(firstDTS, true) +\n                        \", delta: \" +\n                        Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__[\"toMsFromMpegTsClock\"])(delta, true) +\n                        \" ms\"\n                    );\n                  }\n                }\n\n                if (requiresPositiveDts) {\n                  firstDTS = Math.max(0, firstDTS);\n                }\n\n                var nbNalu = 0;\n                var naluLen = 0;\n\n                for (var _i3 = 0; _i3 < nbSamples; _i3++) {\n                  // compute total/avc sample length and nb of NAL units\n                  var _sample = inputSamples[_i3];\n                  var units = _sample.units;\n                  var nbUnits = units.length;\n                  var sampleLen = 0;\n\n                  for (var j = 0; j < nbUnits; j++) {\n                    sampleLen += units[j].data.length;\n                  }\n\n                  naluLen += sampleLen;\n                  nbNalu += nbUnits;\n                  _sample.length = sampleLen; // normalize PTS/DTS\n                  // ensure sample monotonic DTS\n\n                  _sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS\n\n                  _sample.pts = Math.max(_sample.pts, _sample.dts, 0);\n                  minPTS = Math.min(_sample.pts, minPTS);\n                  maxPTS = Math.max(_sample.pts, maxPTS);\n                }\n\n                lastDTS = inputSamples[nbSamples - 1].dts;\n                /* concatenate the video data and construct the mdat in place\n      (need 8 more bytes to fill length and mpdat type) */\n\n                var mdatSize = naluLen + 4 * nbNalu + 8;\n                var mdat;\n\n                try {\n                  mdat = new Uint8Array(mdatSize);\n                } catch (err) {\n                  this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].ERROR, {\n                    type: _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorTypes\"].MUX_ERROR,\n                    details: _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorDetails\"].REMUX_ALLOC_ERROR,\n                    fatal: false,\n                    bytes: mdatSize,\n                    reason: \"fail allocating video mdat \" + mdatSize,\n                  });\n                  return;\n                }\n\n                var view = new DataView(mdat.buffer);\n                view.setUint32(0, mdatSize);\n                mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__[\"default\"].types.mdat, 4);\n\n                for (var _i4 = 0; _i4 < nbSamples; _i4++) {\n                  var avcSample = inputSamples[_i4];\n                  var avcSampleUnits = avcSample.units;\n                  var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)\n\n                  for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {\n                    var unit = avcSampleUnits[_j];\n                    var unitData = unit.data;\n                    var unitDataLen = unit.data.byteLength;\n                    view.setUint32(offset, unitDataLen);\n                    offset += 4;\n                    mdat.set(unitData, offset);\n                    offset += unitDataLen;\n                    mp4SampleLength += 4 + unitDataLen;\n                  } // expected sample duration is the Decoding Timestamp diff of consecutive samples\n\n                  if (_i4 < nbSamples - 1) {\n                    mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;\n                  } else {\n                    var config = this.config;\n                    var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;\n\n                    if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {\n                      // In some cases, a segment's audio track duration may exceed the video track duration.\n                      // Since we've already remuxed audio, and we know how long the audio track is, we look to\n                      // see if the delta to the next segment is longer than maxBufferHole.\n                      // If so, playback would potentially get stuck, so we artificially inflate\n                      // the duration of the last frame to minimize any potential gap between segments.\n                      var gapTolerance = Math.floor(config.maxBufferHole * timeScale);\n                      var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n\n                      if (deltaToFrameEnd > gapTolerance) {\n                        // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n                        // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n                        mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n\n                        if (mp4SampleDuration < 0) {\n                          mp4SampleDuration = lastFrameDuration;\n                        }\n\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].log(\"[mp4-remuxer]: It is approximately \" + deltaToFrameEnd / 90 + \" ms to the next segment; using duration \" + mp4SampleDuration / 90 + \" ms for the last video frame.\");\n                      } else {\n                        mp4SampleDuration = lastFrameDuration;\n                      }\n                    } else {\n                      mp4SampleDuration = lastFrameDuration;\n                    }\n                  }\n\n                  var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n                  outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));\n                }\n\n                if (outputSamples.length && chromeVersion && chromeVersion < 70) {\n                  // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue\n                  // https://code.google.com/p/chromium/issues/detail?id=229412\n                  var flags = outputSamples[0].flags;\n                  flags.dependsOn = 2;\n                  flags.isNonSync = 0;\n                }\n\n                console.assert(mp4SampleDuration !== undefined, \"mp4SampleDuration must be computed\"); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n\n                this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;\n                this.isVideoContiguous = true;\n                var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__[\"default\"].moof(\n                  track.sequenceNumber++,\n                  firstDTS,\n                  _extends({}, track, {\n                    samples: outputSamples,\n                  })\n                );\n                var type = \"video\";\n                var data = {\n                  data1: moof,\n                  data2: mdat,\n                  startPTS: minPTS / timeScale,\n                  endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n                  startDTS: firstDTS / timeScale,\n                  endDTS: nextAvcDts / timeScale,\n                  type: type,\n                  hasAudio: false,\n                  hasVideo: true,\n                  nb: outputSamples.length,\n                  dropped: track.dropped,\n                };\n                track.samples = [];\n                track.dropped = 0;\n                console.assert(mdat.length, \"MDAT length must not be zero\");\n                return data;\n              };\n\n              _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {\n                var inputTimeScale = track.inputTimeScale;\n                var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;\n                var scaleFactor = inputTimeScale / mp4timeScale;\n                var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;\n                var inputSampleDuration = mp4SampleDuration * scaleFactor;\n                var initPTS = this._initPTS;\n                var rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n                var outputSamples = [];\n                var inputSamples = track.samples;\n                var offset = rawMPEG ? 0 : 8;\n                var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);\n                // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n                // for sake of clarity:\n                // consecutive fragments are frags with\n                //  - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n                //  - less than 20 audio frames distance\n                // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n                // this helps ensuring audio continuity\n                // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n\n                var timeOffsetMpegTS = timeOffset * inputTimeScale;\n                this.isAudioContiguous = contiguous =\n                  contiguous || (inputSamples.length && nextAudioPts > 0 && ((accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000) || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration)); // compute normalized PTS\n\n                inputSamples.forEach(function (sample) {\n                  sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);\n                });\n\n                if (!contiguous || nextAudioPts < 0) {\n                  // filter out sample with negative PTS that are not playable anyway\n                  // if we don't remove these negative samples, they will shift all audio samples forward.\n                  // leading to audio overlap between current / next fragment\n                  inputSamples = inputSamples.filter(function (sample) {\n                    return sample.pts >= 0;\n                  }); // in case all samples have negative PTS, and have been filtered out, return now\n\n                  if (!inputSamples.length) {\n                    return;\n                  }\n\n                  if (videoTimeOffset === 0) {\n                    // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence\n                    nextAudioPts = 0;\n                  } else if (accurateTimeOffset) {\n                    // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS\n                    nextAudioPts = Math.max(0, timeOffsetMpegTS);\n                  } else {\n                    // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n                    nextAudioPts = inputSamples[0].pts;\n                  }\n                } // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n                // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n                // In an effort to prevent this from happening, we inject frames here where there are gaps.\n                // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n                // frame.\n\n                if (track.isAAC) {\n                  var alignedWithVideo = videoTimeOffset !== undefined;\n                  var maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n\n                  for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {\n                    // First, let's see how far off this frame is from where we expect it to be\n                    var sample = inputSamples[i];\n                    var pts = sample.pts;\n                    var delta = pts - nextPts;\n                    var duration = Math.abs((1000 * delta) / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync\n\n                    if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {\n                      if (i === 0) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"Audio frame @ \" + (pts / inputTimeScale).toFixed(3) + \"s overlaps nextAudioPts by \" + Math.round((1000 * delta) / inputTimeScale) + \" ms.\");\n                        this.nextAudioPts = nextAudioPts = nextPts = pts;\n                      }\n                    } // eslint-disable-line brace-style\n                    // Insert missing frames if:\n                    // 1: We're more than maxAudioFramesDrift frame away\n                    // 2: Not more than MAX_SILENT_FRAME_DURATION away\n                    // 3: currentTime (aka nextPtsNorm) is not 0\n                    // 4: remuxing with video (videoTimeOffset !== undefined)\n                    else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {\n                      var missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from\n                      // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.\n\n                      nextPts = pts - missing * inputSampleDuration;\n\n                      if (nextPts < 0) {\n                        missing--;\n                        nextPts += inputSampleDuration;\n                      }\n\n                      if (i === 0) {\n                        this.nextAudioPts = nextAudioPts = nextPts;\n                      }\n\n                      _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"[mp4-remuxer]: Injecting \" + missing + \" audio frame @ \" + (nextPts / inputTimeScale).toFixed(3) + \"s due to \" + Math.round((1000 * delta) / inputTimeScale) + \" ms gap.\");\n\n                      for (var j = 0; j < missing; j++) {\n                        var newStamp = Math.max(nextPts, 0);\n                        var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n\n                        if (!fillFrame) {\n                          _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].log(\"[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.\");\n                          fillFrame = sample.unit.subarray();\n                        }\n\n                        inputSamples.splice(i, 0, {\n                          unit: fillFrame,\n                          pts: newStamp,\n                        });\n                        nextPts += inputSampleDuration;\n                        i++;\n                      }\n                    }\n\n                    sample.pts = nextPts;\n                    nextPts += inputSampleDuration;\n                  }\n                }\n\n                var firstPTS = null;\n                var lastPTS = null;\n                var mdat;\n                var mdatSize = 0;\n                var sampleLength = inputSamples.length;\n\n                while (sampleLength--) {\n                  mdatSize += inputSamples[sampleLength].unit.byteLength;\n                }\n\n                for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {\n                  var audioSample = inputSamples[_j2];\n                  var unit = audioSample.unit;\n                  var _pts = audioSample.pts;\n\n                  if (lastPTS !== null) {\n                    // If we have more than one sample, set the duration of the sample to the \"real\" duration; the PTS diff with\n                    // the previous sample\n                    var prevSample = outputSamples[_j2 - 1];\n                    prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor);\n                  } else {\n                    if (contiguous && track.isAAC) {\n                      // set PTS/DTS to expected PTS/DTS\n                      _pts = nextAudioPts;\n                    } // remember first PTS of our audioSamples\n\n                    firstPTS = _pts;\n\n                    if (mdatSize > 0) {\n                      /* concatenate the audio data and construct the mdat in place\n            (need 8 more bytes to fill length and mdat type) */\n                      mdatSize += offset;\n\n                      try {\n                        mdat = new Uint8Array(mdatSize);\n                      } catch (err) {\n                        this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__[\"Events\"].ERROR, {\n                          type: _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorTypes\"].MUX_ERROR,\n                          details: _errors__WEBPACK_IMPORTED_MODULE_4__[\"ErrorDetails\"].REMUX_ALLOC_ERROR,\n                          fatal: false,\n                          bytes: mdatSize,\n                          reason: \"fail allocating audio mdat \" + mdatSize,\n                        });\n                        return;\n                      }\n\n                      if (!rawMPEG) {\n                        var view = new DataView(mdat.buffer);\n                        view.setUint32(0, mdatSize);\n                        mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__[\"default\"].types.mdat, 4);\n                      }\n                    } else {\n                      // no audio samples\n                      return;\n                    }\n                  }\n\n                  mdat.set(unit, offset);\n                  var unitLen = unit.byteLength;\n                  offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG\n                  // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration\n                  // becomes the PTS diff with the previous sample\n\n                  outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));\n                  lastPTS = _pts;\n                } // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones\n\n                var nbSamples = outputSamples.length;\n\n                if (!nbSamples) {\n                  return;\n                } // The next audio sample PTS should be equal to last sample PTS + duration\n\n                var lastSample = outputSamples[outputSamples.length - 1];\n                this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing\n\n                var moof = rawMPEG\n                  ? new Uint8Array(0)\n                  : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__[\"default\"].moof(\n                      track.sequenceNumber++,\n                      firstPTS / scaleFactor,\n                      _extends({}, track, {\n                        samples: outputSamples,\n                      })\n                    ); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared\n\n                track.samples = [];\n                var start = firstPTS / inputTimeScale;\n                var end = nextAudioPts / inputTimeScale;\n                var type = \"audio\";\n                var audioData = {\n                  data1: moof,\n                  data2: mdat,\n                  startPTS: start,\n                  endPTS: end,\n                  startDTS: start,\n                  endDTS: end,\n                  type: type,\n                  hasAudio: true,\n                  hasVideo: false,\n                  nb: nbSamples,\n                };\n                this.isAudioContiguous = true;\n                console.assert(mdat.length, \"MDAT length must not be zero\");\n                return audioData;\n              };\n\n              _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {\n                var inputTimeScale = track.inputTimeScale;\n                var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;\n                var scaleFactor = inputTimeScale / mp4timeScale;\n                var nextAudioPts = this.nextAudioPts; // sync with video's timestamp\n\n                var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;\n                var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value\n\n                var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration\n\n                var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame\n\n                var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n                _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].warn(\"[mp4-remuxer]: remux empty Audio\"); // Can't remux if we can't generate a silent frame...\n\n                if (!silentFrame) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__[\"logger\"].trace(\"[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec\");\n                  return;\n                }\n\n                var samples = [];\n\n                for (var i = 0; i < nbSamples; i++) {\n                  var stamp = startDTS + i * frameDuration;\n                  samples.push({\n                    unit: silentFrame,\n                    pts: stamp,\n                    dts: stamp,\n                  });\n                }\n\n                track.samples = samples;\n                return this.remuxAudio(track, timeOffset, contiguous, false);\n              };\n\n              _proto.remuxID3 = function remuxID3(track, timeOffset) {\n                var length = track.samples.length;\n\n                if (!length) {\n                  return;\n                }\n\n                var inputTimeScale = track.inputTimeScale;\n                var initPTS = this._initPTS;\n                var initDTS = this._initDTS;\n\n                for (var index = 0; index < length; index++) {\n                  var sample = track.samples[index]; // setting id3 pts, dts to relative time\n                  // using this._initPTS and this._initDTS to calculate relative time\n\n                  sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n                  sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;\n                }\n\n                var samples = track.samples;\n                track.samples = [];\n                return {\n                  samples: samples,\n                };\n              };\n\n              _proto.remuxText = function remuxText(track, timeOffset) {\n                var length = track.samples.length;\n\n                if (!length) {\n                  return;\n                }\n\n                var inputTimeScale = track.inputTimeScale;\n                var initPTS = this._initPTS;\n\n                for (var index = 0; index < length; index++) {\n                  var sample = track.samples[index]; // setting text pts, dts to relative time\n                  // using this._initPTS and this._initDTS to calculate relative time\n\n                  sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n                }\n\n                track.samples.sort(function (a, b) {\n                  return a.pts - b.pts;\n                });\n                var samples = track.samples;\n                track.samples = [];\n                return {\n                  samples: samples,\n                };\n              };\n\n              return MP4Remuxer;\n            })();\n\n            function normalizePts(value, reference) {\n              var offset;\n\n              if (reference === null) {\n                return value;\n              }\n\n              if (reference < value) {\n                // - 2^33\n                offset = -8589934592;\n              } else {\n                // + 2^33\n                offset = 8589934592;\n              }\n              /* PTS is 33bit (from 0 to 2^33 -1)\n    if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n    PTS looping occured. fill the gap */\n\n              while (Math.abs(value - reference) > 4294967296) {\n                value += offset;\n              }\n\n              return value;\n            }\n\n            function findKeyframeIndex(samples) {\n              for (var i = 0; i < samples.length; i++) {\n                if (samples[i].key) {\n                  return i;\n                }\n              }\n\n              return -1;\n            }\n\n            var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {\n              this.size = void 0;\n              this.duration = void 0;\n              this.cts = void 0;\n              this.flags = void 0;\n              this.duration = duration;\n              this.size = size;\n              this.cts = cts;\n              this.flags = new Mp4SampleFlags(isKeyframe);\n            };\n\n            var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {\n              this.isLeading = 0;\n              this.isDependedOn = 0;\n              this.hasRedundancy = 0;\n              this.degradPrio = 0;\n              this.dependsOn = 1;\n              this.isNonSync = 1;\n              this.dependsOn = isKeyframe ? 2 : 1;\n              this.isNonSync = isKeyframe ? 0 : 1;\n            };\n\n            /***/\n          },\n\n        /***/ \"./src/remux/passthrough-remuxer.ts\":\n          /*!******************************************!*\\\n  !*** ./src/remux/passthrough-remuxer.ts ***!\n  \\******************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ \"./src/loader/fragment.ts\");\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            var PassThroughRemuxer = /*#__PURE__*/ (function () {\n              function PassThroughRemuxer() {\n                this.emitInitSegment = false;\n                this.audioCodec = void 0;\n                this.videoCodec = void 0;\n                this.initData = void 0;\n                this.initPTS = void 0;\n                this.initTracks = void 0;\n                this.lastEndDTS = null;\n              }\n\n              var _proto = PassThroughRemuxer.prototype;\n\n              _proto.destroy = function destroy() {};\n\n              _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {\n                this.initPTS = defaultInitPTS;\n                this.lastEndDTS = null;\n              };\n\n              _proto.resetNextTimestamp = function resetNextTimestamp() {\n                this.lastEndDTS = null;\n              };\n\n              _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {\n                this.audioCodec = audioCodec;\n                this.videoCodec = videoCodec;\n                this.generateInitSegment(initSegment);\n                this.emitInitSegment = true;\n              };\n\n              _proto.generateInitSegment = function generateInitSegment(initSegment) {\n                var audioCodec = this.audioCodec,\n                  videoCodec = this.videoCodec;\n\n                if (!initSegment || !initSegment.byteLength) {\n                  this.initTracks = undefined;\n                  this.initData = undefined;\n                  return;\n                }\n\n                var initData = (this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__[\"parseInitSegment\"])(initSegment)); // Get codec from initSegment or fallback to default\n\n                if (!audioCodec) {\n                  audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__[\"ElementaryStreamTypes\"].AUDIO);\n                }\n\n                if (!videoCodec) {\n                  videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__[\"ElementaryStreamTypes\"].VIDEO);\n                }\n\n                var tracks = {};\n\n                if (initData.audio && initData.video) {\n                  tracks.audiovideo = {\n                    container: \"video/mp4\",\n                    codec: audioCodec + \",\" + videoCodec,\n                    initSegment: initSegment,\n                    id: \"main\",\n                  };\n                } else if (initData.audio) {\n                  tracks.audio = {\n                    container: \"audio/mp4\",\n                    codec: audioCodec,\n                    initSegment: initSegment,\n                    id: \"audio\",\n                  };\n                } else if (initData.video) {\n                  tracks.video = {\n                    container: \"video/mp4\",\n                    codec: videoCodec,\n                    initSegment: initSegment,\n                    id: \"main\",\n                  };\n                } else {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.\");\n                }\n\n                this.initTracks = tracks;\n              };\n\n              _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {\n                var initPTS = this.initPTS,\n                  lastEndDTS = this.lastEndDTS;\n                var result = {\n                  audio: undefined,\n                  video: undefined,\n                  text: textTrack,\n                  id3: id3Track,\n                  initSegment: undefined,\n                }; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the\n                // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update\n                // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.\n\n                if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(lastEndDTS)) {\n                  lastEndDTS = this.lastEndDTS = timeOffset || 0;\n                } // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only\n                // audio or video (or both); adding it to video was an arbitrary choice.\n\n                var data = videoTrack.samples;\n\n                if (!data || !data.length) {\n                  return result;\n                }\n\n                var initSegment = {\n                  initPTS: undefined,\n                  timescale: 1,\n                };\n                var initData = this.initData;\n\n                if (!initData || !initData.length) {\n                  this.generateInitSegment(data);\n                  initData = this.initData;\n                }\n\n                if (!initData || !initData.length) {\n                  // We can't remux if the initSegment could not be generated\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"[passthrough-remuxer.ts]: Failed to generate initSegment.\");\n                  return result;\n                }\n\n                if (this.emitInitSegment) {\n                  initSegment.tracks = this.initTracks;\n                  this.emitInitSegment = false;\n                }\n\n                if (!Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(initPTS)) {\n                  this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS);\n                }\n\n                var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__[\"getDuration\"])(data, initData);\n                var startDTS = lastEndDTS;\n                var endDTS = duration + startDTS;\n                Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__[\"offsetStartDTS\"])(initData, data, initPTS);\n\n                if (duration > 0) {\n                  this.lastEndDTS = endDTS;\n                } else {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_3__[\"logger\"].warn(\"Duration parsed from mp4 should be greater than zero\");\n                  this.resetNextTimestamp();\n                }\n\n                var hasAudio = !!initData.audio;\n                var hasVideo = !!initData.video;\n                var type = \"\";\n\n                if (hasAudio) {\n                  type += \"audio\";\n                }\n\n                if (hasVideo) {\n                  type += \"video\";\n                }\n\n                var track = {\n                  data1: data,\n                  startPTS: startDTS,\n                  startDTS: startDTS,\n                  endPTS: endDTS,\n                  endDTS: endDTS,\n                  type: type,\n                  hasAudio: hasAudio,\n                  hasVideo: hasVideo,\n                  nb: 1,\n                  dropped: 0,\n                };\n                result.audio = track.type === \"audio\" ? track : undefined;\n                result.video = track.type !== \"audio\" ? track : undefined;\n                result.text = textTrack;\n                result.id3 = id3Track;\n                result.initSegment = initSegment;\n                return result;\n              };\n\n              return PassThroughRemuxer;\n            })();\n\n            var computeInitPTS = function computeInitPTS(initData, data, timeOffset) {\n              return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__[\"getStartDTS\"])(initData, data) - timeOffset;\n            };\n\n            function getParsedTrackCodec(track, type) {\n              var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;\n\n              if (parsedCodec && parsedCodec.length > 4) {\n                return parsedCodec;\n              } // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)\n              // Provide defaults based on codec type\n              // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\n\n              if (parsedCodec === \"hvc1\") {\n                return \"hvc1.1.c.L120.90\";\n              }\n\n              if (parsedCodec === \"av01\") {\n                return \"av01.0.04M.08\";\n              }\n\n              if (parsedCodec === \"avc1\" || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__[\"ElementaryStreamTypes\"].VIDEO) {\n                return \"avc1.42e01e\";\n              }\n\n              return \"mp4a.40.5\";\n            }\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = PassThroughRemuxer;\n\n            /***/\n          },\n\n        /***/ \"./src/task-loop.ts\":\n          /*!**************************!*\\\n  !*** ./src/task-loop.ts ***!\n  \\**************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return TaskLoop;\n            });\n            /**\n             * Sub-class specialization of EventHandler base class.\n             *\n             * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n             * scheduled asynchroneously, avoiding recursive calls in the same tick.\n             *\n             * The task itself is implemented in `doTick`. It can be requested and called for single execution\n             * using the `tick` method.\n             *\n             * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n             * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n             *\n             * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n             * and cancelled with `clearNextTick`.\n             *\n             * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n             *\n             * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n             *\n             * Further explanations:\n             *\n             * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n             * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n             *\n             * When the task execution (`tick` method) is called in re-entrant way this is detected and\n             * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n             * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n             */\n            var TaskLoop = /*#__PURE__*/ (function () {\n              function TaskLoop() {\n                this._boundTick = void 0;\n                this._tickTimer = null;\n                this._tickInterval = null;\n                this._tickCallCount = 0;\n                this._boundTick = this.tick.bind(this);\n              }\n\n              var _proto = TaskLoop.prototype;\n\n              _proto.destroy = function destroy() {\n                this.onHandlerDestroying();\n                this.onHandlerDestroyed();\n              };\n\n              _proto.onHandlerDestroying = function onHandlerDestroying() {\n                // clear all timers before unregistering from event bus\n                this.clearNextTick();\n                this.clearInterval();\n              };\n\n              _proto.onHandlerDestroyed = function onHandlerDestroyed() {};\n              /**\n               * @returns {boolean}\n               */\n\n              _proto.hasInterval = function hasInterval() {\n                return !!this._tickInterval;\n              };\n              /**\n               * @returns {boolean}\n               */\n\n              _proto.hasNextTick = function hasNextTick() {\n                return !!this._tickTimer;\n              };\n              /**\n               * @param {number} millis Interval time (ms)\n               * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n               */\n\n              _proto.setInterval = function setInterval(millis) {\n                if (!this._tickInterval) {\n                  this._tickInterval = self.setInterval(this._boundTick, millis);\n                  return true;\n                }\n\n                return false;\n              };\n              /**\n               * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n               */\n\n              _proto.clearInterval = function clearInterval() {\n                if (this._tickInterval) {\n                  self.clearInterval(this._tickInterval);\n                  this._tickInterval = null;\n                  return true;\n                }\n\n                return false;\n              };\n              /**\n               * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n               */\n\n              _proto.clearNextTick = function clearNextTick() {\n                if (this._tickTimer) {\n                  self.clearTimeout(this._tickTimer);\n                  this._tickTimer = null;\n                  return true;\n                }\n\n                return false;\n              };\n              /**\n               * Will call the subclass doTick implementation in this main loop tick\n               * or in the next one (via setTimeout(,0)) in case it has already been called\n               * in this tick (in case this is a re-entrant call).\n               */\n\n              _proto.tick = function tick() {\n                this._tickCallCount++;\n\n                if (this._tickCallCount === 1) {\n                  this.doTick(); // re-entrant call to tick from previous doTick call stack\n                  // -> schedule a call on the next main loop iteration to process this task processing request\n\n                  if (this._tickCallCount > 1) {\n                    // make sure only one timer exists at any time at max\n                    this.tickImmediate();\n                  }\n\n                  this._tickCallCount = 0;\n                }\n              };\n\n              _proto.tickImmediate = function tickImmediate() {\n                this.clearNextTick();\n                this._tickTimer = self.setTimeout(this._boundTick, 0);\n              };\n              /**\n               * For subclass to implement task logic\n               * @abstract\n               */\n\n              _proto.doTick = function doTick() {};\n\n              return TaskLoop;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/types/cmcd.ts\":\n          /*!***************************!*\\\n  !*** ./src/types/cmcd.ts ***!\n  \\***************************/\n          /*! exports provided: CMCDVersion, CMCDObjectType, CMCDStreamingFormat, CMCDStreamType */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CMCDVersion\", function () {\n              return CMCDVersion;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CMCDObjectType\", function () {\n              return CMCDObjectType;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CMCDStreamingFormat\", function () {\n              return CMCDStreamingFormat;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CMCDStreamType\", function () {\n              return CMCDStreamType;\n            });\n            /**\n             * CMCD spec version\n             */\n            var CMCDVersion = 1;\n            /**\n             * CMCD Object Type\n             */\n\n            var CMCDObjectType;\n            /**\n             * CMCD Streaming Format\n             */\n\n            (function (CMCDObjectType) {\n              CMCDObjectType[\"MANIFEST\"] = \"m\";\n              CMCDObjectType[\"AUDIO\"] = \"a\";\n              CMCDObjectType[\"VIDEO\"] = \"v\";\n              CMCDObjectType[\"MUXED\"] = \"av\";\n              CMCDObjectType[\"INIT\"] = \"i\";\n              CMCDObjectType[\"CAPTION\"] = \"c\";\n              CMCDObjectType[\"TIMED_TEXT\"] = \"tt\";\n              CMCDObjectType[\"KEY\"] = \"k\";\n              CMCDObjectType[\"OTHER\"] = \"o\";\n            })(CMCDObjectType || (CMCDObjectType = {}));\n\n            var CMCDStreamingFormat;\n            /**\n             * CMCD Streaming Type\n             */\n\n            (function (CMCDStreamingFormat) {\n              CMCDStreamingFormat[\"DASH\"] = \"d\";\n              CMCDStreamingFormat[\"CiderHls\"] = \"h\";\n              CMCDStreamingFormat[\"SMOOTH\"] = \"s\";\n              CMCDStreamingFormat[\"OTHER\"] = \"o\";\n            })(CMCDStreamingFormat || (CMCDStreamingFormat = {}));\n\n            var CMCDStreamType;\n            /**\n             * CMCD Headers\n             */\n\n            (function (CMCDStreamType) {\n              CMCDStreamType[\"VOD\"] = \"v\";\n              CMCDStreamType[\"LIVE\"] = \"l\";\n            })(CMCDStreamType || (CMCDStreamType = {}));\n\n            /***/\n          },\n\n        /***/ \"./src/types/level.ts\":\n          /*!****************************!*\\\n  !*** ./src/types/level.ts ***!\n  \\****************************/\n          /*! exports provided: CiderHlsSkip, getSkipValue, CiderHlsUrlParameters, Level */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CiderHlsSkip\", function () {\n              return CiderHlsSkip;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getSkipValue\", function () {\n              return getSkipValue;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CiderHlsUrlParameters\", function () {\n              return CiderHlsUrlParameters;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Level\", function () {\n              return Level;\n            });\n            function _defineProperties(target, props) {\n              for (var i = 0; i < props.length; i++) {\n                var descriptor = props[i];\n                descriptor.enumerable = descriptor.enumerable || false;\n                descriptor.configurable = true;\n                if (\"value\" in descriptor) descriptor.writable = true;\n                Object.defineProperty(target, descriptor.key, descriptor);\n              }\n            }\n\n            function _createClass(Constructor, protoProps, staticProps) {\n              if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n              if (staticProps) _defineProperties(Constructor, staticProps);\n              return Constructor;\n            }\n\n            var CiderHlsSkip;\n\n            (function (CiderHlsSkip) {\n              CiderHlsSkip[\"No\"] = \"\";\n              CiderHlsSkip[\"Yes\"] = \"YES\";\n              CiderHlsSkip[\"v2\"] = \"v2\";\n            })(CiderHlsSkip || (CiderHlsSkip = {}));\n\n            function getSkipValue(details, msn) {\n              var canSkipUntil = details.canSkipUntil,\n                canSkipDateRanges = details.canSkipDateRanges,\n                endSN = details.endSN;\n              var snChangeGoal = msn !== undefined ? msn - endSN : 0;\n\n              if (canSkipUntil && snChangeGoal < canSkipUntil) {\n                if (canSkipDateRanges) {\n                  return CiderHlsSkip.v2;\n                }\n\n                return CiderHlsSkip.Yes;\n              }\n\n              return CiderHlsSkip.No;\n            }\n            var CiderHlsUrlParameters = /*#__PURE__*/ (function () {\n              function CiderHlsUrlParameters(msn, part, skip) {\n                this.msn = void 0;\n                this.part = void 0;\n                this.skip = void 0;\n                this.msn = msn;\n                this.part = part;\n                this.skip = skip;\n              }\n\n              var _proto = CiderHlsUrlParameters.prototype;\n\n              _proto.addDirectives = function addDirectives(uri) {\n                var url = new self.URL(uri);\n\n                if (this.msn !== undefined) {\n                  url.searchParams.set(\"_CiderHls_msn\", this.msn.toString());\n                }\n\n                if (this.part !== undefined) {\n                  url.searchParams.set(\"_CiderHls_part\", this.part.toString());\n                }\n\n                if (this.skip) {\n                  url.searchParams.set(\"_CiderHls_skip\", this.skip);\n                }\n\n                return url.toString();\n              };\n\n              return CiderHlsUrlParameters;\n            })();\n            var Level = /*#__PURE__*/ (function () {\n              function Level(data) {\n                this.attrs = void 0;\n                this.audioCodec = void 0;\n                this.bitrate = void 0;\n                this.codecSet = void 0;\n                this.height = void 0;\n                this.id = void 0;\n                this.name = void 0;\n                this.videoCodec = void 0;\n                this.width = void 0;\n                this.unknownCodecs = void 0;\n                this.audioGroupIds = void 0;\n                this.details = void 0;\n                this.fragmentError = 0;\n                this.loadError = 0;\n                this.loaded = void 0;\n                this.realBitrate = 0;\n                this.textGroupIds = void 0;\n                this.url = void 0;\n                this._urlId = 0;\n                this.url = [data.url];\n                this.attrs = data.attrs;\n                this.bitrate = data.bitrate;\n\n                if (data.details) {\n                  this.details = data.details;\n                }\n\n                this.id = data.id || 0;\n                this.name = data.name;\n                this.width = data.width || 0;\n                this.height = data.height || 0;\n                this.audioCodec = data.audioCodec;\n                this.videoCodec = data.videoCodec;\n                this.unknownCodecs = data.unknownCodecs;\n                this.codecSet = [data.videoCodec, data.audioCodec]\n                  .filter(function (c) {\n                    return c;\n                  })\n                  .join(\",\")\n                  .replace(/\\.[^.,]+/g, \"\");\n              }\n\n              _createClass(Level, [\n                {\n                  key: \"maxBitrate\",\n                  get: function get() {\n                    return Math.max(this.realBitrate, this.bitrate);\n                  },\n                },\n                {\n                  key: \"uri\",\n                  get: function get() {\n                    return this.url[this._urlId] || \"\";\n                  },\n                },\n                {\n                  key: \"urlId\",\n                  get: function get() {\n                    return this._urlId;\n                  },\n                  set: function set(value) {\n                    var newValue = value % this.url.length;\n\n                    if (this._urlId !== newValue) {\n                      this.details = undefined;\n                      this._urlId = newValue;\n                    }\n                  },\n                },\n              ]);\n\n              return Level;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/types/loader.ts\":\n          /*!*****************************!*\\\n  !*** ./src/types/loader.ts ***!\n  \\*****************************/\n          /*! exports provided: PlaylistContextType, PlaylistLevelType */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"PlaylistContextType\", function () {\n              return PlaylistContextType;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"PlaylistLevelType\", function () {\n              return PlaylistLevelType;\n            });\n            var PlaylistContextType;\n\n            (function (PlaylistContextType) {\n              PlaylistContextType[\"MANIFEST\"] = \"manifest\";\n              PlaylistContextType[\"LEVEL\"] = \"level\";\n              PlaylistContextType[\"AUDIO_TRACK\"] = \"audioTrack\";\n              PlaylistContextType[\"SUBTITLE_TRACK\"] = \"subtitleTrack\";\n            })(PlaylistContextType || (PlaylistContextType = {}));\n\n            var PlaylistLevelType;\n\n            (function (PlaylistLevelType) {\n              PlaylistLevelType[\"MAIN\"] = \"main\";\n              PlaylistLevelType[\"AUDIO\"] = \"audio\";\n              PlaylistLevelType[\"SUBTITLE\"] = \"subtitle\";\n            })(PlaylistLevelType || (PlaylistLevelType = {}));\n\n            /***/\n          },\n\n        /***/ \"./src/types/transmuxer.ts\":\n          /*!*********************************!*\\\n  !*** ./src/types/transmuxer.ts ***!\n  \\*********************************/\n          /*! exports provided: ChunkMetadata */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ChunkMetadata\", function () {\n              return ChunkMetadata;\n            });\n            var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {\n              if (size === void 0) {\n                size = 0;\n              }\n\n              if (part === void 0) {\n                part = -1;\n              }\n\n              if (partial === void 0) {\n                partial = false;\n              }\n\n              this.level = void 0;\n              this.sn = void 0;\n              this.part = void 0;\n              this.id = void 0;\n              this.size = void 0;\n              this.partial = void 0;\n              this.transmuxing = getNewPerformanceTiming();\n              this.buffering = {\n                audio: getNewPerformanceTiming(),\n                video: getNewPerformanceTiming(),\n                audiovideo: getNewPerformanceTiming(),\n              };\n              this.level = level;\n              this.sn = sn;\n              this.id = id;\n              this.size = size;\n              this.part = part;\n              this.partial = partial;\n            };\n\n            function getNewPerformanceTiming() {\n              return {\n                start: 0,\n                executeStart: 0,\n                executeEnd: 0,\n                end: 0,\n              };\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/attr-list.ts\":\n          /*!********************************!*\\\n  !*** ./src/utils/attr-list.ts ***!\n  \\********************************/\n          /*! exports provided: AttrList */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"AttrList\", function () {\n              return AttrList;\n            });\n            var DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\n\n            var ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n            // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\n\n            var AttrList = /*#__PURE__*/ (function () {\n              function AttrList(attrs) {\n                if (typeof attrs === \"string\") {\n                  attrs = AttrList.parseAttrList(attrs);\n                }\n\n                for (var attr in attrs) {\n                  if (attrs.hasOwnProperty(attr)) {\n                    this[attr] = attrs[attr];\n                  }\n                }\n              }\n\n              var _proto = AttrList.prototype;\n\n              _proto.decimalInteger = function decimalInteger(attrName) {\n                var intValue = parseInt(this[attrName], 10);\n\n                if (intValue > Number.MAX_SAFE_INTEGER) {\n                  return Infinity;\n                }\n\n                return intValue;\n              };\n\n              _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {\n                if (this[attrName]) {\n                  var stringValue = (this[attrName] || \"0x\").slice(2);\n                  stringValue = (stringValue.length & 1 ? \"0\" : \"\") + stringValue;\n                  var value = new Uint8Array(stringValue.length / 2);\n\n                  for (var i = 0; i < stringValue.length / 2; i++) {\n                    value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n                  }\n\n                  return value;\n                } else {\n                  return null;\n                }\n              };\n\n              _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {\n                var intValue = parseInt(this[attrName], 16);\n\n                if (intValue > Number.MAX_SAFE_INTEGER) {\n                  return Infinity;\n                }\n\n                return intValue;\n              };\n\n              _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {\n                return parseFloat(this[attrName]);\n              };\n\n              _proto.optionalFloat = function optionalFloat(attrName, defaultValue) {\n                var value = this[attrName];\n                return value ? parseFloat(value) : defaultValue;\n              };\n\n              _proto.enumeratedString = function enumeratedString(attrName) {\n                return this[attrName];\n              };\n\n              _proto.bool = function bool(attrName) {\n                return this[attrName] === \"YES\";\n              };\n\n              _proto.decimalResolution = function decimalResolution(attrName) {\n                var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n\n                if (res === null) {\n                  return undefined;\n                }\n\n                return {\n                  width: parseInt(res[1], 10),\n                  height: parseInt(res[2], 10),\n                };\n              };\n\n              AttrList.parseAttrList = function parseAttrList(input) {\n                var match;\n                var attrs = {};\n                var quote = '\"';\n                ATTR_LIST_REGEX.lastIndex = 0;\n\n                while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n                  var value = match[2];\n\n                  if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {\n                    value = value.slice(1, -1);\n                  }\n\n                  attrs[match[1]] = value;\n                }\n\n                return attrs;\n              };\n\n              return AttrList;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/utils/binary-search.ts\":\n          /*!************************************!*\\\n  !*** ./src/utils/binary-search.ts ***!\n  \\************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            var BinarySearch = {\n              /**\n               * Searches for an item in an array which matches a certain condition.\n               * This requires the condition to only match one item in the array,\n               * and for the array to be ordered.\n               *\n               * @param {Array<T>} list The array to search.\n               * @param {BinarySearchComparison<T>} comparisonFn\n               *      Called and provided a candidate item as the first argument.\n               *      Should return:\n               *          > -1 if the item should be located at a lower index than the provided item.\n               *          > 1 if the item should be located at a higher index than the provided item.\n               *          > 0 if the item is the item you're looking for.\n               *\n               * @return {T | null} The object if it is found or null otherwise.\n               */\n              search: function search(list, comparisonFn) {\n                var minIndex = 0;\n                var maxIndex = list.length - 1;\n                var currentIndex = null;\n                var currentElement = null;\n\n                while (minIndex <= maxIndex) {\n                  currentIndex = ((minIndex + maxIndex) / 2) | 0;\n                  currentElement = list[currentIndex];\n                  var comparisonResult = comparisonFn(currentElement);\n\n                  if (comparisonResult > 0) {\n                    minIndex = currentIndex + 1;\n                  } else if (comparisonResult < 0) {\n                    maxIndex = currentIndex - 1;\n                  } else {\n                    return currentElement;\n                  }\n                }\n\n                return null;\n              },\n            };\n            /* harmony default export */ __webpack_exports__[\"default\"] = BinarySearch;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/buffer-helper.ts\":\n          /*!************************************!*\\\n  !*** ./src/utils/buffer-helper.ts ***!\n  \\************************************/\n          /*! exports provided: BufferHelper */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"BufferHelper\", function () {\n              return BufferHelper;\n            });\n            /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ \"./src/utils/logger.ts\");\n            /**\n             * @module BufferHelper\n             *\n             * Providing methods dealing with buffer length retrieval for example.\n             *\n             * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n             *\n             * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n             */\n\n            var noopBuffered = {\n              length: 0,\n              start: function start() {\n                return 0;\n              },\n              end: function end() {\n                return 0;\n              },\n            };\n            var BufferHelper = /*#__PURE__*/ (function () {\n              function BufferHelper() {}\n\n              /**\n               * Return true if `media`'s buffered include `position`\n               * @param {Bufferable} media\n               * @param {number} position\n               * @returns {boolean}\n               */\n              BufferHelper.isBuffered = function isBuffered(media, position) {\n                try {\n                  if (media) {\n                    var buffered = BufferHelper.getBuffered(media);\n\n                    for (var i = 0; i < buffered.length; i++) {\n                      if (position >= buffered.start(i) && position <= buffered.end(i)) {\n                        return true;\n                      }\n                    }\n                  }\n                } catch (error) {\n                  // this is to catch\n                  // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n                  // This SourceBuffer has been removed from the parent media source\n                }\n\n                return false;\n              };\n\n              BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {\n                try {\n                  if (media) {\n                    var vbuffered = BufferHelper.getBuffered(media);\n                    var buffered = [];\n                    var i;\n\n                    for (i = 0; i < vbuffered.length; i++) {\n                      buffered.push({\n                        start: vbuffered.start(i),\n                        end: vbuffered.end(i),\n                      });\n                    }\n\n                    return this.bufferedInfo(buffered, pos, maxHoleDuration);\n                  }\n                } catch (error) {\n                  // this is to catch\n                  // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n                  // This SourceBuffer has been removed from the parent media source\n                }\n\n                return {\n                  len: 0,\n                  start: pos,\n                  end: pos,\n                  nextStart: undefined,\n                };\n              };\n\n              BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {\n                pos = Math.max(0, pos); // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n\n                buffered.sort(function (a, b) {\n                  var diff = a.start - b.start;\n\n                  if (diff) {\n                    return diff;\n                  } else {\n                    return b.end - a.end;\n                  }\n                });\n                var buffered2 = [];\n\n                if (maxHoleDuration) {\n                  // there might be some small holes between buffer time range\n                  // consider that holes smaller than maxHoleDuration are irrelevant and build another\n                  // buffer time range representations that discards those holes\n                  for (var i = 0; i < buffered.length; i++) {\n                    var buf2len = buffered2.length;\n\n                    if (buf2len) {\n                      var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n\n                      if (buffered[i].start - buf2end < maxHoleDuration) {\n                        // merge overlapping time ranges\n                        // update lastRange.end only if smaller than item.end\n                        // e.g.  [ 1, 15] with  [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n                        // whereas [ 1, 8] with  [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n                        if (buffered[i].end > buf2end) {\n                          buffered2[buf2len - 1].end = buffered[i].end;\n                        }\n                      } else {\n                        // big hole\n                        buffered2.push(buffered[i]);\n                      }\n                    } else {\n                      // first value\n                      buffered2.push(buffered[i]);\n                    }\n                  }\n                } else {\n                  buffered2 = buffered;\n                }\n\n                var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below\n\n                var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position\n\n                var bufferStart = pos;\n                var bufferEnd = pos;\n\n                for (var _i = 0; _i < buffered2.length; _i++) {\n                  var start = buffered2[_i].start;\n                  var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n\n                  if (pos + maxHoleDuration >= start && pos < end) {\n                    // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n                    bufferStart = start;\n                    bufferEnd = end;\n                    bufferLen = bufferEnd - pos;\n                  } else if (pos + maxHoleDuration < start) {\n                    bufferStartNext = start;\n                    break;\n                  }\n                }\n\n                return {\n                  len: bufferLen,\n                  start: bufferStart || 0,\n                  end: bufferEnd || 0,\n                  nextStart: bufferStartNext,\n                };\n              };\n              /**\n               * Safe method to get buffered property.\n               * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource\n               */\n\n              BufferHelper.getBuffered = function getBuffered(media) {\n                try {\n                  return media.buffered;\n                } catch (e) {\n                  _logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].log(\"failed to get media.buffered\", e);\n                  return noopBuffered;\n                }\n              };\n\n              return BufferHelper;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/utils/cea-608-parser.ts\":\n          /*!*************************************!*\\\n  !*** ./src/utils/cea-608-parser.ts ***!\n  \\*************************************/\n          /*! exports provided: Row, CaptionScreen, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Row\", function () {\n              return Row;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CaptionScreen\", function () {\n              return CaptionScreen;\n            });\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n\n            /**\n             *\n             * This code was ported from the dash.js project at:\n             *   https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n             *   https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n             *\n             * The original copyright appears below:\n             *\n             * The copyright in this software is being made available under the BSD License,\n             * included below. This software may be subject to other third party and contributor\n             * rights, including patent rights, and no such rights are granted under this license.\n             *\n             * Copyright (c) 2015-2016, DASH Industry Forum.\n             * All rights reserved.\n             *\n             * Redistribution and use in source and binary forms, with or without modification,\n             * are permitted provided that the following conditions are met:\n             *  1. Redistributions of source code must retain the above copyright notice, this\n             *  list of conditions and the following disclaimer.\n             *  * Redistributions in binary form must reproduce the above copyright notice,\n             *  this list of conditions and the following disclaimer in the documentation and/or\n             *  other materials provided with the distribution.\n             *  2. Neither the name of Dash Industry Forum nor the names of its\n             *  contributors may be used to endorse or promote products derived from this software\n             *  without specific prior written permission.\n             *\n             *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n             *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n             *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n             *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n             *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n             *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n             *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n             *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n             *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n             *  POSSIBILITY OF SUCH DAMAGE.\n             */\n\n            /**\n             *  Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n             */\n\n            var specialCea608CharsCodes = {\n              0x2a: 0xe1,\n              // lowercase a, acute accent\n              0x5c: 0xe9,\n              // lowercase e, acute accent\n              0x5e: 0xed,\n              // lowercase i, acute accent\n              0x5f: 0xf3,\n              // lowercase o, acute accent\n              0x60: 0xfa,\n              // lowercase u, acute accent\n              0x7b: 0xe7,\n              // lowercase c with cedilla\n              0x7c: 0xf7,\n              // division symbol\n              0x7d: 0xd1,\n              // uppercase N tilde\n              0x7e: 0xf1,\n              // lowercase n tilde\n              0x7f: 0x2588,\n              // Full block\n              // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n              // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n              // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n              0x80: 0xae,\n              // Registered symbol (R)\n              0x81: 0xb0,\n              // degree sign\n              0x82: 0xbd,\n              // 1/2 symbol\n              0x83: 0xbf,\n              // Inverted (open) question mark\n              0x84: 0x2122,\n              // Trademark symbol (TM)\n              0x85: 0xa2,\n              // Cents symbol\n              0x86: 0xa3,\n              // Pounds sterling\n              0x87: 0x266a,\n              // Music 8'th note\n              0x88: 0xe0,\n              // lowercase a, grave accent\n              0x89: 0x20,\n              // transparent space (regular)\n              0x8a: 0xe8,\n              // lowercase e, grave accent\n              0x8b: 0xe2,\n              // lowercase a, circumflex accent\n              0x8c: 0xea,\n              // lowercase e, circumflex accent\n              0x8d: 0xee,\n              // lowercase i, circumflex accent\n              0x8e: 0xf4,\n              // lowercase o, circumflex accent\n              0x8f: 0xfb,\n              // lowercase u, circumflex accent\n              // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n              // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n              0x90: 0xc1,\n              // capital letter A with acute\n              0x91: 0xc9,\n              // capital letter E with acute\n              0x92: 0xd3,\n              // capital letter O with acute\n              0x93: 0xda,\n              // capital letter U with acute\n              0x94: 0xdc,\n              // capital letter U with diaresis\n              0x95: 0xfc,\n              // lowercase letter U with diaeresis\n              0x96: 0x2018,\n              // opening single quote\n              0x97: 0xa1,\n              // inverted exclamation mark\n              0x98: 0x2a,\n              // asterisk\n              0x99: 0x2019,\n              // closing single quote\n              0x9a: 0x2501,\n              // box drawings heavy horizontal\n              0x9b: 0xa9,\n              // copyright sign\n              0x9c: 0x2120,\n              // Service mark\n              0x9d: 0x2022,\n              // (round) bullet\n              0x9e: 0x201c,\n              // Left double quotation mark\n              0x9f: 0x201d,\n              // Right double quotation mark\n              0xa0: 0xc0,\n              // uppercase A, grave accent\n              0xa1: 0xc2,\n              // uppercase A, circumflex\n              0xa2: 0xc7,\n              // uppercase C with cedilla\n              0xa3: 0xc8,\n              // uppercase E, grave accent\n              0xa4: 0xca,\n              // uppercase E, circumflex\n              0xa5: 0xcb,\n              // capital letter E with diaresis\n              0xa6: 0xeb,\n              // lowercase letter e with diaresis\n              0xa7: 0xce,\n              // uppercase I, circumflex\n              0xa8: 0xcf,\n              // uppercase I, with diaresis\n              0xa9: 0xef,\n              // lowercase i, with diaresis\n              0xaa: 0xd4,\n              // uppercase O, circumflex\n              0xab: 0xd9,\n              // uppercase U, grave accent\n              0xac: 0xf9,\n              // lowercase u, grave accent\n              0xad: 0xdb,\n              // uppercase U, circumflex\n              0xae: 0xab,\n              // left-pointing double angle quotation mark\n              0xaf: 0xbb,\n              // right-pointing double angle quotation mark\n              // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n              // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n              0xb0: 0xc3,\n              // Uppercase A, tilde\n              0xb1: 0xe3,\n              // Lowercase a, tilde\n              0xb2: 0xcd,\n              // Uppercase I, acute accent\n              0xb3: 0xcc,\n              // Uppercase I, grave accent\n              0xb4: 0xec,\n              // Lowercase i, grave accent\n              0xb5: 0xd2,\n              // Uppercase O, grave accent\n              0xb6: 0xf2,\n              // Lowercase o, grave accent\n              0xb7: 0xd5,\n              // Uppercase O, tilde\n              0xb8: 0xf5,\n              // Lowercase o, tilde\n              0xb9: 0x7b,\n              // Open curly brace\n              0xba: 0x7d,\n              // Closing curly brace\n              0xbb: 0x5c,\n              // Backslash\n              0xbc: 0x5e,\n              // Caret\n              0xbd: 0x5f,\n              // Underscore\n              0xbe: 0x7c,\n              // Pipe (vertical line)\n              0xbf: 0x223c,\n              // Tilde operator\n              0xc0: 0xc4,\n              // Uppercase A, umlaut\n              0xc1: 0xe4,\n              // Lowercase A, umlaut\n              0xc2: 0xd6,\n              // Uppercase O, umlaut\n              0xc3: 0xf6,\n              // Lowercase o, umlaut\n              0xc4: 0xdf,\n              // Esszett (sharp S)\n              0xc5: 0xa5,\n              // Yen symbol\n              0xc6: 0xa4,\n              // Generic currency sign\n              0xc7: 0x2503,\n              // Box drawings heavy vertical\n              0xc8: 0xc5,\n              // Uppercase A, ring\n              0xc9: 0xe5,\n              // Lowercase A, ring\n              0xca: 0xd8,\n              // Uppercase O, stroke\n              0xcb: 0xf8,\n              // Lowercase o, strok\n              0xcc: 0x250f,\n              // Box drawings heavy down and right\n              0xcd: 0x2513,\n              // Box drawings heavy down and left\n              0xce: 0x2517,\n              // Box drawings heavy up and right\n              0xcf: 0x251b, // Box drawings heavy up and left\n            };\n            /**\n             * Utils\n             */\n\n            var getCharForByte = function getCharForByte(_byte) {\n              var charCode = _byte;\n\n              if (specialCea608CharsCodes.hasOwnProperty(_byte)) {\n                charCode = specialCea608CharsCodes[_byte];\n              }\n\n              return String.fromCharCode(charCode);\n            };\n\n            var NR_ROWS = 15;\n            var NR_COLS = 100; // Tables to look up row from PAC data\n\n            var rowsLowCh1 = {\n              0x11: 1,\n              0x12: 3,\n              0x15: 5,\n              0x16: 7,\n              0x17: 9,\n              0x10: 11,\n              0x13: 12,\n              0x14: 14,\n            };\n            var rowsHighCh1 = {\n              0x11: 2,\n              0x12: 4,\n              0x15: 6,\n              0x16: 8,\n              0x17: 10,\n              0x13: 13,\n              0x14: 15,\n            };\n            var rowsLowCh2 = {\n              0x19: 1,\n              0x1a: 3,\n              0x1d: 5,\n              0x1e: 7,\n              0x1f: 9,\n              0x18: 11,\n              0x1b: 12,\n              0x1c: 14,\n            };\n            var rowsHighCh2 = {\n              0x19: 2,\n              0x1a: 4,\n              0x1d: 6,\n              0x1e: 8,\n              0x1f: 10,\n              0x1b: 13,\n              0x1c: 15,\n            };\n            var backgroundColors = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\", \"black\", \"transparent\"];\n            var VerboseLevel;\n\n            (function (VerboseLevel) {\n              VerboseLevel[(VerboseLevel[\"ERROR\"] = 0)] = \"ERROR\";\n              VerboseLevel[(VerboseLevel[\"TEXT\"] = 1)] = \"TEXT\";\n              VerboseLevel[(VerboseLevel[\"WARNING\"] = 2)] = \"WARNING\";\n              VerboseLevel[(VerboseLevel[\"INFO\"] = 2)] = \"INFO\";\n              VerboseLevel[(VerboseLevel[\"DEBUG\"] = 3)] = \"DEBUG\";\n              VerboseLevel[(VerboseLevel[\"DATA\"] = 3)] = \"DATA\";\n            })(VerboseLevel || (VerboseLevel = {}));\n\n            var CaptionsLogger = /*#__PURE__*/ (function () {\n              function CaptionsLogger() {\n                this.time = null;\n                this.verboseLevel = VerboseLevel.ERROR;\n              }\n\n              var _proto = CaptionsLogger.prototype;\n\n              _proto.log = function log(severity, msg) {\n                if (this.verboseLevel >= severity) {\n                  _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].log(this.time + \" [\" + severity + \"] \" + msg);\n                }\n              };\n\n              return CaptionsLogger;\n            })();\n\n            var numArrayToHexArray = function numArrayToHexArray(numArray) {\n              var hexArray = [];\n\n              for (var j = 0; j < numArray.length; j++) {\n                hexArray.push(numArray[j].toString(16));\n              }\n\n              return hexArray;\n            };\n\n            var PenState = /*#__PURE__*/ (function () {\n              function PenState(foreground, underline, italics, background, flash) {\n                this.foreground = void 0;\n                this.underline = void 0;\n                this.italics = void 0;\n                this.background = void 0;\n                this.flash = void 0;\n                this.foreground = foreground || \"white\";\n                this.underline = underline || false;\n                this.italics = italics || false;\n                this.background = background || \"black\";\n                this.flash = flash || false;\n              }\n\n              var _proto2 = PenState.prototype;\n\n              _proto2.reset = function reset() {\n                this.foreground = \"white\";\n                this.underline = false;\n                this.italics = false;\n                this.background = \"black\";\n                this.flash = false;\n              };\n\n              _proto2.setStyles = function setStyles(styles) {\n                var attribs = [\"foreground\", \"underline\", \"italics\", \"background\", \"flash\"];\n\n                for (var i = 0; i < attribs.length; i++) {\n                  var style = attribs[i];\n\n                  if (styles.hasOwnProperty(style)) {\n                    this[style] = styles[style];\n                  }\n                }\n              };\n\n              _proto2.isDefault = function isDefault() {\n                return this.foreground === \"white\" && !this.underline && !this.italics && this.background === \"black\" && !this.flash;\n              };\n\n              _proto2.equals = function equals(other) {\n                return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;\n              };\n\n              _proto2.copy = function copy(newPenState) {\n                this.foreground = newPenState.foreground;\n                this.underline = newPenState.underline;\n                this.italics = newPenState.italics;\n                this.background = newPenState.background;\n                this.flash = newPenState.flash;\n              };\n\n              _proto2.toString = function toString() {\n                return \"color=\" + this.foreground + \", underline=\" + this.underline + \", italics=\" + this.italics + \", background=\" + this.background + \", flash=\" + this.flash;\n              };\n\n              return PenState;\n            })();\n            /**\n             * Unicode character with styling and background.\n             * @constructor\n             */\n\n            var StyledUnicodeChar = /*#__PURE__*/ (function () {\n              function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {\n                this.uchar = void 0;\n                this.penState = void 0;\n                this.uchar = uchar || \" \"; // unicode character\n\n                this.penState = new PenState(foreground, underline, italics, background, flash);\n              }\n\n              var _proto3 = StyledUnicodeChar.prototype;\n\n              _proto3.reset = function reset() {\n                this.uchar = \" \";\n                this.penState.reset();\n              };\n\n              _proto3.setChar = function setChar(uchar, newPenState) {\n                this.uchar = uchar;\n                this.penState.copy(newPenState);\n              };\n\n              _proto3.setPenState = function setPenState(newPenState) {\n                this.penState.copy(newPenState);\n              };\n\n              _proto3.equals = function equals(other) {\n                return this.uchar === other.uchar && this.penState.equals(other.penState);\n              };\n\n              _proto3.copy = function copy(newChar) {\n                this.uchar = newChar.uchar;\n                this.penState.copy(newChar.penState);\n              };\n\n              _proto3.isEmpty = function isEmpty() {\n                return this.uchar === \" \" && this.penState.isDefault();\n              };\n\n              return StyledUnicodeChar;\n            })();\n            /**\n             * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n             * @constructor\n             */\n\n            var Row = /*#__PURE__*/ (function () {\n              function Row(logger) {\n                this.chars = void 0;\n                this.pos = void 0;\n                this.currPenState = void 0;\n                this.cueStartTime = void 0;\n                this.logger = void 0;\n                this.chars = [];\n\n                for (var i = 0; i < NR_COLS; i++) {\n                  this.chars.push(new StyledUnicodeChar());\n                }\n\n                this.logger = logger;\n                this.pos = 0;\n                this.currPenState = new PenState();\n              }\n\n              var _proto4 = Row.prototype;\n\n              _proto4.equals = function equals(other) {\n                var equal = true;\n\n                for (var i = 0; i < NR_COLS; i++) {\n                  if (!this.chars[i].equals(other.chars[i])) {\n                    equal = false;\n                    break;\n                  }\n                }\n\n                return equal;\n              };\n\n              _proto4.copy = function copy(other) {\n                for (var i = 0; i < NR_COLS; i++) {\n                  this.chars[i].copy(other.chars[i]);\n                }\n              };\n\n              _proto4.isEmpty = function isEmpty() {\n                var empty = true;\n\n                for (var i = 0; i < NR_COLS; i++) {\n                  if (!this.chars[i].isEmpty()) {\n                    empty = false;\n                    break;\n                  }\n                }\n\n                return empty;\n              };\n              /**\n               *  Set the cursor to a valid column.\n               */\n\n              _proto4.setCursor = function setCursor(absPos) {\n                if (this.pos !== absPos) {\n                  this.pos = absPos;\n                }\n\n                if (this.pos < 0) {\n                  this.logger.log(VerboseLevel.DEBUG, \"Negative cursor position \" + this.pos);\n                  this.pos = 0;\n                } else if (this.pos > NR_COLS) {\n                  this.logger.log(VerboseLevel.DEBUG, \"Too large cursor position \" + this.pos);\n                  this.pos = NR_COLS;\n                }\n              };\n              /**\n               * Move the cursor relative to current position.\n               */\n\n              _proto4.moveCursor = function moveCursor(relPos) {\n                var newPos = this.pos + relPos;\n\n                if (relPos > 1) {\n                  for (var i = this.pos + 1; i < newPos + 1; i++) {\n                    this.chars[i].setPenState(this.currPenState);\n                  }\n                }\n\n                this.setCursor(newPos);\n              };\n              /**\n               * Backspace, move one step back and clear character.\n               */\n\n              _proto4.backSpace = function backSpace() {\n                this.moveCursor(-1);\n                this.chars[this.pos].setChar(\" \", this.currPenState);\n              };\n\n              _proto4.insertChar = function insertChar(_byte2) {\n                if (_byte2 >= 0x90) {\n                  // Extended char\n                  this.backSpace();\n                }\n\n                var _char = getCharForByte(_byte2);\n\n                if (this.pos >= NR_COLS) {\n                  this.logger.log(VerboseLevel.ERROR, \"Cannot insert \" + _byte2.toString(16) + \" (\" + _char + \") at position \" + this.pos + \". Skipping it!\");\n                  return;\n                }\n\n                this.chars[this.pos].setChar(_char, this.currPenState);\n                this.moveCursor(1);\n              };\n\n              _proto4.clearFromPos = function clearFromPos(startPos) {\n                var i;\n\n                for (i = startPos; i < NR_COLS; i++) {\n                  this.chars[i].reset();\n                }\n              };\n\n              _proto4.clear = function clear() {\n                this.clearFromPos(0);\n                this.pos = 0;\n                this.currPenState.reset();\n              };\n\n              _proto4.clearToEndOfRow = function clearToEndOfRow() {\n                this.clearFromPos(this.pos);\n              };\n\n              _proto4.getTextString = function getTextString() {\n                var chars = [];\n                var empty = true;\n\n                for (var i = 0; i < NR_COLS; i++) {\n                  var _char2 = this.chars[i].uchar;\n\n                  if (_char2 !== \" \") {\n                    empty = false;\n                  }\n\n                  chars.push(_char2);\n                }\n\n                if (empty) {\n                  return \"\";\n                } else {\n                  return chars.join(\"\");\n                }\n              };\n\n              _proto4.setPenStyles = function setPenStyles(styles) {\n                this.currPenState.setStyles(styles);\n                var currChar = this.chars[this.pos];\n                currChar.setPenState(this.currPenState);\n              };\n\n              return Row;\n            })();\n            /**\n             * Keep a CEA-608 screen of 32x15 styled characters\n             * @constructor\n             */\n\n            var CaptionScreen = /*#__PURE__*/ (function () {\n              function CaptionScreen(logger) {\n                this.rows = void 0;\n                this.currRow = void 0;\n                this.nrRollUpRows = void 0;\n                this.lastOutputScreen = void 0;\n                this.logger = void 0;\n                this.rows = [];\n\n                for (var i = 0; i < NR_ROWS; i++) {\n                  this.rows.push(new Row(logger));\n                } // Note that we use zero-based numbering (0-14)\n\n                this.logger = logger;\n                this.currRow = NR_ROWS - 1;\n                this.nrRollUpRows = null;\n                this.lastOutputScreen = null;\n                this.reset();\n              }\n\n              var _proto5 = CaptionScreen.prototype;\n\n              _proto5.reset = function reset() {\n                for (var i = 0; i < NR_ROWS; i++) {\n                  this.rows[i].clear();\n                }\n\n                this.currRow = NR_ROWS - 1;\n              };\n\n              _proto5.equals = function equals(other) {\n                var equal = true;\n\n                for (var i = 0; i < NR_ROWS; i++) {\n                  if (!this.rows[i].equals(other.rows[i])) {\n                    equal = false;\n                    break;\n                  }\n                }\n\n                return equal;\n              };\n\n              _proto5.copy = function copy(other) {\n                for (var i = 0; i < NR_ROWS; i++) {\n                  this.rows[i].copy(other.rows[i]);\n                }\n              };\n\n              _proto5.isEmpty = function isEmpty() {\n                var empty = true;\n\n                for (var i = 0; i < NR_ROWS; i++) {\n                  if (!this.rows[i].isEmpty()) {\n                    empty = false;\n                    break;\n                  }\n                }\n\n                return empty;\n              };\n\n              _proto5.backSpace = function backSpace() {\n                var row = this.rows[this.currRow];\n                row.backSpace();\n              };\n\n              _proto5.clearToEndOfRow = function clearToEndOfRow() {\n                var row = this.rows[this.currRow];\n                row.clearToEndOfRow();\n              };\n              /**\n               * Insert a character (without styling) in the current row.\n               */\n\n              _proto5.insertChar = function insertChar(_char3) {\n                var row = this.rows[this.currRow];\n                row.insertChar(_char3);\n              };\n\n              _proto5.setPen = function setPen(styles) {\n                var row = this.rows[this.currRow];\n                row.setPenStyles(styles);\n              };\n\n              _proto5.moveCursor = function moveCursor(relPos) {\n                var row = this.rows[this.currRow];\n                row.moveCursor(relPos);\n              };\n\n              _proto5.setCursor = function setCursor(absPos) {\n                this.logger.log(VerboseLevel.INFO, \"setCursor: \" + absPos);\n                var row = this.rows[this.currRow];\n                row.setCursor(absPos);\n              };\n\n              _proto5.setPAC = function setPAC(pacData) {\n                this.logger.log(VerboseLevel.INFO, \"pacData = \" + JSON.stringify(pacData));\n                var newRow = pacData.row - 1;\n\n                if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n                  newRow = this.nrRollUpRows - 1;\n                } // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n\n                if (this.nrRollUpRows && this.currRow !== newRow) {\n                  // clear all rows first\n                  for (var i = 0; i < NR_ROWS; i++) {\n                    this.rows[i].clear();\n                  } // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n                  // topRowIndex - the start of rows to copy (inclusive index)\n\n                  var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.\n                  // We use the cueStartTime value to check this.\n\n                  var lastOutputScreen = this.lastOutputScreen;\n\n                  if (lastOutputScreen) {\n                    var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n                    var time = this.logger.time;\n\n                    if (prevLineTime && time !== null && prevLineTime < time) {\n                      for (var _i = 0; _i < this.nrRollUpRows; _i++) {\n                        this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);\n                      }\n                    }\n                  }\n                }\n\n                this.currRow = newRow;\n                var row = this.rows[this.currRow];\n\n                if (pacData.indent !== null) {\n                  var indent = pacData.indent;\n                  var prevPos = Math.max(indent - 1, 0);\n                  row.setCursor(pacData.indent);\n                  pacData.color = row.chars[prevPos].penState.foreground;\n                }\n\n                var styles = {\n                  foreground: pacData.color,\n                  underline: pacData.underline,\n                  italics: pacData.italics,\n                  background: \"black\",\n                  flash: false,\n                };\n                this.setPen(styles);\n              };\n              /**\n               * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n               */\n\n              _proto5.setBkgData = function setBkgData(bkgData) {\n                this.logger.log(VerboseLevel.INFO, \"bkgData = \" + JSON.stringify(bkgData));\n                this.backSpace();\n                this.setPen(bkgData);\n                this.insertChar(0x20); // Space\n              };\n\n              _proto5.setRollUpRows = function setRollUpRows(nrRows) {\n                this.nrRollUpRows = nrRows;\n              };\n\n              _proto5.rollUp = function rollUp() {\n                if (this.nrRollUpRows === null) {\n                  this.logger.log(VerboseLevel.DEBUG, \"roll_up but nrRollUpRows not set yet\");\n                  return; // Not properly setup\n                }\n\n                this.logger.log(VerboseLevel.TEXT, this.getDisplayText());\n                var topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n                var topRow = this.rows.splice(topRowIndex, 1)[0];\n                topRow.clear();\n                this.rows.splice(this.currRow, 0, topRow);\n                this.logger.log(VerboseLevel.INFO, \"Rolling up\"); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())\n              };\n              /**\n               * Get all non-empty rows with as unicode text.\n               */\n\n              _proto5.getDisplayText = function getDisplayText(asOneRow) {\n                asOneRow = asOneRow || false;\n                var displayText = [];\n                var text = \"\";\n                var rowNr = -1;\n\n                for (var i = 0; i < NR_ROWS; i++) {\n                  var rowText = this.rows[i].getTextString();\n\n                  if (rowText) {\n                    rowNr = i + 1;\n\n                    if (asOneRow) {\n                      displayText.push(\"Row \" + rowNr + \": '\" + rowText + \"'\");\n                    } else {\n                      displayText.push(rowText.trim());\n                    }\n                  }\n                }\n\n                if (displayText.length > 0) {\n                  if (asOneRow) {\n                    text = \"[\" + displayText.join(\" | \") + \"]\";\n                  } else {\n                    text = displayText.join(\"\\n\");\n                  }\n                }\n\n                return text;\n              };\n\n              _proto5.getTextAndFormat = function getTextAndFormat() {\n                return this.rows;\n              };\n\n              return CaptionScreen;\n            })(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\n            var Cea608Channel = /*#__PURE__*/ (function () {\n              function Cea608Channel(channelNumber, outputFilter, logger) {\n                this.chNr = void 0;\n                this.outputFilter = void 0;\n                this.mode = void 0;\n                this.verbose = void 0;\n                this.displayedMemory = void 0;\n                this.nonDisplayedMemory = void 0;\n                this.lastOutputScreen = void 0;\n                this.currRollUpRow = void 0;\n                this.writeScreen = void 0;\n                this.cueStartTime = void 0;\n                this.logger = void 0;\n                this.chNr = channelNumber;\n                this.outputFilter = outputFilter;\n                this.mode = null;\n                this.verbose = 0;\n                this.displayedMemory = new CaptionScreen(logger);\n                this.nonDisplayedMemory = new CaptionScreen(logger);\n                this.lastOutputScreen = new CaptionScreen(logger);\n                this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n                this.writeScreen = this.displayedMemory;\n                this.mode = null;\n                this.cueStartTime = null; // Keeps track of where a cue started.\n\n                this.logger = logger;\n              }\n\n              var _proto6 = Cea608Channel.prototype;\n\n              _proto6.reset = function reset() {\n                this.mode = null;\n                this.displayedMemory.reset();\n                this.nonDisplayedMemory.reset();\n                this.lastOutputScreen.reset();\n                this.outputFilter.reset();\n                this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n                this.writeScreen = this.displayedMemory;\n                this.mode = null;\n                this.cueStartTime = null;\n              };\n\n              _proto6.getHandler = function getHandler() {\n                return this.outputFilter;\n              };\n\n              _proto6.setHandler = function setHandler(newHandler) {\n                this.outputFilter = newHandler;\n              };\n\n              _proto6.setPAC = function setPAC(pacData) {\n                this.writeScreen.setPAC(pacData);\n              };\n\n              _proto6.setBkgData = function setBkgData(bkgData) {\n                this.writeScreen.setBkgData(bkgData);\n              };\n\n              _proto6.setMode = function setMode(newMode) {\n                if (newMode === this.mode) {\n                  return;\n                }\n\n                this.mode = newMode;\n                this.logger.log(VerboseLevel.INFO, \"MODE=\" + newMode);\n\n                if (this.mode === \"MODE_POP-ON\") {\n                  this.writeScreen = this.nonDisplayedMemory;\n                } else {\n                  this.writeScreen = this.displayedMemory;\n                  this.writeScreen.reset();\n                }\n\n                if (this.mode !== \"MODE_ROLL-UP\") {\n                  this.displayedMemory.nrRollUpRows = null;\n                  this.nonDisplayedMemory.nrRollUpRows = null;\n                }\n\n                this.mode = newMode;\n              };\n\n              _proto6.insertChars = function insertChars(chars) {\n                for (var i = 0; i < chars.length; i++) {\n                  this.writeScreen.insertChar(chars[i]);\n                }\n\n                var screen = this.writeScreen === this.displayedMemory ? \"DISP\" : \"NON_DISP\";\n                this.logger.log(VerboseLevel.INFO, screen + \": \" + this.writeScreen.getDisplayText(true));\n\n                if (this.mode === \"MODE_PAINT-ON\" || this.mode === \"MODE_ROLL-UP\") {\n                  this.logger.log(VerboseLevel.TEXT, \"DISPLAYED: \" + this.displayedMemory.getDisplayText(true));\n                  this.outputDataUpdate();\n                }\n              };\n\n              _proto6.ccRCL = function ccRCL() {\n                // Resume Caption Loading (switch mode to Pop On)\n                this.logger.log(VerboseLevel.INFO, \"RCL - Resume Caption Loading\");\n                this.setMode(\"MODE_POP-ON\");\n              };\n\n              _proto6.ccBS = function ccBS() {\n                // BackSpace\n                this.logger.log(VerboseLevel.INFO, \"BS - BackSpace\");\n\n                if (this.mode === \"MODE_TEXT\") {\n                  return;\n                }\n\n                this.writeScreen.backSpace();\n\n                if (this.writeScreen === this.displayedMemory) {\n                  this.outputDataUpdate();\n                }\n              };\n\n              _proto6.ccAOF = function ccAOF() {\n                // Reserved (formerly Alarm Off)\n              };\n\n              _proto6.ccAON = function ccAON() {\n                // Reserved (formerly Alarm On)\n              };\n\n              _proto6.ccDER = function ccDER() {\n                // Delete to End of Row\n                this.logger.log(VerboseLevel.INFO, \"DER- Delete to End of Row\");\n                this.writeScreen.clearToEndOfRow();\n                this.outputDataUpdate();\n              };\n\n              _proto6.ccRU = function ccRU(nrRows) {\n                // Roll-Up Captions-2,3,or 4 Rows\n                this.logger.log(VerboseLevel.INFO, \"RU(\" + nrRows + \") - Roll Up\");\n                this.writeScreen = this.displayedMemory;\n                this.setMode(\"MODE_ROLL-UP\");\n                this.writeScreen.setRollUpRows(nrRows);\n              };\n\n              _proto6.ccFON = function ccFON() {\n                // Flash On\n                this.logger.log(VerboseLevel.INFO, \"FON - Flash On\");\n                this.writeScreen.setPen({\n                  flash: true,\n                });\n              };\n\n              _proto6.ccRDC = function ccRDC() {\n                // Resume Direct Captioning (switch mode to PaintOn)\n                this.logger.log(VerboseLevel.INFO, \"RDC - Resume Direct Captioning\");\n                this.setMode(\"MODE_PAINT-ON\");\n              };\n\n              _proto6.ccTR = function ccTR() {\n                // Text Restart in text mode (not supported, however)\n                this.logger.log(VerboseLevel.INFO, \"TR\");\n                this.setMode(\"MODE_TEXT\");\n              };\n\n              _proto6.ccRTD = function ccRTD() {\n                // Resume Text Display in Text mode (not supported, however)\n                this.logger.log(VerboseLevel.INFO, \"RTD\");\n                this.setMode(\"MODE_TEXT\");\n              };\n\n              _proto6.ccEDM = function ccEDM() {\n                // Erase Displayed Memory\n                this.logger.log(VerboseLevel.INFO, \"EDM - Erase Displayed Memory\");\n                this.displayedMemory.reset();\n                this.outputDataUpdate(true);\n              };\n\n              _proto6.ccCR = function ccCR() {\n                // Carriage Return\n                this.logger.log(VerboseLevel.INFO, \"CR - Carriage Return\");\n                this.writeScreen.rollUp();\n                this.outputDataUpdate(true);\n              };\n\n              _proto6.ccENM = function ccENM() {\n                // Erase Non-Displayed Memory\n                this.logger.log(VerboseLevel.INFO, \"ENM - Erase Non-displayed Memory\");\n                this.nonDisplayedMemory.reset();\n              };\n\n              _proto6.ccEOC = function ccEOC() {\n                // End of Caption (Flip Memories)\n                this.logger.log(VerboseLevel.INFO, \"EOC - End Of Caption\");\n\n                if (this.mode === \"MODE_POP-ON\") {\n                  var tmp = this.displayedMemory;\n                  this.displayedMemory = this.nonDisplayedMemory;\n                  this.nonDisplayedMemory = tmp;\n                  this.writeScreen = this.nonDisplayedMemory;\n                  this.logger.log(VerboseLevel.TEXT, \"DISP: \" + this.displayedMemory.getDisplayText());\n                }\n\n                this.outputDataUpdate(true);\n              };\n\n              _proto6.ccTO = function ccTO(nrCols) {\n                // Tab Offset 1,2, or 3 columns\n                this.logger.log(VerboseLevel.INFO, \"TO(\" + nrCols + \") - Tab Offset\");\n                this.writeScreen.moveCursor(nrCols);\n              };\n\n              _proto6.ccMIDROW = function ccMIDROW(secondByte) {\n                // Parse MIDROW command\n                var styles = {\n                  flash: false,\n                };\n                styles.underline = secondByte % 2 === 1;\n                styles.italics = secondByte >= 0x2e;\n\n                if (!styles.italics) {\n                  var colorIndex = Math.floor(secondByte / 2) - 0x10;\n                  var colors = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\"];\n                  styles.foreground = colors[colorIndex];\n                } else {\n                  styles.foreground = \"white\";\n                }\n\n                this.logger.log(VerboseLevel.INFO, \"MIDROW: \" + JSON.stringify(styles));\n                this.writeScreen.setPen(styles);\n              };\n\n              _proto6.outputDataUpdate = function outputDataUpdate(dispatch) {\n                if (dispatch === void 0) {\n                  dispatch = false;\n                }\n\n                var time = this.logger.time;\n\n                if (time === null) {\n                  return;\n                }\n\n                if (this.outputFilter) {\n                  if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n                    // Start of a new cue\n                    this.cueStartTime = time;\n                  } else {\n                    if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n                      this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);\n\n                      if (dispatch && this.outputFilter.dispatchCue) {\n                        this.outputFilter.dispatchCue();\n                      }\n\n                      this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\n                    }\n                  }\n\n                  this.lastOutputScreen.copy(this.displayedMemory);\n                }\n              };\n\n              _proto6.cueSplitAtTime = function cueSplitAtTime(t) {\n                if (this.outputFilter) {\n                  if (!this.displayedMemory.isEmpty()) {\n                    if (this.outputFilter.newCue) {\n                      this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);\n                    }\n\n                    this.cueStartTime = t;\n                  }\n                }\n              };\n\n              return Cea608Channel;\n            })();\n\n            var Cea608Parser = /*#__PURE__*/ (function () {\n              function Cea608Parser(field, out1, out2) {\n                this.channels = void 0;\n                this.currentChannel = 0;\n                this.cmdHistory = void 0;\n                this.logger = void 0;\n                var logger = new CaptionsLogger();\n                this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];\n                this.cmdHistory = createCmdHistory();\n                this.logger = logger;\n              }\n\n              var _proto7 = Cea608Parser.prototype;\n\n              _proto7.getHandler = function getHandler(channel) {\n                return this.channels[channel].getHandler();\n              };\n\n              _proto7.setHandler = function setHandler(channel, newHandler) {\n                this.channels[channel].setHandler(newHandler);\n              };\n              /**\n               * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n               */\n\n              _proto7.addData = function addData(time, byteList) {\n                var cmdFound;\n                var a;\n                var b;\n                var charsFound = false;\n                this.logger.time = time;\n\n                for (var i = 0; i < byteList.length; i += 2) {\n                  a = byteList[i] & 0x7f;\n                  b = byteList[i + 1] & 0x7f;\n\n                  if (a === 0 && b === 0) {\n                    continue;\n                  } else {\n                    this.logger.log(VerboseLevel.DATA, \"[\" + numArrayToHexArray([byteList[i], byteList[i + 1]]) + \"] -> (\" + numArrayToHexArray([a, b]) + \")\");\n                  }\n\n                  cmdFound = this.parseCmd(a, b);\n\n                  if (!cmdFound) {\n                    cmdFound = this.parseMidrow(a, b);\n                  }\n\n                  if (!cmdFound) {\n                    cmdFound = this.parsePAC(a, b);\n                  }\n\n                  if (!cmdFound) {\n                    cmdFound = this.parseBackgroundAttributes(a, b);\n                  }\n\n                  if (!cmdFound) {\n                    charsFound = this.parseChars(a, b);\n\n                    if (charsFound) {\n                      var currChNr = this.currentChannel;\n\n                      if (currChNr && currChNr > 0) {\n                        var channel = this.channels[currChNr];\n                        channel.insertChars(charsFound);\n                      } else {\n                        this.logger.log(VerboseLevel.WARNING, \"No channel found yet. TEXT-MODE?\");\n                      }\n                    }\n                  }\n\n                  if (!cmdFound && !charsFound) {\n                    this.logger.log(VerboseLevel.WARNING, \"Couldn't parse cleaned data \" + numArrayToHexArray([a, b]) + \" orig: \" + numArrayToHexArray([byteList[i], byteList[i + 1]]));\n                  }\n                }\n              };\n              /**\n               * Parse Command.\n               * @returns {Boolean} Tells if a command was found\n               */\n\n              _proto7.parseCmd = function parseCmd(a, b) {\n                var cmdHistory = this.cmdHistory;\n                var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;\n                var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;\n\n                if (!(cond1 || cond2)) {\n                  return false;\n                }\n\n                if (hasCmdRepeated(a, b, cmdHistory)) {\n                  setLastCmd(null, null, cmdHistory);\n                  this.logger.log(VerboseLevel.DEBUG, \"Repeated command (\" + numArrayToHexArray([a, b]) + \") is dropped\");\n                  return true;\n                }\n\n                var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;\n                var channel = this.channels[chNr];\n\n                if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {\n                  if (b === 0x20) {\n                    channel.ccRCL();\n                  } else if (b === 0x21) {\n                    channel.ccBS();\n                  } else if (b === 0x22) {\n                    channel.ccAOF();\n                  } else if (b === 0x23) {\n                    channel.ccAON();\n                  } else if (b === 0x24) {\n                    channel.ccDER();\n                  } else if (b === 0x25) {\n                    channel.ccRU(2);\n                  } else if (b === 0x26) {\n                    channel.ccRU(3);\n                  } else if (b === 0x27) {\n                    channel.ccRU(4);\n                  } else if (b === 0x28) {\n                    channel.ccFON();\n                  } else if (b === 0x29) {\n                    channel.ccRDC();\n                  } else if (b === 0x2a) {\n                    channel.ccTR();\n                  } else if (b === 0x2b) {\n                    channel.ccRTD();\n                  } else if (b === 0x2c) {\n                    channel.ccEDM();\n                  } else if (b === 0x2d) {\n                    channel.ccCR();\n                  } else if (b === 0x2e) {\n                    channel.ccENM();\n                  } else if (b === 0x2f) {\n                    channel.ccEOC();\n                  }\n                } else {\n                  // a == 0x17 || a == 0x1F\n                  channel.ccTO(b - 0x20);\n                }\n\n                setLastCmd(a, b, cmdHistory);\n                this.currentChannel = chNr;\n                return true;\n              };\n              /**\n               * Parse midrow styling command\n               * @returns {Boolean}\n               */\n\n              _proto7.parseMidrow = function parseMidrow(a, b) {\n                var chNr = 0;\n\n                if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {\n                  if (a === 0x11) {\n                    chNr = 1;\n                  } else {\n                    chNr = 2;\n                  }\n\n                  if (chNr !== this.currentChannel) {\n                    this.logger.log(VerboseLevel.ERROR, \"Mismatch channel in midrow parsing\");\n                    return false;\n                  }\n\n                  var channel = this.channels[chNr];\n\n                  if (!channel) {\n                    return false;\n                  }\n\n                  channel.ccMIDROW(b);\n                  this.logger.log(VerboseLevel.DEBUG, \"MIDROW (\" + numArrayToHexArray([a, b]) + \")\");\n                  return true;\n                }\n\n                return false;\n              };\n              /**\n               * Parse Preable Access Codes (Table 53).\n               * @returns {Boolean} Tells if PAC found\n               */\n\n              _proto7.parsePAC = function parsePAC(a, b) {\n                var row;\n                var cmdHistory = this.cmdHistory;\n                var case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1f)) && b >= 0x40 && b <= 0x7f;\n                var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;\n\n                if (!(case1 || case2)) {\n                  return false;\n                }\n\n                if (hasCmdRepeated(a, b, cmdHistory)) {\n                  setLastCmd(null, null, cmdHistory);\n                  return true; // Repeated commands are dropped (once)\n                }\n\n                var chNr = a <= 0x17 ? 1 : 2;\n\n                if (b >= 0x40 && b <= 0x5f) {\n                  row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n                } else {\n                  // 0x60 <= b <= 0x7F\n                  row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];\n                }\n\n                var channel = this.channels[chNr];\n\n                if (!channel) {\n                  return false;\n                }\n\n                channel.setPAC(this.interpretPAC(row, b));\n                setLastCmd(a, b, cmdHistory);\n                this.currentChannel = chNr;\n                return true;\n              };\n              /**\n               * Interpret the second byte of the pac, and return the information.\n               * @returns {Object} pacData with style parameters.\n               */\n\n              _proto7.interpretPAC = function interpretPAC(row, _byte3) {\n                var pacIndex;\n                var pacData = {\n                  color: null,\n                  italics: false,\n                  indent: null,\n                  underline: false,\n                  row: row,\n                };\n\n                if (_byte3 > 0x5f) {\n                  pacIndex = _byte3 - 0x60;\n                } else {\n                  pacIndex = _byte3 - 0x40;\n                }\n\n                pacData.underline = (pacIndex & 1) === 1;\n\n                if (pacIndex <= 0xd) {\n                  pacData.color = [\"white\", \"green\", \"blue\", \"cyan\", \"red\", \"yellow\", \"magenta\", \"white\"][Math.floor(pacIndex / 2)];\n                } else if (pacIndex <= 0xf) {\n                  pacData.italics = true;\n                  pacData.color = \"white\";\n                } else {\n                  pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;\n                }\n\n                return pacData; // Note that row has zero offset. The spec uses 1.\n              };\n              /**\n               * Parse characters.\n               * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n               */\n\n              _proto7.parseChars = function parseChars(a, b) {\n                var channelNr;\n                var charCodes = null;\n                var charCode1 = null;\n\n                if (a >= 0x19) {\n                  channelNr = 2;\n                  charCode1 = a - 8;\n                } else {\n                  channelNr = 1;\n                  charCode1 = a;\n                }\n\n                if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n                  // Special character\n                  var oneCode;\n\n                  if (charCode1 === 0x11) {\n                    oneCode = b + 0x50;\n                  } else if (charCode1 === 0x12) {\n                    oneCode = b + 0x70;\n                  } else {\n                    oneCode = b + 0x90;\n                  }\n\n                  this.logger.log(VerboseLevel.INFO, \"Special char '\" + getCharForByte(oneCode) + \"' in channel \" + channelNr);\n                  charCodes = [oneCode];\n                } else if (a >= 0x20 && a <= 0x7f) {\n                  charCodes = b === 0 ? [a] : [a, b];\n                }\n\n                if (charCodes) {\n                  var hexCodes = numArrayToHexArray(charCodes);\n                  this.logger.log(VerboseLevel.DEBUG, \"Char codes =  \" + hexCodes.join(\",\"));\n                  setLastCmd(a, b, this.cmdHistory);\n                }\n\n                return charCodes;\n              };\n              /**\n               * Parse extended background attributes as well as new foreground color black.\n               * @returns {Boolean} Tells if background attributes are found\n               */\n\n              _proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {\n                var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;\n                var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;\n\n                if (!(case1 || case2)) {\n                  return false;\n                }\n\n                var index;\n                var bkgData = {};\n\n                if (a === 0x10 || a === 0x18) {\n                  index = Math.floor((b - 0x20) / 2);\n                  bkgData.background = backgroundColors[index];\n\n                  if (b % 2 === 1) {\n                    bkgData.background = bkgData.background + \"_semi\";\n                  }\n                } else if (b === 0x2d) {\n                  bkgData.background = \"transparent\";\n                } else {\n                  bkgData.foreground = \"black\";\n\n                  if (b === 0x2f) {\n                    bkgData.underline = true;\n                  }\n                }\n\n                var chNr = a <= 0x17 ? 1 : 2;\n                var channel = this.channels[chNr];\n                channel.setBkgData(bkgData);\n                setLastCmd(a, b, this.cmdHistory);\n                return true;\n              };\n              /**\n               * Reset state of parser and its channels.\n               */\n\n              _proto7.reset = function reset() {\n                for (var i = 0; i < Object.keys(this.channels).length; i++) {\n                  var channel = this.channels[i];\n\n                  if (channel) {\n                    channel.reset();\n                  }\n                }\n\n                this.cmdHistory = createCmdHistory();\n              };\n              /**\n               * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n               */\n\n              _proto7.cueSplitAtTime = function cueSplitAtTime(t) {\n                for (var i = 0; i < this.channels.length; i++) {\n                  var channel = this.channels[i];\n\n                  if (channel) {\n                    channel.cueSplitAtTime(t);\n                  }\n                }\n              };\n\n              return Cea608Parser;\n            })();\n\n            function setLastCmd(a, b, cmdHistory) {\n              cmdHistory.a = a;\n              cmdHistory.b = b;\n            }\n\n            function hasCmdRepeated(a, b, cmdHistory) {\n              return cmdHistory.a === a && cmdHistory.b === b;\n            }\n\n            function createCmdHistory() {\n              return {\n                a: null,\n                b: null,\n              };\n            }\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = Cea608Parser;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/codecs.ts\":\n          /*!*****************************!*\\\n  !*** ./src/utils/codecs.ts ***!\n  \\*****************************/\n          /*! exports provided: isCodecType, isCodecSupportedInMp4 */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isCodecType\", function () {\n              return isCodecType;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isCodecSupportedInMp4\", function () {\n              return isCodecSupportedInMp4;\n            });\n            // from http://mp4ra.org/codecs.html\n            var sampleEntryCodesISO = {\n              audio: {\n                a3ds: true,\n                \"ac-3\": true,\n                \"ac-4\": true,\n                alac: true,\n                alaw: true,\n                dra1: true,\n                \"dts+\": true,\n                \"dts-\": true,\n                dtsc: true,\n                dtse: true,\n                dtsh: true,\n                \"ec-3\": true,\n                enca: true,\n                g719: true,\n                g726: true,\n                m4ae: true,\n                mha1: true,\n                mha2: true,\n                mhm1: true,\n                mhm2: true,\n                mlpa: true,\n                mp4a: true,\n                \"raw \": true,\n                Opus: true,\n                samr: true,\n                sawb: true,\n                sawp: true,\n                sevc: true,\n                sqcp: true,\n                ssmv: true,\n                twos: true,\n                ulaw: true,\n              },\n              video: {\n                avc1: true,\n                avc2: true,\n                avc3: true,\n                avc4: true,\n                avcp: true,\n                av01: true,\n                drac: true,\n                dvav: true,\n                dvhe: true,\n                encv: true,\n                hev1: true,\n                hvc1: true,\n                mjp2: true,\n                mp4v: true,\n                mvc1: true,\n                mvc2: true,\n                mvc3: true,\n                mvc4: true,\n                resv: true,\n                rv60: true,\n                s263: true,\n                svc1: true,\n                svc2: true,\n                \"vc-1\": true,\n                vp08: true,\n                vp09: true,\n              },\n              text: {\n                stpp: true,\n                wvtt: true,\n              },\n            };\n            function isCodecType(codec, type) {\n              var typeCodes = sampleEntryCodesISO[type];\n              return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n            }\n            function isCodecSupportedInMp4(codec, type) {\n              return MediaSource.isTypeSupported((type || \"video\") + '/mp4;codecs=\"' + codec + '\"');\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/cues.ts\":\n          /*!***************************!*\\\n  !*** ./src/utils/cues.ts ***!\n  \\***************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttparser */ \"./src/utils/vttparser.ts\");\n            /* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webvtt-parser */ \"./src/utils/webvtt-parser.ts\");\n            /* harmony import */ var _texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./texttrack-utils */ \"./src/utils/texttrack-utils.ts\");\n\n            var WHITESPACE_CHAR = /\\s/;\n            var Cues = {\n              newCue: function newCue(track, startTime, endTime, captionScreen) {\n                var result = [];\n                var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers\n\n                var cue;\n                var indenting;\n                var indent;\n                var text;\n                var Cue = self.VTTCue || self.TextTrackCue;\n\n                for (var r = 0; r < captionScreen.rows.length; r++) {\n                  row = captionScreen.rows[r];\n                  indenting = true;\n                  indent = 0;\n                  text = \"\";\n\n                  if (!row.isEmpty()) {\n                    for (var c = 0; c < row.chars.length; c++) {\n                      if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {\n                        indent++;\n                      } else {\n                        text += row.chars[c].uchar;\n                        indenting = false;\n                      }\n                    } // To be used for cleaning-up orphaned roll-up captions\n\n                    row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n\n                    if (startTime === endTime) {\n                      endTime += 0.0001;\n                    }\n\n                    if (indent >= 16) {\n                      indent--;\n                    } else {\n                      indent++;\n                    }\n\n                    var cueText = Object(_vttparser__WEBPACK_IMPORTED_MODULE_0__[\"fixLineBreaks\"])(text.trim());\n                    var id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_1__[\"generateCueId\"])(startTime, endTime, cueText); // If this cue already exists in the track do not push it\n\n                    if (!track || !track.cues || !track.cues.getCueById(id)) {\n                      cue = new Cue(startTime, endTime, cueText);\n                      cue.id = id;\n                      cue.line = r + 1;\n                      cue.align = \"left\"; // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)\n                      // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608\n                      // Firefox throws an exception and captions break with out of bounds 0-100 values\n\n                      cue.position = 10 + Math.min(80, Math.floor((indent * 8) / 32) * 10);\n                      result.push(cue);\n                    }\n                  }\n                }\n\n                if (track && result.length) {\n                  // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome\n                  result.sort(function (cueA, cueB) {\n                    if (cueA.line === \"auto\" || cueB.line === \"auto\") {\n                      return 0;\n                    }\n\n                    if (cueA.line > 8 && cueB.line > 8) {\n                      return cueB.line - cueA.line;\n                    }\n\n                    return cueA.line - cueB.line;\n                  });\n                  result.forEach(function (cue) {\n                    return Object(_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__[\"addCueToTrack\"])(track, cue);\n                  });\n                }\n\n                return result;\n              },\n            };\n            /* harmony default export */ __webpack_exports__[\"default\"] = Cues;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/discontinuities.ts\":\n          /*!**************************************!*\\\n  !*** ./src/utils/discontinuities.ts ***!\n  \\**************************************/\n          /*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT, alignFragmentByPDTDelta, alignMediaPlaylistByPDT */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"findFirstFragWithCC\", function () {\n              return findFirstFragWithCC;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"shouldAlignOnDiscontinuities\", function () {\n              return shouldAlignOnDiscontinuities;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"findDiscontinuousReferenceFrag\", function () {\n              return findDiscontinuousReferenceFrag;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"adjustSlidingStart\", function () {\n              return adjustSlidingStart;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"alignStream\", function () {\n              return alignStream;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"alignPDT\", function () {\n              return alignPDT;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"alignFragmentByPDTDelta\", function () {\n              return alignFragmentByPDTDelta;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"alignMediaPlaylistByPDT\", function () {\n              return alignMediaPlaylistByPDT;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ \"./src/controller/level-helper.ts\");\n\n            function findFirstFragWithCC(fragments, cc) {\n              var firstFrag = null;\n\n              for (var i = 0, len = fragments.length; i < len; i++) {\n                var currentFrag = fragments[i];\n\n                if (currentFrag && currentFrag.cc === cc) {\n                  firstFrag = currentFrag;\n                  break;\n                }\n              }\n\n              return firstFrag;\n            }\n            function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {\n              if (lastLevel.details) {\n                if (details.endCC > details.startCC || (lastFrag && lastFrag.cc < details.startCC)) {\n                  return true;\n                }\n              }\n\n              return false;\n            } // Find the first frag in the previous level which matches the CC of the first frag of the new level\n\n            function findDiscontinuousReferenceFrag(prevDetails, curDetails) {\n              var prevFrags = prevDetails.fragments;\n              var curFrags = curDetails.fragments;\n\n              if (!curFrags.length || !prevFrags.length) {\n                _logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].log(\"No fragments to align\");\n                return;\n              }\n\n              var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n              if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n                _logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].log(\"No frag in previous level to align on\");\n                return;\n              }\n\n              return prevStartFrag;\n            }\n\n            function adjustFragmentStart(frag, sliding) {\n              if (frag) {\n                var start = frag.start + sliding;\n                frag.start = frag.startPTS = start;\n                frag.endPTS = start + frag.duration;\n              }\n            }\n\n            function adjustSlidingStart(sliding, details) {\n              // Update segments\n              var fragments = details.fragments;\n\n              for (var i = 0, len = fragments.length; i < len; i++) {\n                adjustFragmentStart(fragments[i], sliding);\n              } // Update LL-CiderHls parts at the end of the playlist\n\n              if (details.fragmentHint) {\n                adjustFragmentStart(details.fragmentHint, sliding);\n              }\n\n              details.alignedSliding = true;\n            }\n            /**\n             * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n             * contiguous stream with the last fragments.\n             * The PTS of a fragment lets CiderHls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n             * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n             * and an extra download.\n             * @param lastFrag\n             * @param lastLevel\n             * @param details\n             */\n\n            function alignStream(lastFrag, lastLevel, details) {\n              if (!lastLevel) {\n                return;\n              }\n\n              alignDiscontinuities(lastFrag, details, lastLevel);\n\n              if (!details.alignedSliding && lastLevel.details) {\n                // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n                // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n                // discontinuity sequence.\n                alignPDT(details, lastLevel.details);\n              }\n\n              if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {\n                // Try to align on sn so that we pick a better start fragment.\n                // Do not perform this on playlists with delta updates as this is only to align levels on switch\n                // and adjustSliding only adjusts fragments after skippedSegments.\n                Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__[\"adjustSliding\"])(lastLevel.details, details);\n              }\n            }\n            /**\n             * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n             * discontinuity sequence.\n             * @param lastFrag - The last Fragment which shares the same discontinuity sequence\n             * @param lastLevel - The details of the last loaded level\n             * @param details - The details of the new level\n             */\n\n            function alignDiscontinuities(lastFrag, details, lastLevel) {\n              if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n                var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n\n                if (referenceFrag && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(referenceFrag.start)) {\n                  _logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].log(\"Adjusting PTS using last level due to CC increase within current level \" + details.url);\n                  adjustSlidingStart(referenceFrag.start, details);\n                }\n              }\n            }\n            /**\n             * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n             * @param details - The details of the new level\n             * @param lastDetails - The details of the last loaded level\n             */\n\n            function alignPDT(details, lastDetails) {\n              // This check protects the unsafe \"!\" usage below for null program date time access.\n              if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {\n                return;\n              } // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n              // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n              // then we can deduce that playlist B sliding is 1000+8 = 1008s\n\n              var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.\n\n              var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds\n\n              var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n\n              if (sliding && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(sliding)) {\n                _logger__WEBPACK_IMPORTED_MODULE_1__[\"logger\"].log(\"Adjusting PTS using programDateTime delta \" + (newPDT - lastPDT) + \"ms, sliding:\" + sliding.toFixed(3) + \" \" + details.url + \" \");\n                adjustSlidingStart(sliding, details);\n              }\n            }\n            function alignFragmentByPDTDelta(frag, delta) {\n              var programDateTime = frag.programDateTime;\n              if (!programDateTime) return;\n              var start = (programDateTime - delta) / 1000;\n              frag.start = frag.startPTS = start;\n              frag.endPTS = start + frag.duration;\n            }\n            /**\n             * Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts\n             * the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,\n             * this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,\n             * and uses the \"wallclock\"/PDT timeline as a cross-reference to `details`, adjusting the presentation\n             * times/timelines of `details` accordingly.\n             * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,\n             * the primary purpose of this function is to ensure the \"local timelines\" of audio/subtitle tracks\n             * are aligned to the main/video timeline, using PDT as the cross-reference/\"anchor\" that should\n             * be consistent across playlists, per the CiderHls spec.\n             * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).\n             * @param refDetails - The details of the reference rendition with start and PDT times for alignment.\n             */\n\n            function alignMediaPlaylistByPDT(details, refDetails) {\n              // This check protects the unsafe \"!\" usage below for null program date time access.\n              if (!refDetails.fragments.length || !details.hasProgramDateTime || !refDetails.hasProgramDateTime) {\n                return;\n              }\n\n              var refPDT = refDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.\n\n              var refStart = refDetails.fragments[0].start; // Use the delta between the reference details' presentation timeline's start time and its PDT\n              // to align the other rendtion's timeline.\n\n              var delta = refPDT - refStart * 1000; // Per spec: \"If any Media Playlist in a Master Playlist contains an EXT-X-PROGRAM-DATE-TIME tag, then all\n              // Media Playlists in that Master Playlist MUST contain EXT-X-PROGRAM-DATE-TIME tags with consistent mappings\n              // of date and time to media timestamps.\"\n              // So we should be able to use each rendition's PDT as a reference time and use the delta to compute our relevant\n              // start and end times.\n              // NOTE: This code assumes each level/details timelines have already been made \"internally consistent\"\n\n              details.fragments.forEach(function (frag) {\n                alignFragmentByPDTDelta(frag, delta);\n              });\n\n              if (details.fragmentHint) {\n                alignFragmentByPDTDelta(details.fragmentHint, delta);\n              }\n\n              details.alignedSliding = true;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/ewma-bandwidth-estimator.ts\":\n          /*!***********************************************!*\\\n  !*** ./src/utils/ewma-bandwidth-estimator.ts ***!\n  \\***********************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ \"./src/utils/ewma.ts\");\n            /*\n             * EWMA Bandwidth Estimator\n             *  - heavily inspired from shaka-player\n             * Tracks bandwidth samples and estimates available bandwidth.\n             * Based on the minimum of two exponentially-weighted moving averages with\n             * different half-lives.\n             */\n\n            var EwmaBandWidthEstimator = /*#__PURE__*/ (function () {\n              function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {\n                this.defaultEstimate_ = void 0;\n                this.minWeight_ = void 0;\n                this.minDelayMs_ = void 0;\n                this.slow_ = void 0;\n                this.fast_ = void 0;\n                this.defaultEstimate_ = defaultEstimate;\n                this.minWeight_ = 0.001;\n                this.minDelayMs_ = 50;\n                this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__[\"default\"](slow);\n                this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__[\"default\"](fast);\n              }\n\n              var _proto = EwmaBandWidthEstimator.prototype;\n\n              _proto.update = function update(slow, fast) {\n                var slow_ = this.slow_,\n                  fast_ = this.fast_;\n\n                if (this.slow_.halfLife !== slow) {\n                  this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__[\"default\"](slow, slow_.getEstimate(), slow_.getTotalWeight());\n                }\n\n                if (this.fast_.halfLife !== fast) {\n                  this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__[\"default\"](fast, fast_.getEstimate(), fast_.getTotalWeight());\n                }\n              };\n\n              _proto.sample = function sample(durationMs, numBytes) {\n                durationMs = Math.max(durationMs, this.minDelayMs_);\n                var numBits = 8 * numBytes; // weight is duration in seconds\n\n                var durationS = durationMs / 1000; // value is bandwidth in bits/s\n\n                var bandwidthInBps = numBits / durationS;\n                this.fast_.sample(durationS, bandwidthInBps);\n                this.slow_.sample(durationS, bandwidthInBps);\n              };\n\n              _proto.canEstimate = function canEstimate() {\n                var fast = this.fast_;\n                return fast && fast.getTotalWeight() >= this.minWeight_;\n              };\n\n              _proto.getEstimate = function getEstimate() {\n                if (this.canEstimate()) {\n                  // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n                  // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n                  // Take the minimum of these two estimates.  This should have the effect of\n                  // adapting down quickly, but up more slowly.\n                  return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n                } else {\n                  return this.defaultEstimate_;\n                }\n              };\n\n              _proto.destroy = function destroy() {};\n\n              return EwmaBandWidthEstimator;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = EwmaBandWidthEstimator;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/ewma.ts\":\n          /*!***************************!*\\\n  !*** ./src/utils/ewma.ts ***!\n  \\***************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /*\n             * compute an Exponential Weighted moving average\n             * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n             *  - heavily inspired from shaka-player\n             */\n            var EWMA = /*#__PURE__*/ (function () {\n              //  About half of the estimated value will be from the last |halfLife| samples by weight.\n              function EWMA(halfLife, estimate, weight) {\n                if (estimate === void 0) {\n                  estimate = 0;\n                }\n\n                if (weight === void 0) {\n                  weight = 0;\n                }\n\n                this.halfLife = void 0;\n                this.alpha_ = void 0;\n                this.estimate_ = void 0;\n                this.totalWeight_ = void 0;\n                this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly.\n\n                this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n                this.estimate_ = estimate;\n                this.totalWeight_ = weight;\n              }\n\n              var _proto = EWMA.prototype;\n\n              _proto.sample = function sample(weight, value) {\n                var adjAlpha = Math.pow(this.alpha_, weight);\n                this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n                this.totalWeight_ += weight;\n              };\n\n              _proto.getTotalWeight = function getTotalWeight() {\n                return this.totalWeight_;\n              };\n\n              _proto.getEstimate = function getEstimate() {\n                if (this.alpha_) {\n                  var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n\n                  if (zeroFactor) {\n                    return this.estimate_ / zeroFactor;\n                  }\n                }\n\n                return this.estimate_;\n              };\n\n              return EWMA;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = EWMA;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/fetch-loader.ts\":\n          /*!***********************************!*\\\n  !*** ./src/utils/fetch-loader.ts ***!\n  \\***********************************/\n          /*! exports provided: fetchSupported, default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"fetchSupported\", function () {\n              return fetchSupported;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ \"./src/loader/load-stats.ts\");\n            /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ \"./src/demux/chunk-cache.ts\");\n\n            function _inheritsLoose(subClass, superClass) {\n              subClass.prototype = Object.create(superClass.prototype);\n              subClass.prototype.constructor = subClass;\n              _setPrototypeOf(subClass, superClass);\n            }\n\n            function _wrapNativeSuper(Class) {\n              var _cache = typeof Map === \"function\" ? new Map() : undefined;\n              _wrapNativeSuper = function _wrapNativeSuper(Class) {\n                if (Class === null || !_isNativeFunction(Class)) return Class;\n                if (typeof Class !== \"function\") {\n                  throw new TypeError(\"Super expression must either be null or a function\");\n                }\n                if (typeof _cache !== \"undefined\") {\n                  if (_cache.has(Class)) return _cache.get(Class);\n                  _cache.set(Class, Wrapper);\n                }\n                function Wrapper() {\n                  return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n                }\n                Wrapper.prototype = Object.create(Class.prototype, {\n                  constructor: {\n                    value: Wrapper,\n                    enumerable: false,\n                    writable: true,\n                    configurable: true,\n                  },\n                });\n                return _setPrototypeOf(Wrapper, Class);\n              };\n              return _wrapNativeSuper(Class);\n            }\n\n            function _construct(Parent, args, Class) {\n              if (_isNativeReflectConstruct()) {\n                _construct = Reflect.construct;\n              } else {\n                _construct = function _construct(Parent, args, Class) {\n                  var a = [null];\n                  a.push.apply(a, args);\n                  var Constructor = Function.bind.apply(Parent, a);\n                  var instance = new Constructor();\n                  if (Class) _setPrototypeOf(instance, Class.prototype);\n                  return instance;\n                };\n              }\n              return _construct.apply(null, arguments);\n            }\n\n            function _isNativeReflectConstruct() {\n              if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n              if (Reflect.construct.sham) return false;\n              if (typeof Proxy === \"function\") return true;\n              try {\n                Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n                return true;\n              } catch (e) {\n                return false;\n              }\n            }\n\n            function _isNativeFunction(fn) {\n              return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n            }\n\n            function _setPrototypeOf(o, p) {\n              _setPrototypeOf =\n                Object.setPrototypeOf ||\n                function _setPrototypeOf(o, p) {\n                  o.__proto__ = p;\n                  return o;\n                };\n              return _setPrototypeOf(o, p);\n            }\n\n            function _getPrototypeOf(o) {\n              _getPrototypeOf = Object.setPrototypeOf\n                ? Object.getPrototypeOf\n                : function _getPrototypeOf(o) {\n                    return o.__proto__ || Object.getPrototypeOf(o);\n                  };\n              return _getPrototypeOf(o);\n            }\n\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            function fetchSupported() {\n              if (\n                // @ts-ignore\n                self.fetch &&\n                self.AbortController &&\n                self.ReadableStream &&\n                self.Request\n              ) {\n                try {\n                  new self.ReadableStream({}); // eslint-disable-line no-new\n\n                  return true;\n                } catch (e) {\n                  /* noop */\n                }\n              }\n\n              return false;\n            }\n\n            var FetchLoader = /*#__PURE__*/ (function () {\n              function FetchLoader(\n                config\n                /* CiderHlsConfig */\n              ) {\n                this.fetchSetup = void 0;\n                this.requestTimeout = void 0;\n                this.request = void 0;\n                this.response = void 0;\n                this.controller = void 0;\n                this.context = void 0;\n                this.config = null;\n                this.callbacks = null;\n                this.stats = void 0;\n                this.loader = null;\n                this.fetchSetup = config.fetchSetup || getRequest;\n                this.controller = new self.AbortController();\n                this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__[\"LoadStats\"]();\n              }\n\n              var _proto = FetchLoader.prototype;\n\n              _proto.destroy = function destroy() {\n                this.loader = this.callbacks = null;\n                this.abortInternal();\n              };\n\n              _proto.abortInternal = function abortInternal() {\n                var response = this.response;\n\n                if (!response || !response.ok) {\n                  this.stats.aborted = true;\n                  this.controller.abort();\n                }\n              };\n\n              _proto.abort = function abort() {\n                var _this$callbacks;\n\n                this.abortInternal();\n\n                if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {\n                  this.callbacks.onAbort(this.stats, this.context, this.response);\n                }\n              };\n\n              _proto.load = function load(context, config, callbacks) {\n                var _this = this;\n\n                var stats = this.stats;\n\n                if (stats.loading.start) {\n                  throw new Error(\"Loader can only be used once.\");\n                }\n\n                stats.loading.start = self.performance.now();\n                var initParams = getRequestParameters(context, this.controller.signal);\n                var onProgress = callbacks.onProgress;\n                var isArrayBuffer = context.responseType === \"arraybuffer\";\n                var LENGTH = isArrayBuffer ? \"byteLength\" : \"length\";\n                this.context = context;\n                this.config = config;\n                this.callbacks = callbacks;\n                this.request = this.fetchSetup(context, initParams);\n                self.clearTimeout(this.requestTimeout);\n                this.requestTimeout = self.setTimeout(function () {\n                  _this.abortInternal();\n\n                  callbacks.onTimeout(stats, context, _this.response);\n                }, config.timeout);\n                self\n                  .fetch(this.request)\n                  .then(function (response) {\n                    _this.response = _this.loader = response;\n\n                    if (!response.ok) {\n                      var status = response.status,\n                        statusText = response.statusText;\n                      throw new FetchError(statusText || \"fetch, bad network response\", status, response);\n                    }\n\n                    stats.loading.first = Math.max(self.performance.now(), stats.loading.start);\n                    stats.total = parseInt(response.headers.get(\"Content-Length\") || \"0\");\n\n                    if (onProgress && Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(config.highWaterMark)) {\n                      return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);\n                    }\n\n                    if (isArrayBuffer) {\n                      return response.arrayBuffer();\n                    }\n\n                    return response.text();\n                  })\n                  .then(function (responseData) {\n                    var response = _this.response;\n                    self.clearTimeout(_this.requestTimeout);\n                    stats.loading.end = Math.max(self.performance.now(), stats.loading.first);\n                    stats.loaded = stats.total = responseData[LENGTH];\n                    var loaderResponse = {\n                      url: response.url,\n                      data: responseData,\n                    };\n\n                    if (onProgress && !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(config.highWaterMark)) {\n                      onProgress(stats, context, responseData, response);\n                    }\n\n                    callbacks.onSuccess(loaderResponse, stats, context, response);\n                  })\n                  .catch(function (error) {\n                    self.clearTimeout(_this.requestTimeout);\n\n                    if (stats.aborted) {\n                      return;\n                    } // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior\n\n                    var code = error.code || 0;\n                    callbacks.onError(\n                      {\n                        code: code,\n                        text: error.message,\n                      },\n                      context,\n                      error.details\n                    );\n                  });\n              };\n\n              _proto.getCacheAge = function getCacheAge() {\n                var result = null;\n\n                if (this.response) {\n                  var ageHeader = this.response.headers.get(\"age\");\n                  result = ageHeader ? parseFloat(ageHeader) : null;\n                }\n\n                return result;\n              };\n\n              _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {\n                if (highWaterMark === void 0) {\n                  highWaterMark = 0;\n                }\n\n                var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__[\"default\"]();\n                var reader = response.body.getReader();\n\n                var pump = function pump() {\n                  return reader\n                    .read()\n                    .then(function (data) {\n                      if (data.done) {\n                        if (chunkCache.dataLength) {\n                          onProgress(stats, context, chunkCache.flush(), response);\n                        }\n\n                        return Promise.resolve(new ArrayBuffer(0));\n                      }\n\n                      var chunk = data.value;\n                      var len = chunk.length;\n                      stats.loaded += len;\n\n                      if (len < highWaterMark || chunkCache.dataLength) {\n                        // The current chunk is too small to to be emitted or the cache already has data\n                        // Push it to the cache\n                        chunkCache.push(chunk);\n\n                        if (chunkCache.dataLength >= highWaterMark) {\n                          // flush in order to join the typed arrays\n                          onProgress(stats, context, chunkCache.flush(), response);\n                        }\n                      } else {\n                        // If there's nothing cached already, and the chache is large enough\n                        // just emit the progress event\n                        onProgress(stats, context, chunk, response);\n                      }\n\n                      return pump();\n                    })\n                    .catch(function () {\n                      /* aborted */\n                      return Promise.reject();\n                    });\n                };\n\n                return pump();\n              };\n\n              return FetchLoader;\n            })();\n\n            function getRequestParameters(context, signal) {\n              var initParams = {\n                method: \"GET\",\n                mode: \"cors\",\n                credentials: \"same-origin\",\n                signal: signal,\n                headers: new self.Headers(_extends({}, context.headers)),\n              };\n\n              if (context.rangeEnd) {\n                initParams.headers.set(\"Range\", \"bytes=\" + context.rangeStart + \"-\" + String(context.rangeEnd - 1));\n              }\n\n              return initParams;\n            }\n\n            function getRequest(context, initParams) {\n              return new self.Request(context.url, initParams);\n            }\n\n            var FetchError = /*#__PURE__*/ (function (_Error) {\n              _inheritsLoose(FetchError, _Error);\n\n              function FetchError(message, code, details) {\n                var _this2;\n\n                _this2 = _Error.call(this, message) || this;\n                _this2.code = void 0;\n                _this2.details = void 0;\n                _this2.code = code;\n                _this2.details = details;\n                return _this2;\n              }\n\n              return FetchError;\n            })(/*#__PURE__*/ _wrapNativeSuper(Error));\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = FetchLoader;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/imsc1-ttml-parser.ts\":\n          /*!****************************************!*\\\n  !*** ./src/utils/imsc1-ttml-parser.ts ***!\n  \\****************************************/\n          /*! exports provided: IMSC1_CODEC, parseIMSC1 */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"IMSC1_CODEC\", function () {\n              return IMSC1_CODEC;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseIMSC1\", function () {\n              return parseIMSC1;\n            });\n            /* harmony import */ var _mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mp4-tools */ \"./src/utils/mp4-tools.ts\");\n            /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ \"./src/utils/vttparser.ts\");\n            /* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vttcue */ \"./src/utils/vttcue.ts\");\n            /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ \"./src/demux/id3.ts\");\n            /* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timescale-conversion */ \"./src/utils/timescale-conversion.ts\");\n            /* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webvtt-parser */ \"./src/utils/webvtt-parser.ts\");\n            function _extends() {\n              _extends =\n                Object.assign ||\n                function (target) {\n                  for (var i = 1; i < arguments.length; i++) {\n                    var source = arguments[i];\n                    for (var key in source) {\n                      if (Object.prototype.hasOwnProperty.call(source, key)) {\n                        target[key] = source[key];\n                      }\n                    }\n                  }\n                  return target;\n                };\n              return _extends.apply(this, arguments);\n            }\n\n            var IMSC1_CODEC = \"stpp.ttml.im1t\"; // Time format: h:m:s:frames(.subframes)\n\n            var HMSF_REGEX = /^(\\d{2,}):(\\d{2}):(\\d{2}):(\\d{2})\\.?(\\d+)?$/; // Time format: hours, minutes, seconds, milliseconds, frames, ticks\n\n            var TIME_UNIT_REGEX = /^(\\d*(?:\\.\\d*)?)(h|m|s|ms|f|t)$/;\n            var textAlignToLineAlign = {\n              left: \"start\",\n              center: \"center\",\n              right: \"end\",\n              start: \"start\",\n              end: \"end\",\n            };\n            function parseIMSC1(payload, initPTS, timescale, callBack, errorCallBack) {\n              var results = Object(_mp4_tools__WEBPACK_IMPORTED_MODULE_0__[\"findBox\"])(new Uint8Array(payload), [\"mdat\"]);\n\n              if (results.length === 0) {\n                errorCallBack(new Error(\"Could not parse IMSC1 mdat\"));\n                return;\n              }\n\n              var mdat = results[0];\n              var ttml = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_3__[\"utf8ArrayToStr\"])(new Uint8Array(payload, mdat.start, mdat.end - mdat.start));\n              var syncTime = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_4__[\"toTimescaleFromScale\"])(initPTS, 1, timescale);\n\n              try {\n                callBack(parseTTML(ttml, syncTime));\n              } catch (error) {\n                errorCallBack(error);\n              }\n            }\n\n            function parseTTML(ttml, syncTime) {\n              var parser = new DOMParser();\n              var xmlDoc = parser.parseFromString(ttml, \"text/xml\");\n              var tt = xmlDoc.getElementsByTagName(\"tt\")[0];\n\n              if (!tt) {\n                throw new Error(\"Invalid ttml\");\n              }\n\n              var defaultRateInfo = {\n                frameRate: 30,\n                subFrameRate: 1,\n                frameRateMultiplier: 0,\n                tickRate: 0,\n              };\n              var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) {\n                result[key] = tt.getAttribute(\"ttp:\" + key) || defaultRateInfo[key];\n                return result;\n              }, {});\n              var trim = tt.getAttribute(\"xml:space\") !== \"preserve\";\n              var styleElements = collectionToDictionary(getElementCollection(tt, \"styling\", \"style\"));\n              var regionElements = collectionToDictionary(getElementCollection(tt, \"layout\", \"region\"));\n              var cueElements = getElementCollection(tt, \"body\", \"[begin]\");\n              return [].map\n                .call(cueElements, function (cueElement) {\n                  var cueText = getTextContent(cueElement, trim);\n\n                  if (!cueText || !cueElement.hasAttribute(\"begin\")) {\n                    return null;\n                  }\n\n                  var startTime = parseTtmlTime(cueElement.getAttribute(\"begin\"), rateInfo);\n                  var duration = parseTtmlTime(cueElement.getAttribute(\"dur\"), rateInfo);\n                  var endTime = parseTtmlTime(cueElement.getAttribute(\"end\"), rateInfo);\n\n                  if (startTime === null) {\n                    throw timestampParsingError(cueElement);\n                  }\n\n                  if (endTime === null) {\n                    if (duration === null) {\n                      throw timestampParsingError(cueElement);\n                    }\n\n                    endTime = startTime + duration;\n                  }\n\n                  var cue = new _vttcue__WEBPACK_IMPORTED_MODULE_2__[\"default\"](startTime - syncTime, endTime - syncTime, cueText);\n                  cue.id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_5__[\"generateCueId\"])(cue.startTime, cue.endTime, cue.text);\n                  var region = regionElements[cueElement.getAttribute(\"region\")];\n                  var style = styleElements[cueElement.getAttribute(\"style\")]; // TODO: Add regions to track and cue (origin and extend)\n                  // These values are hard-coded (for now) to simulate region settings in the demo\n\n                  cue.position = 10;\n                  cue.size = 80; // Apply styles to cue\n\n                  var styles = getTtmlStyles(region, style);\n                  var textAlign = styles.textAlign;\n\n                  if (textAlign) {\n                    // cue.positionAlign not settable in FF~2016\n                    var lineAlign = textAlignToLineAlign[textAlign];\n\n                    if (lineAlign) {\n                      cue.lineAlign = lineAlign;\n                    }\n\n                    cue.align = textAlign;\n                  }\n\n                  _extends(cue, styles);\n\n                  return cue;\n                })\n                .filter(function (cue) {\n                  return cue !== null;\n                });\n            }\n\n            function getElementCollection(fromElement, parentName, childName) {\n              var parent = fromElement.getElementsByTagName(parentName)[0];\n\n              if (parent) {\n                return [].slice.call(parent.querySelectorAll(childName));\n              }\n\n              return [];\n            }\n\n            function collectionToDictionary(elementsWithId) {\n              return elementsWithId.reduce(function (dict, element) {\n                var id = element.getAttribute(\"xml:id\");\n\n                if (id) {\n                  dict[id] = element;\n                }\n\n                return dict;\n              }, {});\n            }\n\n            function getTextContent(element, trim) {\n              return [].slice.call(element.childNodes).reduce(function (str, node, i) {\n                var _node$childNodes;\n\n                if (node.nodeName === \"br\" && i) {\n                  return str + \"\\n\";\n                }\n\n                if ((_node$childNodes = node.childNodes) !== null && _node$childNodes !== void 0 && _node$childNodes.length) {\n                  return getTextContent(node, trim);\n                } else if (trim) {\n                  return str + node.textContent.trim().replace(/\\s+/g, \" \");\n                }\n\n                return str + node.textContent;\n              }, \"\");\n            }\n\n            function getTtmlStyles(region, style) {\n              var ttsNs = \"http://www.w3.org/ns/ttml#styling\";\n              var styleAttributes = [\n                \"displayAlign\",\n                \"textAlign\",\n                \"color\",\n                \"backgroundColor\",\n                \"fontSize\",\n                \"fontFamily\", // 'fontWeight',\n                // 'lineHeight',\n                // 'wrapOption',\n                // 'fontStyle',\n                // 'direction',\n                // 'writingMode'\n              ];\n              return styleAttributes.reduce(function (styles, name) {\n                var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name);\n\n                if (value) {\n                  styles[name] = value;\n                }\n\n                return styles;\n              }, {});\n            }\n\n            function getAttributeNS(element, ns, name) {\n              return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;\n            }\n\n            function timestampParsingError(node) {\n              return new Error(\"Could not parse ttml timestamp \" + node);\n            }\n\n            function parseTtmlTime(timeAttributeValue, rateInfo) {\n              if (!timeAttributeValue) {\n                return null;\n              }\n\n              var seconds = Object(_vttparser__WEBPACK_IMPORTED_MODULE_1__[\"parseTimeStamp\"])(timeAttributeValue);\n\n              if (seconds === null) {\n                if (HMSF_REGEX.test(timeAttributeValue)) {\n                  seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);\n                } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {\n                  seconds = parseTimeUnits(timeAttributeValue, rateInfo);\n                }\n              }\n\n              return seconds;\n            }\n\n            function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {\n              var m = HMSF_REGEX.exec(timeAttributeValue);\n              var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;\n              return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;\n            }\n\n            function parseTimeUnits(timeAttributeValue, rateInfo) {\n              var m = TIME_UNIT_REGEX.exec(timeAttributeValue);\n              var value = Number(m[1]);\n              var unit = m[2];\n\n              switch (unit) {\n                case \"h\":\n                  return value * 3600;\n\n                case \"m\":\n                  return value * 60;\n\n                case \"ms\":\n                  return value * 1000;\n\n                case \"f\":\n                  return value / rateInfo.frameRate;\n\n                case \"t\":\n                  return value / rateInfo.tickRate;\n              }\n\n              return value;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/logger.ts\":\n          /*!*****************************!*\\\n  !*** ./src/utils/logger.ts ***!\n  \\*****************************/\n          /*! exports provided: enableLogs, logger */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"enableLogs\", function () {\n              return enableLogs;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"logger\", function () {\n              return logger;\n            });\n            var noop = function noop() {};\n\n            var fakeLogger = {\n              trace: noop,\n              debug: noop,\n              log: noop,\n              warn: noop,\n              info: noop,\n              error: noop,\n            };\n            var exportedLogger = fakeLogger; // let lastCallTime;\n            // function formatMsgWithTimeInfo(type, msg) {\n            //   const now = Date.now();\n            //   const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n            //   lastCallTime = now;\n            //   msg = (new Date(now)).toISOString() + ' | [' +  type + '] > ' + msg + ' ( ' + diff + ' ms )';\n            //   return msg;\n            // }\n\n            function consolePrintFn(type) {\n              var func = self.console[type];\n\n              if (func) {\n                return func.bind(self.console, \"[\" + type + \"] >\");\n              }\n\n              return noop;\n            }\n\n            function exportLoggerFunctions(debugConfig) {\n              for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n                functions[_key - 1] = arguments[_key];\n              }\n\n              functions.forEach(function (type) {\n                exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n              });\n            }\n\n            function enableLogs(debugConfig) {\n              // check that console is available\n              if ((self.console && debugConfig === true) || typeof debugConfig === \"object\") {\n                exportLoggerFunctions(\n                  debugConfig, // Remove out from list here to hard-disable a log-level\n                  // 'trace',\n                  \"debug\",\n                  \"log\",\n                  \"info\",\n                  \"warn\",\n                  \"error\"\n                ); // Some browsers don't allow to use bind on console object anyway\n                // fallback to default if needed\n\n                try {\n                  exportedLogger.log();\n                } catch (e) {\n                  exportedLogger = fakeLogger;\n                }\n              } else {\n                exportedLogger = fakeLogger;\n              }\n            }\n            var logger = exportedLogger;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/mediakeys-helper.ts\":\n          /*!***************************************!*\\\n  !*** ./src/utils/mediakeys-helper.ts ***!\n  \\***************************************/\n          /*! exports provided: KeySystems, requestMediaKeySystemAccess */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"KeySystems\", function () {\n              return KeySystems;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"requestMediaKeySystemAccess\", function () {\n              return requestMediaKeySystemAccess;\n            });\n            /**\n             * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n             */\n            var KeySystems;\n\n            (function (KeySystems) {\n              KeySystems[\"WIDEVINE\"] = \"com.widevine.alpha\";\n              KeySystems[\"PLAYREADY\"] = \"com.microsoft.playready\";\n            })(KeySystems || (KeySystems = {}));\n\n            var requestMediaKeySystemAccess = (function () {\n              if (typeof self !== \"undefined\" && self.navigator && self.navigator.requestMediaKeySystemAccess) {\n                return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);\n              } else {\n                return null;\n              }\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/utils/mediasource-helper.ts\":\n          /*!*****************************************!*\\\n  !*** ./src/utils/mediasource-helper.ts ***!\n  \\*****************************************/\n          /*! exports provided: getMediaSource */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getMediaSource\", function () {\n              return getMediaSource;\n            });\n            /**\n             * MediaSource helper\n             */\n            function getMediaSource() {\n              return self.MediaSource || self.WebKitMediaSource;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/mp4-tools.ts\":\n          /*!********************************!*\\\n  !*** ./src/utils/mp4-tools.ts ***!\n  \\********************************/\n          /*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"bin2str\", function () {\n              return bin2str;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"readUint16\", function () {\n              return readUint16;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"readUint32\", function () {\n              return readUint32;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"writeUint32\", function () {\n              return writeUint32;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"findBox\", function () {\n              return findBox;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseSegmentIndex\", function () {\n              return parseSegmentIndex;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseInitSegment\", function () {\n              return parseInitSegment;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getStartDTS\", function () {\n              return getStartDTS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDuration\", function () {\n              return getDuration;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computeRawDurationFromSamples\", function () {\n              return computeRawDurationFromSamples;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"offsetStartDTS\", function () {\n              return offsetStartDTS;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"segmentValidRange\", function () {\n              return segmentValidRange;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"appendUint8Array\", function () {\n              return appendUint8Array;\n            });\n            /* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ \"./src/utils/typed-array.ts\");\n            /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ \"./src/loader/fragment.ts\");\n\n            var UINT32_MAX = Math.pow(2, 32) - 1;\n            var push = [].push;\n            function bin2str(data) {\n              return String.fromCharCode.apply(null, data);\n            }\n            function readUint16(buffer, offset) {\n              if (\"data\" in buffer) {\n                offset += buffer.start;\n                buffer = buffer.data;\n              }\n\n              var val = (buffer[offset] << 8) | buffer[offset + 1];\n              return val < 0 ? 65536 + val : val;\n            }\n            function readUint32(buffer, offset) {\n              if (\"data\" in buffer) {\n                offset += buffer.start;\n                buffer = buffer.data;\n              }\n\n              var val = (buffer[offset] << 24) | (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | buffer[offset + 3];\n              return val < 0 ? 4294967296 + val : val;\n            }\n            function writeUint32(buffer, offset, value) {\n              if (\"data\" in buffer) {\n                offset += buffer.start;\n                buffer = buffer.data;\n              }\n\n              buffer[offset] = value >> 24;\n              buffer[offset + 1] = (value >> 16) & 0xff;\n              buffer[offset + 2] = (value >> 8) & 0xff;\n              buffer[offset + 3] = value & 0xff;\n            } // Find the data for a box specified by its path\n\n            function findBox(input, path) {\n              var results = [];\n\n              if (!path.length) {\n                // short-circuit the search for empty paths\n                return results;\n              }\n\n              var data;\n              var start;\n              var end;\n\n              if (\"data\" in input) {\n                data = input.data;\n                start = input.start;\n                end = input.end;\n              } else {\n                data = input;\n                start = 0;\n                end = data.byteLength;\n              }\n\n              for (var i = start; i < end; ) {\n                var size = readUint32(data, i);\n                var type = bin2str(data.subarray(i + 4, i + 8));\n                var endbox = size > 1 ? i + size : end;\n\n                if (type === path[0]) {\n                  if (path.length === 1) {\n                    // this is the end of the path and we've found the box we were\n                    // looking for\n                    results.push({\n                      data: data,\n                      start: i + 8,\n                      end: endbox,\n                    });\n                  } else {\n                    // recursively search for the next box along the path\n                    var subresults = findBox(\n                      {\n                        data: data,\n                        start: i + 8,\n                        end: endbox,\n                      },\n                      path.slice(1)\n                    );\n\n                    if (subresults.length) {\n                      push.apply(results, subresults);\n                    }\n                  }\n                }\n\n                i = endbox;\n              } // we've finished searching all of data\n\n              return results;\n            }\n            function parseSegmentIndex(initSegment) {\n              var moovBox = findBox(initSegment, [\"moov\"]);\n              var moov = moovBox[0];\n              var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n              var sidxBox = findBox(initSegment, [\"sidx\"]);\n\n              if (!sidxBox || !sidxBox[0]) {\n                return null;\n              }\n\n              var references = [];\n              var sidx = sidxBox[0];\n              var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)\n\n              var index = version === 0 ? 8 : 16;\n              var timescale = readUint32(sidx, index);\n              index += 4; // TODO: parse earliestPresentationTime and firstOffset\n              // usually zero in our case\n\n              var earliestPresentationTime = 0;\n              var firstOffset = 0;\n\n              if (version === 0) {\n                index += 8;\n              } else {\n                index += 16;\n              } // skip reserved\n\n              index += 2;\n              var startByte = sidx.end + firstOffset;\n              var referencesCount = readUint16(sidx, index);\n              index += 2;\n\n              for (var i = 0; i < referencesCount; i++) {\n                var referenceIndex = index;\n                var referenceInfo = readUint32(sidx, referenceIndex);\n                referenceIndex += 4;\n                var referenceSize = referenceInfo & 0x7fffffff;\n                var referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n                if (referenceType === 1) {\n                  // eslint-disable-next-line no-console\n                  console.warn(\"SIDX has hierarchical references (not supported)\");\n                  return null;\n                }\n\n                var subsegmentDuration = readUint32(sidx, referenceIndex);\n                referenceIndex += 4;\n                references.push({\n                  referenceSize: referenceSize,\n                  subsegmentDuration: subsegmentDuration,\n                  // unscaled\n                  info: {\n                    duration: subsegmentDuration / timescale,\n                    start: startByte,\n                    end: startByte + referenceSize - 1,\n                  },\n                });\n                startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n                // for |sapDelta|.\n\n                referenceIndex += 4; // skip to next ref\n\n                index = referenceIndex;\n              }\n\n              return {\n                earliestPresentationTime: earliestPresentationTime,\n                timescale: timescale,\n                version: version,\n                referencesCount: referencesCount,\n                references: references,\n                moovEndOffset: moovEndOffset,\n              };\n            }\n            /**\n             * Parses an MP4 initialization segment and extracts stream type and\n             * timescale values for any declared tracks. Timescale values indicate the\n             * number of clock ticks per second to assume for time-based values\n             * elsewhere in the MP4.\n             *\n             * To determine the start time of an MP4, you need two pieces of\n             * information: the timescale unit and the earliest base media decode\n             * time. Multiple timescales can be specified within an MP4 but the\n             * base media decode time is always expressed in the timescale from\n             * the media header box for the track:\n             * ```\n             * moov > trak > mdia > mdhd.timescale\n             * moov > trak > mdia > hdlr\n             * ```\n             * @param initSegment {Uint8Array} the bytes of the init segment\n             * @return {InitData} a hash of track type to timescale values or null if\n             * the init segment is malformed.\n             */\n\n            function parseInitSegment(initSegment) {\n              var result = [];\n              var traks = findBox(initSegment, [\"moov\", \"trak\"]);\n\n              for (var i = 0; i < traks.length; i++) {\n                var trak = traks[i];\n                var tkhd = findBox(trak, [\"tkhd\"])[0];\n\n                if (tkhd) {\n                  var version = tkhd.data[tkhd.start];\n\n                  var _index = version === 0 ? 12 : 20;\n\n                  var trackId = readUint32(tkhd, _index);\n                  var mdhd = findBox(trak, [\"mdia\", \"mdhd\"])[0];\n\n                  if (mdhd) {\n                    version = mdhd.data[mdhd.start];\n                    _index = version === 0 ? 12 : 20;\n                    var timescale = readUint32(mdhd, _index);\n                    var hdlr = findBox(trak, [\"mdia\", \"hdlr\"])[0];\n\n                    if (hdlr) {\n                      var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));\n                      var type = {\n                        soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__[\"ElementaryStreamTypes\"].AUDIO,\n                        vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__[\"ElementaryStreamTypes\"].VIDEO,\n                      }[hdlrType];\n\n                      if (type) {\n                        // Parse codec details\n                        var stsd = findBox(trak, [\"mdia\", \"minf\", \"stbl\", \"stsd\"])[0];\n                        var codec = void 0;\n\n                        if (stsd) {\n                          codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type.\n                          // stsd.start += 8;\n                          // const codecBox = findBox(stsd, [codec])[0];\n                          // if (codecBox) {\n                          //   TODO: Codec parsing support for avc1, mp4a, hevc, av01...\n                          // }\n                        }\n\n                        result[trackId] = {\n                          timescale: timescale,\n                          type: type,\n                        };\n                        result[type] = {\n                          timescale: timescale,\n                          id: trackId,\n                          codec: codec,\n                        };\n                      }\n                    }\n                  }\n                }\n              }\n\n              var trex = findBox(initSegment, [\"moov\", \"mvex\", \"trex\"]);\n              trex.forEach(function (trex) {\n                var trackId = readUint32(trex, 4);\n                var track = result[trackId];\n\n                if (track) {\n                  track.default = {\n                    duration: readUint32(trex, 12),\n                    flags: readUint32(trex, 20),\n                  };\n                }\n              });\n              return result;\n            }\n            /**\n             * Determine the base media decode start time, in seconds, for an MP4\n             * fragment. If multiple fragments are specified, the earliest time is\n             * returned.\n             *\n             * The base media decode time can be parsed from track fragment\n             * metadata:\n             * ```\n             * moof > traf > tfdt.baseMediaDecodeTime\n             * ```\n             * It requires the timescale value from the mdhd to interpret.\n             *\n             * @param initData {InitData} a hash of track type to timescale values\n             * @param fmp4 {Uint8Array} the bytes of the mp4 fragment\n             * @return {number} the earliest base media decode start time for the\n             * fragment, in seconds\n             */\n\n            function getStartDTS(initData, fmp4) {\n              // we need info from two children of each track fragment box\n              return (\n                findBox(fmp4, [\"moof\", \"traf\"]).reduce(function (result, traf) {\n                  var tfdt = findBox(traf, [\"tfdt\"])[0];\n                  var version = tfdt.data[tfdt.start];\n                  var start = findBox(traf, [\"tfhd\"]).reduce(function (result, tfhd) {\n                    // get the track id from the tfhd\n                    var id = readUint32(tfhd, 4);\n                    var track = initData[id];\n\n                    if (track) {\n                      var baseTime = readUint32(tfdt, 4);\n\n                      if (version === 1) {\n                        baseTime *= Math.pow(2, 32);\n                        baseTime += readUint32(tfdt, 8);\n                      } // assume a 90kHz clock if no timescale was specified\n\n                      var scale = track.timescale || 90e3; // convert base time to seconds\n\n                      var startTime = baseTime / scale;\n\n                      if (isFinite(startTime) && (result === null || startTime < result)) {\n                        return startTime;\n                      }\n                    }\n\n                    return result;\n                  }, null);\n\n                  if (start !== null && isFinite(start) && (result === null || start < result)) {\n                    return start;\n                  }\n\n                  return result;\n                }, null) || 0\n              );\n            }\n            /*\n  For Reference:\n  aligned(8) class TrackFragmentHeaderBox\n           extends FullBox(‘tfhd’, 0, tf_flags){\n     unsigned int(32)  track_ID;\n     // all the following are optional fields\n     unsigned int(64)  base_data_offset;\n     unsigned int(32)  sample_description_index;\n     unsigned int(32)  default_sample_duration;\n     unsigned int(32)  default_sample_size;\n     unsigned int(32)  default_sample_flags\n  }\n */\n\n            function getDuration(data, initData) {\n              var rawDuration = 0;\n              var videoDuration = 0;\n              var audioDuration = 0;\n              var trafs = findBox(data, [\"moof\", \"traf\"]);\n\n              for (var i = 0; i < trafs.length; i++) {\n                var traf = trafs[i]; // There is only one tfhd & trun per traf\n                // This is true for CMAF style content, and we should perhaps check the ftyp\n                // and only look for a single trun then, but for ISOBMFF we should check\n                // for multiple track runs.\n\n                var tfhd = findBox(traf, [\"tfhd\"])[0]; // get the track id from the tfhd\n\n                var id = readUint32(tfhd, 4);\n                var track = initData[id];\n\n                if (!track) {\n                  continue;\n                }\n\n                var trackDefault = track.default;\n                var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);\n                var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;\n\n                if (tfhdFlags & 0x000008) {\n                  // 0x000008 indicates the presence of the default_sample_duration field\n                  if (tfhdFlags & 0x000002) {\n                    // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration\n                    // If present, the default_sample_duration exists at byte offset 12\n                    sampleDuration = readUint32(tfhd, 12);\n                  } else {\n                    // Otherwise, the duration is at byte offset 8\n                    sampleDuration = readUint32(tfhd, 8);\n                  }\n                } // assume a 90kHz clock if no timescale was specified\n\n                var timescale = track.timescale || 90e3;\n                var truns = findBox(traf, [\"trun\"]);\n\n                for (var j = 0; j < truns.length; j++) {\n                  if (sampleDuration) {\n                    var sampleCount = readUint32(truns[j], 4);\n                    rawDuration = sampleDuration * sampleCount;\n                  } else {\n                    rawDuration = computeRawDurationFromSamples(truns[j]);\n                  }\n\n                  if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__[\"ElementaryStreamTypes\"].VIDEO) {\n                    videoDuration += rawDuration / timescale;\n                  } else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__[\"ElementaryStreamTypes\"].AUDIO) {\n                    audioDuration += rawDuration / timescale;\n                  }\n                }\n              }\n\n              if (videoDuration === 0 && audioDuration === 0) {\n                // If duration samples are not available in the traf use sidx subsegment_duration\n                var sidx = parseSegmentIndex(data);\n\n                if (sidx !== null && sidx !== void 0 && sidx.references) {\n                  return sidx.references.reduce(function (dur, ref) {\n                    return dur + ref.info.duration || 0;\n                  }, 0);\n                }\n              }\n\n              if (videoDuration) {\n                return videoDuration;\n              }\n\n              return audioDuration;\n            }\n            /*\n  For Reference:\n  aligned(8) class TrackRunBox\n           extends FullBox(‘trun’, version, tr_flags) {\n     unsigned int(32)  sample_count;\n     // the following are optional fields\n     signed int(32) data_offset;\n     unsigned int(32)  first_sample_flags;\n     // all fields in the following array are optional\n     {\n        unsigned int(32)  sample_duration;\n        unsigned int(32)  sample_size;\n        unsigned int(32)  sample_flags\n        if (version == 0)\n           { unsigned int(32)\n        else\n           { signed int(32)\n     }[ sample_count ]\n  }\n */\n\n            function computeRawDurationFromSamples(trun) {\n              var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.\n              // Each field is an int32, which is 4 bytes\n\n              var offset = 8; // data-offset-present flag\n\n              if (flags & 0x000001) {\n                offset += 4;\n              } // first-sample-flags-present flag\n\n              if (flags & 0x000004) {\n                offset += 4;\n              }\n\n              var duration = 0;\n              var sampleCount = readUint32(trun, 4);\n\n              for (var i = 0; i < sampleCount; i++) {\n                // sample-duration-present flag\n                if (flags & 0x000100) {\n                  var sampleDuration = readUint32(trun, offset);\n                  duration += sampleDuration;\n                  offset += 4;\n                } // sample-size-present flag\n\n                if (flags & 0x000200) {\n                  offset += 4;\n                } // sample-flags-present flag\n\n                if (flags & 0x000400) {\n                  offset += 4;\n                } // sample-composition-time-offsets-present flag\n\n                if (flags & 0x000800) {\n                  offset += 4;\n                }\n              }\n\n              return duration;\n            }\n            function offsetStartDTS(initData, fmp4, timeOffset) {\n              findBox(fmp4, [\"moof\", \"traf\"]).forEach(function (traf) {\n                findBox(traf, [\"tfhd\"]).forEach(function (tfhd) {\n                  // get the track id from the tfhd\n                  var id = readUint32(tfhd, 4);\n                  var track = initData[id];\n\n                  if (!track) {\n                    return;\n                  } // assume a 90kHz clock if no timescale was specified\n\n                  var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt\n\n                  findBox(traf, [\"tfdt\"]).forEach(function (tfdt) {\n                    var version = tfdt.data[tfdt.start];\n                    var baseMediaDecodeTime = readUint32(tfdt, 4);\n\n                    if (version === 0) {\n                      writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);\n                    } else {\n                      baseMediaDecodeTime *= Math.pow(2, 32);\n                      baseMediaDecodeTime += readUint32(tfdt, 8);\n                      baseMediaDecodeTime -= timeOffset * timescale;\n                      baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n                      var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n                      var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n                      writeUint32(tfdt, 4, upper);\n                      writeUint32(tfdt, 8, lower);\n                    }\n                  });\n                });\n              });\n            } // TODO: Check if the last moof+mdat pair is part of the valid range\n\n            function segmentValidRange(data) {\n              var segmentedRange = {\n                valid: null,\n                remainder: null,\n              };\n              var moofs = findBox(data, [\"moof\"]);\n\n              if (!moofs) {\n                return segmentedRange;\n              } else if (moofs.length < 2) {\n                segmentedRange.remainder = data;\n                return segmentedRange;\n              }\n\n              var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much\n\n              segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__[\"sliceUint8\"])(data, 0, last.start - 8);\n              segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__[\"sliceUint8\"])(data, last.start - 8);\n              return segmentedRange;\n            }\n            function appendUint8Array(data1, data2) {\n              var temp = new Uint8Array(data1.length + data2.length);\n              temp.set(data1);\n              temp.set(data2, data1.length);\n              return temp;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/output-filter.ts\":\n          /*!************************************!*\\\n  !*** ./src/utils/output-filter.ts ***!\n  \\************************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function () {\n              return OutputFilter;\n            });\n            var OutputFilter = /*#__PURE__*/ (function () {\n              function OutputFilter(timelineController, trackName) {\n                this.timelineController = void 0;\n                this.cueRanges = [];\n                this.trackName = void 0;\n                this.startTime = null;\n                this.endTime = null;\n                this.screen = null;\n                this.timelineController = timelineController;\n                this.trackName = trackName;\n              }\n\n              var _proto = OutputFilter.prototype;\n\n              _proto.dispatchCue = function dispatchCue() {\n                if (this.startTime === null) {\n                  return;\n                }\n\n                this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);\n                this.startTime = null;\n              };\n\n              _proto.newCue = function newCue(startTime, endTime, screen) {\n                if (this.startTime === null || this.startTime > startTime) {\n                  this.startTime = startTime;\n                }\n\n                this.endTime = endTime;\n                this.screen = screen;\n                this.timelineController.createCaptionsTrack(this.trackName);\n              };\n\n              _proto.reset = function reset() {\n                this.cueRanges = [];\n              };\n\n              return OutputFilter;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/utils/texttrack-utils.ts\":\n          /*!**************************************!*\\\n  !*** ./src/utils/texttrack-utils.ts ***!\n  \\**************************************/\n          /*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"sendAddTrackEvent\", function () {\n              return sendAddTrackEvent;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"addCueToTrack\", function () {\n              return addCueToTrack;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"clearCurrentCues\", function () {\n              return clearCurrentCues;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"removeCuesInRange\", function () {\n              return removeCuesInRange;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getCuesInRange\", function () {\n              return getCuesInRange;\n            });\n            /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ \"./src/utils/logger.ts\");\n\n            function sendAddTrackEvent(track, videoEl) {\n              var event;\n\n              try {\n                event = new Event(\"addtrack\");\n              } catch (err) {\n                // for IE11\n                event = document.createEvent(\"Event\");\n                event.initEvent(\"addtrack\", false, false);\n              }\n\n              event.track = track;\n              videoEl.dispatchEvent(event);\n            }\n            function addCueToTrack(track, cue) {\n              // Sometimes there are cue overlaps on segmented vtts so the same\n              // cue can appear more than once in different vtt files.\n              // This avoid showing duplicated cues with same timecode and text.\n              var mode = track.mode;\n\n              if (mode === \"disabled\") {\n                track.mode = \"hidden\";\n              }\n\n              if (track.cues && !track.cues.getCueById(cue.id)) {\n                try {\n                  track.addCue(cue);\n\n                  if (!track.cues.getCueById(cue.id)) {\n                    throw new Error(\"addCue is failed for: \" + cue);\n                  }\n                } catch (err) {\n                  _logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].debug(\"[texttrack-utils]: \" + err);\n                  var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);\n                  textTrackCue.id = cue.id;\n                  track.addCue(textTrackCue);\n                }\n              }\n\n              if (mode === \"disabled\") {\n                track.mode = mode;\n              }\n            }\n            function clearCurrentCues(track) {\n              // When track.mode is disabled, track.cues will be null.\n              // To guarantee the removal of cues, we need to temporarily\n              // change the mode to hidden\n              var mode = track.mode;\n\n              if (mode === \"disabled\") {\n                track.mode = \"hidden\";\n              }\n\n              if (track.cues) {\n                for (var i = track.cues.length; i--; ) {\n                  track.removeCue(track.cues[i]);\n                }\n              }\n\n              if (mode === \"disabled\") {\n                track.mode = mode;\n              }\n            }\n            function removeCuesInRange(track, start, end) {\n              var mode = track.mode;\n\n              if (mode === \"disabled\") {\n                track.mode = \"hidden\";\n              }\n\n              if (track.cues && track.cues.length > 0) {\n                var cues = getCuesInRange(track.cues, start, end);\n\n                for (var i = 0; i < cues.length; i++) {\n                  track.removeCue(cues[i]);\n                }\n              }\n\n              if (mode === \"disabled\") {\n                track.mode = mode;\n              }\n            } // Find first cue starting after given time.\n            // Modified version of binary search O(log(n)).\n\n            function getFirstCueIndexAfterTime(cues, time) {\n              // If first cue starts after time, start there\n              if (time < cues[0].startTime) {\n                return 0;\n              } // If the last cue ends before time there is no overlap\n\n              var len = cues.length - 1;\n\n              if (time > cues[len].endTime) {\n                return -1;\n              }\n\n              var left = 0;\n              var right = len;\n\n              while (left <= right) {\n                var mid = Math.floor((right + left) / 2);\n\n                if (time < cues[mid].startTime) {\n                  right = mid - 1;\n                } else if (time > cues[mid].startTime && left < len) {\n                  left = mid + 1;\n                } else {\n                  // If it's not lower or higher, it must be equal.\n                  return mid;\n                }\n              } // At this point, left and right have swapped.\n              // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n\n              return cues[left].startTime - time < time - cues[right].startTime ? left : right;\n            }\n\n            function getCuesInRange(cues, start, end) {\n              var cuesFound = [];\n              var firstCueInRange = getFirstCueIndexAfterTime(cues, start);\n\n              if (firstCueInRange > -1) {\n                for (var i = firstCueInRange, len = cues.length; i < len; i++) {\n                  var cue = cues[i];\n\n                  if (cue.startTime >= start && cue.endTime <= end) {\n                    cuesFound.push(cue);\n                  } else if (cue.startTime > end) {\n                    return cuesFound;\n                  }\n                }\n              }\n\n              return cuesFound;\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/time-ranges.ts\":\n          /*!**********************************!*\\\n  !*** ./src/utils/time-ranges.ts ***!\n  \\**********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /**\n             *  TimeRanges to string helper\n             */\n            var TimeRanges = {\n              toString: function toString(r) {\n                var log = \"\";\n                var len = r.length;\n\n                for (var i = 0; i < len; i++) {\n                  log += \"[\" + r.start(i).toFixed(3) + \",\" + r.end(i).toFixed(3) + \"]\";\n                }\n\n                return log;\n              },\n            };\n            /* harmony default export */ __webpack_exports__[\"default\"] = TimeRanges;\n\n            /***/\n          },\n\n        /***/ \"./src/utils/timescale-conversion.ts\":\n          /*!*******************************************!*\\\n  !*** ./src/utils/timescale-conversion.ts ***!\n  \\*******************************************/\n          /*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toTimescaleFromBase\", function () {\n              return toTimescaleFromBase;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toTimescaleFromScale\", function () {\n              return toTimescaleFromScale;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toMsFromMpegTsClock\", function () {\n              return toMsFromMpegTsClock;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toMpegTsClockFromTimescale\", function () {\n              return toMpegTsClockFromTimescale;\n            });\n            var MPEG_TS_CLOCK_FREQ_HZ = 90000;\n            function toTimescaleFromBase(value, destScale, srcBase, round) {\n              if (srcBase === void 0) {\n                srcBase = 1;\n              }\n\n              if (round === void 0) {\n                round = false;\n              }\n\n              var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n\n              return round ? Math.round(result) : result;\n            }\n            function toTimescaleFromScale(value, destScale, srcScale, round) {\n              if (srcScale === void 0) {\n                srcScale = 1;\n              }\n\n              if (round === void 0) {\n                round = false;\n              }\n\n              return toTimescaleFromBase(value, destScale, 1 / srcScale, round);\n            }\n            function toMsFromMpegTsClock(value, round) {\n              if (round === void 0) {\n                round = false;\n              }\n\n              return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n            }\n            function toMpegTsClockFromTimescale(value, srcScale) {\n              if (srcScale === void 0) {\n                srcScale = 1;\n              }\n\n              return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/typed-array.ts\":\n          /*!**********************************!*\\\n  !*** ./src/utils/typed-array.ts ***!\n  \\**********************************/\n          /*! exports provided: sliceUint8 */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"sliceUint8\", function () {\n              return sliceUint8;\n            });\n            function sliceUint8(array, start, end) {\n              // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.\n              // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.\n              return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/vttcue.ts\":\n          /*!*****************************!*\\\n  !*** ./src/utils/vttcue.ts ***!\n  \\*****************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /**\n             * Copyright 2013 vtt.js Contributors\n             *\n             * Licensed under the Apache License, Version 2.0 (the 'License');\n             * you may not use this file except in compliance with the License.\n             * You may obtain a copy of the License at\n             *\n             *   http://www.apache.org/licenses/LICENSE-2.0\n             *\n             * Unless required by applicable law or agreed to in writing, software\n             * distributed under the License is distributed on an 'AS IS' BASIS,\n             * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n             * See the License for the specific language governing permissions and\n             * limitations under the License.\n             */\n            /* harmony default export */ __webpack_exports__[\"default\"] = (function () {\n              if (typeof self !== \"undefined\" && self.VTTCue) {\n                return self.VTTCue;\n              }\n\n              var AllowedDirections = [\"\", \"lr\", \"rl\"];\n              var AllowedAlignments = [\"start\", \"middle\", \"end\", \"left\", \"right\"];\n\n              function isAllowedValue(allowed, value) {\n                if (typeof value !== \"string\") {\n                  return false;\n                } // necessary for assuring the generic conforms to the Array interface\n\n                if (!Array.isArray(allowed)) {\n                  return false;\n                } // reset the type so that the next narrowing works well\n\n                var lcValue = value.toLowerCase(); // use the allow list to narrow the type to a specific subset of strings\n\n                if (~allowed.indexOf(lcValue)) {\n                  return lcValue;\n                }\n\n                return false;\n              }\n\n              function findDirectionSetting(value) {\n                return isAllowedValue(AllowedDirections, value);\n              }\n\n              function findAlignSetting(value) {\n                return isAllowedValue(AllowedAlignments, value);\n              }\n\n              function extend(obj) {\n                for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n                  rest[_key - 1] = arguments[_key];\n                }\n\n                var i = 1;\n\n                for (; i < arguments.length; i++) {\n                  var cobj = arguments[i];\n\n                  for (var p in cobj) {\n                    obj[p] = cobj[p];\n                  }\n                }\n\n                return obj;\n              }\n\n              function VTTCue(startTime, endTime, text) {\n                var cue = this;\n                var baseObj = {\n                  enumerable: true,\n                };\n                /**\n                 * Shim implementation specific properties. These properties are not in\n                 * the spec.\n                 */\n                // Lets us know when the VTTCue's data has changed in such a way that we need\n                // to recompute its display state. This lets us compute its display state\n                // lazily.\n\n                cue.hasBeenReset = false;\n                /**\n                 * VTTCue and TextTrackCue properties\n                 * http://dev.w3.org/html5/webvtt/#vttcue-interface\n                 */\n\n                var _id = \"\";\n                var _pauseOnExit = false;\n                var _startTime = startTime;\n                var _endTime = endTime;\n                var _text = text;\n                var _region = null;\n                var _vertical = \"\";\n                var _snapToLines = true;\n                var _line = \"auto\";\n                var _lineAlign = \"start\";\n                var _position = 50;\n                var _positionAlign = \"middle\";\n                var _size = 50;\n                var _align = \"middle\";\n                Object.defineProperty(\n                  cue,\n                  \"id\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _id;\n                    },\n                    set: function set(value) {\n                      _id = \"\" + value;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"pauseOnExit\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _pauseOnExit;\n                    },\n                    set: function set(value) {\n                      _pauseOnExit = !!value;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"startTime\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _startTime;\n                    },\n                    set: function set(value) {\n                      if (typeof value !== \"number\") {\n                        throw new TypeError(\"Start time must be set to a number.\");\n                      }\n\n                      _startTime = value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"endTime\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _endTime;\n                    },\n                    set: function set(value) {\n                      if (typeof value !== \"number\") {\n                        throw new TypeError(\"End time must be set to a number.\");\n                      }\n\n                      _endTime = value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"text\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _text;\n                    },\n                    set: function set(value) {\n                      _text = \"\" + value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                ); // todo: implement VTTRegion polyfill?\n\n                Object.defineProperty(\n                  cue,\n                  \"region\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _region;\n                    },\n                    set: function set(value) {\n                      _region = value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"vertical\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _vertical;\n                    },\n                    set: function set(value) {\n                      var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.\n\n                      if (setting === false) {\n                        throw new SyntaxError(\"An invalid or illegal string was specified.\");\n                      }\n\n                      _vertical = setting;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"snapToLines\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _snapToLines;\n                    },\n                    set: function set(value) {\n                      _snapToLines = !!value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"line\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _line;\n                    },\n                    set: function set(value) {\n                      if (typeof value !== \"number\" && value !== \"auto\") {\n                        throw new SyntaxError(\"An invalid number or illegal string was specified.\");\n                      }\n\n                      _line = value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"lineAlign\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _lineAlign;\n                    },\n                    set: function set(value) {\n                      var setting = findAlignSetting(value);\n\n                      if (!setting) {\n                        throw new SyntaxError(\"An invalid or illegal string was specified.\");\n                      }\n\n                      _lineAlign = setting;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"position\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _position;\n                    },\n                    set: function set(value) {\n                      if (value < 0 || value > 100) {\n                        throw new Error(\"Position must be between 0 and 100.\");\n                      }\n\n                      _position = value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"positionAlign\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _positionAlign;\n                    },\n                    set: function set(value) {\n                      var setting = findAlignSetting(value);\n\n                      if (!setting) {\n                        throw new SyntaxError(\"An invalid or illegal string was specified.\");\n                      }\n\n                      _positionAlign = setting;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"size\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _size;\n                    },\n                    set: function set(value) {\n                      if (value < 0 || value > 100) {\n                        throw new Error(\"Size must be between 0 and 100.\");\n                      }\n\n                      _size = value;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                Object.defineProperty(\n                  cue,\n                  \"align\",\n                  extend({}, baseObj, {\n                    get: function get() {\n                      return _align;\n                    },\n                    set: function set(value) {\n                      var setting = findAlignSetting(value);\n\n                      if (!setting) {\n                        throw new SyntaxError(\"An invalid or illegal string was specified.\");\n                      }\n\n                      _align = setting;\n                      this.hasBeenReset = true;\n                    },\n                  })\n                );\n                /**\n                 * Other <track> spec defined properties\n                 */\n                // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n\n                cue.displayState = undefined;\n              }\n              /**\n               * VTTCue methods\n               */\n\n              VTTCue.prototype.getCueAsHTML = function () {\n                // Assume WebVTT.convertCueToDOMTree is on the global.\n                var WebVTT = self.WebVTT;\n                return WebVTT.convertCueToDOMTree(self, this.text);\n              }; // this is a polyfill hack\n\n              return VTTCue;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/utils/vttparser.ts\":\n          /*!********************************!*\\\n  !*** ./src/utils/vttparser.ts ***!\n  \\********************************/\n          /*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseTimeStamp\", function () {\n              return parseTimeStamp;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"fixLineBreaks\", function () {\n              return fixLineBreaks;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"VTTParser\", function () {\n              return VTTParser;\n            });\n            /* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttcue */ \"./src/utils/vttcue.ts\");\n            /*\n             * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js\n             */\n\n            var StringDecoder = /*#__PURE__*/ (function () {\n              function StringDecoder() {}\n\n              var _proto = StringDecoder.prototype;\n\n              // eslint-disable-next-line @typescript-eslint/no-unused-vars\n              _proto.decode = function decode(data, options) {\n                if (!data) {\n                  return \"\";\n                }\n\n                if (typeof data !== \"string\") {\n                  throw new Error(\"Error - expected string data.\");\n                }\n\n                return decodeURIComponent(encodeURIComponent(data));\n              };\n\n              return StringDecoder;\n            })(); // Try to parse input as a time stamp.\n\n            function parseTimeStamp(input) {\n              function computeSeconds(h, m, s, f) {\n                return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);\n              }\n\n              var m = input.match(/^(?:(\\d+):)?(\\d{2}):(\\d{2})(\\.\\d+)?/);\n\n              if (!m) {\n                return null;\n              }\n\n              if (parseFloat(m[2]) > 59) {\n                // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n                // First position is hours as it's over 59.\n                return computeSeconds(m[2], m[3], 0, m[4]);\n              } // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]\n\n              return computeSeconds(m[1], m[2], m[3], m[4]);\n            } // A settings object holds key/value pairs and will ignore anything but the first\n            // assignment to a specific key.\n\n            var Settings = /*#__PURE__*/ (function () {\n              function Settings() {\n                this.values = Object.create(null);\n              }\n\n              var _proto2 = Settings.prototype;\n\n              // Only accept the first assignment to any key.\n              _proto2.set = function set(k, v) {\n                if (!this.get(k) && v !== \"\") {\n                  this.values[k] = v;\n                }\n              }; // Return the value for a key, or a default value.\n              // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n              // a number of possible default values as properties where 'defaultKey' is\n              // the key of the property that will be chosen; otherwise it's assumed to be\n              // a single value.\n\n              _proto2.get = function get(k, dflt, defaultKey) {\n                if (defaultKey) {\n                  return this.has(k) ? this.values[k] : dflt[defaultKey];\n                }\n\n                return this.has(k) ? this.values[k] : dflt;\n              }; // Check whether we have a value for a key.\n\n              _proto2.has = function has(k) {\n                return k in this.values;\n              }; // Accept a setting if its one of the given alternatives.\n\n              _proto2.alt = function alt(k, v, a) {\n                for (var n = 0; n < a.length; ++n) {\n                  if (v === a[n]) {\n                    this.set(k, v);\n                    break;\n                  }\n                }\n              }; // Accept a setting if its a valid (signed) integer.\n\n              _proto2.integer = function integer(k, v) {\n                if (/^-?\\d+$/.test(v)) {\n                  // integer\n                  this.set(k, parseInt(v, 10));\n                }\n              }; // Accept a setting if its a valid percentage.\n\n              _proto2.percent = function percent(k, v) {\n                if (/^([\\d]{1,3})(\\.[\\d]*)?%$/.test(v)) {\n                  var percent = parseFloat(v);\n\n                  if (percent >= 0 && percent <= 100) {\n                    this.set(k, percent);\n                    return true;\n                  }\n                }\n\n                return false;\n              };\n\n              return Settings;\n            })(); // Helper function to parse input into groups separated by 'groupDelim', and\n            // interpret each group as a key/value pair separated by 'keyValueDelim'.\n\n            function parseOptions(input, callback, keyValueDelim, groupDelim) {\n              var groups = groupDelim ? input.split(groupDelim) : [input];\n\n              for (var i in groups) {\n                if (typeof groups[i] !== \"string\") {\n                  continue;\n                }\n\n                var kv = groups[i].split(keyValueDelim);\n\n                if (kv.length !== 2) {\n                  continue;\n                }\n\n                var _k = kv[0];\n                var _v = kv[1];\n                callback(_k, _v);\n              }\n            }\n\n            var defaults = new _vttcue__WEBPACK_IMPORTED_MODULE_0__[\"default\"](0, 0, \"\"); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n            //  Safari doesn't yet support this change, but FF and Chrome do.\n\n            var center = defaults.align === \"middle\" ? \"middle\" : \"center\";\n\n            function parseCue(input, cue, regionList) {\n              // Remember the original input if we need to throw an error.\n              var oInput = input; // 4.1 WebVTT timestamp\n\n              function consumeTimeStamp() {\n                var ts = parseTimeStamp(input);\n\n                if (ts === null) {\n                  throw new Error(\"Malformed timestamp: \" + oInput);\n                } // Remove time stamp from input.\n\n                input = input.replace(/^[^\\sa-zA-Z-]+/, \"\");\n                return ts;\n              } // 4.4.2 WebVTT cue settings\n\n              function consumeCueSettings(input, cue) {\n                var settings = new Settings();\n                parseOptions(\n                  input,\n                  function (k, v) {\n                    var vals;\n\n                    switch (k) {\n                      case \"region\":\n                        // Find the last region we parsed with the same region id.\n                        for (var i = regionList.length - 1; i >= 0; i--) {\n                          if (regionList[i].id === v) {\n                            settings.set(k, regionList[i].region);\n                            break;\n                          }\n                        }\n\n                        break;\n\n                      case \"vertical\":\n                        settings.alt(k, v, [\"rl\", \"lr\"]);\n                        break;\n\n                      case \"line\":\n                        vals = v.split(\",\");\n                        settings.integer(k, vals[0]);\n\n                        if (settings.percent(k, vals[0])) {\n                          settings.set(\"snapToLines\", false);\n                        }\n\n                        settings.alt(k, vals[0], [\"auto\"]);\n\n                        if (vals.length === 2) {\n                          settings.alt(\"lineAlign\", vals[1], [\"start\", center, \"end\"]);\n                        }\n\n                        break;\n\n                      case \"position\":\n                        vals = v.split(\",\");\n                        settings.percent(k, vals[0]);\n\n                        if (vals.length === 2) {\n                          settings.alt(\"positionAlign\", vals[1], [\"start\", center, \"end\", \"line-left\", \"line-right\", \"auto\"]);\n                        }\n\n                        break;\n\n                      case \"size\":\n                        settings.percent(k, v);\n                        break;\n\n                      case \"align\":\n                        settings.alt(k, v, [\"start\", center, \"end\", \"left\", \"right\"]);\n                        break;\n                    }\n                  },\n                  /:/,\n                  /\\s/\n                ); // Apply default values for any missing fields.\n\n                cue.region = settings.get(\"region\", null);\n                cue.vertical = settings.get(\"vertical\", \"\");\n                var line = settings.get(\"line\", \"auto\");\n\n                if (line === \"auto\" && defaults.line === -1) {\n                  // set numeric line number for Safari\n                  line = -1;\n                }\n\n                cue.line = line;\n                cue.lineAlign = settings.get(\"lineAlign\", \"start\");\n                cue.snapToLines = settings.get(\"snapToLines\", true);\n                cue.size = settings.get(\"size\", 100);\n                cue.align = settings.get(\"align\", center);\n                var position = settings.get(\"position\", \"auto\");\n\n                if (position === \"auto\" && defaults.position === 50) {\n                  // set numeric position for Safari\n                  position = cue.align === \"start\" || cue.align === \"left\" ? 0 : cue.align === \"end\" || cue.align === \"right\" ? 100 : 50;\n                }\n\n                cue.position = position;\n              }\n\n              function skipWhitespace() {\n                input = input.replace(/^\\s+/, \"\");\n              } // 4.1 WebVTT cue timings.\n\n              skipWhitespace();\n              cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n\n              skipWhitespace();\n\n              if (input.substr(0, 3) !== \"-->\") {\n                // (3) next characters must match '-->'\n                throw new Error(\"Malformed time stamp (time stamps must be separated by '-->'): \" + oInput);\n              }\n\n              input = input.substr(3);\n              skipWhitespace();\n              cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n              // 4.1 WebVTT cue settings list.\n\n              skipWhitespace();\n              consumeCueSettings(input, cue);\n            }\n\n            function fixLineBreaks(input) {\n              return input.replace(/<br(?: \\/)?>/gi, \"\\n\");\n            }\n            var VTTParser = /*#__PURE__*/ (function () {\n              function VTTParser() {\n                this.state = \"INITIAL\";\n                this.buffer = \"\";\n                this.decoder = new StringDecoder();\n                this.regionList = [];\n                this.cue = null;\n                this.oncue = void 0;\n                this.onparsingerror = void 0;\n                this.onflush = void 0;\n              }\n\n              var _proto3 = VTTParser.prototype;\n\n              _proto3.parse = function parse(data) {\n                var _this = this; // If there is no data then we won't decode it, but will just try to parse\n                // whatever is in buffer already. This may occur in circumstances, for\n                // example when flush() is called.\n\n                if (data) {\n                  // Try to decode the data that we received.\n                  _this.buffer += _this.decoder.decode(data, {\n                    stream: true,\n                  });\n                }\n\n                function collectNextLine() {\n                  var buffer = _this.buffer;\n                  var pos = 0;\n                  buffer = fixLineBreaks(buffer);\n\n                  while (pos < buffer.length && buffer[pos] !== \"\\r\" && buffer[pos] !== \"\\n\") {\n                    ++pos;\n                  }\n\n                  var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.\n\n                  if (buffer[pos] === \"\\r\") {\n                    ++pos;\n                  }\n\n                  if (buffer[pos] === \"\\n\") {\n                    ++pos;\n                  }\n\n                  _this.buffer = buffer.substr(pos);\n                  return line;\n                } // 3.2 WebVTT metadata header syntax\n\n                function parseHeader(input) {\n                  parseOptions(\n                    input,\n                    function (k, v) {\n                      // switch (k) {\n                      // case 'region':\n                      // 3.3 WebVTT region metadata header syntax\n                      // console.log('parse region', v);\n                      // parseRegion(v);\n                      // break;\n                      // }\n                    },\n                    /:/\n                  );\n                } // 5.1 WebVTT file parsing.\n\n                try {\n                  var line = \"\";\n\n                  if (_this.state === \"INITIAL\") {\n                    // We can't start parsing until we have the first line.\n                    if (!/\\r\\n|\\n/.test(_this.buffer)) {\n                      return this;\n                    }\n\n                    line = collectNextLine(); // strip of UTF-8 BOM if any\n                    // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n\n                    var m = line.match(/^(ï»¿)?WEBVTT([ \\t].*)?$/);\n\n                    if (!m || !m[0]) {\n                      throw new Error(\"Malformed WebVTT signature.\");\n                    }\n\n                    _this.state = \"HEADER\";\n                  }\n\n                  var alreadyCollectedLine = false;\n\n                  while (_this.buffer) {\n                    // We can't parse a line until we have the full line.\n                    if (!/\\r\\n|\\n/.test(_this.buffer)) {\n                      return this;\n                    }\n\n                    if (!alreadyCollectedLine) {\n                      line = collectNextLine();\n                    } else {\n                      alreadyCollectedLine = false;\n                    }\n\n                    switch (_this.state) {\n                      case \"HEADER\":\n                        // 13-18 - Allow a header (metadata) under the WEBVTT line.\n                        if (/:/.test(line)) {\n                          parseHeader(line);\n                        } else if (!line) {\n                          // An empty line terminates the header and starts the body (cues).\n                          _this.state = \"ID\";\n                        }\n\n                        continue;\n\n                      case \"NOTE\":\n                        // Ignore NOTE blocks.\n                        if (!line) {\n                          _this.state = \"ID\";\n                        }\n\n                        continue;\n\n                      case \"ID\":\n                        // Check for the start of NOTE blocks.\n                        if (/^NOTE($|[ \\t])/.test(line)) {\n                          _this.state = \"NOTE\";\n                          break;\n                        } // 19-29 - Allow any number of line terminators, then initialize new cue values.\n\n                        if (!line) {\n                          continue;\n                        }\n\n                        _this.cue = new _vttcue__WEBPACK_IMPORTED_MODULE_0__[\"default\"](0, 0, \"\");\n                        _this.state = \"CUE\"; // 30-39 - Check if self line contains an optional identifier or timing data.\n\n                        if (line.indexOf(\"-->\") === -1) {\n                          _this.cue.id = line;\n                          continue;\n                        }\n\n                      // Process line as start of a cue.\n\n                      /* falls through */\n\n                      case \"CUE\":\n                        // 40 - Collect cue timings and settings.\n                        if (!_this.cue) {\n                          _this.state = \"BADCUE\";\n                          continue;\n                        }\n\n                        try {\n                          parseCue(line, _this.cue, _this.regionList);\n                        } catch (e) {\n                          // In case of an error ignore rest of the cue.\n                          _this.cue = null;\n                          _this.state = \"BADCUE\";\n                          continue;\n                        }\n\n                        _this.state = \"CUETEXT\";\n                        continue;\n\n                      case \"CUETEXT\":\n                        {\n                          var hasSubstring = line.indexOf(\"-->\") !== -1; // 34 - If we have an empty line then report the cue.\n                          // 35 - If we have the special substring '-->' then report the cue,\n                          // but do not collect the line as we need to process the current\n                          // one as a new cue.\n\n                          if (!line || (hasSubstring && (alreadyCollectedLine = true))) {\n                            // We are done parsing self cue.\n                            if (_this.oncue && _this.cue) {\n                              _this.oncue(_this.cue);\n                            }\n\n                            _this.cue = null;\n                            _this.state = \"ID\";\n                            continue;\n                          }\n\n                          if (_this.cue === null) {\n                            continue;\n                          }\n\n                          if (_this.cue.text) {\n                            _this.cue.text += \"\\n\";\n                          }\n\n                          _this.cue.text += line;\n                        }\n                        continue;\n\n                      case \"BADCUE\":\n                        // 54-62 - Collect and discard the remaining cue.\n                        if (!line) {\n                          _this.state = \"ID\";\n                        }\n                    }\n                  }\n                } catch (e) {\n                  // If we are currently parsing a cue, report what we have.\n                  if (_this.state === \"CUETEXT\" && _this.cue && _this.oncue) {\n                    _this.oncue(_this.cue);\n                  }\n\n                  _this.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise\n                  // another exception occurred so enter BADCUE state.\n\n                  _this.state = _this.state === \"INITIAL\" ? \"BADWEBVTT\" : \"BADCUE\";\n                }\n\n                return this;\n              };\n\n              _proto3.flush = function flush() {\n                var _this = this;\n\n                try {\n                  // Finish decoding the stream.\n                  // _this.buffer += _this.decoder.decode();\n                  // Synthesize the end of the current cue or region.\n                  if (_this.cue || _this.state === \"HEADER\") {\n                    _this.buffer += \"\\n\\n\";\n\n                    _this.parse();\n                  } // If we've flushed, parsed, and we're still on the INITIAL state then\n                  // that means we don't have enough of the stream to parse the first\n                  // line.\n\n                  if (_this.state === \"INITIAL\" || _this.state === \"BADWEBVTT\") {\n                    throw new Error(\"Malformed WebVTT signature.\");\n                  }\n                } catch (e) {\n                  if (_this.onparsingerror) {\n                    _this.onparsingerror(e);\n                  }\n                }\n\n                if (_this.onflush) {\n                  _this.onflush();\n                }\n\n                return this;\n              };\n\n              return VTTParser;\n            })();\n\n            /***/\n          },\n\n        /***/ \"./src/utils/webvtt-parser.ts\":\n          /*!************************************!*\\\n  !*** ./src/utils/webvtt-parser.ts ***!\n  \\************************************/\n          /*! exports provided: generateCueId, parseWebVTT */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"generateCueId\", function () {\n              return generateCueId;\n            });\n            /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parseWebVTT\", function () {\n              return parseWebVTT;\n            });\n            /* harmony import */ var _home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ \"./src/polyfills/number.ts\");\n            /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ \"./src/utils/vttparser.ts\");\n            /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ \"./src/demux/id3.ts\");\n            /* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timescale-conversion */ \"./src/utils/timescale-conversion.ts\");\n            /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../remux/mp4-remuxer */ \"./src/remux/mp4-remuxer.ts\");\n\n            var LINEBREAKS = /\\r\\n|\\n\\r|\\n|\\r/g; // String.prototype.startsWith is not supported in IE11\n\n            var startsWith = function startsWith(inputString, searchString, position) {\n              if (position === void 0) {\n                position = 0;\n              }\n\n              return inputString.substr(position, searchString.length) === searchString;\n            };\n\n            var cueString2millis = function cueString2millis(timeString) {\n              var ts = parseInt(timeString.substr(-3));\n              var secs = parseInt(timeString.substr(-6, 2));\n              var mins = parseInt(timeString.substr(-9, 2));\n              var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(\":\"))) : 0;\n\n              if (\n                !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(ts) ||\n                !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(secs) ||\n                !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(mins) ||\n                !Object(_home_runner_work_CiderHls_js_CiderHls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__[\"isFiniteNumber\"])(hours)\n              ) {\n                throw Error(\"Malformed X-TIMESTAMP-MAP: Local:\" + timeString);\n              }\n\n              ts += 1000 * secs;\n              ts += 60 * 1000 * mins;\n              ts += 60 * 60 * 1000 * hours;\n              return ts;\n            }; // From https://github.com/darkskyapp/string-hash\n\n            var hash = function hash(text) {\n              var hash = 5381;\n              var i = text.length;\n\n              while (i) {\n                hash = (hash * 33) ^ text.charCodeAt(--i);\n              }\n\n              return (hash >>> 0).toString();\n            }; // Create a unique hash id for a cue based on start/end times and text.\n            // This helps timeline-controller to avoid showing repeated captions.\n\n            function generateCueId(startTime, endTime, text) {\n              return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);\n            }\n\n            var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {\n              var currCC = vttCCs[cc];\n              var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity\n              // Offset = current discontinuity time\n\n              if (!prevCC || (!prevCC.new && currCC.new)) {\n                vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n                currCC.new = false;\n                return;\n              } // There have been discontinuities since cues were last parsed.\n              // Offset = time elapsed\n\n              while ((_prevCC = prevCC) !== null && _prevCC !== void 0 && _prevCC.new) {\n                var _prevCC;\n\n                vttCCs.ccOffset += currCC.start - prevCC.start;\n                currCC.new = false;\n                currCC = prevCC;\n                prevCC = vttCCs[currCC.prevCC];\n              }\n\n              vttCCs.presentationOffset = presentationTime;\n            };\n\n            function parseWebVTT(vttByteArray, initPTS, timescale, vttCCs, cc, timeOffset, callBack, errorCallBack) {\n              var parser = new _vttparser__WEBPACK_IMPORTED_MODULE_1__[\"VTTParser\"](); // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n              // Uint8Array.prototype.reduce is not implemented in IE11\n\n              var vttLines = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_2__[\"utf8ArrayToStr\"])(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, \"\\n\").split(\"\\n\");\n              var cues = [];\n              var initPTS90Hz = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_3__[\"toMpegTsClockFromTimescale\"])(initPTS, timescale);\n              var cueTime = \"00:00.000\";\n              var timestampMapMPEGTS = 0;\n              var timestampMapLOCAL = 0;\n              var parsingError;\n              var inHeader = true;\n              var timestampMap = false;\n\n              parser.oncue = function (cue) {\n                // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n                var currCC = vttCCs[cc];\n                var cueOffset = vttCCs.ccOffset; // Calculate subtitle PTS offset\n\n                var webVttMpegTsMapOffset = (timestampMapMPEGTS - initPTS90Hz) / 90000; // Update offsets for new discontinuities\n\n                if (currCC !== null && currCC !== void 0 && currCC.new) {\n                  if (timestampMapLOCAL !== undefined) {\n                    // When local time is provided, offset = discontinuity start time - local time\n                    cueOffset = vttCCs.ccOffset = currCC.start;\n                  } else {\n                    calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);\n                  }\n                }\n\n                if (webVttMpegTsMapOffset) {\n                  // If we have MPEGTS, offset = presentation time + discontinuity offset\n                  cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;\n                }\n\n                if (timestampMap) {\n                  var duration = cue.endTime - cue.startTime;\n                  var startTime = Object(_remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__[\"normalizePts\"])((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;\n                  cue.startTime = startTime;\n                  cue.endTime = startTime + duration;\n                } //trim trailing webvtt block whitespaces\n\n                var text = cue.text.trim(); // Fix encoding of special characters\n\n                cue.text = decodeURIComponent(encodeURIComponent(text)); // If the cue was not assigned an id from the VTT file (line above the content), create one.\n\n                if (!cue.id) {\n                  cue.id = generateCueId(cue.startTime, cue.endTime, text);\n                }\n\n                if (cue.endTime > 0) {\n                  cues.push(cue);\n                }\n              };\n\n              parser.onparsingerror = function (error) {\n                parsingError = error;\n              };\n\n              parser.onflush = function () {\n                if (parsingError) {\n                  errorCallBack(parsingError);\n                  return;\n                }\n\n                callBack(cues);\n              }; // Go through contents line by line.\n\n              vttLines.forEach(function (line) {\n                if (inHeader) {\n                  // Look for X-TIMESTAMP-MAP in header.\n                  if (startsWith(line, \"X-TIMESTAMP-MAP=\")) {\n                    // Once found, no more are allowed anyway, so stop searching.\n                    inHeader = false;\n                    timestampMap = true; // Extract LOCAL and MPEGTS.\n\n                    line\n                      .substr(16)\n                      .split(\",\")\n                      .forEach(function (timestamp) {\n                        if (startsWith(timestamp, \"LOCAL:\")) {\n                          cueTime = timestamp.substr(6);\n                        } else if (startsWith(timestamp, \"MPEGTS:\")) {\n                          timestampMapMPEGTS = parseInt(timestamp.substr(7));\n                        }\n                      });\n\n                    try {\n                      // Convert cue time to seconds\n                      timestampMapLOCAL = cueString2millis(cueTime) / 1000;\n                    } catch (error) {\n                      timestampMap = false;\n                      parsingError = error;\n                    } // Return without parsing X-TIMESTAMP-MAP line.\n\n                    return;\n                  } else if (line === \"\") {\n                    inHeader = false;\n                  }\n                } // Parse line by default.\n\n                parser.parse(line + \"\\n\");\n              });\n              parser.flush();\n            }\n\n            /***/\n          },\n\n        /***/ \"./src/utils/xhr-loader.ts\":\n          /*!*********************************!*\\\n  !*** ./src/utils/xhr-loader.ts ***!\n  \\*********************************/\n          /*! exports provided: default */\n          /***/ function (module, __webpack_exports__, __webpack_require__) {\n            \"use strict\";\n            __webpack_require__.r(__webpack_exports__);\n            /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ \"./src/utils/logger.ts\");\n            /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ \"./src/loader/load-stats.ts\");\n\n            var AGE_HEADER_LINE_REGEX = /^age:\\s*[\\d.]+\\s*$/m;\n\n            var XhrLoader = /*#__PURE__*/ (function () {\n              function XhrLoader(\n                config\n                /* CiderHlsConfig */\n              ) {\n                this.xhrSetup = void 0;\n                this.requestTimeout = void 0;\n                this.retryTimeout = void 0;\n                this.retryDelay = void 0;\n                this.config = null;\n                this.callbacks = null;\n                this.context = void 0;\n                this.loader = null;\n                this.stats = void 0;\n                this.xhrSetup = config ? config.xhrSetup : null;\n                this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__[\"LoadStats\"]();\n                this.retryDelay = 0;\n              }\n\n              var _proto = XhrLoader.prototype;\n\n              _proto.destroy = function destroy() {\n                this.callbacks = null;\n                this.abortInternal();\n                this.loader = null;\n                this.config = null;\n              };\n\n              _proto.abortInternal = function abortInternal() {\n                var loader = this.loader;\n                self.clearTimeout(this.requestTimeout);\n                self.clearTimeout(this.retryTimeout);\n\n                if (loader) {\n                  loader.onreadystatechange = null;\n                  loader.onprogress = null;\n\n                  if (loader.readyState !== 4) {\n                    this.stats.aborted = true;\n                    loader.abort();\n                  }\n                }\n              };\n\n              _proto.abort = function abort() {\n                var _this$callbacks;\n\n                this.abortInternal();\n\n                if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {\n                  this.callbacks.onAbort(this.stats, this.context, this.loader);\n                }\n              };\n\n              _proto.load = function load(context, config, callbacks) {\n                if (this.stats.loading.start) {\n                  throw new Error(\"Loader can only be used once.\");\n                }\n\n                this.stats.loading.start = self.performance.now();\n                this.context = context;\n                this.config = config;\n                this.callbacks = callbacks;\n                this.retryDelay = config.retryDelay;\n                this.loadInternal();\n              };\n\n              _proto.loadInternal = function loadInternal() {\n                var config = this.config,\n                  context = this.context;\n\n                if (!config) {\n                  return;\n                }\n\n                var xhr = (this.loader = new self.XMLHttpRequest());\n                var stats = this.stats;\n                stats.loading.first = 0;\n                stats.loaded = 0;\n                var xhrSetup = this.xhrSetup;\n\n                try {\n                  if (xhrSetup) {\n                    try {\n                      xhrSetup(xhr, context.url);\n                    } catch (e) {\n                      // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n                      // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n                      xhr.open(\"GET\", context.url, true);\n                      xhrSetup(xhr, context.url);\n                    }\n                  }\n\n                  if (!xhr.readyState) {\n                    xhr.open(\"GET\", context.url, true);\n                  }\n\n                  var headers = this.context.headers;\n\n                  if (headers) {\n                    for (var header in headers) {\n                      xhr.setRequestHeader(header, headers[header]);\n                    }\n                  }\n                } catch (e) {\n                  // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n                  this.callbacks.onError(\n                    {\n                      code: xhr.status,\n                      text: e.message,\n                    },\n                    context,\n                    xhr\n                  );\n                  return;\n                }\n\n                if (context.rangeEnd) {\n                  xhr.setRequestHeader(\"Range\", \"bytes=\" + context.rangeStart + \"-\" + (context.rangeEnd - 1));\n                }\n\n                xhr.onreadystatechange = this.readystatechange.bind(this);\n                xhr.onprogress = this.loadprogress.bind(this);\n                xhr.responseType = context.responseType; // setup timeout before we perform request\n\n                self.clearTimeout(this.requestTimeout);\n                this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);\n                xhr.send();\n              };\n\n              _proto.readystatechange = function readystatechange() {\n                var context = this.context,\n                  xhr = this.loader,\n                  stats = this.stats;\n\n                if (!context || !xhr) {\n                  return;\n                }\n\n                var readyState = xhr.readyState;\n                var config = this.config; // don't proceed if xhr has been aborted\n\n                if (stats.aborted) {\n                  return;\n                } // >= HEADERS_RECEIVED\n\n                if (readyState >= 2) {\n                  // clear xhr timeout and rearm it if readyState less than 4\n                  self.clearTimeout(this.requestTimeout);\n\n                  if (stats.loading.first === 0) {\n                    stats.loading.first = Math.max(self.performance.now(), stats.loading.start);\n                  }\n\n                  if (readyState === 4) {\n                    xhr.onreadystatechange = null;\n                    xhr.onprogress = null;\n                    var status = xhr.status; // http status between 200 to 299 are all successful\n\n                    if (status >= 200 && status < 300) {\n                      stats.loading.end = Math.max(self.performance.now(), stats.loading.first);\n                      var data;\n                      var len;\n\n                      if (context.responseType === \"arraybuffer\") {\n                        data = xhr.response;\n                        len = data.byteLength;\n                      } else {\n                        data = xhr.responseText;\n                        len = data.length;\n                      }\n\n                      stats.loaded = stats.total = len;\n\n                      if (!this.callbacks) {\n                        return;\n                      }\n\n                      var onProgress = this.callbacks.onProgress;\n\n                      if (onProgress) {\n                        onProgress(stats, context, data, xhr);\n                      }\n\n                      if (!this.callbacks) {\n                        return;\n                      }\n\n                      var response = {\n                        url: xhr.responseURL,\n                        data: data,\n                      };\n                      this.callbacks.onSuccess(response, stats, context, xhr);\n                    } else {\n                      // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n                      if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].error(status + \" while loading \" + context.url);\n                        this.callbacks.onError(\n                          {\n                            code: status,\n                            text: xhr.statusText,\n                          },\n                          context,\n                          xhr\n                        );\n                      } else {\n                        // retry\n                        _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].warn(status + \" while loading \" + context.url + \", retrying in \" + this.retryDelay + \"...\"); // abort and reset internal state\n\n                        this.abortInternal();\n                        this.loader = null; // schedule retry\n\n                        self.clearTimeout(this.retryTimeout);\n                        this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff\n\n                        this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n                        stats.retry++;\n                      }\n                    }\n                  } else {\n                    // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n                    self.clearTimeout(this.requestTimeout);\n                    this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);\n                  }\n                }\n              };\n\n              _proto.loadtimeout = function loadtimeout() {\n                _utils_logger__WEBPACK_IMPORTED_MODULE_0__[\"logger\"].warn(\"timeout while loading \" + this.context.url);\n                var callbacks = this.callbacks;\n\n                if (callbacks) {\n                  this.abortInternal();\n                  callbacks.onTimeout(this.stats, this.context, this.loader);\n                }\n              };\n\n              _proto.loadprogress = function loadprogress(event) {\n                var stats = this.stats;\n                stats.loaded = event.loaded;\n\n                if (event.lengthComputable) {\n                  stats.total = event.total;\n                }\n              };\n\n              _proto.getCacheAge = function getCacheAge() {\n                var result = null;\n\n                if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {\n                  var ageHeader = this.loader.getResponseHeader(\"age\");\n                  result = ageHeader ? parseFloat(ageHeader) : null;\n                }\n\n                return result;\n              };\n\n              return XhrLoader;\n            })();\n\n            /* harmony default export */ __webpack_exports__[\"default\"] = XhrLoader;\n\n            /***/\n          },\n\n        /******/\n      }\n    )[\"default\"];\n  });\n//# sourceMappingURL=CiderHls.js.map\n"
  },
  {
    "path": "src/renderer/index.js",
    "content": "var notyf = new Notyf();\n\nfunction clamp(num, min, max) {\n  return Math.min(Math.max(num, min), max);\n}\n\nconst MusicKitObjects = {\n  LibraryPlaylist: function () {\n    this.id = \"\";\n    this.type = \"library-playlist-folders\";\n    this.href = \"\";\n    this.attributes = {\n      dateAdded: \"\",\n      name: \"\",\n    };\n    this.playlists = [];\n  },\n};\n\n// limit an array to a certain number of items\nArray.prototype.limit = function (n) {\n  return this.slice(0, n);\n};\n\nVue.component(\"animated-number\", {\n  template: \"<div style='display: inline-block;'>{{ displayNumber }}</div>\",\n  props: { number: { default: 0 } },\n\n  data() {\n    return {\n      displayNumber: 0,\n      interval: false,\n    };\n  },\n\n  ready() {\n    this.displayNumber = this.number ? this.number : 0;\n  },\n\n  watch: {\n    number() {\n      clearInterval(this.interval);\n\n      if (this.number == this.displayNumber) {\n        return;\n      }\n\n      this.interval = window.setInterval(() => {\n        if (this.displayNumber != this.number) {\n          var change = (this.number - this.displayNumber) / 10;\n          change = change >= 0 ? Math.ceil(change) : Math.floor(change);\n          this.displayNumber = this.displayNumber + change;\n        }\n      }, 20);\n    },\n  },\n});\n\nfunction initMusicKit() {\n  if (!this.responseText) {\n    console.log(\"Using stored token\");\n    this.responseText = JSON.stringify({\n      token: localStorage.getItem(\"lastToken\"),\n    });\n  }\n  let parsedJson = JSON.parse(this.responseText);\n  localStorage.setItem(\"lastToken\", parsedJson.token);\n  MusicKit.configure({\n    developerToken: parsedJson.token,\n    app: {\n      name: \"Apple Music\",\n      build: \"1978.4.1\",\n      version: \"1.0\",\n    },\n    sourceType: 24,\n    suppressErrorDialog: true,\n  }).then(() => {\n    function waitForApp() {\n      if (typeof app.init !== \"undefined\") {\n        app.init();\n        if (app.cfg.visual.window_background_style == \"mica\" && !app.isDev) {\n          app.spawnMica();\n        }\n      } else {\n        setTimeout(waitForApp, 250);\n      }\n    }\n    waitForApp();\n  });\n}\n\nfunction capiInit() {\n  const request = new XMLHttpRequest();\n  request.timeout = 5000;\n  request.addEventListener(\"load\", initMusicKit);\n  request.onreadystatechange = function (aEvt) {\n    if (request.readyState == 4 && request.status != 200) {\n      if (localStorage.getItem(\"lastToken\") != null) {\n        initMusicKit();\n      } else {\n        console.error(`Failed to load capi, cannot get token [${request.status}]`);\n      }\n    }\n  };\n  request.open(\"GET\", \"https://api.cider.sh/v1/\");\n  request.send();\n}\n\ndocument.addEventListener(\"musickitloaded\", function () {\n  if (showOobe()) return;\n  console.log(\"MusicKit loaded\");\n  // MusicKit global is now defined\n  capiInit();\n});\nwindow.addEventListener(\"drmUnsupported\", function () {\n  initMusicKit();\n});\nif (\"serviceWorker\" in navigator) {\n  // Use the window load event to keep the page load performant\n  window.addEventListener(\"load\", () => {\n    navigator.serviceWorker.register(\"sw.js?v=1\");\n  });\n}\n\nconst getBase64FromUrl = async (url) => {\n  const data = await fetch(url);\n  const blob = await data.blob();\n  return new Promise((resolve) => {\n    const reader = new FileReader();\n    reader.readAsDataURL(blob);\n    reader.onloadend = () => {\n      const base64data = reader.result;\n      resolve(base64data);\n    };\n  });\n};\n\nfunction Clone(obj) {\n  return JSON.parse(JSON.stringify(obj));\n}\n\nfunction uuidv4() {\n  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16));\n}\n\nfunction xmlToJson(xml) {\n  // Create the return object\n  let obj = {};\n\n  if (xml.nodeType == 1) {\n    // element\n    // do attributes\n    if (xml.attributes.length > 0) {\n      obj[\"@attributes\"] = {};\n      for (var j = 0; j < xml.attributes.length; j++) {\n        let attribute = xml.attributes.item(j);\n        obj[\"@attributes\"][attribute.nodeName] = attribute.nodeValue;\n      }\n    }\n  } else if (xml.nodeType == 3) {\n    // text\n    obj = xml.nodeValue;\n  }\n\n  // do children\n  if (xml.hasChildNodes()) {\n    for (var i = 0; i < xml.childNodes.length; i++) {\n      var item = xml.childNodes.item(i);\n      var nodeName = item.nodeName;\n      if (typeof obj[nodeName] == \"undefined\") {\n        obj[nodeName] = xmlToJson(item);\n      } else {\n        if (typeof obj[nodeName].push == \"undefined\") {\n          var old = obj[nodeName];\n          obj[nodeName] = [];\n          obj[nodeName].push(old);\n        }\n        obj[nodeName].push(xmlToJson(item));\n      }\n    }\n  }\n  console.log(obj);\n  return obj;\n}\n\nasync function asyncForEach(array, callback) {\n  for (let index = 0; index < array.length; index++) {\n    await callback(array[index], index, array);\n  }\n}\n\nvar checkIfScrollIsStatic = setInterval(() => {\n  try {\n    if (position === document.getElementsByClassName(\"lyric-body\")[0].scrollTop) {\n      clearInterval(checkIfScrollIsStatic);\n      // do something\n    }\n    position = document.getElementsByClassName(\"lyric-body\")[0].scrollTop;\n  } catch (e) {}\n}, 50);\n\n// WebGPU Console Notification\nasync function webGPU() {\n  try {\n    const currentGPU = await navigator.gpu.requestAdapter();\n    console.log(\"WebGPU enabled on\", currentGPU.name, \"with feature ID\", currentGPU.features.size);\n  } catch (e) {\n    console.log(\"WebGPU disabled / WebGPU initialization failed\");\n  }\n}\n\nfunction isJson(item) {\n  item = typeof item !== \"string\" ? JSON.stringify(item) : item;\n\n  try {\n    item = JSON.parse(item);\n  } catch (e) {\n    return false;\n  }\n\n  if (typeof item === \"object\" && item !== null) {\n    return true;\n  }\n\n  return false;\n}\n\nwebGPU().then();\n\nfunction showOobe() {\n  if (localStorage.getItem(\"music.ampwebplay.media-user-token\") && localStorage.getItem(\"seenOOBE\")) {\n    return false;\n  } else {\n    function waitForApp() {\n      if (typeof app.init !== \"undefined\") {\n        app.oobeInit();\n      } else {\n        setTimeout(waitForApp, 250);\n      }\n    }\n    waitForApp();\n    return true;\n  }\n}\n\nlet screenWidth = screen.width;\nlet screenHeight = screen.height;\n\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n  // app.oobeInit()\n});\n\ndocument.addEventListener(\n  \"contextmenu\",\n  function (e) {\n    if (e.target.tagName.toLowerCase() == \"textarea\" || (e.target.tagName.toLowerCase() == \"input\" && e.target.type != \"checkbox\" && e.target.type != \"radio\" && e.target.disabled == false)) {\n      e.preventDefault();\n      const menuPanel = {\n        items: {\n          cut: {\n            name: app.getLz(\"action.cut\"),\n            action: function () {\n              document.execCommand(\"cut\");\n            },\n          },\n          copy: {\n            name: app.getLz(\"action.copy\"),\n            action: function () {\n              document.execCommand(\"copy\");\n            },\n          },\n          paste: {\n            name: app.getLz(\"action.paste\"),\n            action: function () {\n              document.execCommand(\"paste\");\n            },\n          },\n          delete: {\n            name: app.getLz(\"action.delete\"),\n            action: function () {\n              document.execCommand(\"delete\");\n            },\n          },\n          selectAll: {\n            name: app.getLz(\"action.selectAll\"),\n            action: function () {\n              document.execCommand(\"selectAll\");\n            },\n          },\n        },\n      };\n      app.showMenuPanel(menuPanel, e);\n    }\n  },\n  false,\n);\n"
  },
  {
    "path": "src/renderer/less/ameframework.less",
    "content": ":root {\n  --appleEase: cubic-bezier(0.42, 0, 0.58, 1);\n  --appleTransition: 0.2s var(--appleEase);\n}\n\n/* Simple CSS framework for Apple Music Electron */\n\n.md-labeltext {\n  font-size: 14px;\n  text-transform: uppercase;\n  opacity: 0.75;\n  font-weight: 500;\n}\n\n.md-option-container {\n  /* border-radius: 10px; */\n  overflow: hidden;\n}\n\n.md-option-line {\n  display: flex;\n  width: 100%;\n  padding: 14px;\n  background: var(--opaquePageBGColor);\n  font-size: 0.85em;\n\n  &.child {\n    background: rgb(0 0 0 / 15%);\n  }\n}\n\n.md-option-segment.md-option-segment_auto {\n  width: auto;\n  white-space: nowrap;\n}\n\n.md-option-container .md-option-line:not(:last-child) {\n  border-bottom: 1px solid rgb(0 0 0 / 15%);\n}\n\ninput[type=\"range\"].md-slider {\n  -webkit-appearance: none;\n  height: 7px;\n  background: rgba(255, 255, 255, 0.6);\n  border-radius: 5px;\n  background-size: 70% 100%;\n  background-repeat: no-repeat;\n}\n\ninput[type=\"range\"].md-slider::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  height: 20px;\n  width: 20px;\n  border-radius: 50%;\n  background: rgb(255 255 255);\n  cursor: ew-resize;\n  box-shadow: 0 0 2px 0 #555;\n}\n\ninput[type=\"range\"].md-slider::-webkit-slider-runnable-track {\n  -webkit-appearance: none;\n  box-shadow: none;\n  border: none;\n  background: transparent;\n}\n\n.md-option-header {\n  padding: 10px;\n  border-bottom: 1px solid rgb(200 200 200 / 25%);\n  font-weight: 500;\n  font-size: 0.9em;\n  background: rgb(255 255 255 / 10%);\n}\n\n.md-option-segment {\n  width: 100%;\n  display: flex;\n  justify-content: center;\n  flex-direction: column;\n}\n\n.md-h1 {\n  font-size: 3em;\n  text-align: center;\n}\n\n.md-header {\n  padding: 16px;\n}\n\n.md-header-title {\n  padding: 18px;\n  font-weight: 600;\n  font-size: 16px;\n  height: 55px;\n  background: var(--opaquePageBGColor);\n  border-bottom: 1px solid rgb(0 0 0 / 15%);\n}\n\n.md-footer {\n  padding: 16px;\n  text-align: center;\n}\n\n.md-transparent {\n  background: transparent;\n}\n\n.md-container {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  position: absolute;\n  top: 0px;\n  left: 0px;\n  width: 100%;\n  padding: 32px;\n}\n\n.md-container_panel {\n  padding: 0px;\n}\n\n.md-body {\n  height: 100%;\n  padding: 16px;\n  font-size: 1.25em;\n}\n\n@media (prefers-color-scheme: light) {\n  .md-btn {\n    box-shadow:\n      rgb(0 0 0 / 10%) 0px 0px 1px,\n      rgb(0 0 0 / 20%) 0px 1px 1px;\n    border: 1px solid rgb(0 0 0 / 15%);\n  }\n\n  .md-close-btn {\n    background-color: #000;\n  }\n}\n\n/* Vue transitions */\n.fade_simple-enter-active,\n.fade_simple-leave-active {\n  transition: all 0.5s;\n}\n\n.fade_simple-enter,\n.fade_simple-leave-to {\n  opacity: 0;\n}\n\n.fade-enter-active,\n.fade-leave-active {\n  transition: all 0.5s;\n}\n\n.fade-enter,\n.fade-leave-to {\n  opacity: 0;\n  transform: scale(0.95);\n}\n\n/* CSS Grids */\n\n.container,\n.container-fluid,\n.container-xxl,\n.container-xl,\n.container-lg,\n.container-md,\n.container-sm {\n  width: 100%;\n  padding-right: var(--bs-gutter-x, 0.75rem);\n  padding-left: var(--bs-gutter-x, 0.75rem);\n  margin-right: auto;\n  margin-left: auto;\n}\n\n.row {\n  --bs-gutter-x: 1.5rem;\n  --bs-gutter-y: 0;\n  display: flex;\n  flex-wrap: wrap;\n  /*margin-top: calc(-1 * var(--bs-gutter-y));*/\n  /*margin-right: calc(-0.5 * var(--bs-gutter-x));*/\n  /*margin-left: calc(-0.5 * var(--bs-gutter-x));*/\n}\n\n.row > * {\n  box-sizing: border-box;\n  flex-shrink: 0;\n  width: 100%;\n  max-width: 100%;\n  padding-right: calc(var(--bs-gutter-x) * 0.5);\n  padding-left: calc(var(--bs-gutter-x) * 0.5);\n  margin-top: var(--bs-gutter-y);\n}\n\n.col {\n  flex: 1 0 0%;\n}\n\n.row-cols-auto > * {\n  flex: 0 0 auto;\n  width: auto;\n}\n\n.row-cols-1 > * {\n  flex: 0 0 auto;\n  width: 100%;\n}\n\n.row-cols-2 > * {\n  flex: 0 0 auto;\n  width: 50%;\n}\n\n.row-cols-3 > * {\n  flex: 0 0 auto;\n  width: 33.3333333333%;\n}\n\n.row-cols-4 > * {\n  flex: 0 0 auto;\n  width: 25%;\n}\n\n.row-cols-5 > * {\n  flex: 0 0 auto;\n  width: 20%;\n}\n\n.row-cols-6 > * {\n  flex: 0 0 auto;\n  width: 16.6666666667%;\n}\n\n.col-auto {\n  flex: 0 0 auto;\n  width: auto;\n}\n\n@media only screen and (min-width: 1133px) and (max-width: 1233px) {\n  .about-page {\n    .row .col-auto {\n      display: none !important;\n    }\n  }\n}\n\n.col-1 {\n  flex: 0 0 auto;\n  width: 8.33333333%;\n}\n\n.col-2 {\n  flex: 0 0 auto;\n  width: 16.66666667%;\n}\n\n.col-3 {\n  flex: 0 0 auto;\n  width: 25%;\n}\n\n.col-4 {\n  flex: 0 0 auto;\n  width: 33.33333333%;\n}\n\n.col-5 {\n  flex: 0 0 auto;\n  width: 41.66666667%;\n}\n\n.col-6 {\n  flex: 0 0 auto;\n  width: 50%;\n}\n\n.col-7 {\n  flex: 0 0 auto;\n  width: 58.33333333%;\n}\n\n.col-8 {\n  flex: 0 0 auto;\n  width: 66.66666667%;\n}\n\n.col-9 {\n  flex: 0 0 auto;\n  width: 75%;\n}\n\n.col-10 {\n  flex: 0 0 auto;\n  width: 83.33333333%;\n}\n\n.col-11 {\n  flex: 0 0 auto;\n  width: 91.66666667%;\n}\n\n.col-12 {\n  flex: 0 0 auto;\n  width: 100%;\n}\n\n.offset-1 {\n  margin-left: 8.33333333%;\n}\n\n.offset-2 {\n  margin-left: 16.66666667%;\n}\n\n.offset-3 {\n  margin-left: 25%;\n}\n\n.offset-4 {\n  margin-left: 33.33333333%;\n}\n\n.offset-5 {\n  margin-left: 41.66666667%;\n}\n\n.offset-6 {\n  margin-left: 50%;\n}\n\n.offset-7 {\n  margin-left: 58.33333333%;\n}\n\n.offset-8 {\n  margin-left: 66.66666667%;\n}\n\n.offset-9 {\n  margin-left: 75%;\n}\n\n.offset-10 {\n  margin-left: 83.33333333%;\n}\n\n.offset-11 {\n  margin-left: 91.66666667%;\n}\n\n.g-0,\n.gx-0 {\n  --bs-gutter-x: 0;\n}\n\n.g-0,\n.gy-0 {\n  --bs-gutter-y: 0;\n}\n\n.g-1,\n.gx-1 {\n  --bs-gutter-x: 0.25rem;\n}\n\n.g-1,\n.gy-1 {\n  --bs-gutter-y: 0.25rem;\n}\n\n.g-2,\n.gx-2 {\n  --bs-gutter-x: 0.5rem;\n}\n\n.g-2,\n.gy-2 {\n  --bs-gutter-y: 0.5rem;\n}\n\n.g-3,\n.gx-3 {\n  --bs-gutter-x: 1rem;\n}\n\n.g-3,\n.gy-3 {\n  --bs-gutter-y: 1rem;\n}\n\n.g-4,\n.gx-4 {\n  --bs-gutter-x: 1.5rem;\n}\n\n.g-4,\n.gy-4 {\n  --bs-gutter-y: 1.5rem;\n}\n\n.g-5,\n.gx-5 {\n  --bs-gutter-x: 3rem;\n}\n\n.g-5,\n.gy-5 {\n  --bs-gutter-y: 3rem;\n}\n\n.d-inline {\n  display: inline !important;\n}\n\n.d-inline-block {\n  display: inline-block !important;\n}\n\n.d-block {\n  display: block !important;\n}\n\n.d-grid {\n  display: grid !important;\n}\n\n.d-table {\n  display: table !important;\n}\n\n.d-table-row {\n  display: table-row !important;\n}\n\n.d-table-cell {\n  display: table-cell !important;\n}\n\n.d-flex {\n  display: flex !important;\n}\n\n.d-inline-flex {\n  display: inline-flex !important;\n}\n\n.d-none {\n  display: none !important;\n}\n\n.flex-fill {\n  flex: 1 1 auto !important;\n}\n\n.flex-row {\n  flex-direction: row !important;\n}\n\n.flex-column {\n  flex-direction: column !important;\n}\n\n.flex-row-reverse {\n  flex-direction: row-reverse !important;\n}\n\n.flex-column-reverse {\n  flex-direction: column-reverse !important;\n}\n\n.flex-grow-0 {\n  flex-grow: 0 !important;\n}\n\n.flex-grow-1 {\n  flex-grow: 1 !important;\n}\n\n.flex-shrink-0 {\n  flex-shrink: 0 !important;\n}\n\n.flex-shrink-1 {\n  flex-shrink: 1 !important;\n}\n\n.flex-wrap {\n  flex-wrap: wrap !important;\n}\n\n.flex-nowrap {\n  flex-wrap: nowrap !important;\n}\n\n.flex-wrap-reverse {\n  flex-wrap: wrap-reverse !important;\n}\n\n.justify-content-start {\n  justify-content: flex-start !important;\n}\n\n.justify-content-end {\n  justify-content: flex-end !important;\n}\n\n.justify-content-center {\n  justify-content: center !important;\n}\n\n.justify-content-between {\n  justify-content: space-between !important;\n}\n\n.justify-content-around {\n  justify-content: space-around !important;\n}\n\n.justify-content-evenly {\n  justify-content: space-evenly !important;\n}\n\n.align-items-start {\n  align-items: flex-start !important;\n}\n\n.align-items-end {\n  align-items: flex-end !important;\n}\n\n.align-items-center {\n  align-items: center !important;\n}\n\n.align-items-baseline {\n  align-items: baseline !important;\n}\n\n.align-items-stretch {\n  align-items: stretch !important;\n}\n\n.align-content-start {\n  align-content: flex-start !important;\n}\n\n.align-content-end {\n  align-content: flex-end !important;\n}\n\n.align-content-center {\n  align-content: center !important;\n}\n\n.align-content-between {\n  align-content: space-between !important;\n}\n\n.align-content-around {\n  align-content: space-around !important;\n}\n\n.align-content-stretch {\n  align-content: stretch !important;\n}\n\n.align-self-auto {\n  align-self: auto !important;\n}\n\n.align-self-start {\n  align-self: flex-start !important;\n}\n\n.align-self-end {\n  align-self: flex-end !important;\n}\n\n.align-self-center {\n  align-self: center !important;\n}\n\n.align-self-baseline {\n  align-self: baseline !important;\n}\n\n.align-self-stretch {\n  align-self: stretch !important;\n}\n\n.order-first {\n  order: -1 !important;\n}\n\n.order-0 {\n  order: 0 !important;\n}\n\n.order-1 {\n  order: 1 !important;\n}\n\n.order-2 {\n  order: 2 !important;\n}\n\n.order-3 {\n  order: 3 !important;\n}\n\n.order-4 {\n  order: 4 !important;\n}\n\n.order-5 {\n  order: 5 !important;\n}\n\n.order-last {\n  order: 6 !important;\n}\n\n.m-0 {\n  margin: 0 !important;\n}\n\n.m-1 {\n  margin: 0.25rem !important;\n}\n\n.m-2 {\n  margin: 0.5rem !important;\n}\n\n.m-3 {\n  margin: 1rem !important;\n}\n\n.m-4 {\n  margin: 1.5rem !important;\n}\n\n.m-5 {\n  margin: 3rem !important;\n}\n\n.m-auto {\n  margin: auto !important;\n}\n\n.mx-0 {\n  margin-right: 0 !important;\n  margin-left: 0 !important;\n}\n\n.mx-1 {\n  margin-right: 0.25rem !important;\n  margin-left: 0.25rem !important;\n}\n\n.mx-2 {\n  margin-right: 0.5rem !important;\n  margin-left: 0.5rem !important;\n}\n\n.mx-3 {\n  margin-right: 1rem !important;\n  margin-left: 1rem !important;\n}\n\n.mx-4 {\n  margin-right: 1.5rem !important;\n  margin-left: 1.5rem !important;\n}\n\n.mx-5 {\n  margin-right: 3rem !important;\n  margin-left: 3rem !important;\n}\n\n.mx-auto {\n  margin-right: auto !important;\n  margin-left: auto !important;\n}\n\n.my-0 {\n  margin-top: 0 !important;\n  margin-bottom: 0 !important;\n}\n\n.my-1 {\n  margin-top: 0.25rem !important;\n  margin-bottom: 0.25rem !important;\n}\n\n.my-2 {\n  margin-top: 0.5rem !important;\n  margin-bottom: 0.5rem !important;\n}\n\n.my-3 {\n  margin-top: 1rem !important;\n  margin-bottom: 1rem !important;\n}\n\n.my-4 {\n  margin-top: 1.5rem !important;\n  margin-bottom: 1.5rem !important;\n}\n\n.my-5 {\n  margin-top: 3rem !important;\n  margin-bottom: 3rem !important;\n}\n\n.my-auto {\n  margin-top: auto !important;\n  margin-bottom: auto !important;\n}\n\n.mt-0 {\n  margin-top: 0 !important;\n}\n\n.mt-1 {\n  margin-top: 0.25rem !important;\n}\n\n.mt-2 {\n  margin-top: 0.5rem !important;\n}\n\n.mt-3 {\n  margin-top: 1rem !important;\n}\n\n.mt-4 {\n  margin-top: 1.5rem !important;\n}\n\n.mt-5 {\n  margin-top: 3rem !important;\n}\n\n.mt-auto {\n  margin-top: auto !important;\n}\n\n.me-0 {\n  margin-right: 0 !important;\n}\n\n.me-1 {\n  margin-right: 0.25rem !important;\n}\n\n.me-2 {\n  margin-right: 0.5rem !important;\n}\n\n.me-3 {\n  margin-right: 1rem !important;\n}\n\n.me-4 {\n  margin-right: 1.5rem !important;\n}\n\n.me-5 {\n  margin-right: 3rem !important;\n}\n\n.me-auto {\n  margin-right: auto !important;\n}\n\n.mb-0 {\n  margin-bottom: 0 !important;\n}\n\n.mb-1 {\n  margin-bottom: 0.25rem !important;\n}\n\n.mb-2 {\n  margin-bottom: 0.5rem !important;\n}\n\n.mb-3 {\n  margin-bottom: 1rem !important;\n}\n\n.mb-4 {\n  margin-bottom: 1.5rem !important;\n}\n\n.mb-5 {\n  margin-bottom: 3rem !important;\n}\n\n.mb-auto {\n  margin-bottom: auto !important;\n}\n\n.ms-0 {\n  margin-left: 0 !important;\n}\n\n.ms-1 {\n  margin-left: 0.25rem !important;\n}\n\n.ms-2 {\n  margin-left: 0.5rem !important;\n}\n\n.ms-3 {\n  margin-left: 1rem !important;\n}\n\n.ms-4 {\n  margin-left: 1.5rem !important;\n}\n\n.ms-5 {\n  margin-left: 3rem !important;\n}\n\n.ms-auto {\n  margin-left: auto !important;\n}\n\n.p-0 {\n  padding: 0 !important;\n}\n\n.p-1 {\n  padding: 0.25rem !important;\n}\n\n.p-2 {\n  padding: 0.5rem !important;\n}\n\n.p-3 {\n  padding: 1rem !important;\n}\n\n.p-4 {\n  padding: 1.5rem !important;\n}\n\n.p-5 {\n  padding: 3rem !important;\n}\n\n.px-0 {\n  padding-right: 0 !important;\n  padding-left: 0 !important;\n}\n\n.px-1 {\n  padding-right: 0.25rem !important;\n  padding-left: 0.25rem !important;\n}\n\n.px-2 {\n  padding-right: 0.5rem !important;\n  padding-left: 0.5rem !important;\n}\n\n.px-3 {\n  padding-right: 1rem !important;\n  padding-left: 1rem !important;\n}\n\n.px-4 {\n  padding-right: 1.5rem !important;\n  padding-left: 1.5rem !important;\n}\n\n.px-5 {\n  padding-right: 3rem !important;\n  padding-left: 3rem !important;\n}\n\n.py-0 {\n  padding-top: 0 !important;\n  padding-bottom: 0 !important;\n}\n\n.py-1 {\n  padding-top: 0.25rem !important;\n  padding-bottom: 0.25rem !important;\n}\n\n.py-2 {\n  padding-top: 0.5rem !important;\n  padding-bottom: 0.5rem !important;\n}\n\n.py-3 {\n  padding-top: 1rem !important;\n  padding-bottom: 1rem !important;\n}\n\n.py-4 {\n  padding-top: 1.5rem !important;\n  padding-bottom: 1.5rem !important;\n}\n\n.py-5 {\n  padding-top: 3rem !important;\n  padding-bottom: 3rem !important;\n}\n\n.pt-0 {\n  padding-top: 0 !important;\n}\n\n.pt-1 {\n  padding-top: 0.25rem !important;\n}\n\n.pt-2 {\n  padding-top: 0.5rem !important;\n}\n\n.pt-3 {\n  padding-top: 1rem !important;\n}\n\n.pt-4 {\n  padding-top: 1.5rem !important;\n}\n\n.pt-5 {\n  padding-top: 3rem !important;\n}\n\n.pe-0 {\n  padding-right: 0 !important;\n}\n\n.pe-1 {\n  padding-right: 0.25rem !important;\n}\n\n.pe-2 {\n  padding-right: 0.5rem !important;\n}\n\n.pe-3 {\n  padding-right: 1rem !important;\n}\n\n.pe-4 {\n  padding-right: 1.5rem !important;\n}\n\n.pe-5 {\n  padding-right: 3rem !important;\n}\n\n.pb-0 {\n  padding-bottom: 0 !important;\n}\n\n.pb-1 {\n  padding-bottom: 0.25rem !important;\n}\n\n.pb-2 {\n  padding-bottom: 0.5rem !important;\n}\n\n.pb-3 {\n  padding-bottom: 1rem !important;\n}\n\n.pb-4 {\n  padding-bottom: 1.5rem !important;\n}\n\n.pb-5 {\n  padding-bottom: 3rem !important;\n}\n\n.ps-0 {\n  padding-left: 0 !important;\n}\n\n.ps-1 {\n  padding-left: 0.25rem !important;\n}\n\n.ps-2 {\n  padding-left: 0.5rem !important;\n}\n\n.ps-3 {\n  padding-left: 1rem !important;\n}\n\n.ps-4 {\n  padding-left: 1.5rem !important;\n}\n\n.ps-5 {\n  padding-left: 3rem !important;\n}\n"
  },
  {
    "path": "src/renderer/less/appvars.less",
    "content": "@colorMixRate: 1%;\n@transparencyRate: 50%;\n\n@keyColor: #fc3c44;\n@ciderColor: #ff2654;\n@baseColor: #1e1e1e;\n@baseColorMix: mix(@baseColor, transparent, @transparencyRate);\n@sidebarColor: #2e2e2e;\n@sidebarColorMix: mix(@sidebarColor, transparent, @transparencyRate);\n@appOpacity: 0.15;\n\n:root {\n  --baseColor: @baseColor;\n  --baseColorMix: @baseColorMix;\n  --sidebarColor: @sidebarColor;\n  --sidebarColorMix: @sidebarColorMix;\n  --ciderColor: @ciderColor;\n  --appOpacity: @appOpacity;\n  --transparencyRate: @transparencyRate;\n  --macOSChromeColor: rgb(14 14 14 / 32%);\n}\n"
  },
  {
    "path": "src/renderer/less/bootstrap-vue.min.less",
    "content": "@charset \"UTF-8\";\n/*!\n * BootstrapVue Custom CSS (https://bootstrap-vue.org)\n */\n.bv-no-focus-ring:focus {\n  outline: none;\n}\n\n@media (max-width: 575.98px) {\n  .bv-d-xs-down-none {\n    display: none !important;\n  }\n}\n@media (max-width: 767.98px) {\n  .bv-d-sm-down-none {\n    display: none !important;\n  }\n}\n@media (max-width: 991.98px) {\n  .bv-d-md-down-none {\n    display: none !important;\n  }\n}\n@media (max-width: 1199.98px) {\n  .bv-d-lg-down-none {\n    display: none !important;\n  }\n}\n.bv-d-xl-down-none {\n  display: none !important;\n}\n\n.form-control.focus {\n  color: #495057;\n  background-color: #fff;\n  border-color: #80bdff;\n  outline: 0;\n  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);\n}\n.form-control.focus.is-valid {\n  border-color: #28a745;\n  box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);\n}\n.form-control.focus.is-invalid {\n  border-color: #dc3545;\n  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);\n}\n\n.b-avatar {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  vertical-align: middle;\n  flex-shrink: 0;\n  width: 2.5rem;\n  height: 2.5rem;\n  font-size: inherit;\n  font-weight: 400;\n  line-height: 1;\n  max-width: 100%;\n  max-height: auto;\n  text-align: center;\n  overflow: visible;\n  position: relative;\n  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;\n}\n.b-avatar:focus {\n  outline: 0;\n}\n.b-avatar.btn, .b-avatar[href] {\n  padding: 0;\n  border: 0;\n}\n.b-avatar.btn .b-avatar-img img, .b-avatar[href] .b-avatar-img img {\n  transition: -webkit-transform 0.15s ease-in-out;\n  transition: transform 0.15s ease-in-out;\n  transition: transform 0.15s ease-in-out, -webkit-transform 0.15s ease-in-out;\n}\n.b-avatar.btn:not(:disabled):not(.disabled), .b-avatar[href]:not(:disabled):not(.disabled) {\n  cursor: pointer;\n}\n.b-avatar.btn:not(:disabled):not(.disabled):hover .b-avatar-img img, .b-avatar[href]:not(:disabled):not(.disabled):hover .b-avatar-img img {\n  -webkit-transform: scale(1.15);\n  transform: scale(1.15);\n}\n.b-avatar.disabled, .b-avatar:disabled, .b-avatar[disabled] {\n  opacity: 0.65;\n  pointer-events: none;\n}\n.b-avatar .b-avatar-custom,\n.b-avatar .b-avatar-text,\n.b-avatar .b-avatar-img {\n  border-radius: inherit;\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  -webkit-mask-image: radial-gradient(white, black);\n  mask-image: radial-gradient(white, black);\n}\n.b-avatar .b-avatar-text {\n  text-transform: uppercase;\n  white-space: nowrap;\n}\n.b-avatar[href] {\n  text-decoration: none;\n}\n.b-avatar > .b-icon {\n  width: 60%;\n  height: auto;\n  max-width: 100%;\n}\n.b-avatar .b-avatar-img img {\n  width: 100%;\n  height: 100%;\n  max-height: auto;\n  border-radius: inherit;\n  -o-object-fit: cover;\n  object-fit: cover;\n}\n.b-avatar .b-avatar-badge {\n  position: absolute;\n  min-height: 1.5em;\n  min-width: 1.5em;\n  padding: 0.25em;\n  line-height: 1;\n  border-radius: 10em;\n  font-size: 70%;\n  font-weight: 700;\n  z-index: 1;\n}\n\n.b-avatar-sm {\n  width: 1.5rem;\n  height: 1.5rem;\n}\n.b-avatar-sm .b-avatar-text {\n  font-size: calc(0.6rem);\n}\n.b-avatar-sm .b-avatar-badge {\n  font-size: calc(0.42rem);\n}\n\n.b-avatar-lg {\n  width: 3.5rem;\n  height: 3.5rem;\n}\n.b-avatar-lg .b-avatar-text {\n  font-size: calc(1.4rem);\n}\n.b-avatar-lg .b-avatar-badge {\n  font-size: calc(0.98rem);\n}\n\n.b-avatar-group .b-avatar-group-inner {\n  display: flex;\n  flex-wrap: wrap;\n}\n.b-avatar-group .b-avatar {\n  border: 1px solid #dee2e6;\n}\n.b-avatar-group a.b-avatar:hover:not(.disabled):not(disabled),\n.b-avatar-group .btn.b-avatar:hover:not(.disabled):not(disabled) {\n  z-index: 1;\n}\n\n.b-calendar {\n  display: inline-flex;\n}\n.b-calendar .b-calendar-inner {\n  min-width: 250px;\n}\n.b-calendar .b-calendar-header,\n.b-calendar .b-calendar-nav {\n  margin-bottom: 0.25rem;\n}\n.b-calendar .b-calendar-nav .btn {\n  padding: 0.25rem;\n}\n.b-calendar output {\n  padding: 0.25rem;\n  font-size: 80%;\n}\n.b-calendar output.readonly {\n  background-color: #e9ecef;\n  opacity: 1;\n}\n.b-calendar .b-calendar-footer {\n  margin-top: 0.5rem;\n}\n.b-calendar .b-calendar-grid {\n  padding: 0;\n  margin: 0;\n  overflow: hidden;\n}\n.b-calendar .b-calendar-grid .row {\n  flex-wrap: nowrap;\n}\n.b-calendar .b-calendar-grid-caption {\n  padding: 0.25rem;\n}\n.b-calendar .b-calendar-grid-body .col[data-date] .btn {\n  width: 32px;\n  height: 32px;\n  font-size: 14px;\n  line-height: 1;\n  margin: 3px auto;\n  padding: 9px 0;\n}\n.b-calendar .btn:disabled, .b-calendar .btn.disabled, .b-calendar .btn[aria-disabled=true] {\n  cursor: default;\n  pointer-events: none;\n}\n\n.card-img-left {\n  border-top-left-radius: calc(0.25rem - 1px);\n  border-bottom-left-radius: calc(0.25rem - 1px);\n}\n\n.card-img-right {\n  border-top-right-radius: calc(0.25rem - 1px);\n  border-bottom-right-radius: calc(0.25rem - 1px);\n}\n\n.dropdown:not(.dropleft) .dropdown-toggle.dropdown-toggle-no-caret::after {\n  display: none !important;\n}\n.dropdown.dropleft .dropdown-toggle.dropdown-toggle-no-caret::before {\n  display: none !important;\n}\n.dropdown .dropdown-menu:focus {\n  outline: none;\n}\n\n.b-dropdown-form {\n  display: inline-block;\n  padding: 0.25rem 1.5rem;\n  width: 100%;\n  clear: both;\n  font-weight: 400;\n}\n.b-dropdown-form:focus {\n  outline: 1px dotted !important;\n  outline: 5px auto -webkit-focus-ring-color !important;\n}\n.b-dropdown-form.disabled, .b-dropdown-form:disabled {\n  outline: 0 !important;\n  color: #6c757d;\n  pointer-events: none;\n}\n\n.b-dropdown-text {\n  display: inline-block;\n  padding: 0.25rem 1.5rem;\n  margin-bottom: 0;\n  width: 100%;\n  clear: both;\n  font-weight: lighter;\n}\n\n.custom-checkbox.b-custom-control-lg,\n.input-group-lg .custom-checkbox {\n  font-size: 1.25rem;\n  line-height: 1.5;\n  padding-left: 1.875rem;\n}\n.custom-checkbox.b-custom-control-lg .custom-control-label::before,\n.input-group-lg .custom-checkbox .custom-control-label::before {\n  top: 0.3125rem;\n  left: -1.875rem;\n  width: 1.25rem;\n  height: 1.25rem;\n  border-radius: 0.3rem;\n}\n.custom-checkbox.b-custom-control-lg .custom-control-label::after,\n.input-group-lg .custom-checkbox .custom-control-label::after {\n  top: 0.3125rem;\n  left: -1.875rem;\n  width: 1.25rem;\n  height: 1.25rem;\n  background-size: 50% 50%;\n}\n\n.custom-checkbox.b-custom-control-sm,\n.input-group-sm .custom-checkbox {\n  font-size: 0.875rem;\n  line-height: 1.5;\n  padding-left: 1.3125rem;\n}\n.custom-checkbox.b-custom-control-sm .custom-control-label::before,\n.input-group-sm .custom-checkbox .custom-control-label::before {\n  top: 0.21875rem;\n  left: -1.3125rem;\n  width: 0.875rem;\n  height: 0.875rem;\n  border-radius: 0.2rem;\n}\n.custom-checkbox.b-custom-control-sm .custom-control-label::after,\n.input-group-sm .custom-checkbox .custom-control-label::after {\n  top: 0.21875rem;\n  left: -1.3125rem;\n  width: 0.875rem;\n  height: 0.875rem;\n  background-size: 50% 50%;\n}\n\n.custom-switch.b-custom-control-lg,\n.input-group-lg .custom-switch {\n  padding-left: 2.8125rem;\n}\n.custom-switch.b-custom-control-lg .custom-control-label,\n.input-group-lg .custom-switch .custom-control-label {\n  font-size: 1.25rem;\n  line-height: 1.5;\n}\n.custom-switch.b-custom-control-lg .custom-control-label::before,\n.input-group-lg .custom-switch .custom-control-label::before {\n  top: 0.3125rem;\n  height: 1.25rem;\n  left: -2.8125rem;\n  width: 2.1875rem;\n  border-radius: 0.625rem;\n}\n.custom-switch.b-custom-control-lg .custom-control-label::after,\n.input-group-lg .custom-switch .custom-control-label::after {\n  top: calc( 0.3125rem + 2px );\n  left: calc( -2.8125rem + 2px );\n  width: calc( 1.25rem - 4px );\n  height: calc( 1.25rem - 4px );\n  border-radius: 0.625rem;\n  background-size: 50% 50%;\n}\n.custom-switch.b-custom-control-lg .custom-control-input:checked ~ .custom-control-label::after,\n.input-group-lg .custom-switch .custom-control-input:checked ~ .custom-control-label::after {\n  -webkit-transform: translateX(0.9375rem);\n  transform: translateX(0.9375rem);\n}\n\n.custom-switch.b-custom-control-sm,\n.input-group-sm .custom-switch {\n  padding-left: 1.96875rem;\n}\n.custom-switch.b-custom-control-sm .custom-control-label,\n.input-group-sm .custom-switch .custom-control-label {\n  font-size: 0.875rem;\n  line-height: 1.5;\n}\n.custom-switch.b-custom-control-sm .custom-control-label::before,\n.input-group-sm .custom-switch .custom-control-label::before {\n  top: 0.21875rem;\n  left: -1.96875rem;\n  width: 1.53125rem;\n  height: 0.875rem;\n  border-radius: 0.4375rem;\n}\n.custom-switch.b-custom-control-sm .custom-control-label::after,\n.input-group-sm .custom-switch .custom-control-label::after {\n  top: calc( 0.21875rem + 2px );\n  left: calc( -1.96875rem + 2px );\n  width: calc( 0.875rem - 4px );\n  height: calc( 0.875rem - 4px );\n  border-radius: 0.4375rem;\n  background-size: 50% 50%;\n}\n.custom-switch.b-custom-control-sm .custom-control-input:checked ~ .custom-control-label::after,\n.input-group-sm .custom-switch .custom-control-input:checked ~ .custom-control-label::after {\n  -webkit-transform: translateX(0.65625rem);\n  transform: translateX(0.65625rem);\n}\n\n.input-group > .input-group-prepend > .btn-group > .btn,\n.input-group > .input-group-append:not(:last-child) > .btn-group > .btn,\n.input-group > .input-group-append:last-child > .btn-group:not(:last-child):not(.dropdown-toggle) > .btn {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n.input-group > .input-group-append > .btn-group > .btn,\n.input-group > .input-group-prepend:not(:first-child) > .btn-group > .btn,\n.input-group > .input-group-prepend:first-child > .btn-group:not(:first-child) > .btn {\n  border-top-left-radius: 0;\n  border-bottom-left-radius: 0;\n}\n\n.b-form-btn-label-control.form-control {\n  display: flex;\n  align-items: stretch;\n  height: auto;\n  padding: 0;\n  background-image: none;\n}\n.input-group .b-form-btn-label-control.form-control {\n  padding: 0;\n}\n\n[dir=rtl] .b-form-btn-label-control.form-control, .b-form-btn-label-control.form-control[dir=rtl] {\n  flex-direction: row-reverse;\n}\n[dir=rtl] .b-form-btn-label-control.form-control > label, .b-form-btn-label-control.form-control[dir=rtl] > label {\n  text-align: right;\n}\n\n.b-form-btn-label-control.form-control > .btn {\n  line-height: 1;\n  font-size: inherit;\n  box-shadow: none !important;\n  border: 0;\n}\n.b-form-btn-label-control.form-control > .btn:disabled {\n  pointer-events: none;\n}\n.b-form-btn-label-control.form-control.is-valid > .btn {\n  color: #28a745;\n}\n.b-form-btn-label-control.form-control.is-invalid > .btn {\n  color: #dc3545;\n}\n.b-form-btn-label-control.form-control > .dropdown-menu {\n  padding: 0.5rem;\n}\n.b-form-btn-label-control.form-control > .form-control {\n  height: auto;\n  min-height: calc(calc(1.5em + 0.75rem + 2px) - 2px);\n  padding-left: 0.25rem;\n  margin: 0;\n  border: 0;\n  outline: 0;\n  background: transparent;\n  word-break: break-word;\n  font-size: inherit;\n  white-space: normal;\n  cursor: pointer;\n}\n.b-form-btn-label-control.form-control > .form-control.form-control-sm {\n  min-height: calc(calc(1.5em + 0.5rem + 2px) - 2px);\n}\n.b-form-btn-label-control.form-control > .form-control.form-control-lg {\n  min-height: calc(calc(1.5em + 1rem + 2px) - 2px);\n}\n.input-group.input-group-sm .b-form-btn-label-control.form-control > .form-control {\n  min-height: calc(calc(1.5em + 0.5rem + 2px) - 2px);\n  padding-top: 0.25rem;\n  padding-bottom: 0.25rem;\n}\n\n.input-group.input-group-lg .b-form-btn-label-control.form-control > .form-control {\n  min-height: calc(calc(1.5em + 1rem + 2px) - 2px);\n  padding-top: 0.5rem;\n  padding-bottom: 0.5rem;\n}\n\n.b-form-btn-label-control.form-control[aria-disabled=true], .b-form-btn-label-control.form-control[aria-readonly=true] {\n  background-color: #e9ecef;\n  opacity: 1;\n}\n.b-form-btn-label-control.form-control[aria-disabled=true] {\n  pointer-events: none;\n}\n.b-form-btn-label-control.form-control[aria-disabled=true] > label {\n  cursor: default;\n}\n\n.b-form-btn-label-control.btn-group > .dropdown-menu {\n  padding: 0.5rem;\n}\n\n.custom-file-label {\n  white-space: nowrap;\n  overflow-x: hidden;\n}\n\n.b-custom-control-lg.custom-file,\n.b-custom-control-lg .custom-file-input,\n.b-custom-control-lg .custom-file-label,\n.input-group-lg.custom-file,\n.input-group-lg .custom-file-input,\n.input-group-lg .custom-file-label {\n  font-size: 1.25rem;\n  height: calc(1.5em + 1rem + 2px);\n}\n.b-custom-control-lg .custom-file-label,\n.b-custom-control-lg .custom-file-label:after,\n.input-group-lg .custom-file-label,\n.input-group-lg .custom-file-label:after {\n  padding: 0.5rem 1rem;\n  line-height: 1.5;\n}\n.b-custom-control-lg .custom-file-label,\n.input-group-lg .custom-file-label {\n  border-radius: 0.3rem;\n}\n.b-custom-control-lg .custom-file-label::after,\n.input-group-lg .custom-file-label::after {\n  font-size: inherit;\n  height: calc( 1.5em + 1rem );\n  border-radius: 0 0.3rem 0.3rem 0;\n}\n\n.b-custom-control-sm.custom-file,\n.b-custom-control-sm .custom-file-input,\n.b-custom-control-sm .custom-file-label,\n.input-group-sm.custom-file,\n.input-group-sm .custom-file-input,\n.input-group-sm .custom-file-label {\n  font-size: 0.875rem;\n  height: calc(1.5em + 0.5rem + 2px);\n}\n.b-custom-control-sm .custom-file-label,\n.b-custom-control-sm .custom-file-label:after,\n.input-group-sm .custom-file-label,\n.input-group-sm .custom-file-label:after {\n  padding: 0.25rem 0.5rem;\n  line-height: 1.5;\n}\n.b-custom-control-sm .custom-file-label,\n.input-group-sm .custom-file-label {\n  border-radius: 0.2rem;\n}\n.b-custom-control-sm .custom-file-label::after,\n.input-group-sm .custom-file-label::after {\n  font-size: inherit;\n  height: calc( 1.5em + 0.5rem );\n  border-radius: 0 0.2rem 0.2rem 0;\n}\n\n.was-validated .form-control:invalid, .was-validated .form-control:valid, .form-control.is-invalid, .form-control.is-valid {\n  background-position: right calc(0.375em + 0.1875rem) center;\n}\n\ninput[type=color].form-control {\n  height: calc(1.5em + 0.75rem + 2px);\n  padding: 0.125rem 0.25rem;\n}\n\ninput[type=color].form-control.form-control-sm,\n.input-group-sm input[type=color].form-control {\n  height: calc(1.5em + 0.5rem + 2px);\n  padding: 0.125rem 0.25rem;\n}\n\ninput[type=color].form-control.form-control-lg,\n.input-group-lg input[type=color].form-control {\n  height: calc(1.5em + 1rem + 2px);\n  padding: 0.125rem 0.25rem;\n}\n\ninput[type=color].form-control:disabled {\n  background-color: #adb5bd;\n  opacity: 0.65;\n}\n\n.input-group > .custom-range {\n  position: relative;\n  flex: 1 1 auto;\n  width: 1%;\n  margin-bottom: 0;\n}\n.input-group > .custom-range + .form-control,\n.input-group > .custom-range + .form-control-plaintext,\n.input-group > .custom-range + .custom-select,\n.input-group > .custom-range + .custom-range,\n.input-group > .custom-range + .custom-file {\n  margin-left: -1px;\n}\n.input-group > .form-control + .custom-range,\n.input-group > .form-control-plaintext + .custom-range,\n.input-group > .custom-select + .custom-range,\n.input-group > .custom-range + .custom-range,\n.input-group > .custom-file + .custom-range {\n  margin-left: -1px;\n}\n.input-group > .custom-range:focus {\n  z-index: 3;\n}\n.input-group > .custom-range:not(:last-child) {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n.input-group > .custom-range:not(:first-child) {\n  border-top-left-radius: 0;\n  border-bottom-left-radius: 0;\n}\n.input-group > .custom-range {\n  height: calc(1.5em + 0.75rem + 2px);\n  padding: 0 0.75rem;\n  background-color: #fff;\n  background-clip: padding-box;\n  border: 1px solid #ced4da;\n  height: calc(1.5em + 0.75rem + 2px);\n  border-radius: 0.25rem;\n  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;\n}\n@media (prefers-reduced-motion: reduce) {\n  .input-group > .custom-range {\n    transition: none;\n  }\n}\n.input-group > .custom-range:focus {\n  color: #495057;\n  background-color: #fff;\n  border-color: #80bdff;\n  outline: 0;\n  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);\n}\n.input-group > .custom-range:disabled, .input-group > .custom-range[readonly] {\n  background-color: #e9ecef;\n}\n\n.input-group-lg > .custom-range {\n  height: calc(1.5em + 1rem + 2px);\n  padding: 0 1rem;\n  border-radius: 0.3rem;\n}\n\n.input-group-sm > .custom-range {\n  height: calc(1.5em + 0.5rem + 2px);\n  padding: 0 0.5rem;\n  border-radius: 0.2rem;\n}\n\n.was-validated .input-group .custom-range:valid, .input-group .custom-range.is-valid {\n  border-color: #28a745;\n}\n.was-validated .input-group .custom-range:valid:focus, .input-group .custom-range.is-valid:focus {\n  border-color: #28a745;\n  box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);\n}\n\n.was-validated .custom-range:valid:focus::-webkit-slider-thumb, .custom-range.is-valid:focus::-webkit-slider-thumb {\n  box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem #9be7ac;\n}\n.was-validated .custom-range:valid:focus::-moz-range-thumb, .custom-range.is-valid:focus::-moz-range-thumb {\n  box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem #9be7ac;\n}\n.was-validated .custom-range:valid:focus::-ms-thumb, .custom-range.is-valid:focus::-ms-thumb {\n  box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem #9be7ac;\n}\n.was-validated .custom-range:valid::-webkit-slider-thumb, .custom-range.is-valid::-webkit-slider-thumb {\n  background-color: #28a745;\n  background-image: none;\n}\n.was-validated .custom-range:valid::-webkit-slider-thumb:active, .custom-range.is-valid::-webkit-slider-thumb:active {\n  background-color: #9be7ac;\n  background-image: none;\n}\n.was-validated .custom-range:valid::-webkit-slider-runnable-track, .custom-range.is-valid::-webkit-slider-runnable-track {\n  background-color: rgba(40, 167, 69, 0.35);\n}\n.was-validated .custom-range:valid::-moz-range-thumb, .custom-range.is-valid::-moz-range-thumb {\n  background-color: #28a745;\n  background-image: none;\n}\n.was-validated .custom-range:valid::-moz-range-thumb:active, .custom-range.is-valid::-moz-range-thumb:active {\n  background-color: #9be7ac;\n  background-image: none;\n}\n.was-validated .custom-range:valid::-moz-range-track, .custom-range.is-valid::-moz-range-track {\n  background: rgba(40, 167, 69, 0.35);\n}\n.was-validated .custom-range:valid ~ .valid-feedback,\n.was-validated .custom-range:valid ~ .valid-tooltip, .custom-range.is-valid ~ .valid-feedback,\n.custom-range.is-valid ~ .valid-tooltip {\n  display: block;\n}\n.was-validated .custom-range:valid::-ms-thumb, .custom-range.is-valid::-ms-thumb {\n  background-color: #28a745;\n  background-image: none;\n}\n.was-validated .custom-range:valid::-ms-thumb:active, .custom-range.is-valid::-ms-thumb:active {\n  background-color: #9be7ac;\n  background-image: none;\n}\n.was-validated .custom-range:valid::-ms-track-lower, .custom-range.is-valid::-ms-track-lower {\n  background: rgba(40, 167, 69, 0.35);\n}\n.was-validated .custom-range:valid::-ms-track-upper, .custom-range.is-valid::-ms-track-upper {\n  background: rgba(40, 167, 69, 0.35);\n}\n\n.was-validated .input-group .custom-range:invalid, .input-group .custom-range.is-invalid {\n  border-color: #dc3545;\n}\n.was-validated .input-group .custom-range:invalid:focus, .input-group .custom-range.is-invalid:focus {\n  border-color: #dc3545;\n  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);\n}\n\n.was-validated .custom-range:invalid:focus::-webkit-slider-thumb, .custom-range.is-invalid:focus::-webkit-slider-thumb {\n  box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem #f6cdd1;\n}\n.was-validated .custom-range:invalid:focus::-moz-range-thumb, .custom-range.is-invalid:focus::-moz-range-thumb {\n  box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem #f6cdd1;\n}\n.was-validated .custom-range:invalid:focus::-ms-thumb, .custom-range.is-invalid:focus::-ms-thumb {\n  box-shadow: 0 0 0 1px #fff, 0 0 0 0.2rem #f6cdd1;\n}\n.was-validated .custom-range:invalid::-webkit-slider-thumb, .custom-range.is-invalid::-webkit-slider-thumb {\n  background-color: #dc3545;\n  background-image: none;\n}\n.was-validated .custom-range:invalid::-webkit-slider-thumb:active, .custom-range.is-invalid::-webkit-slider-thumb:active {\n  background-color: #f6cdd1;\n  background-image: none;\n}\n.was-validated .custom-range:invalid::-webkit-slider-runnable-track, .custom-range.is-invalid::-webkit-slider-runnable-track {\n  background-color: rgba(220, 53, 69, 0.35);\n}\n.was-validated .custom-range:invalid::-moz-range-thumb, .custom-range.is-invalid::-moz-range-thumb {\n  background-color: #dc3545;\n  background-image: none;\n}\n.was-validated .custom-range:invalid::-moz-range-thumb:active, .custom-range.is-invalid::-moz-range-thumb:active {\n  background-color: #f6cdd1;\n  background-image: none;\n}\n.was-validated .custom-range:invalid::-moz-range-track, .custom-range.is-invalid::-moz-range-track {\n  background: rgba(220, 53, 69, 0.35);\n}\n.was-validated .custom-range:invalid ~ .invalid-feedback,\n.was-validated .custom-range:invalid ~ .invalid-tooltip, .custom-range.is-invalid ~ .invalid-feedback,\n.custom-range.is-invalid ~ .invalid-tooltip {\n  display: block;\n}\n.was-validated .custom-range:invalid::-ms-thumb, .custom-range.is-invalid::-ms-thumb {\n  background-color: #dc3545;\n  background-image: none;\n}\n.was-validated .custom-range:invalid::-ms-thumb:active, .custom-range.is-invalid::-ms-thumb:active {\n  background-color: #f6cdd1;\n  background-image: none;\n}\n.was-validated .custom-range:invalid::-ms-track-lower, .custom-range.is-invalid::-ms-track-lower {\n  background: rgba(220, 53, 69, 0.35);\n}\n.was-validated .custom-range:invalid::-ms-track-upper, .custom-range.is-invalid::-ms-track-upper {\n  background: rgba(220, 53, 69, 0.35);\n}\n\n.custom-radio.b-custom-control-lg,\n.input-group-lg .custom-radio {\n  font-size: 1.25rem;\n  line-height: 1.5;\n  padding-left: 1.875rem;\n}\n.custom-radio.b-custom-control-lg .custom-control-label::before,\n.input-group-lg .custom-radio .custom-control-label::before {\n  top: 0.3125rem;\n  left: -1.875rem;\n  width: 1.25rem;\n  height: 1.25rem;\n  border-radius: 50%;\n}\n.custom-radio.b-custom-control-lg .custom-control-label::after,\n.input-group-lg .custom-radio .custom-control-label::after {\n  top: 0.3125rem;\n  left: -1.875rem;\n  width: 1.25rem;\n  height: 1.25rem;\n  background: no-repeat 50%/50% 50%;\n}\n\n.custom-radio.b-custom-control-sm,\n.input-group-sm .custom-radio {\n  font-size: 0.875rem;\n  line-height: 1.5;\n  padding-left: 1.3125rem;\n}\n.custom-radio.b-custom-control-sm .custom-control-label::before,\n.input-group-sm .custom-radio .custom-control-label::before {\n  top: 0.21875rem;\n  left: -1.3125rem;\n  width: 0.875rem;\n  height: 0.875rem;\n  border-radius: 50%;\n}\n.custom-radio.b-custom-control-sm .custom-control-label::after,\n.input-group-sm .custom-radio .custom-control-label::after {\n  top: 0.21875rem;\n  left: -1.3125rem;\n  width: 0.875rem;\n  height: 0.875rem;\n  background: no-repeat 50%/50% 50%;\n}\n\n.b-rating {\n  text-align: center;\n}\n.b-rating.d-inline-flex {\n  width: auto;\n}\n.b-rating .b-rating-star,\n.b-rating .b-rating-value {\n  padding: 0 0.25em;\n}\n.b-rating .b-rating-value {\n  min-width: 2.5em;\n}\n.b-rating .b-rating-star {\n  display: inline-flex;\n  justify-content: center;\n  outline: 0;\n}\n.b-rating .b-rating-star .b-rating-icon {\n  display: inline-flex;\n  transition: all 0.15s ease-in-out;\n}\n.b-rating.disabled, .b-rating:disabled {\n  background-color: #e9ecef;\n  color: #6c757d;\n}\n.b-rating:not(.disabled):not(.readonly) .b-rating-star {\n  cursor: pointer;\n}\n.b-rating:not(.disabled):not(.readonly):focus:not(:hover) .b-rating-star.focused .b-rating-icon,\n.b-rating:not(.disabled):not(.readonly) .b-rating-star:hover .b-rating-icon {\n  -webkit-transform: scale(1.5);\n  transform: scale(1.5);\n}\n.b-rating[dir=rtl] .b-rating-star-half {\n  -webkit-transform: scale(-1, 1);\n  transform: scale(-1, 1);\n}\n\n.b-form-spinbutton {\n  text-align: center;\n  overflow: hidden;\n  background-image: none;\n  padding: 0;\n}\n[dir=rtl] .b-form-spinbutton:not(.flex-column), .b-form-spinbutton[dir=rtl]:not(.flex-column) {\n  flex-direction: row-reverse;\n}\n\n.b-form-spinbutton output {\n  font-size: inherit;\n  outline: 0;\n  border: 0;\n  background-color: transparent;\n  width: auto;\n  margin: 0;\n  padding: 0 0.25rem;\n}\n.b-form-spinbutton output > div,\n.b-form-spinbutton output > bdi {\n  display: block;\n  min-width: 2.25em;\n  height: 1.5em;\n}\n.b-form-spinbutton.flex-column {\n  height: auto;\n  width: auto;\n}\n.b-form-spinbutton.flex-column output {\n  margin: 0 0.25rem;\n  padding: 0.25rem 0;\n}\n.b-form-spinbutton:not(.d-inline-flex):not(.flex-column) {\n  output-width: 100%;\n}\n.b-form-spinbutton.d-inline-flex:not(.flex-column) {\n  width: auto;\n}\n.b-form-spinbutton .btn {\n  line-height: 1;\n  box-shadow: none !important;\n}\n.b-form-spinbutton .btn:disabled {\n  pointer-events: none;\n}\n.b-form-spinbutton .btn:hover:not(:disabled) > div > .b-icon {\n  -webkit-transform: scale(1.25);\n  transform: scale(1.25);\n}\n.b-form-spinbutton.disabled, .b-form-spinbutton.readonly {\n  background-color: #e9ecef;\n}\n.b-form-spinbutton.disabled {\n  pointer-events: none;\n}\n\n.b-form-tags .b-form-tags-list {\n  margin-top: -0.25rem;\n}\n.b-form-tags .b-form-tags-list .b-from-tags-field,\n.b-form-tags .b-form-tags-list .b-form-tag {\n  margin-top: 0.25rem;\n}\n.b-form-tags.focus {\n  color: #495057;\n  background-color: #fff;\n  border-color: #80bdff;\n  outline: 0;\n  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);\n}\n.b-form-tags.focus.is-valid {\n  border-color: #28a745;\n  box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);\n}\n.b-form-tags.focus.is-invalid {\n  border-color: #dc3545;\n  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);\n}\n.b-form-tags.disabled {\n  background-color: #e9ecef;\n}\n\n.b-form-tag {\n  font-size: 75%;\n  font-weight: normal;\n  line-height: 1.5;\n  margin-right: 0.25rem;\n}\n.b-form-tag.disabled {\n  opacity: 0.75;\n}\n.b-form-tag > button.b-form-tag-remove {\n  color: inherit;\n  font-size: 125%;\n  line-height: 1;\n  float: none;\n  margin-left: 0.25rem;\n}\n\n.form-control-sm .b-form-tag {\n  line-height: 1.5;\n}\n\n.form-control-lg .b-form-tag {\n  line-height: 1.5;\n}\n\n.media-aside {\n  display: flex;\n  margin-right: 1rem;\n}\n\n.media-aside-right {\n  margin-right: 0;\n  margin-left: 1rem;\n}\n\n.modal-backdrop {\n  opacity: 0.5;\n}\n\n.b-pagination-pills .page-item .page-link {\n  border-radius: 50rem !important;\n  margin-left: 0.25rem;\n  line-height: 1;\n}\n.b-pagination-pills .page-item:first-child .page-link {\n  margin-left: 0;\n}\n\n.popover.b-popover {\n  display: block;\n  opacity: 1;\n  outline: 0;\n}\n.popover.b-popover.fade:not(.show) {\n  opacity: 0;\n}\n.popover.b-popover.show {\n  opacity: 1;\n}\n\n.b-popover-primary.popover {\n  background-color: #cce5ff;\n  border-color: #b8daff;\n}\n.b-popover-primary.bs-popover-top > .arrow::before, .b-popover-primary.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #b8daff;\n}\n.b-popover-primary.bs-popover-top > .arrow::after, .b-popover-primary.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #cce5ff;\n}\n.b-popover-primary.bs-popover-right > .arrow::before, .b-popover-primary.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #b8daff;\n}\n.b-popover-primary.bs-popover-right > .arrow::after, .b-popover-primary.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #cce5ff;\n}\n.b-popover-primary.bs-popover-bottom > .arrow::before, .b-popover-primary.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #b8daff;\n}\n.b-popover-primary.bs-popover-bottom > .arrow::after, .b-popover-primary.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #bdddff;\n}\n.b-popover-primary.bs-popover-bottom .popover-header::before, .b-popover-primary.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #bdddff;\n}\n.b-popover-primary.bs-popover-left > .arrow::before, .b-popover-primary.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #b8daff;\n}\n.b-popover-primary.bs-popover-left > .arrow::after, .b-popover-primary.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #cce5ff;\n}\n.b-popover-primary .popover-header {\n  color: #212529;\n  background-color: #bdddff;\n  border-bottom-color: #a3d0ff;\n}\n.b-popover-primary .popover-body {\n  color: #004085;\n}\n\n.b-popover-secondary.popover {\n  background-color: #e2e3e5;\n  border-color: #d6d8db;\n}\n.b-popover-secondary.bs-popover-top > .arrow::before, .b-popover-secondary.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #d6d8db;\n}\n.b-popover-secondary.bs-popover-top > .arrow::after, .b-popover-secondary.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #e2e3e5;\n}\n.b-popover-secondary.bs-popover-right > .arrow::before, .b-popover-secondary.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #d6d8db;\n}\n.b-popover-secondary.bs-popover-right > .arrow::after, .b-popover-secondary.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #e2e3e5;\n}\n.b-popover-secondary.bs-popover-bottom > .arrow::before, .b-popover-secondary.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #d6d8db;\n}\n.b-popover-secondary.bs-popover-bottom > .arrow::after, .b-popover-secondary.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #dadbde;\n}\n.b-popover-secondary.bs-popover-bottom .popover-header::before, .b-popover-secondary.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #dadbde;\n}\n.b-popover-secondary.bs-popover-left > .arrow::before, .b-popover-secondary.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #d6d8db;\n}\n.b-popover-secondary.bs-popover-left > .arrow::after, .b-popover-secondary.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #e2e3e5;\n}\n.b-popover-secondary .popover-header {\n  color: #212529;\n  background-color: #dadbde;\n  border-bottom-color: #ccced2;\n}\n.b-popover-secondary .popover-body {\n  color: #383d41;\n}\n\n.b-popover-success.popover {\n  background-color: #d4edda;\n  border-color: #c3e6cb;\n}\n.b-popover-success.bs-popover-top > .arrow::before, .b-popover-success.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #c3e6cb;\n}\n.b-popover-success.bs-popover-top > .arrow::after, .b-popover-success.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #d4edda;\n}\n.b-popover-success.bs-popover-right > .arrow::before, .b-popover-success.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #c3e6cb;\n}\n.b-popover-success.bs-popover-right > .arrow::after, .b-popover-success.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #d4edda;\n}\n.b-popover-success.bs-popover-bottom > .arrow::before, .b-popover-success.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #c3e6cb;\n}\n.b-popover-success.bs-popover-bottom > .arrow::after, .b-popover-success.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #c9e8d1;\n}\n.b-popover-success.bs-popover-bottom .popover-header::before, .b-popover-success.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #c9e8d1;\n}\n.b-popover-success.bs-popover-left > .arrow::before, .b-popover-success.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #c3e6cb;\n}\n.b-popover-success.bs-popover-left > .arrow::after, .b-popover-success.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #d4edda;\n}\n.b-popover-success .popover-header {\n  color: #212529;\n  background-color: #c9e8d1;\n  border-bottom-color: #b7e1c1;\n}\n.b-popover-success .popover-body {\n  color: #155724;\n}\n\n.b-popover-info.popover {\n  background-color: #d1ecf1;\n  border-color: #bee5eb;\n}\n.b-popover-info.bs-popover-top > .arrow::before, .b-popover-info.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #bee5eb;\n}\n.b-popover-info.bs-popover-top > .arrow::after, .b-popover-info.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #d1ecf1;\n}\n.b-popover-info.bs-popover-right > .arrow::before, .b-popover-info.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #bee5eb;\n}\n.b-popover-info.bs-popover-right > .arrow::after, .b-popover-info.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #d1ecf1;\n}\n.b-popover-info.bs-popover-bottom > .arrow::before, .b-popover-info.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #bee5eb;\n}\n.b-popover-info.bs-popover-bottom > .arrow::after, .b-popover-info.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #c5e7ed;\n}\n.b-popover-info.bs-popover-bottom .popover-header::before, .b-popover-info.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #c5e7ed;\n}\n.b-popover-info.bs-popover-left > .arrow::before, .b-popover-info.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #bee5eb;\n}\n.b-popover-info.bs-popover-left > .arrow::after, .b-popover-info.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #d1ecf1;\n}\n.b-popover-info .popover-header {\n  color: #212529;\n  background-color: #c5e7ed;\n  border-bottom-color: #b2dfe7;\n}\n.b-popover-info .popover-body {\n  color: #0c5460;\n}\n\n.b-popover-warning.popover {\n  background-color: #fff3cd;\n  border-color: #ffeeba;\n}\n.b-popover-warning.bs-popover-top > .arrow::before, .b-popover-warning.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #ffeeba;\n}\n.b-popover-warning.bs-popover-top > .arrow::after, .b-popover-warning.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #fff3cd;\n}\n.b-popover-warning.bs-popover-right > .arrow::before, .b-popover-warning.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #ffeeba;\n}\n.b-popover-warning.bs-popover-right > .arrow::after, .b-popover-warning.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #fff3cd;\n}\n.b-popover-warning.bs-popover-bottom > .arrow::before, .b-popover-warning.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #ffeeba;\n}\n.b-popover-warning.bs-popover-bottom > .arrow::after, .b-popover-warning.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #ffefbe;\n}\n.b-popover-warning.bs-popover-bottom .popover-header::before, .b-popover-warning.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #ffefbe;\n}\n.b-popover-warning.bs-popover-left > .arrow::before, .b-popover-warning.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #ffeeba;\n}\n.b-popover-warning.bs-popover-left > .arrow::after, .b-popover-warning.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #fff3cd;\n}\n.b-popover-warning .popover-header {\n  color: #212529;\n  background-color: #ffefbe;\n  border-bottom-color: #ffe9a4;\n}\n.b-popover-warning .popover-body {\n  color: #856404;\n}\n\n.b-popover-danger.popover {\n  background-color: #f8d7da;\n  border-color: #f5c6cb;\n}\n.b-popover-danger.bs-popover-top > .arrow::before, .b-popover-danger.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #f5c6cb;\n}\n.b-popover-danger.bs-popover-top > .arrow::after, .b-popover-danger.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #f8d7da;\n}\n.b-popover-danger.bs-popover-right > .arrow::before, .b-popover-danger.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #f5c6cb;\n}\n.b-popover-danger.bs-popover-right > .arrow::after, .b-popover-danger.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #f8d7da;\n}\n.b-popover-danger.bs-popover-bottom > .arrow::before, .b-popover-danger.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #f5c6cb;\n}\n.b-popover-danger.bs-popover-bottom > .arrow::after, .b-popover-danger.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #f6cace;\n}\n.b-popover-danger.bs-popover-bottom .popover-header::before, .b-popover-danger.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #f6cace;\n}\n.b-popover-danger.bs-popover-left > .arrow::before, .b-popover-danger.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #f5c6cb;\n}\n.b-popover-danger.bs-popover-left > .arrow::after, .b-popover-danger.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #f8d7da;\n}\n.b-popover-danger .popover-header {\n  color: #212529;\n  background-color: #f6cace;\n  border-bottom-color: #f2b4ba;\n}\n.b-popover-danger .popover-body {\n  color: #721c24;\n}\n\n.b-popover-light.popover {\n  background-color: #fefefe;\n  border-color: #fdfdfe;\n}\n.b-popover-light.bs-popover-top > .arrow::before, .b-popover-light.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #fdfdfe;\n}\n.b-popover-light.bs-popover-top > .arrow::after, .b-popover-light.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #fefefe;\n}\n.b-popover-light.bs-popover-right > .arrow::before, .b-popover-light.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #fdfdfe;\n}\n.b-popover-light.bs-popover-right > .arrow::after, .b-popover-light.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #fefefe;\n}\n.b-popover-light.bs-popover-bottom > .arrow::before, .b-popover-light.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #fdfdfe;\n}\n.b-popover-light.bs-popover-bottom > .arrow::after, .b-popover-light.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #f6f6f6;\n}\n.b-popover-light.bs-popover-bottom .popover-header::before, .b-popover-light.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #f6f6f6;\n}\n.b-popover-light.bs-popover-left > .arrow::before, .b-popover-light.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #fdfdfe;\n}\n.b-popover-light.bs-popover-left > .arrow::after, .b-popover-light.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #fefefe;\n}\n.b-popover-light .popover-header {\n  color: #212529;\n  background-color: #f6f6f6;\n  border-bottom-color: #eaeaea;\n}\n.b-popover-light .popover-body {\n  color: #818182;\n}\n\n.b-popover-dark.popover {\n  background-color: #d6d8d9;\n  border-color: #c6c8ca;\n}\n.b-popover-dark.bs-popover-top > .arrow::before, .b-popover-dark.bs-popover-auto[x-placement^=top] > .arrow::before {\n  border-top-color: #c6c8ca;\n}\n.b-popover-dark.bs-popover-top > .arrow::after, .b-popover-dark.bs-popover-auto[x-placement^=top] > .arrow::after {\n  border-top-color: #d6d8d9;\n}\n.b-popover-dark.bs-popover-right > .arrow::before, .b-popover-dark.bs-popover-auto[x-placement^=right] > .arrow::before {\n  border-right-color: #c6c8ca;\n}\n.b-popover-dark.bs-popover-right > .arrow::after, .b-popover-dark.bs-popover-auto[x-placement^=right] > .arrow::after {\n  border-right-color: #d6d8d9;\n}\n.b-popover-dark.bs-popover-bottom > .arrow::before, .b-popover-dark.bs-popover-auto[x-placement^=bottom] > .arrow::before {\n  border-bottom-color: #c6c8ca;\n}\n.b-popover-dark.bs-popover-bottom > .arrow::after, .b-popover-dark.bs-popover-auto[x-placement^=bottom] > .arrow::after {\n  border-bottom-color: #ced0d2;\n}\n.b-popover-dark.bs-popover-bottom .popover-header::before, .b-popover-dark.bs-popover-auto[x-placement^=bottom] .popover-header::before {\n  border-bottom-color: #ced0d2;\n}\n.b-popover-dark.bs-popover-left > .arrow::before, .b-popover-dark.bs-popover-auto[x-placement^=left] > .arrow::before {\n  border-left-color: #c6c8ca;\n}\n.b-popover-dark.bs-popover-left > .arrow::after, .b-popover-dark.bs-popover-auto[x-placement^=left] > .arrow::after {\n  border-left-color: #d6d8d9;\n}\n.b-popover-dark .popover-header {\n  color: #212529;\n  background-color: #ced0d2;\n  border-bottom-color: #c1c4c5;\n}\n.b-popover-dark .popover-body {\n  color: #1b1e21;\n}\n\n.b-sidebar-outer {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  height: 0;\n  overflow: visible;\n  z-index: calc(1030 + 5);\n}\n\n.b-sidebar-backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: -1;\n  width: 100vw;\n  height: 100vh;\n  opacity: 0.6;\n}\n\n.b-sidebar {\n  display: flex;\n  flex-direction: column;\n  position: fixed;\n  top: 0;\n  width: 320px;\n  max-width: 100%;\n  height: 100vh;\n  max-height: 100%;\n  margin: 0;\n  outline: 0;\n  -webkit-transform: translateX(0);\n  transform: translateX(0);\n}\n.b-sidebar.slide {\n  transition: -webkit-transform 0.3s ease-in-out;\n  transition: transform 0.3s ease-in-out;\n  transition: transform 0.3s ease-in-out, -webkit-transform 0.3s ease-in-out;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-sidebar.slide {\n    transition: none;\n  }\n}\n.b-sidebar:not(.b-sidebar-right) {\n  left: 0;\n  right: auto;\n}\n.b-sidebar:not(.b-sidebar-right).slide:not(.show) {\n  -webkit-transform: translateX(-100%);\n  transform: translateX(-100%);\n}\n.b-sidebar:not(.b-sidebar-right) > .b-sidebar-header .close {\n  margin-left: auto;\n}\n.b-sidebar.b-sidebar-right {\n  left: auto;\n  right: 0;\n}\n.b-sidebar.b-sidebar-right.slide:not(.show) {\n  -webkit-transform: translateX(100%);\n  transform: translateX(100%);\n}\n.b-sidebar.b-sidebar-right > .b-sidebar-header .close {\n  margin-right: auto;\n}\n.b-sidebar > .b-sidebar-header {\n  font-size: 1.5rem;\n  padding: 0.5rem 1rem;\n  display: flex;\n  flex-direction: row;\n  flex-grow: 0;\n  align-items: center;\n}\n[dir=rtl] .b-sidebar > .b-sidebar-header {\n  flex-direction: row-reverse;\n}\n\n.b-sidebar > .b-sidebar-header .close {\n  float: none;\n  font-size: 1.5rem;\n}\n.b-sidebar > .b-sidebar-body {\n  flex-grow: 1;\n  height: 100%;\n  overflow-y: auto;\n}\n.b-sidebar > .b-sidebar-footer {\n  flex-grow: 0;\n}\n\n.b-skeleton-wrapper {\n  cursor: wait;\n}\n\n.b-skeleton {\n  position: relative;\n  overflow: hidden;\n  background-color: rgba(0, 0, 0, 0.12);\n  cursor: wait;\n  -webkit-mask-image: radial-gradient(white, black);\n  mask-image: radial-gradient(white, black);\n}\n.b-skeleton::before {\n  content: \" \";\n}\n\n.b-skeleton-text {\n  height: 1rem;\n  margin-bottom: 0.25rem;\n  border-radius: 0.25rem;\n}\n\n.b-skeleton-button {\n  width: 75px;\n  padding: 0.375rem 0.75rem;\n  font-size: 1rem;\n  line-height: 1.5;\n  border-radius: 0.25rem;\n}\n\n.b-skeleton-avatar {\n  width: 2.5em;\n  height: 2.5em;\n  border-radius: 50%;\n}\n\n.b-skeleton-input {\n  height: calc(1.5em + 0.75rem + 2px);\n  padding: 0.375rem 0.75rem;\n  line-height: 1.5;\n  border: #ced4da solid 1px;\n  border-radius: 0.25rem;\n}\n\n.b-skeleton-icon-wrapper svg {\n  color: rgba(0, 0, 0, 0.12);\n}\n\n.b-skeleton-img {\n  height: 100%;\n  width: 100%;\n}\n\n.b-skeleton-animate-wave::after {\n  content: \"\";\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 0;\n  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);\n  -webkit-animation: b-skeleton-animate-wave 1.75s linear infinite;\n  animation: b-skeleton-animate-wave 1.75s linear infinite;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-skeleton-animate-wave::after {\n    background: none;\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n\n@-webkit-keyframes b-skeleton-animate-wave {\n  from {\n    -webkit-transform: translateX(-100%);\n    transform: translateX(-100%);\n  }\n  to {\n    -webkit-transform: translateX(100%);\n    transform: translateX(100%);\n  }\n}\n\n@keyframes b-skeleton-animate-wave {\n  from {\n    -webkit-transform: translateX(-100%);\n    transform: translateX(-100%);\n  }\n  to {\n    -webkit-transform: translateX(100%);\n    transform: translateX(100%);\n  }\n}\n.b-skeleton-animate-fade {\n  -webkit-animation: b-skeleton-animate-fade 0.875s ease-in-out alternate infinite;\n  animation: b-skeleton-animate-fade 0.875s ease-in-out alternate infinite;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-skeleton-animate-fade {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n\n@-webkit-keyframes b-skeleton-animate-fade {\n  0% {\n    opacity: 1;\n  }\n  100% {\n    opacity: 0.4;\n  }\n}\n\n@keyframes b-skeleton-animate-fade {\n  0% {\n    opacity: 1;\n  }\n  100% {\n    opacity: 0.4;\n  }\n}\n.b-skeleton-animate-throb {\n  -webkit-animation: b-skeleton-animate-throb 0.875s ease-in alternate infinite;\n  animation: b-skeleton-animate-throb 0.875s ease-in alternate infinite;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-skeleton-animate-throb {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n\n@-webkit-keyframes b-skeleton-animate-throb {\n  0% {\n    -webkit-transform: scale(1);\n    transform: scale(1);\n  }\n  100% {\n    -webkit-transform: scale(0.975);\n    transform: scale(0.975);\n  }\n}\n\n@keyframes b-skeleton-animate-throb {\n  0% {\n    -webkit-transform: scale(1);\n    transform: scale(1);\n  }\n  100% {\n    -webkit-transform: scale(0.975);\n    transform: scale(0.975);\n  }\n}\n.table.b-table.b-table-fixed {\n  table-layout: fixed;\n}\n.table.b-table.b-table-no-border-collapse {\n  border-collapse: separate;\n  border-spacing: 0;\n}\n.table.b-table[aria-busy=true] {\n  opacity: 0.55;\n}\n.table.b-table > tbody > tr.b-table-details > td {\n  border-top: none !important;\n}\n.table.b-table > caption {\n  caption-side: bottom;\n}\n.table.b-table.b-table-caption-top > caption {\n  caption-side: top !important;\n}\n.table.b-table > tbody > .table-active,\n.table.b-table > tbody > .table-active > th,\n.table.b-table > tbody > .table-active > td {\n  background-color: rgba(0, 0, 0, 0.075);\n}\n.table.b-table.table-hover > tbody > tr.table-active:hover td,\n.table.b-table.table-hover > tbody > tr.table-active:hover th {\n  color: #212529;\n  background-image: linear-gradient(rgba(0, 0, 0, 0.075), rgba(0, 0, 0, 0.075));\n  background-repeat: no-repeat;\n}\n.table.b-table > tbody > .bg-active,\n.table.b-table > tbody > .bg-active > th,\n.table.b-table > tbody > .bg-active > td {\n  background-color: rgba(255, 255, 255, 0.075) !important;\n}\n.table.b-table.table-hover.table-dark > tbody > tr.bg-active:hover td,\n.table.b-table.table-hover.table-dark > tbody > tr.bg-active:hover th {\n  color: #fff;\n  background-image: linear-gradient(rgba(255, 255, 255, 0.075), rgba(255, 255, 255, 0.075));\n  background-repeat: no-repeat;\n}\n\n.b-table-sticky-header,\n.table-responsive,\n[class*=table-responsive-] {\n  margin-bottom: 1rem;\n}\n.b-table-sticky-header > .table,\n.table-responsive > .table,\n[class*=table-responsive-] > .table {\n  margin-bottom: 0;\n}\n\n.b-table-sticky-header {\n  overflow-y: auto;\n  max-height: 300px;\n}\n\n@media print {\n  .b-table-sticky-header {\n    overflow-y: visible !important;\n    max-height: none !important;\n  }\n}\n@supports ((position: -webkit-sticky) or (position: sticky)) {\n  .b-table-sticky-header > .table.b-table > thead > tr > th {\n    position: -webkit-sticky;\n    position: sticky;\n    top: 0;\n    z-index: 2;\n  }\n\n  .b-table-sticky-header > .table.b-table > thead > tr > .b-table-sticky-column,\n.b-table-sticky-header > .table.b-table > tbody > tr > .b-table-sticky-column,\n.b-table-sticky-header > .table.b-table > tfoot > tr > .b-table-sticky-column,\n.table-responsive > .table.b-table > thead > tr > .b-table-sticky-column,\n.table-responsive > .table.b-table > tbody > tr > .b-table-sticky-column,\n.table-responsive > .table.b-table > tfoot > tr > .b-table-sticky-column,\n[class*=table-responsive-] > .table.b-table > thead > tr > .b-table-sticky-column,\n[class*=table-responsive-] > .table.b-table > tbody > tr > .b-table-sticky-column,\n[class*=table-responsive-] > .table.b-table > tfoot > tr > .b-table-sticky-column {\n    position: -webkit-sticky;\n    position: sticky;\n    left: 0;\n  }\n  .b-table-sticky-header > .table.b-table > thead > tr > .b-table-sticky-column,\n.table-responsive > .table.b-table > thead > tr > .b-table-sticky-column,\n[class*=table-responsive-] > .table.b-table > thead > tr > .b-table-sticky-column {\n    z-index: 5;\n  }\n  .b-table-sticky-header > .table.b-table > tbody > tr > .b-table-sticky-column,\n.b-table-sticky-header > .table.b-table > tfoot > tr > .b-table-sticky-column,\n.table-responsive > .table.b-table > tbody > tr > .b-table-sticky-column,\n.table-responsive > .table.b-table > tfoot > tr > .b-table-sticky-column,\n[class*=table-responsive-] > .table.b-table > tbody > tr > .b-table-sticky-column,\n[class*=table-responsive-] > .table.b-table > tfoot > tr > .b-table-sticky-column {\n    z-index: 2;\n  }\n\n  .table.b-table > thead > tr > .table-b-table-default,\n.table.b-table > tbody > tr > .table-b-table-default,\n.table.b-table > tfoot > tr > .table-b-table-default {\n    color: #212529;\n    background-color: #fff;\n  }\n  .table.b-table.table-dark > thead > tr > .bg-b-table-default,\n.table.b-table.table-dark > tbody > tr > .bg-b-table-default,\n.table.b-table.table-dark > tfoot > tr > .bg-b-table-default {\n    color: #fff;\n    background-color: #343a40;\n  }\n  .table.b-table.table-striped > tbody > tr:nth-of-type(odd) > .table-b-table-default {\n    background-image: linear-gradient(rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05));\n    background-repeat: no-repeat;\n  }\n  .table.b-table.table-striped.table-dark > tbody > tr:nth-of-type(odd) > .bg-b-table-default {\n    background-image: linear-gradient(rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.05));\n    background-repeat: no-repeat;\n  }\n  .table.b-table.table-hover > tbody > tr:hover > .table-b-table-default {\n    color: #212529;\n    background-image: linear-gradient(rgba(0, 0, 0, 0.075), rgba(0, 0, 0, 0.075));\n    background-repeat: no-repeat;\n  }\n  .table.b-table.table-hover.table-dark > tbody > tr:hover > .bg-b-table-default {\n    color: #fff;\n    background-image: linear-gradient(rgba(255, 255, 255, 0.075), rgba(255, 255, 255, 0.075));\n    background-repeat: no-repeat;\n  }\n}\n.table.b-table > thead > tr > [aria-sort],\n.table.b-table > tfoot > tr > [aria-sort] {\n  cursor: pointer;\n  background-image: none;\n  background-repeat: no-repeat;\n  background-size: 0.65em 1em;\n}\n.table.b-table > thead > tr > [aria-sort]:not(.b-table-sort-icon-left),\n.table.b-table > tfoot > tr > [aria-sort]:not(.b-table-sort-icon-left) {\n  background-position: right calc(0.75rem / 2) center;\n  padding-right: calc(0.75rem + 0.65em);\n}\n.table.b-table > thead > tr > [aria-sort].b-table-sort-icon-left,\n.table.b-table > tfoot > tr > [aria-sort].b-table-sort-icon-left {\n  background-position: left calc(0.75rem / 2) center;\n  padding-left: calc(0.75rem + 0.65em);\n}\n.table.b-table > thead > tr > [aria-sort=none],\n.table.b-table > tfoot > tr > [aria-sort=none] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='black' opacity='.3' d='M51 1l25 23 24 22H1l25-22zM51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table > thead > tr > [aria-sort=ascending],\n.table.b-table > tfoot > tr > [aria-sort=ascending] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='black' d='M51 1l25 23 24 22H1l25-22z'/%3e%3cpath fill='black' opacity='.3' d='M51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table > thead > tr > [aria-sort=descending],\n.table.b-table > tfoot > tr > [aria-sort=descending] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='black' opacity='.3' d='M51 1l25 23 24 22H1l25-22z'/%3e%3cpath fill='black' d='M51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table.table-dark > thead > tr > [aria-sort=none], .table.b-table.table-dark > tfoot > tr > [aria-sort=none],\n.table.b-table > .thead-dark > tr > [aria-sort=none] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='white' opacity='.3' d='M51 1l25 23 24 22H1l25-22zM51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table.table-dark > thead > tr > [aria-sort=ascending], .table.b-table.table-dark > tfoot > tr > [aria-sort=ascending],\n.table.b-table > .thead-dark > tr > [aria-sort=ascending] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='white' d='M51 1l25 23 24 22H1l25-22z'/%3e%3cpath fill='white' opacity='.3' d='M51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table.table-dark > thead > tr > [aria-sort=descending], .table.b-table.table-dark > tfoot > tr > [aria-sort=descending],\n.table.b-table > .thead-dark > tr > [aria-sort=descending] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='white' opacity='.3' d='M51 1l25 23 24 22H1l25-22z'/%3e%3cpath fill='white' d='M51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table > thead > tr > .table-dark[aria-sort=none],\n.table.b-table > tfoot > tr > .table-dark[aria-sort=none] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='white' opacity='.3' d='M51 1l25 23 24 22H1l25-22zM51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table > thead > tr > .table-dark[aria-sort=ascending],\n.table.b-table > tfoot > tr > .table-dark[aria-sort=ascending] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='white' d='M51 1l25 23 24 22H1l25-22z'/%3e%3cpath fill='white' opacity='.3' d='M51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table > thead > tr > .table-dark[aria-sort=descending],\n.table.b-table > tfoot > tr > .table-dark[aria-sort=descending] {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='101' height='101' view-box='0 0 101 101' preserveAspectRatio='none'%3e%3cpath fill='white' opacity='.3' d='M51 1l25 23 24 22H1l25-22z'/%3e%3cpath fill='white' d='M51 101l25-23 24-22H1l25 22z'/%3e%3c/svg%3e\");\n}\n.table.b-table.table-sm > thead > tr > [aria-sort]:not(.b-table-sort-icon-left),\n.table.b-table.table-sm > tfoot > tr > [aria-sort]:not(.b-table-sort-icon-left) {\n  background-position: right calc(0.3rem / 2) center;\n  padding-right: calc(0.3rem + 0.65em);\n}\n.table.b-table.table-sm > thead > tr > [aria-sort].b-table-sort-icon-left,\n.table.b-table.table-sm > tfoot > tr > [aria-sort].b-table-sort-icon-left {\n  background-position: left calc(0.3rem / 2) center;\n  padding-left: calc(0.3rem + 0.65em);\n}\n\n.table.b-table.b-table-selectable:not(.b-table-selectable-no-click) > tbody > tr {\n  cursor: pointer;\n}\n.table.b-table.b-table-selectable:not(.b-table-selectable-no-click).b-table-selecting.b-table-select-range > tbody > tr {\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\n@media (max-width: 575.98px) {\n  .table.b-table.b-table-stacked-sm {\n    display: block;\n    width: 100%;\n  }\n  .table.b-table.b-table-stacked-sm > caption,\n.table.b-table.b-table-stacked-sm > tbody,\n.table.b-table.b-table-stacked-sm > tbody > tr,\n.table.b-table.b-table-stacked-sm > tbody > tr > td,\n.table.b-table.b-table-stacked-sm > tbody > tr > th {\n    display: block;\n  }\n  .table.b-table.b-table-stacked-sm > thead,\n.table.b-table.b-table-stacked-sm > tfoot {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-sm > thead > tr.b-table-top-row,\n.table.b-table.b-table-stacked-sm > thead > tr.b-table-bottom-row,\n.table.b-table.b-table-stacked-sm > tfoot > tr.b-table-top-row,\n.table.b-table.b-table-stacked-sm > tfoot > tr.b-table-bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-sm > caption {\n    caption-side: top !important;\n  }\n  .table.b-table.b-table-stacked-sm > tbody > tr > [data-label]::before {\n    content: attr(data-label);\n    width: 40%;\n    float: left;\n    text-align: right;\n    overflow-wrap: break-word;\n    font-weight: bold;\n    font-style: normal;\n    padding: 0 calc(1rem / 2) 0 0;\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-sm > tbody > tr > [data-label]::after {\n    display: block;\n    clear: both;\n    content: \"\";\n  }\n  .table.b-table.b-table-stacked-sm > tbody > tr > [data-label] > div {\n    display: inline-block;\n    width: calc(100% - 40%);\n    padding: 0 0 0 calc(1rem / 2);\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-sm > tbody > tr.top-row, .table.b-table.b-table-stacked-sm > tbody > tr.bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-sm > tbody > tr > :first-child {\n    border-top-width: 3px;\n  }\n  .table.b-table.b-table-stacked-sm > tbody > tr > [rowspan] + td,\n.table.b-table.b-table-stacked-sm > tbody > tr > [rowspan] + th {\n    border-top-width: 3px;\n  }\n}\n@media (max-width: 767.98px) {\n  .table.b-table.b-table-stacked-md {\n    display: block;\n    width: 100%;\n  }\n  .table.b-table.b-table-stacked-md > caption,\n.table.b-table.b-table-stacked-md > tbody,\n.table.b-table.b-table-stacked-md > tbody > tr,\n.table.b-table.b-table-stacked-md > tbody > tr > td,\n.table.b-table.b-table-stacked-md > tbody > tr > th {\n    display: block;\n  }\n  .table.b-table.b-table-stacked-md > thead,\n.table.b-table.b-table-stacked-md > tfoot {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-md > thead > tr.b-table-top-row,\n.table.b-table.b-table-stacked-md > thead > tr.b-table-bottom-row,\n.table.b-table.b-table-stacked-md > tfoot > tr.b-table-top-row,\n.table.b-table.b-table-stacked-md > tfoot > tr.b-table-bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-md > caption {\n    caption-side: top !important;\n  }\n  .table.b-table.b-table-stacked-md > tbody > tr > [data-label]::before {\n    content: attr(data-label);\n    width: 40%;\n    float: left;\n    text-align: right;\n    overflow-wrap: break-word;\n    font-weight: bold;\n    font-style: normal;\n    padding: 0 calc(1rem / 2) 0 0;\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-md > tbody > tr > [data-label]::after {\n    display: block;\n    clear: both;\n    content: \"\";\n  }\n  .table.b-table.b-table-stacked-md > tbody > tr > [data-label] > div {\n    display: inline-block;\n    width: calc(100% - 40%);\n    padding: 0 0 0 calc(1rem / 2);\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-md > tbody > tr.top-row, .table.b-table.b-table-stacked-md > tbody > tr.bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-md > tbody > tr > :first-child {\n    border-top-width: 3px;\n  }\n  .table.b-table.b-table-stacked-md > tbody > tr > [rowspan] + td,\n.table.b-table.b-table-stacked-md > tbody > tr > [rowspan] + th {\n    border-top-width: 3px;\n  }\n}\n@media (max-width: 991.98px) {\n  .table.b-table.b-table-stacked-lg {\n    display: block;\n    width: 100%;\n  }\n  .table.b-table.b-table-stacked-lg > caption,\n.table.b-table.b-table-stacked-lg > tbody,\n.table.b-table.b-table-stacked-lg > tbody > tr,\n.table.b-table.b-table-stacked-lg > tbody > tr > td,\n.table.b-table.b-table-stacked-lg > tbody > tr > th {\n    display: block;\n  }\n  .table.b-table.b-table-stacked-lg > thead,\n.table.b-table.b-table-stacked-lg > tfoot {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-lg > thead > tr.b-table-top-row,\n.table.b-table.b-table-stacked-lg > thead > tr.b-table-bottom-row,\n.table.b-table.b-table-stacked-lg > tfoot > tr.b-table-top-row,\n.table.b-table.b-table-stacked-lg > tfoot > tr.b-table-bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-lg > caption {\n    caption-side: top !important;\n  }\n  .table.b-table.b-table-stacked-lg > tbody > tr > [data-label]::before {\n    content: attr(data-label);\n    width: 40%;\n    float: left;\n    text-align: right;\n    overflow-wrap: break-word;\n    font-weight: bold;\n    font-style: normal;\n    padding: 0 calc(1rem / 2) 0 0;\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-lg > tbody > tr > [data-label]::after {\n    display: block;\n    clear: both;\n    content: \"\";\n  }\n  .table.b-table.b-table-stacked-lg > tbody > tr > [data-label] > div {\n    display: inline-block;\n    width: calc(100% - 40%);\n    padding: 0 0 0 calc(1rem / 2);\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-lg > tbody > tr.top-row, .table.b-table.b-table-stacked-lg > tbody > tr.bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-lg > tbody > tr > :first-child {\n    border-top-width: 3px;\n  }\n  .table.b-table.b-table-stacked-lg > tbody > tr > [rowspan] + td,\n.table.b-table.b-table-stacked-lg > tbody > tr > [rowspan] + th {\n    border-top-width: 3px;\n  }\n}\n@media (max-width: 1199.98px) {\n  .table.b-table.b-table-stacked-xl {\n    display: block;\n    width: 100%;\n  }\n  .table.b-table.b-table-stacked-xl > caption,\n.table.b-table.b-table-stacked-xl > tbody,\n.table.b-table.b-table-stacked-xl > tbody > tr,\n.table.b-table.b-table-stacked-xl > tbody > tr > td,\n.table.b-table.b-table-stacked-xl > tbody > tr > th {\n    display: block;\n  }\n  .table.b-table.b-table-stacked-xl > thead,\n.table.b-table.b-table-stacked-xl > tfoot {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-xl > thead > tr.b-table-top-row,\n.table.b-table.b-table-stacked-xl > thead > tr.b-table-bottom-row,\n.table.b-table.b-table-stacked-xl > tfoot > tr.b-table-top-row,\n.table.b-table.b-table-stacked-xl > tfoot > tr.b-table-bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-xl > caption {\n    caption-side: top !important;\n  }\n  .table.b-table.b-table-stacked-xl > tbody > tr > [data-label]::before {\n    content: attr(data-label);\n    width: 40%;\n    float: left;\n    text-align: right;\n    overflow-wrap: break-word;\n    font-weight: bold;\n    font-style: normal;\n    padding: 0 calc(1rem / 2) 0 0;\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-xl > tbody > tr > [data-label]::after {\n    display: block;\n    clear: both;\n    content: \"\";\n  }\n  .table.b-table.b-table-stacked-xl > tbody > tr > [data-label] > div {\n    display: inline-block;\n    width: calc(100% - 40%);\n    padding: 0 0 0 calc(1rem / 2);\n    margin: 0;\n  }\n  .table.b-table.b-table-stacked-xl > tbody > tr.top-row, .table.b-table.b-table-stacked-xl > tbody > tr.bottom-row {\n    display: none;\n  }\n  .table.b-table.b-table-stacked-xl > tbody > tr > :first-child {\n    border-top-width: 3px;\n  }\n  .table.b-table.b-table-stacked-xl > tbody > tr > [rowspan] + td,\n.table.b-table.b-table-stacked-xl > tbody > tr > [rowspan] + th {\n    border-top-width: 3px;\n  }\n}\n.table.b-table.b-table-stacked {\n  display: block;\n  width: 100%;\n}\n.table.b-table.b-table-stacked > caption,\n.table.b-table.b-table-stacked > tbody,\n.table.b-table.b-table-stacked > tbody > tr,\n.table.b-table.b-table-stacked > tbody > tr > td,\n.table.b-table.b-table-stacked > tbody > tr > th {\n  display: block;\n}\n.table.b-table.b-table-stacked > thead,\n.table.b-table.b-table-stacked > tfoot {\n  display: none;\n}\n.table.b-table.b-table-stacked > thead > tr.b-table-top-row,\n.table.b-table.b-table-stacked > thead > tr.b-table-bottom-row,\n.table.b-table.b-table-stacked > tfoot > tr.b-table-top-row,\n.table.b-table.b-table-stacked > tfoot > tr.b-table-bottom-row {\n  display: none;\n}\n.table.b-table.b-table-stacked > caption {\n  caption-side: top !important;\n}\n.table.b-table.b-table-stacked > tbody > tr > [data-label]::before {\n  content: attr(data-label);\n  width: 40%;\n  float: left;\n  text-align: right;\n  overflow-wrap: break-word;\n  font-weight: bold;\n  font-style: normal;\n  padding: 0 calc(1rem / 2) 0 0;\n  margin: 0;\n}\n.table.b-table.b-table-stacked > tbody > tr > [data-label]::after {\n  display: block;\n  clear: both;\n  content: \"\";\n}\n.table.b-table.b-table-stacked > tbody > tr > [data-label] > div {\n  display: inline-block;\n  width: calc(100% - 40%);\n  padding: 0 0 0 calc(1rem / 2);\n  margin: 0;\n}\n.table.b-table.b-table-stacked > tbody > tr.top-row, .table.b-table.b-table-stacked > tbody > tr.bottom-row {\n  display: none;\n}\n.table.b-table.b-table-stacked > tbody > tr > :first-child {\n  border-top-width: 3px;\n}\n.table.b-table.b-table-stacked > tbody > tr > [rowspan] + td,\n.table.b-table.b-table-stacked > tbody > tr > [rowspan] + th {\n  border-top-width: 3px;\n}\n\n.b-time {\n  min-width: 150px;\n}\n.b-time[aria-disabled=true] output, .b-time[aria-readonly=true] output,\n.b-time output.disabled {\n  background-color: #e9ecef;\n  opacity: 1;\n}\n.b-time[aria-disabled=true] output {\n  pointer-events: none;\n}\n[dir=rtl] .b-time > .d-flex:not(.flex-column) {\n  flex-direction: row-reverse;\n}\n\n.b-time .b-time-header {\n  margin-bottom: 0.5rem;\n}\n.b-time .b-time-header output {\n  padding: 0.25rem;\n  font-size: 80%;\n}\n.b-time .b-time-footer {\n  margin-top: 0.5rem;\n}\n.b-time .b-time-ampm {\n  margin-left: 0.5rem;\n}\n\n.b-toast {\n  display: block;\n  position: relative;\n  max-width: 350px;\n  -webkit-backface-visibility: hidden;\n  backface-visibility: hidden;\n  background-clip: padding-box;\n  z-index: 1;\n  border-radius: 0.25rem;\n}\n.b-toast .toast {\n  background-color: rgba(255, 255, 255, 0.85);\n}\n.b-toast:not(:last-child) {\n  margin-bottom: 0.75rem;\n}\n.b-toast.b-toast-solid .toast {\n  background-color: white;\n}\n.b-toast .toast {\n  opacity: 1;\n}\n.b-toast .toast.fade:not(.show) {\n  opacity: 0;\n}\n.b-toast .toast .toast-body {\n  display: block;\n}\n\n.b-toast-primary .toast {\n  background-color: rgba(230, 242, 255, 0.85);\n  border-color: rgba(184, 218, 255, 0.85);\n  color: #004085;\n}\n.b-toast-primary .toast .toast-header {\n  color: #004085;\n  background-color: rgba(204, 229, 255, 0.85);\n  border-bottom-color: rgba(184, 218, 255, 0.85);\n}\n.b-toast-primary.b-toast-solid .toast {\n  background-color: #e6f2ff;\n}\n\n.b-toast-secondary .toast {\n  background-color: rgba(239, 240, 241, 0.85);\n  border-color: rgba(214, 216, 219, 0.85);\n  color: #383d41;\n}\n.b-toast-secondary .toast .toast-header {\n  color: #383d41;\n  background-color: rgba(226, 227, 229, 0.85);\n  border-bottom-color: rgba(214, 216, 219, 0.85);\n}\n.b-toast-secondary.b-toast-solid .toast {\n  background-color: #eff0f1;\n}\n\n.b-toast-success .toast {\n  background-color: rgba(230, 245, 233, 0.85);\n  border-color: rgba(195, 230, 203, 0.85);\n  color: #155724;\n}\n.b-toast-success .toast .toast-header {\n  color: #155724;\n  background-color: rgba(212, 237, 218, 0.85);\n  border-bottom-color: rgba(195, 230, 203, 0.85);\n}\n.b-toast-success.b-toast-solid .toast {\n  background-color: #e6f5e9;\n}\n\n.b-toast-info .toast {\n  background-color: rgba(229, 244, 247, 0.85);\n  border-color: rgba(190, 229, 235, 0.85);\n  color: #0c5460;\n}\n.b-toast-info .toast .toast-header {\n  color: #0c5460;\n  background-color: rgba(209, 236, 241, 0.85);\n  border-bottom-color: rgba(190, 229, 235, 0.85);\n}\n.b-toast-info.b-toast-solid .toast {\n  background-color: #e5f4f7;\n}\n\n.b-toast-warning .toast {\n  background-color: rgba(255, 249, 231, 0.85);\n  border-color: rgba(255, 238, 186, 0.85);\n  color: #856404;\n}\n.b-toast-warning .toast .toast-header {\n  color: #856404;\n  background-color: rgba(255, 243, 205, 0.85);\n  border-bottom-color: rgba(255, 238, 186, 0.85);\n}\n.b-toast-warning.b-toast-solid .toast {\n  background-color: #fff9e7;\n}\n\n.b-toast-danger .toast {\n  background-color: rgba(252, 237, 238, 0.85);\n  border-color: rgba(245, 198, 203, 0.85);\n  color: #721c24;\n}\n.b-toast-danger .toast .toast-header {\n  color: #721c24;\n  background-color: rgba(248, 215, 218, 0.85);\n  border-bottom-color: rgba(245, 198, 203, 0.85);\n}\n.b-toast-danger.b-toast-solid .toast {\n  background-color: #fcedee;\n}\n\n.b-toast-light .toast {\n  background-color: rgba(255, 255, 255, 0.85);\n  border-color: rgba(253, 253, 254, 0.85);\n  color: #818182;\n}\n.b-toast-light .toast .toast-header {\n  color: #818182;\n  background-color: rgba(254, 254, 254, 0.85);\n  border-bottom-color: rgba(253, 253, 254, 0.85);\n}\n.b-toast-light.b-toast-solid .toast {\n  background-color: white;\n}\n\n.b-toast-dark .toast {\n  background-color: rgba(227, 229, 229, 0.85);\n  border-color: rgba(198, 200, 202, 0.85);\n  color: #1b1e21;\n}\n.b-toast-dark .toast .toast-header {\n  color: #1b1e21;\n  background-color: rgba(214, 216, 217, 0.85);\n  border-bottom-color: rgba(198, 200, 202, 0.85);\n}\n.b-toast-dark.b-toast-solid .toast {\n  background-color: #e3e5e5;\n}\n\n.b-toaster {\n  z-index: 1100;\n}\n.b-toaster .b-toaster-slot {\n  position: relative;\n  display: block;\n}\n.b-toaster .b-toaster-slot:empty {\n  display: none !important;\n}\n\n.b-toaster.b-toaster-top-right, .b-toaster.b-toaster-top-left, .b-toaster.b-toaster-top-center, .b-toaster.b-toaster-top-full, .b-toaster.b-toaster-bottom-right, .b-toaster.b-toaster-bottom-left, .b-toaster.b-toaster-bottom-center, .b-toaster.b-toaster-bottom-full {\n  position: fixed;\n  left: 0.5rem;\n  right: 0.5rem;\n  margin: 0;\n  padding: 0;\n  height: 0;\n  overflow: visible;\n}\n.b-toaster.b-toaster-top-right .b-toaster-slot, .b-toaster.b-toaster-top-left .b-toaster-slot, .b-toaster.b-toaster-top-center .b-toaster-slot, .b-toaster.b-toaster-top-full .b-toaster-slot, .b-toaster.b-toaster-bottom-right .b-toaster-slot, .b-toaster.b-toaster-bottom-left .b-toaster-slot, .b-toaster.b-toaster-bottom-center .b-toaster-slot, .b-toaster.b-toaster-bottom-full .b-toaster-slot {\n  position: absolute;\n  max-width: 350px;\n  width: 100%;\n  /* IE 11 fix */\n  left: 0;\n  right: 0;\n  padding: 0;\n  margin: 0;\n}\n.b-toaster.b-toaster-top-full .b-toaster-slot, .b-toaster.b-toaster-bottom-full .b-toaster-slot {\n  width: 100%;\n  max-width: 100%;\n}\n.b-toaster.b-toaster-top-full .b-toaster-slot .b-toast,\n.b-toaster.b-toaster-top-full .b-toaster-slot .toast, .b-toaster.b-toaster-bottom-full .b-toaster-slot .b-toast,\n.b-toaster.b-toaster-bottom-full .b-toaster-slot .toast {\n  width: 100%;\n  max-width: 100%;\n}\n.b-toaster.b-toaster-top-right, .b-toaster.b-toaster-top-left, .b-toaster.b-toaster-top-center, .b-toaster.b-toaster-top-full {\n  top: 0;\n}\n.b-toaster.b-toaster-top-right .b-toaster-slot, .b-toaster.b-toaster-top-left .b-toaster-slot, .b-toaster.b-toaster-top-center .b-toaster-slot, .b-toaster.b-toaster-top-full .b-toaster-slot {\n  top: 0.5rem;\n}\n.b-toaster.b-toaster-bottom-right, .b-toaster.b-toaster-bottom-left, .b-toaster.b-toaster-bottom-center, .b-toaster.b-toaster-bottom-full {\n  bottom: 0;\n}\n.b-toaster.b-toaster-bottom-right .b-toaster-slot, .b-toaster.b-toaster-bottom-left .b-toaster-slot, .b-toaster.b-toaster-bottom-center .b-toaster-slot, .b-toaster.b-toaster-bottom-full .b-toaster-slot {\n  bottom: 0.5rem;\n}\n.b-toaster.b-toaster-top-right .b-toaster-slot, .b-toaster.b-toaster-bottom-right .b-toaster-slot, .b-toaster.b-toaster-top-center .b-toaster-slot, .b-toaster.b-toaster-bottom-center .b-toaster-slot {\n  margin-left: auto;\n}\n.b-toaster.b-toaster-top-left .b-toaster-slot, .b-toaster.b-toaster-bottom-left .b-toaster-slot, .b-toaster.b-toaster-top-center .b-toaster-slot, .b-toaster.b-toaster-bottom-center .b-toaster-slot {\n  margin-right: auto;\n}\n\n.b-toaster.b-toaster-top-right .b-toast.b-toaster-enter-active, .b-toaster.b-toaster-top-right .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-top-right .b-toast.b-toaster-move, .b-toaster.b-toaster-top-left .b-toast.b-toaster-enter-active, .b-toaster.b-toaster-top-left .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-top-left .b-toast.b-toaster-move, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-enter-active, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-move, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-enter-active, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-move {\n  transition: -webkit-transform 0.175s;\n  transition: transform 0.175s;\n  transition: transform 0.175s, -webkit-transform 0.175s;\n}\n.b-toaster.b-toaster-top-right .b-toast.b-toaster-enter-to .toast.fade, .b-toaster.b-toaster-top-right .b-toast.b-toaster-enter-active .toast.fade, .b-toaster.b-toaster-top-left .b-toast.b-toaster-enter-to .toast.fade, .b-toaster.b-toaster-top-left .b-toast.b-toaster-enter-active .toast.fade, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-enter-to .toast.fade, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-enter-active .toast.fade, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-enter-to .toast.fade, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-enter-active .toast.fade {\n  transition-delay: 0.175s;\n}\n.b-toaster.b-toaster-top-right .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-top-left .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-leave-active, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-leave-active {\n  position: absolute;\n  transition-delay: 0.175s;\n}\n.b-toaster.b-toaster-top-right .b-toast.b-toaster-leave-active .toast.fade, .b-toaster.b-toaster-top-left .b-toast.b-toaster-leave-active .toast.fade, .b-toaster.b-toaster-bottom-right .b-toast.b-toaster-leave-active .toast.fade, .b-toaster.b-toaster-bottom-left .b-toast.b-toaster-leave-active .toast.fade {\n  transition-delay: 0s;\n}\n.tooltip.b-tooltip {\n  display: block;\n  opacity: 1;\n  outline: 0;\n  transition: opacity 0.1s var(--appleEase);\n}\n.tooltip.b-tooltip.fade:not(.show) {\n  opacity: 0;\n}\n.tooltip.b-tooltip.show {\n  opacity: 0.9;\n}\n.tooltip.b-tooltip.noninteractive {\n  pointer-events: none;\n}\n.tooltip.b-tooltip .arrow {\n  margin: 0 0.25rem;\n}\n.tooltip.b-tooltip.bs-tooltip-right .arrow, .tooltip.b-tooltip.b-tooltip-dark.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-light.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-danger.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-warning.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-info.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-success.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-secondary.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.b-tooltip-primary.bs-tooltip-auto[x-placement^=right] .arrow, .tooltip.b-tooltip.bs-tooltip-left .arrow, .tooltip.b-tooltip.b-tooltip-dark.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-light.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-danger.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-warning.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-info.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-success.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-secondary.bs-tooltip-auto[x-placement^=left] .arrow, .tooltip.b-tooltip.b-tooltip-primary.bs-tooltip-auto[x-placement^=left] .arrow {\n  margin: 0.25rem 0;\n}\n\n.tooltip.b-tooltip-primary.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-primary.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #007bff;\n}\n.tooltip.b-tooltip-primary.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-primary.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #007bff;\n}\n.tooltip.b-tooltip-primary.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-primary.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #007bff;\n}\n.tooltip.b-tooltip-primary.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-primary.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #007bff;\n}\n.tooltip.b-tooltip-primary .tooltip-inner {\n  color: #fff;\n  background-color: #007bff;\n}\n\n.tooltip.b-tooltip-secondary.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-secondary.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #6c757d;\n}\n.tooltip.b-tooltip-secondary.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-secondary.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #6c757d;\n}\n.tooltip.b-tooltip-secondary.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-secondary.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #6c757d;\n}\n.tooltip.b-tooltip-secondary.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-secondary.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #6c757d;\n}\n.tooltip.b-tooltip-secondary .tooltip-inner {\n  color: #fff;\n  background-color: #6c757d;\n}\n\n.tooltip.b-tooltip-success.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-success.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #28a745;\n}\n.tooltip.b-tooltip-success.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-success.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #28a745;\n}\n.tooltip.b-tooltip-success.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-success.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #28a745;\n}\n.tooltip.b-tooltip-success.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-success.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #28a745;\n}\n.tooltip.b-tooltip-success .tooltip-inner {\n  color: #fff;\n  background-color: #28a745;\n}\n\n.tooltip.b-tooltip-info.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-info.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #17a2b8;\n}\n.tooltip.b-tooltip-info.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-info.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #17a2b8;\n}\n.tooltip.b-tooltip-info.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-info.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #17a2b8;\n}\n.tooltip.b-tooltip-info.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-info.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #17a2b8;\n}\n.tooltip.b-tooltip-info .tooltip-inner {\n  color: #fff;\n  background-color: #17a2b8;\n}\n\n.tooltip.b-tooltip-warning.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-warning.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #ffc107;\n}\n.tooltip.b-tooltip-warning.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-warning.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #ffc107;\n}\n.tooltip.b-tooltip-warning.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-warning.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #ffc107;\n}\n.tooltip.b-tooltip-warning.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-warning.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #ffc107;\n}\n.tooltip.b-tooltip-warning .tooltip-inner {\n  color: #212529;\n  background-color: #ffc107;\n}\n\n.tooltip.b-tooltip-danger.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-danger.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #dc3545;\n}\n.tooltip.b-tooltip-danger.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-danger.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #dc3545;\n}\n.tooltip.b-tooltip-danger.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-danger.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #dc3545;\n}\n.tooltip.b-tooltip-danger.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-danger.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #dc3545;\n}\n.tooltip.b-tooltip-danger .tooltip-inner {\n  color: #fff;\n  background-color: #dc3545;\n}\n\n.tooltip.b-tooltip-light.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-light.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #f8f9fa;\n}\n.tooltip.b-tooltip-light.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-light.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #f8f9fa;\n}\n.tooltip.b-tooltip-light.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-light.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #f8f9fa;\n}\n.tooltip.b-tooltip-light.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-light.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #f8f9fa;\n}\n.tooltip.b-tooltip-light .tooltip-inner {\n  color: #212529;\n  background-color: #f8f9fa;\n}\n\n.tooltip.b-tooltip-dark.bs-tooltip-top .arrow::before, .tooltip.b-tooltip-dark.bs-tooltip-auto[x-placement^=top] .arrow::before {\n  border-top-color: #343a40;\n}\n.tooltip.b-tooltip-dark.bs-tooltip-right .arrow::before, .tooltip.b-tooltip-dark.bs-tooltip-auto[x-placement^=right] .arrow::before {\n  border-right-color: #343a40;\n}\n.tooltip.b-tooltip-dark.bs-tooltip-bottom .arrow::before, .tooltip.b-tooltip-dark.bs-tooltip-auto[x-placement^=bottom] .arrow::before {\n  border-bottom-color: #343a40;\n}\n.tooltip.b-tooltip-dark.bs-tooltip-left .arrow::before, .tooltip.b-tooltip-dark.bs-tooltip-auto[x-placement^=left] .arrow::before {\n  border-left-color: #343a40;\n}\n.tooltip.b-tooltip-dark .tooltip-inner {\n  color: #fff;\n  background-color: #343a40;\n}\n\n.b-icon.bi {\n  display: inline-block;\n  overflow: visible;\n  vertical-align: -0.15em;\n}\n.b-icon.b-icon-animation-cylon, .b-icon.b-iconstack .b-icon-animation-cylon > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  -webkit-animation: 0.75s infinite ease-in-out alternate b-icon-animation-cylon;\n  animation: 0.75s infinite ease-in-out alternate b-icon-animation-cylon;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-cylon, .b-icon.b-iconstack .b-icon-animation-cylon > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-cylon-vertical, .b-icon.b-iconstack .b-icon-animation-cylon-vertical > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  -webkit-animation: 0.75s infinite ease-in-out alternate b-icon-animation-cylon-vertical;\n  animation: 0.75s infinite ease-in-out alternate b-icon-animation-cylon-vertical;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-cylon-vertical, .b-icon.b-iconstack .b-icon-animation-cylon-vertical > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-fade, .b-icon.b-iconstack .b-icon-animation-fade > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  -webkit-animation: 0.75s infinite ease-in-out alternate b-icon-animation-fade;\n  animation: 0.75s infinite ease-in-out alternate b-icon-animation-fade;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-fade, .b-icon.b-iconstack .b-icon-animation-fade > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-spin, .b-icon.b-iconstack .b-icon-animation-spin > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  -webkit-animation: 2s infinite linear normal b-icon-animation-spin;\n  animation: 2s infinite linear normal b-icon-animation-spin;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-spin, .b-icon.b-iconstack .b-icon-animation-spin > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-spin-reverse, .b-icon.b-iconstack .b-icon-animation-spin-reverse > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  animation: 2s infinite linear reverse b-icon-animation-spin;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-spin-reverse, .b-icon.b-iconstack .b-icon-animation-spin-reverse > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-spin-pulse, .b-icon.b-iconstack .b-icon-animation-spin-pulse > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  -webkit-animation: 1s infinite steps(8) normal b-icon-animation-spin;\n  animation: 1s infinite steps(8) normal b-icon-animation-spin;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-spin-pulse, .b-icon.b-iconstack .b-icon-animation-spin-pulse > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-spin-reverse-pulse, .b-icon.b-iconstack .b-icon-animation-spin-reverse-pulse > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  animation: 1s infinite steps(8) reverse b-icon-animation-spin;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-spin-reverse-pulse, .b-icon.b-iconstack .b-icon-animation-spin-reverse-pulse > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n.b-icon.b-icon-animation-throb, .b-icon.b-iconstack .b-icon-animation-throb > g {\n  -webkit-transform-origin: center;\n  transform-origin: center;\n  -webkit-animation: 0.75s infinite ease-in-out alternate b-icon-animation-throb;\n  animation: 0.75s infinite ease-in-out alternate b-icon-animation-throb;\n}\n@media (prefers-reduced-motion: reduce) {\n  .b-icon.b-icon-animation-throb, .b-icon.b-iconstack .b-icon-animation-throb > g {\n    -webkit-animation: none;\n    animation: none;\n  }\n}\n\n@-webkit-keyframes b-icon-animation-cylon {\n  0% {\n    -webkit-transform: translateX(-25%);\n    transform: translateX(-25%);\n  }\n  100% {\n    -webkit-transform: translateX(25%);\n    transform: translateX(25%);\n  }\n}\n\n@keyframes b-icon-animation-cylon {\n  0% {\n    -webkit-transform: translateX(-25%);\n    transform: translateX(-25%);\n  }\n  100% {\n    -webkit-transform: translateX(25%);\n    transform: translateX(25%);\n  }\n}\n@-webkit-keyframes b-icon-animation-cylon-vertical {\n  0% {\n    -webkit-transform: translateY(25%);\n    transform: translateY(25%);\n  }\n  100% {\n    -webkit-transform: translateY(-25%);\n    transform: translateY(-25%);\n  }\n}\n@keyframes b-icon-animation-cylon-vertical {\n  0% {\n    -webkit-transform: translateY(25%);\n    transform: translateY(25%);\n  }\n  100% {\n    -webkit-transform: translateY(-25%);\n    transform: translateY(-25%);\n  }\n}\n@-webkit-keyframes b-icon-animation-fade {\n  0% {\n    opacity: 0.1;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n@keyframes b-icon-animation-fade {\n  0% {\n    opacity: 0.1;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n@-webkit-keyframes b-icon-animation-spin {\n  0% {\n    -webkit-transform: rotate(0deg);\n    transform: rotate(0deg);\n  }\n  100% {\n    -webkit-transform: rotate(359deg);\n    transform: rotate(359deg);\n  }\n}\n@keyframes b-icon-animation-spin {\n  0% {\n    -webkit-transform: rotate(0deg);\n    transform: rotate(0deg);\n  }\n  100% {\n    -webkit-transform: rotate(359deg);\n    transform: rotate(359deg);\n  }\n}\n@-webkit-keyframes b-icon-animation-throb {\n  0% {\n    opacity: 0.5;\n    -webkit-transform: scale(0.5);\n    transform: scale(0.5);\n  }\n  100% {\n    opacity: 1;\n    -webkit-transform: scale(1);\n    transform: scale(1);\n  }\n}\n@keyframes b-icon-animation-throb {\n  0% {\n    opacity: 0.5;\n    -webkit-transform: scale(0.5);\n    transform: scale(0.5);\n  }\n  100% {\n    opacity: 1;\n    -webkit-transform: scale(1);\n    transform: scale(1);\n  }\n}\n.btn .b-icon.bi,\n.nav-link .b-icon.bi,\n.dropdown-toggle .b-icon.bi,\n.dropdown-item .b-icon.bi,\n.input-group-text .b-icon.bi {\n  font-size: 125%;\n  vertical-align: text-bottom;\n}\n\n/*# sourceMappingURL=bootstrap-vue.css.map */"
  },
  {
    "path": "src/renderer/less/bootstrap.less",
    "content": "// Dropdown\n\n.dropup,\n.dropend,\n.dropdown,\n.dropstart {\n  position: relative;\n}\n\n.dropdown-toggle {\n  white-space: nowrap;\n}\n.dropdown-toggle::after {\n  display: inline-block;\n  margin-left: 0.255em;\n  vertical-align: 0.255em;\n  content: \"\";\n  border-top: 0.3em solid;\n  border-right: 0.3em solid transparent;\n  border-bottom: 0;\n  border-left: 0.3em solid transparent;\n}\n.dropdown-toggle:empty::after {\n  margin-left: 0;\n}\n\n.dropdown-menu {\n  position: absolute;\n  z-index: 1000;\n  display: none;\n  min-width: 10rem;\n  padding: 0.5rem 0;\n  margin: 0;\n  font-size: 1rem;\n  color: #212529;\n  text-align: left;\n  list-style: none;\n  background-color: var(--color1);\n  background-clip: padding-box;\n  border: 1px solid rgba(0, 0, 0, 0.15);\n  border-radius: 0.25rem;\n  box-shadow: var(--mediaItemShadow), var(--mediaItemShadow-ShadowSubtle);\n  backdrop-filter: var(--glassFilter);\n}\n.dropdown-menu[data-bs-popper] {\n  top: 100%;\n  left: 0;\n  margin-top: 0.125rem;\n}\n\n.dropdown-menu-start {\n  --bs-position: start;\n}\n.dropdown-menu-start[data-bs-popper] {\n  right: auto;\n  left: 0;\n}\n\n.dropdown-menu-end {\n  --bs-position: end;\n}\n.dropdown-menu-end[data-bs-popper] {\n  right: 0;\n  left: auto;\n}\n\n@media (min-width: 576px) {\n  .dropdown-menu-sm-start {\n    --bs-position: start;\n  }\n  .dropdown-menu-sm-start[data-bs-popper] {\n    right: auto;\n    left: 0;\n  }\n\n  .dropdown-menu-sm-end {\n    --bs-position: end;\n  }\n  .dropdown-menu-sm-end[data-bs-popper] {\n    right: 0;\n    left: auto;\n  }\n}\n@media (min-width: 768px) {\n  .dropdown-menu-md-start {\n    --bs-position: start;\n  }\n  .dropdown-menu-md-start[data-bs-popper] {\n    right: auto;\n    left: 0;\n  }\n\n  .dropdown-menu-md-end {\n    --bs-position: end;\n  }\n  .dropdown-menu-md-end[data-bs-popper] {\n    right: 0;\n    left: auto;\n  }\n}\n@media (min-width: 992px) {\n  .dropdown-menu-lg-start {\n    --bs-position: start;\n  }\n  .dropdown-menu-lg-start[data-bs-popper] {\n    right: auto;\n    left: 0;\n  }\n\n  .dropdown-menu-lg-end {\n    --bs-position: end;\n  }\n  .dropdown-menu-lg-end[data-bs-popper] {\n    right: 0;\n    left: auto;\n  }\n}\n@media (min-width: 1200px) {\n  .dropdown-menu-xl-start {\n    --bs-position: start;\n  }\n  .dropdown-menu-xl-start[data-bs-popper] {\n    right: auto;\n    left: 0;\n  }\n\n  .dropdown-menu-xl-end {\n    --bs-position: end;\n  }\n  .dropdown-menu-xl-end[data-bs-popper] {\n    right: 0;\n    left: auto;\n  }\n}\n@media (min-width: 1400px) {\n  .dropdown-menu-xxl-start {\n    --bs-position: start;\n  }\n  .dropdown-menu-xxl-start[data-bs-popper] {\n    right: auto;\n    left: 0;\n  }\n\n  .dropdown-menu-xxl-end {\n    --bs-position: end;\n  }\n  .dropdown-menu-xxl-end[data-bs-popper] {\n    right: 0;\n    left: auto;\n  }\n}\n.dropup .dropdown-menu[data-bs-popper] {\n  top: auto;\n  bottom: 100%;\n  margin-top: 0;\n  margin-bottom: 0.125rem;\n}\n.dropup .dropdown-toggle::after {\n  display: inline-block;\n  margin-left: 0.255em;\n  vertical-align: 0.255em;\n  content: \"\";\n  border-top: 0;\n  border-right: 0.3em solid transparent;\n  border-bottom: 0.3em solid;\n  border-left: 0.3em solid transparent;\n}\n.dropup .dropdown-toggle:empty::after {\n  margin-left: 0;\n}\n\n.dropend .dropdown-menu[data-bs-popper] {\n  top: 0;\n  right: auto;\n  left: 100%;\n  margin-top: 0;\n  margin-left: 0.125rem;\n}\n.dropend .dropdown-toggle::after {\n  display: inline-block;\n  margin-left: 0.255em;\n  vertical-align: 0.255em;\n  content: \"\";\n  border-top: 0.3em solid transparent;\n  border-right: 0;\n  border-bottom: 0.3em solid transparent;\n  border-left: 0.3em solid;\n}\n.dropend .dropdown-toggle:empty::after {\n  margin-left: 0;\n}\n.dropend .dropdown-toggle::after {\n  vertical-align: 0;\n}\n\n.dropstart .dropdown-menu[data-bs-popper] {\n  top: 0;\n  right: 100%;\n  left: auto;\n  margin-top: 0;\n  margin-right: 0.125rem;\n}\n.dropstart .dropdown-toggle::after {\n  display: inline-block;\n  margin-left: 0.255em;\n  vertical-align: 0.255em;\n  content: \"\";\n}\n.dropstart .dropdown-toggle::after {\n  display: none;\n}\n.dropstart .dropdown-toggle::before {\n  display: inline-block;\n  margin-right: 0.255em;\n  vertical-align: 0.255em;\n  content: \"\";\n  border-top: 0.3em solid transparent;\n  border-right: 0.3em solid;\n  border-bottom: 0.3em solid transparent;\n}\n.dropstart .dropdown-toggle:empty::after {\n  margin-left: 0;\n}\n.dropstart .dropdown-toggle::before {\n  vertical-align: 0;\n}\n\n.dropdown-divider {\n  height: 0;\n  margin: 0.5rem 0;\n  overflow: hidden;\n  border-top: 1px solid rgba(0, 0, 0, 0.15);\n}\n\n.dropdown-item {\n  display: block;\n  width: 100%;\n  padding: 0.25rem 1rem;\n  clear: both;\n  font-weight: 400;\n  color: #212529;\n  text-align: inherit;\n  text-decoration: none;\n  white-space: nowrap;\n  background-color: transparent;\n  border: 0;\n}\n.dropdown-item:hover,\n.dropdown-item:focus {\n  color: #1e2125;\n  background-color: #e9ecef;\n}\n.dropdown-item.active,\n.dropdown-item:active {\n  color: #fff;\n  text-decoration: none;\n  background-color: #0d6efd;\n}\n.dropdown-item.disabled,\n.dropdown-item:disabled {\n  color: #adb5bd;\n  pointer-events: none;\n  background-color: transparent;\n}\n\n.dropdown-menu.show {\n  display: block;\n}\n\n.dropdown-header {\n  display: block;\n  padding: 0.5rem 1rem;\n  margin-bottom: 0;\n  font-size: 0.875rem;\n  color: #6c757d;\n  white-space: nowrap;\n}\n\n.dropdown-item-text {\n  display: block;\n  padding: 0.25rem 1rem;\n  color: #212529;\n}\n\n.dropdown-menu-dark {\n  color: #dee2e6;\n  background-color: #343a40;\n  border-color: rgba(0, 0, 0, 0.15);\n}\n.dropdown-menu-dark .dropdown-item {\n  color: #dee2e6;\n}\n.dropdown-menu-dark .dropdown-item:hover,\n.dropdown-menu-dark .dropdown-item:focus {\n  color: #fff;\n  background-color: rgba(255, 255, 255, 0.15);\n}\n.dropdown-menu-dark .dropdown-item.active,\n.dropdown-menu-dark .dropdown-item:active {\n  color: #fff;\n  background-color: #0d6efd;\n}\n.dropdown-menu-dark .dropdown-item.disabled,\n.dropdown-menu-dark .dropdown-item:disabled {\n  color: #adb5bd;\n}\n.dropdown-menu-dark .dropdown-divider {\n  border-color: rgba(0, 0, 0, 0.15);\n}\n.dropdown-menu-dark .dropdown-item-text {\n  color: #dee2e6;\n}\n.dropdown-menu-dark .dropdown-header {\n  color: #adb5bd;\n}\n\n// List Group\n.list-group {\n  display: flex;\n  flex-direction: column;\n  padding-left: 0;\n  margin-bottom: 0;\n  border-radius: 0.25rem;\n}\n\n.list-group-numbered {\n  list-style-type: none;\n  counter-reset: section;\n}\n\n.list-group-numbered > li::before {\n  content: counters(section, \".\") \". \";\n  counter-increment: section;\n}\n\n.list-group-item-action {\n  width: 100%;\n  color: #495057;\n  text-align: inherit;\n}\n\n.list-group-item-action:hover,\n.list-group-item-action:focus {\n  z-index: 1;\n  color: #495057;\n  text-decoration: none;\n  background-color: #f8f9fa;\n}\n\n.list-group-item-action:active {\n  color: #212529;\n  background-color: #e9ecef;\n}\n\n.list-group-item {\n  position: relative;\n  display: block;\n  padding: 0.5rem 1rem;\n  color: #212529;\n  text-decoration: none;\n  background-color: #fff;\n  border: 1px solid rgba(0, 0, 0, 0.125);\n}\n\n.list-group-item:first-child {\n  border-top-left-radius: inherit;\n  border-top-right-radius: inherit;\n}\n\n.list-group-item:last-child {\n  border-bottom-right-radius: inherit;\n  border-bottom-left-radius: inherit;\n}\n\n.list-group-item.disabled,\n.list-group-item:disabled {\n  color: #6c757d;\n  pointer-events: none;\n  background-color: #fff;\n}\n\n.list-group-item.active {\n  z-index: 2;\n  color: #fff;\n  background-color: #0d6efd;\n  border-color: #0d6efd;\n}\n\n.list-group-item + .list-group-item {\n  border-top-width: 0;\n}\n\n.list-group-item + .list-group-item.active {\n  margin-top: -1px;\n  border-top-width: 1px;\n}\n\n.list-group-horizontal {\n  flex-direction: row;\n}\n\n.list-group-horizontal > .list-group-item:first-child {\n  border-bottom-left-radius: 0.25rem;\n  border-top-right-radius: 0;\n}\n\n.list-group-horizontal > .list-group-item:last-child {\n  border-top-right-radius: 0.25rem;\n  border-bottom-left-radius: 0;\n}\n\n.list-group-horizontal > .list-group-item.active {\n  margin-top: 0;\n}\n\n.list-group-horizontal > .list-group-item + .list-group-item {\n  border-top-width: 1px;\n  border-left-width: 0;\n}\n\n.list-group-horizontal > .list-group-item + .list-group-item.active {\n  margin-left: -1px;\n  border-left-width: 1px;\n}\n\n@media (min-width: 576px) {\n  .list-group-horizontal-sm {\n    flex-direction: row;\n  }\n\n  .list-group-horizontal-sm > .list-group-item:first-child {\n    border-bottom-left-radius: 0.25rem;\n    border-top-right-radius: 0;\n  }\n\n  .list-group-horizontal-sm > .list-group-item:last-child {\n    border-top-right-radius: 0.25rem;\n    border-bottom-left-radius: 0;\n  }\n\n  .list-group-horizontal-sm > .list-group-item.active {\n    margin-top: 0;\n  }\n\n  .list-group-horizontal-sm > .list-group-item + .list-group-item {\n    border-top-width: 1px;\n    border-left-width: 0;\n  }\n\n  .list-group-horizontal-sm > .list-group-item + .list-group-item.active {\n    margin-left: -1px;\n    border-left-width: 1px;\n  }\n}\n\n@media (min-width: 768px) {\n  .list-group-horizontal-md {\n    flex-direction: row;\n  }\n\n  .list-group-horizontal-md > .list-group-item:first-child {\n    border-bottom-left-radius: 0.25rem;\n    border-top-right-radius: 0;\n  }\n\n  .list-group-horizontal-md > .list-group-item:last-child {\n    border-top-right-radius: 0.25rem;\n    border-bottom-left-radius: 0;\n  }\n\n  .list-group-horizontal-md > .list-group-item.active {\n    margin-top: 0;\n  }\n\n  .list-group-horizontal-md > .list-group-item + .list-group-item {\n    border-top-width: 1px;\n    border-left-width: 0;\n  }\n\n  .list-group-horizontal-md > .list-group-item + .list-group-item.active {\n    margin-left: -1px;\n    border-left-width: 1px;\n  }\n}\n\n@media (min-width: 992px) {\n  .list-group-horizontal-lg {\n    flex-direction: row;\n  }\n\n  .list-group-horizontal-lg > .list-group-item:first-child {\n    border-bottom-left-radius: 0.25rem;\n    border-top-right-radius: 0;\n  }\n\n  .list-group-horizontal-lg > .list-group-item:last-child {\n    border-top-right-radius: 0.25rem;\n    border-bottom-left-radius: 0;\n  }\n\n  .list-group-horizontal-lg > .list-group-item.active {\n    margin-top: 0;\n  }\n\n  .list-group-horizontal-lg > .list-group-item + .list-group-item {\n    border-top-width: 1px;\n    border-left-width: 0;\n  }\n\n  .list-group-horizontal-lg > .list-group-item + .list-group-item.active {\n    margin-left: -1px;\n    border-left-width: 1px;\n  }\n}\n\n@media (min-width: 1200px) {\n  .list-group-horizontal-xl {\n    flex-direction: row;\n  }\n\n  .list-group-horizontal-xl > .list-group-item:first-child {\n    border-bottom-left-radius: 0.25rem;\n    border-top-right-radius: 0;\n  }\n\n  .list-group-horizontal-xl > .list-group-item:last-child {\n    border-top-right-radius: 0.25rem;\n    border-bottom-left-radius: 0;\n  }\n\n  .list-group-horizontal-xl > .list-group-item.active {\n    margin-top: 0;\n  }\n\n  .list-group-horizontal-xl > .list-group-item + .list-group-item {\n    border-top-width: 1px;\n    border-left-width: 0;\n  }\n\n  .list-group-horizontal-xl > .list-group-item + .list-group-item.active {\n    margin-left: -1px;\n    border-left-width: 1px;\n  }\n}\n\n@media (min-width: 1400px) {\n  .list-group-horizontal-xxl {\n    flex-direction: row;\n  }\n\n  .list-group-horizontal-xxl > .list-group-item:first-child {\n    border-bottom-left-radius: 0.25rem;\n    border-top-right-radius: 0;\n  }\n\n  .list-group-horizontal-xxl > .list-group-item:last-child {\n    border-top-right-radius: 0.25rem;\n    border-bottom-left-radius: 0;\n  }\n\n  .list-group-horizontal-xxl > .list-group-item.active {\n    margin-top: 0;\n  }\n\n  .list-group-horizontal-xxl > .list-group-item + .list-group-item {\n    border-top-width: 1px;\n    border-left-width: 0;\n  }\n\n  .list-group-horizontal-xxl > .list-group-item + .list-group-item.active {\n    margin-left: -1px;\n    border-left-width: 1px;\n  }\n}\n\n.list-group-flush {\n  border-radius: 0;\n}\n\n.list-group-flush > .list-group-item {\n  border-width: 0 0 1px;\n}\n\n.list-group-flush > .list-group-item:last-child {\n  border-bottom-width: 0;\n}\n\n.list-group-item-primary {\n  color: #084298;\n  background-color: #cfe2ff;\n}\n\n.list-group-item-primary.list-group-item-action:hover,\n.list-group-item-primary.list-group-item-action:focus {\n  color: #084298;\n  background-color: #bacbe6;\n}\n\n.list-group-item-primary.list-group-item-action.active {\n  color: #fff;\n  background-color: #084298;\n  border-color: #084298;\n}\n\n.list-group-item-secondary {\n  color: #41464b;\n  background-color: #e2e3e5;\n}\n\n.list-group-item-secondary.list-group-item-action:hover,\n.list-group-item-secondary.list-group-item-action:focus {\n  color: #41464b;\n  background-color: #cbccce;\n}\n\n.list-group-item-secondary.list-group-item-action.active {\n  color: #fff;\n  background-color: #41464b;\n  border-color: #41464b;\n}\n\n.list-group-item-success {\n  color: #0f5132;\n  background-color: #d1e7dd;\n}\n\n.list-group-item-success.list-group-item-action:hover,\n.list-group-item-success.list-group-item-action:focus {\n  color: #0f5132;\n  background-color: #bcd0c7;\n}\n\n.list-group-item-success.list-group-item-action.active {\n  color: #fff;\n  background-color: #0f5132;\n  border-color: #0f5132;\n}\n\n.list-group-item-info {\n  color: #055160;\n  background-color: #cff4fc;\n}\n\n.list-group-item-info.list-group-item-action:hover,\n.list-group-item-info.list-group-item-action:focus {\n  color: #055160;\n  background-color: #badce3;\n}\n\n.list-group-item-info.list-group-item-action.active {\n  color: #fff;\n  background-color: #055160;\n  border-color: #055160;\n}\n\n.list-group-item-warning {\n  color: #664d03;\n  background-color: #fff3cd;\n}\n\n.list-group-item-warning.list-group-item-action:hover,\n.list-group-item-warning.list-group-item-action:focus {\n  color: #664d03;\n  background-color: #e6dbb9;\n}\n\n.list-group-item-warning.list-group-item-action.active {\n  color: #fff;\n  background-color: #664d03;\n  border-color: #664d03;\n}\n\n.list-group-item-danger {\n  color: #842029;\n  background-color: #f8d7da;\n}\n\n.list-group-item-danger.list-group-item-action:hover,\n.list-group-item-danger.list-group-item-action:focus {\n  color: #842029;\n  background-color: #dfc2c4;\n}\n\n.list-group-item-danger.list-group-item-action.active {\n  color: #fff;\n  background-color: #842029;\n  border-color: #842029;\n}\n\n.list-group-item-light {\n  color: #636464;\n  background-color: #fefefe;\n}\n\n.list-group-item-light.list-group-item-action:hover,\n.list-group-item-light.list-group-item-action:focus {\n  color: #636464;\n  background-color: #e5e5e5;\n}\n\n.list-group-item-light.list-group-item-action.active {\n  color: #fff;\n  background-color: #636464;\n  border-color: #636464;\n}\n\n.list-group-item-dark {\n  color: var(--textColor);\n  background-color: #333;\n}\n\n.list-group-item-dark.list-group-item-action:hover,\n.list-group-item-dark.list-group-item-action:focus {\n  color: #141619;\n  background-color: #bebebf;\n}\n\n.list-group-item-dark.list-group-item-action.active {\n  color: #fff;\n  background-color: #141619;\n  border-color: #141619;\n}\n\n// Toasts\n\n.toast {\n  width: 350px;\n  max-width: 100%;\n  font-size: 0.875rem;\n  pointer-events: auto;\n  background-color: rgba(255, 255, 255, 0.85);\n  background-clip: padding-box;\n  border: 1px solid rgba(0, 0, 0, 0.1);\n  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);\n  border-radius: 0.25rem;\n}\n.toast.showing {\n  opacity: 0;\n}\n.toast:not(.show) {\n  display: none;\n}\n\n.toast-container {\n  width: -webkit-max-content;\n  width: -moz-max-content;\n  width: max-content;\n  max-width: 100%;\n  pointer-events: none;\n}\n.toast-container > :not(:last-child) {\n  margin-bottom: 0.75rem;\n}\n\n.toast-header {\n  display: flex;\n  align-items: center;\n  padding: 0.5rem 0.75rem;\n  color: #6c757d;\n  background-color: rgba(255, 255, 255, 0.85);\n  background-clip: padding-box;\n  border-bottom: 1px solid rgba(0, 0, 0, 0.05);\n  border-top-left-radius: calc(0.25rem - 1px);\n  border-top-right-radius: calc(0.25rem - 1px);\n}\n.toast-header .btn-close {\n  margin-right: -0.375rem;\n  margin-left: 0.75rem;\n}\n\n.toast-body {\n  padding: 0.75rem;\n  word-wrap: break-word;\n}\n\n// Card\n.card {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  min-width: 0;\n  word-wrap: break-word;\n  background-color: #333;\n  background-clip: border-box;\n  border: 1px solid rgba(0, 0, 0, 0.125);\n  border-radius: 0.25rem;\n}\n\n.card > hr {\n  margin-right: 0;\n  margin-left: 0;\n}\n\n.card > .list-group {\n  border-top: inherit;\n  border-bottom: inherit;\n}\n\n.card > .list-group:first-child {\n  border-top-width: 0;\n  border-top-left-radius: calc(0.25rem - 1px);\n  border-top-right-radius: calc(0.25rem - 1px);\n}\n\n.card > .list-group:last-child {\n  border-bottom-width: 0;\n  border-bottom-right-radius: calc(0.25rem - 1px);\n  border-bottom-left-radius: calc(0.25rem - 1px);\n}\n\n.card > .card-header + .list-group,\n.card > .list-group + .card-footer {\n  border-top: 0;\n}\n\n.card-body {\n  flex: 1 1 auto;\n  padding: 1rem 1rem;\n}\n\n.card-title {\n  margin-bottom: 0.5rem;\n}\n\n.card-subtitle {\n  margin-top: -0.25rem;\n  margin-bottom: 0;\n}\n\n.card-text:last-child {\n  margin-bottom: 0;\n}\n\n.card-link + .card-link {\n  margin-left: 1rem;\n}\n\n.card-header {\n  padding: 0.5rem 1rem;\n  margin-bottom: 0;\n  background-color: rgba(0, 0, 0, 0.03);\n  border-bottom: 1px solid rgba(0, 0, 0, 0.125);\n}\n\n.card-header:first-child {\n  border-radius: calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0;\n}\n\n.card-footer {\n  padding: 0.5rem 1rem;\n  background-color: rgba(0, 0, 0, 0.03);\n  border-top: 1px solid rgba(0, 0, 0, 0.125);\n  text-align: center;\n}\n\n.card-footer:last-child {\n  border-radius: 0 0 calc(0.25rem - 1px) calc(0.25rem - 1px);\n}\n\n.card-header-tabs {\n  margin-right: -0.5rem;\n  margin-bottom: -0.5rem;\n  margin-left: -0.5rem;\n  border-bottom: 0;\n}\n\n.card-header-pills {\n  margin-right: -0.5rem;\n  margin-left: -0.5rem;\n}\n\n.card-img-overlay {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  padding: 1rem;\n  border-radius: calc(0.25rem - 1px);\n}\n\n.card-img,\n.card-img-top,\n.card-img-bottom {\n  width: 100%;\n}\n\n.card-img,\n.card-img-top {\n  border-top-left-radius: calc(0.25rem - 1px);\n  border-top-right-radius: calc(0.25rem - 1px);\n}\n\n.card-img,\n.card-img-bottom {\n  border-bottom-right-radius: calc(0.25rem - 1px);\n  border-bottom-left-radius: calc(0.25rem - 1px);\n}\n\n.card-group > .card {\n  margin-bottom: 0.75rem;\n}\n\n@media (min-width: 576px) {\n  .card-group {\n    display: flex;\n    flex-flow: row wrap;\n  }\n\n  .card-group > .card {\n    flex: 1 0 0%;\n    margin-bottom: 0;\n  }\n\n  .card-group > .card + .card {\n    margin-left: 0;\n    border-left: 0;\n  }\n\n  .card-group > .card:not(:last-child) {\n    border-top-right-radius: 0;\n    border-bottom-right-radius: 0;\n  }\n\n  .card-group > .card:not(:last-child) .card-img-top,\n  .card-group > .card:not(:last-child) .card-header {\n    border-top-right-radius: 0;\n  }\n\n  .card-group > .card:not(:last-child) .card-img-bottom,\n  .card-group > .card:not(:last-child) .card-footer {\n    border-bottom-right-radius: 0;\n  }\n\n  .card-group > .card:not(:first-child) {\n    border-top-left-radius: 0;\n    border-bottom-left-radius: 0;\n  }\n\n  .card-group > .card:not(:first-child) .card-img-top,\n  .card-group > .card:not(:first-child) .card-header {\n    border-top-left-radius: 0;\n  }\n\n  .card-group > .card:not(:first-child) .card-img-bottom,\n  .card-group > .card:not(:first-child) .card-footer {\n    border-bottom-left-radius: 0;\n  }\n}\n\n.modal {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1055;\n  display: none;\n  width: 100%;\n  height: 100%;\n  overflow-x: hidden;\n  overflow-y: auto;\n  outline: 0;\n  user-select: none;\n\n  .close {\n    width: 50px;\n    height: 42px;\n    background-image: var(--gfx-closeBtn);\n    background-position: center;\n    background-repeat: no-repeat;\n    -webkit-app-region: no-drag;\n    appearance: none;\n    border: 0;\n    background-color: transparent;\n    position: absolute;\n    top: 0;\n    right: 0;\n\n    &:hover {\n      background-color: rgb(196, 43, 28);\n    }\n  }\n}\n\n.modal-dialog {\n  position: relative;\n  width: auto;\n  margin: 0.5rem;\n  pointer-events: none;\n  color: var(--textColor);\n}\n\n.modal.fade .modal-dialog {\n  transition:\n    transform 0.1s var(--appleEase),\n    opacity 0.1s var(--appleEase);\n  transform: scale(0.9);\n  opacity: 0;\n}\n\n.fade {\n  transition: opacity 0.15s var(--appleEase);\n}\n@media (prefers-reduced-motion: reduce) {\n  .fade {\n    transition: none;\n  }\n}\n.fade:not(.show) {\n  opacity: 0;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .modal.fade .modal-dialog {\n    transition: none;\n  }\n}\n\n.modal.show .modal-dialog {\n  transform: none;\n  opacity: 1;\n}\n\n.modal.modal-static .modal-dialog {\n  transform: scale(1.02);\n}\n\n.modal-dialog-scrollable {\n  height: calc(100% - 1rem);\n}\n\n.modal-dialog-scrollable .modal-content {\n  max-height: 100%;\n  overflow: hidden;\n}\n\n.modal-dialog-scrollable .modal-body {\n  overflow-y: auto;\n}\n\n.modal-dialog-centered {\n  display: flex;\n  align-items: center;\n  min-height: calc(100% - 1rem);\n}\n\n.modal-content {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  width: 100%;\n  pointer-events: auto;\n  background-color: var(--modalBackground);\n  background-clip: padding-box;\n  border: 1px solid rgba(0, 0, 0, 0.2);\n  border-radius: var(--panelRadius);\n  outline: 0;\n  box-shadow: var(--ciderShadow-Generic);\n  overflow: hidden;\n}\n\n.modal-backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1050;\n  width: 100vw;\n  height: 100vh;\n  background-color: #000;\n}\n\n.modal-backdrop.fade {\n  opacity: 0;\n}\n\n.modal-backdrop.show {\n  opacity: 0.5;\n}\n\n.modal-header {\n  display: flex;\n  flex-shrink: 0;\n  align-items: center;\n  justify-content: space-between;\n  padding: 1rem 1rem;\n  border-top-left-radius: calc(0.3rem - 1px);\n  border-top-right-radius: calc(0.3rem - 1px);\n}\n\n.modal-header .btn-close {\n  padding: 0.5rem 0.5rem;\n  margin: -0.5rem -0.5rem -0.5rem auto;\n}\n\n.modal-title {\n  line-height: 1.5;\n  margin: 0;\n  font-size: 1em;\n}\n\n.modal-body {\n  position: relative;\n  flex: 1 1 auto;\n  padding: 3rem 1rem 1rem 1rem;\n  //font-size: 0.9em\n}\n\n.modal-footer {\n  display: flex;\n  flex-wrap: wrap;\n  flex-shrink: 0;\n  align-items: center;\n  justify-content: flex-end;\n  padding: 0.75rem;\n  border-bottom-right-radius: calc(0.3rem - 1px);\n  border-bottom-left-radius: calc(0.3rem - 1px);\n}\n\n.modal-footer > * {\n  margin: 0.25rem;\n}\n\n@media (min-width: 576px) {\n  .modal-dialog {\n    max-width: 500px;\n    margin: 1.75rem auto;\n  }\n\n  .modal-dialog-scrollable {\n    height: calc(100% - 3.5rem);\n  }\n\n  .modal-dialog-centered {\n    min-height: calc(100% - 3.5rem);\n  }\n\n  .modal-sm {\n    max-width: 300px;\n  }\n}\n\n@media (min-width: 992px) {\n  .modal-lg,\n  .modal-xl {\n    max-width: 800px;\n  }\n}\n\n@media (min-width: 1200px) {\n  .modal-xl {\n    max-width: 1140px;\n  }\n}\n\n.modal-fullscreen {\n  width: 100vw;\n  max-width: none;\n  height: 100%;\n  margin: 0;\n}\n\n.modal-fullscreen .modal-content {\n  height: 100%;\n  border: 0;\n  border-radius: 0;\n}\n\n.modal-fullscreen .modal-header {\n  border-radius: 0;\n}\n\n.modal-fullscreen .modal-body {\n  overflow-y: auto;\n}\n\n.modal-fullscreen .modal-footer {\n  border-radius: 0;\n}\n\n@media (max-width: 575.98px) {\n  .modal-fullscreen-sm-down {\n    width: 100vw;\n    max-width: none;\n    height: 100%;\n    margin: 0;\n  }\n\n  .modal-fullscreen-sm-down .modal-content {\n    height: 100%;\n    border: 0;\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-sm-down .modal-header {\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-sm-down .modal-body {\n    overflow-y: auto;\n  }\n\n  .modal-fullscreen-sm-down .modal-footer {\n    border-radius: 0;\n  }\n}\n\n@media (max-width: 767.98px) {\n  .modal-fullscreen-md-down {\n    width: 100vw;\n    max-width: none;\n    height: 100%;\n    margin: 0;\n  }\n\n  .modal-fullscreen-md-down .modal-content {\n    height: 100%;\n    border: 0;\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-md-down .modal-header {\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-md-down .modal-body {\n    overflow-y: auto;\n  }\n\n  .modal-fullscreen-md-down .modal-footer {\n    border-radius: 0;\n  }\n}\n\n@media (max-width: 991.98px) {\n  .modal-fullscreen-lg-down {\n    width: 100vw;\n    max-width: none;\n    height: 100%;\n    margin: 0;\n  }\n\n  .modal-fullscreen-lg-down .modal-content {\n    height: 100%;\n    border: 0;\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-lg-down .modal-header {\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-lg-down .modal-body {\n    overflow-y: auto;\n  }\n\n  .modal-fullscreen-lg-down .modal-footer {\n    border-radius: 0;\n  }\n}\n\n@media (max-width: 1199.98px) {\n  .modal-fullscreen-xl-down {\n    width: 100vw;\n    max-width: none;\n    height: 100%;\n    margin: 0;\n  }\n\n  .modal-fullscreen-xl-down .modal-content {\n    height: 100%;\n    border: 0;\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-xl-down .modal-header {\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-xl-down .modal-body {\n    overflow-y: auto;\n  }\n\n  .modal-fullscreen-xl-down .modal-footer {\n    border-radius: 0;\n  }\n}\n\n@media (max-width: 1399.98px) {\n  .modal-fullscreen-xxl-down {\n    width: 100vw;\n    max-width: none;\n    height: 100%;\n    margin: 0;\n  }\n\n  .modal-fullscreen-xxl-down .modal-content {\n    height: 100%;\n    border: 0;\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-xxl-down .modal-header {\n    border-radius: 0;\n  }\n\n  .modal-fullscreen-xxl-down .modal-body {\n    overflow-y: auto;\n  }\n\n  .modal-fullscreen-xxl-down .modal-footer {\n    border-radius: 0;\n  }\n}\n\n.btn {\n  display: inline-block;\n  font-weight: 400;\n  line-height: 1.5;\n  color: #212529;\n  text-align: center;\n  text-decoration: none;\n  vertical-align: middle;\n  cursor: pointer;\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  user-select: none;\n  background-color: transparent;\n  border: 1px solid transparent;\n  padding: 0.375rem 0.75rem;\n  font-size: 1rem;\n  border-radius: 0.25rem;\n  font-family: inherit;\n  transition:\n    color 0.15s ease-in-out,\n    background-color 0.15s ease-in-out,\n    border-color 0.15s ease-in-out,\n    box-shadow 0.15s ease-in-out;\n  border: 1px solid rgba(100, 100, 100, 0.35);\n  border-top: 1px solid rgba(100, 100, 100, 0.5);\n  border-radius: 6px;\n  font-size: 14px;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .btn {\n    transition: none;\n  }\n}\n\n.btn:hover {\n  color: #212529;\n}\n\n.btn-check:focus + .btn,\n.btn:focus {\n  outline: 0;\n  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);\n}\n\n.btn:disabled,\n.btn.disabled,\nfieldset:disabled .btn {\n  pointer-events: none;\n  opacity: 0.65;\n}\n\n.btn-primary {\n  color: #fff;\n  background-color: var(--keyColor-primary);\n  //border-color    : #0d6efd;\n}\n\n.btn-primary:hover {\n  color: #fff;\n  //background-color: #0b5ed7;\n  //border-color    : #0a58ca;\n}\n\n.btn-check:focus + .btn-primary,\n.btn-primary:focus {\n  color: #fff;\n  //background-color: #0b5ed7;\n  //border-color    : #0a58ca;\n  //box-shadow      : 0 0 0 0.25rem rgba(49, 132, 253, 0.5);\n}\n\n.btn-check:checked + .btn-primary,\n.btn-check:active + .btn-primary,\n.btn-primary:active,\n.btn-primary.active,\n.show > .btn-primary.dropdown-toggle {\n  color: #fff;\n  //background-color: #0a58ca;\n  //border-color    : #0a53be;\n}\n\n.btn-check:checked + .btn-primary:focus,\n.btn-check:active + .btn-primary:focus,\n.btn-primary:active:focus,\n.btn-primary.active:focus,\n.show > .btn-primary.dropdown-toggle:focus {\n  //box-shadow: 0 0 0 0.25rem rgba(49, 132, 253, 0.5);\n}\n\n.btn-primary:disabled,\n.btn-primary.disabled {\n  color: #fff;\n  background-color: #0d6efd;\n  border-color: #0d6efd;\n}\n\n.btn-secondary {\n  color: #fff;\n  border-color: 1px solid rgba(100, 100, 100, 0.35);\n  background-color: rgba(100, 100, 100, 0.25);\n  border-top-color: 1px solid rgba(100, 100, 100, 0.5);\n}\n\n.btn-secondary:hover {\n  color: #fff;\n  // background-color: #5c636a;\n  // border-color    : #565e64;\n}\n\n// .btn-check:focus+.btn-secondary,\n// .btn-secondary:focus {\n//   color           : #fff;\n//   background-color: #5c636a;\n//   border-color    : #565e64;\n//   box-shadow      : 0 0 0 0.25rem rgba(130, 138, 145, 0.5);\n// }\n\n.btn-check:checked + .btn-secondary,\n.btn-check:active + .btn-secondary,\n.btn-secondary:active,\n.btn-secondary.active,\n.show > .btn-secondary.dropdown-toggle {\n  color: #fff;\n  background-color: #565e64;\n  border-color: #51585e;\n}\n\n.btn-check:checked + .btn-secondary:focus,\n.btn-check:active + .btn-secondary:focus,\n.btn-secondary:active:focus,\n.btn-secondary.active:focus,\n.show > .btn-secondary.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(130, 138, 145, 0.5);\n}\n\n.btn-secondary:disabled,\n.btn-secondary.disabled {\n  color: #fff;\n  background-color: #6c757d;\n  border-color: #6c757d;\n}\n\n.btn-success {\n  color: #fff;\n  background-color: #198754;\n  border-color: #198754;\n}\n\n.btn-success:hover {\n  color: #fff;\n  background-color: #157347;\n  border-color: #146c43;\n}\n\n.btn-check:focus + .btn-success,\n.btn-success:focus {\n  color: #fff;\n  background-color: #157347;\n  border-color: #146c43;\n  box-shadow: 0 0 0 0.25rem rgba(60, 153, 110, 0.5);\n}\n\n.btn-check:checked + .btn-success,\n.btn-check:active + .btn-success,\n.btn-success:active,\n.btn-success.active,\n.show > .btn-success.dropdown-toggle {\n  color: #fff;\n  background-color: #146c43;\n  border-color: #13653f;\n}\n\n.btn-check:checked + .btn-success:focus,\n.btn-check:active + .btn-success:focus,\n.btn-success:active:focus,\n.btn-success.active:focus,\n.show > .btn-success.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(60, 153, 110, 0.5);\n}\n\n.btn-success:disabled,\n.btn-success.disabled {\n  color: #fff;\n  background-color: #198754;\n  border-color: #198754;\n}\n\n.btn-info {\n  color: #000;\n  background-color: #0dcaf0;\n  border-color: #0dcaf0;\n}\n\n.btn-info:hover {\n  color: #000;\n  background-color: #31d2f2;\n  border-color: #25cff2;\n}\n\n.btn-check:focus + .btn-info,\n.btn-info:focus {\n  color: #000;\n  background-color: #31d2f2;\n  border-color: #25cff2;\n  box-shadow: 0 0 0 0.25rem rgba(11, 172, 204, 0.5);\n}\n\n.btn-check:checked + .btn-info,\n.btn-check:active + .btn-info,\n.btn-info:active,\n.btn-info.active,\n.show > .btn-info.dropdown-toggle {\n  color: #000;\n  background-color: #3dd5f3;\n  border-color: #25cff2;\n}\n\n.btn-check:checked + .btn-info:focus,\n.btn-check:active + .btn-info:focus,\n.btn-info:active:focus,\n.btn-info.active:focus,\n.show > .btn-info.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(11, 172, 204, 0.5);\n}\n\n.btn-info:disabled,\n.btn-info.disabled {\n  color: #000;\n  background-color: #0dcaf0;\n  border-color: #0dcaf0;\n}\n\n.btn-warning {\n  color: #000;\n  background-color: #ffc107;\n  border-color: #ffc107;\n}\n\n.btn-warning:hover {\n  color: #000;\n  background-color: #ffca2c;\n  border-color: #ffc720;\n}\n\n.btn-check:focus + .btn-warning,\n.btn-warning:focus {\n  color: #000;\n  background-color: #ffca2c;\n  border-color: #ffc720;\n  box-shadow: 0 0 0 0.25rem rgba(217, 164, 6, 0.5);\n}\n\n.btn-check:checked + .btn-warning,\n.btn-check:active + .btn-warning,\n.btn-warning:active,\n.btn-warning.active,\n.show > .btn-warning.dropdown-toggle {\n  color: #000;\n  background-color: #ffcd39;\n  border-color: #ffc720;\n}\n\n.btn-check:checked + .btn-warning:focus,\n.btn-check:active + .btn-warning:focus,\n.btn-warning:active:focus,\n.btn-warning.active:focus,\n.show > .btn-warning.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(217, 164, 6, 0.5);\n}\n\n.btn-warning:disabled,\n.btn-warning.disabled {\n  color: #000;\n  background-color: #ffc107;\n  border-color: #ffc107;\n}\n\n.btn-danger {\n  color: #fff;\n  background-color: #dc3545;\n  border-color: #dc3545;\n}\n\n.btn-danger:hover {\n  color: #fff;\n  background-color: #bb2d3b;\n  border-color: #b02a37;\n}\n\n.btn-check:focus + .btn-danger,\n.btn-danger:focus {\n  color: #fff;\n  background-color: #bb2d3b;\n  border-color: #b02a37;\n  box-shadow: 0 0 0 0.25rem rgba(225, 83, 97, 0.5);\n}\n\n.btn-check:checked + .btn-danger,\n.btn-check:active + .btn-danger,\n.btn-danger:active,\n.btn-danger.active,\n.show > .btn-danger.dropdown-toggle {\n  color: #fff;\n  background-color: #b02a37;\n  border-color: #a52834;\n}\n\n.btn-check:checked + .btn-danger:focus,\n.btn-check:active + .btn-danger:focus,\n.btn-danger:active:focus,\n.btn-danger.active:focus,\n.show > .btn-danger.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(225, 83, 97, 0.5);\n}\n\n.btn-danger:disabled,\n.btn-danger.disabled {\n  color: #fff;\n  background-color: #dc3545;\n  border-color: #dc3545;\n}\n\n.btn-light {\n  color: #000;\n  background-color: #f8f9fa;\n  border-color: #f8f9fa;\n}\n\n.btn-light:hover {\n  color: #000;\n  background-color: #f9fafb;\n  border-color: #f9fafb;\n}\n\n.btn-check:focus + .btn-light,\n.btn-light:focus {\n  color: #000;\n  background-color: #f9fafb;\n  border-color: #f9fafb;\n  box-shadow: 0 0 0 0.25rem rgba(211, 212, 213, 0.5);\n}\n\n.btn-check:checked + .btn-light,\n.btn-check:active + .btn-light,\n.btn-light:active,\n.btn-light.active,\n.show > .btn-light.dropdown-toggle {\n  color: #000;\n  background-color: #f9fafb;\n  border-color: #f9fafb;\n}\n\n.btn-check:checked + .btn-light:focus,\n.btn-check:active + .btn-light:focus,\n.btn-light:active:focus,\n.btn-light.active:focus,\n.show > .btn-light.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(211, 212, 213, 0.5);\n}\n\n.btn-light:disabled,\n.btn-light.disabled {\n  color: #000;\n  background-color: #f8f9fa;\n  border-color: #f8f9fa;\n}\n\n.btn-dark {\n  color: #fff;\n  background-color: #212529;\n  border-color: #212529;\n}\n\n.btn-dark:hover {\n  color: #fff;\n  background-color: #1c1f23;\n  border-color: #1a1e21;\n}\n\n.btn-check:focus + .btn-dark,\n.btn-dark:focus {\n  color: #fff;\n  background-color: #1c1f23;\n  border-color: #1a1e21;\n  box-shadow: 0 0 0 0.25rem rgba(66, 70, 73, 0.5);\n}\n\n.btn-check:checked + .btn-dark,\n.btn-check:active + .btn-dark,\n.btn-dark:active,\n.btn-dark.active,\n.show > .btn-dark.dropdown-toggle {\n  color: #fff;\n  background-color: #1a1e21;\n  border-color: #191c1f;\n}\n\n.btn-check:checked + .btn-dark:focus,\n.btn-check:active + .btn-dark:focus,\n.btn-dark:active:focus,\n.btn-dark.active:focus,\n.show > .btn-dark.dropdown-toggle:focus {\n  box-shadow: 0 0 0 0.25rem rgba(66, 70, 73, 0.5);\n}\n\n.btn-dark:disabled,\n.btn-dark.disabled {\n  color: #fff;\n  background-color: #212529;\n  border-color: #212529;\n}\n\n.btn-outline-primary {\n  color: #0d6efd;\n  border-color: #0d6efd;\n}\n\n.btn-outline-primary:hover {\n  color: #fff;\n  background-color: #0d6efd;\n  border-color: #0d6efd;\n}\n\n.btn-check:focus + .btn-outline-primary,\n.btn-outline-primary:focus {\n  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.5);\n}\n\n.btn-check:checked + .btn-outline-primary,\n.btn-check:active + .btn-outline-primary,\n.btn-outline-primary:active,\n.btn-outline-primary.active,\n.btn-outline-primary.dropdown-toggle.show {\n  color: #fff;\n  background-color: #0d6efd;\n  border-color: #0d6efd;\n}\n\n.btn-check:checked + .btn-outline-primary:focus,\n.btn-check:active + .btn-outline-primary:focus,\n.btn-outline-primary:active:focus,\n.btn-outline-primary.active:focus,\n.btn-outline-primary.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.5);\n}\n\n.btn-outline-primary:disabled,\n.btn-outline-primary.disabled {\n  color: #0d6efd;\n  background-color: transparent;\n}\n\n.btn-outline-secondary {\n  color: #6c757d;\n  border-color: #6c757d;\n}\n\n.btn-outline-secondary:hover {\n  color: #fff;\n  background-color: #6c757d;\n  border-color: #6c757d;\n}\n\n.btn-check:focus + .btn-outline-secondary,\n.btn-outline-secondary:focus {\n  box-shadow: 0 0 0 0.25rem rgba(108, 117, 125, 0.5);\n}\n\n.btn-check:checked + .btn-outline-secondary,\n.btn-check:active + .btn-outline-secondary,\n.btn-outline-secondary:active,\n.btn-outline-secondary.active,\n.btn-outline-secondary.dropdown-toggle.show {\n  color: #fff;\n  background-color: #6c757d;\n  border-color: #6c757d;\n}\n\n.btn-check:checked + .btn-outline-secondary:focus,\n.btn-check:active + .btn-outline-secondary:focus,\n.btn-outline-secondary:active:focus,\n.btn-outline-secondary.active:focus,\n.btn-outline-secondary.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(108, 117, 125, 0.5);\n}\n\n.btn-outline-secondary:disabled,\n.btn-outline-secondary.disabled {\n  color: #6c757d;\n  background-color: transparent;\n}\n\n.btn-outline-success {\n  color: #198754;\n  border-color: #198754;\n}\n\n.btn-outline-success:hover {\n  color: #fff;\n  background-color: #198754;\n  border-color: #198754;\n}\n\n.btn-check:focus + .btn-outline-success,\n.btn-outline-success:focus {\n  box-shadow: 0 0 0 0.25rem rgba(25, 135, 84, 0.5);\n}\n\n.btn-check:checked + .btn-outline-success,\n.btn-check:active + .btn-outline-success,\n.btn-outline-success:active,\n.btn-outline-success.active,\n.btn-outline-success.dropdown-toggle.show {\n  color: #fff;\n  background-color: #198754;\n  border-color: #198754;\n}\n\n.btn-check:checked + .btn-outline-success:focus,\n.btn-check:active + .btn-outline-success:focus,\n.btn-outline-success:active:focus,\n.btn-outline-success.active:focus,\n.btn-outline-success.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(25, 135, 84, 0.5);\n}\n\n.btn-outline-success:disabled,\n.btn-outline-success.disabled {\n  color: #198754;\n  background-color: transparent;\n}\n\n.btn-outline-info {\n  color: #0dcaf0;\n  border-color: #0dcaf0;\n}\n\n.btn-outline-info:hover {\n  color: #000;\n  background-color: #0dcaf0;\n  border-color: #0dcaf0;\n}\n\n.btn-check:focus + .btn-outline-info,\n.btn-outline-info:focus {\n  box-shadow: 0 0 0 0.25rem rgba(13, 202, 240, 0.5);\n}\n\n.btn-check:checked + .btn-outline-info,\n.btn-check:active + .btn-outline-info,\n.btn-outline-info:active,\n.btn-outline-info.active,\n.btn-outline-info.dropdown-toggle.show {\n  color: #000;\n  background-color: #0dcaf0;\n  border-color: #0dcaf0;\n}\n\n.btn-check:checked + .btn-outline-info:focus,\n.btn-check:active + .btn-outline-info:focus,\n.btn-outline-info:active:focus,\n.btn-outline-info.active:focus,\n.btn-outline-info.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(13, 202, 240, 0.5);\n}\n\n.btn-outline-info:disabled,\n.btn-outline-info.disabled {\n  color: #0dcaf0;\n  background-color: transparent;\n}\n\n.btn-outline-warning {\n  color: #ffc107;\n  border-color: #ffc107;\n}\n\n.btn-outline-warning:hover {\n  color: #000;\n  background-color: #ffc107;\n  border-color: #ffc107;\n}\n\n.btn-check:focus + .btn-outline-warning,\n.btn-outline-warning:focus {\n  box-shadow: 0 0 0 0.25rem rgba(255, 193, 7, 0.5);\n}\n\n.btn-check:checked + .btn-outline-warning,\n.btn-check:active + .btn-outline-warning,\n.btn-outline-warning:active,\n.btn-outline-warning.active,\n.btn-outline-warning.dropdown-toggle.show {\n  color: #000;\n  background-color: #ffc107;\n  border-color: #ffc107;\n}\n\n.btn-check:checked + .btn-outline-warning:focus,\n.btn-check:active + .btn-outline-warning:focus,\n.btn-outline-warning:active:focus,\n.btn-outline-warning.active:focus,\n.btn-outline-warning.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(255, 193, 7, 0.5);\n}\n\n.btn-outline-warning:disabled,\n.btn-outline-warning.disabled {\n  color: #ffc107;\n  background-color: transparent;\n}\n\n.btn-outline-danger {\n  color: #dc3545;\n  border-color: #dc3545;\n}\n\n.btn-outline-danger:hover {\n  color: #fff;\n  background-color: #dc3545;\n  border-color: #dc3545;\n}\n\n.btn-check:focus + .btn-outline-danger,\n.btn-outline-danger:focus {\n  box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.5);\n}\n\n.btn-check:checked + .btn-outline-danger,\n.btn-check:active + .btn-outline-danger,\n.btn-outline-danger:active,\n.btn-outline-danger.active,\n.btn-outline-danger.dropdown-toggle.show {\n  color: #fff;\n  background-color: #dc3545;\n  border-color: #dc3545;\n}\n\n.btn-check:checked + .btn-outline-danger:focus,\n.btn-check:active + .btn-outline-danger:focus,\n.btn-outline-danger:active:focus,\n.btn-outline-danger.active:focus,\n.btn-outline-danger.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.5);\n}\n\n.btn-outline-danger:disabled,\n.btn-outline-danger.disabled {\n  color: #dc3545;\n  background-color: transparent;\n}\n\n.btn-outline-light {\n  color: #f8f9fa;\n  border-color: #f8f9fa;\n}\n\n.btn-outline-light:hover {\n  color: #000;\n  background-color: #f8f9fa;\n  border-color: #f8f9fa;\n}\n\n.btn-check:focus + .btn-outline-light,\n.btn-outline-light:focus {\n  box-shadow: 0 0 0 0.25rem rgba(248, 249, 250, 0.5);\n}\n\n.btn-check:checked + .btn-outline-light,\n.btn-check:active + .btn-outline-light,\n.btn-outline-light:active,\n.btn-outline-light.active,\n.btn-outline-light.dropdown-toggle.show {\n  color: #000;\n  background-color: #f8f9fa;\n  border-color: #f8f9fa;\n}\n\n.btn-check:checked + .btn-outline-light:focus,\n.btn-check:active + .btn-outline-light:focus,\n.btn-outline-light:active:focus,\n.btn-outline-light.active:focus,\n.btn-outline-light.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(248, 249, 250, 0.5);\n}\n\n.btn-outline-light:disabled,\n.btn-outline-light.disabled {\n  color: #f8f9fa;\n  background-color: transparent;\n}\n\n.btn-outline-dark {\n  color: #212529;\n  border-color: #212529;\n}\n\n.btn-outline-dark:hover {\n  color: #fff;\n  background-color: #212529;\n  border-color: #212529;\n}\n\n.btn-check:focus + .btn-outline-dark,\n.btn-outline-dark:focus {\n  box-shadow: 0 0 0 0.25rem rgba(33, 37, 41, 0.5);\n}\n\n.btn-check:checked + .btn-outline-dark,\n.btn-check:active + .btn-outline-dark,\n.btn-outline-dark:active,\n.btn-outline-dark.active,\n.btn-outline-dark.dropdown-toggle.show {\n  color: #fff;\n  background-color: #212529;\n  border-color: #212529;\n}\n\n.btn-check:checked + .btn-outline-dark:focus,\n.btn-check:active + .btn-outline-dark:focus,\n.btn-outline-dark:active:focus,\n.btn-outline-dark.active:focus,\n.btn-outline-dark.dropdown-toggle.show:focus {\n  box-shadow: 0 0 0 0.25rem rgba(33, 37, 41, 0.5);\n}\n\n.btn-outline-dark:disabled,\n.btn-outline-dark.disabled {\n  color: #212529;\n  background-color: transparent;\n}\n\n.btn-link {\n  font-weight: 400;\n  color: #0d6efd;\n  text-decoration: underline;\n}\n\n.btn-link:hover {\n  color: #0a58ca;\n}\n\n.btn-link:disabled,\n.btn-link.disabled {\n  color: #6c757d;\n}\n\n.btn-lg,\n.btn-group-lg > .btn {\n  padding: 0.5rem 1rem;\n  font-size: 1.25rem;\n  border-radius: 0.3rem;\n}\n\n.btn-sm,\n.btn-group-sm > .btn {\n  padding: 0.25rem 0.5rem;\n  font-size: 0.875rem;\n  border-radius: 0.2rem;\n}\n\n.form-control {\n  width: 100%;\n}\n\n// Button Group\n\n.btn-group,\n.btn-group-vertical {\n  position: relative;\n  display: inline-flex;\n  vertical-align: middle;\n}\n.btn-group > .btn,\n.btn-group-vertical > .btn {\n  position: relative;\n  flex: 1 1 auto;\n}\n.btn-group > .btn-check:checked + .btn,\n.btn-group > .btn-check:focus + .btn,\n.btn-group > .btn:hover,\n.btn-group > .btn:focus,\n.btn-group > .btn:active,\n.btn-group > .btn.active,\n.btn-group-vertical > .btn-check:checked + .btn,\n.btn-group-vertical > .btn-check:focus + .btn,\n.btn-group-vertical > .btn:hover,\n.btn-group-vertical > .btn:focus,\n.btn-group-vertical > .btn:active,\n.btn-group-vertical > .btn.active {\n  z-index: 1;\n}\n\n.btn-toolbar {\n  display: flex;\n  flex-wrap: wrap;\n  justify-content: flex-start;\n}\n.btn-toolbar .input-group {\n  width: auto;\n}\n\n.btn-group > .btn:not(:first-child),\n.btn-group > .btn-group:not(:first-child) {\n  margin-left: -1px;\n}\n.btn-group > .btn:not(:last-child):not(.dropdown-toggle),\n.btn-group > .btn-group:not(:last-child) > .btn {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n.btn-group > .btn:nth-child(n + 3),\n.btn-group > :not(.btn-check) + .btn,\n.btn-group > .btn-group:not(:first-child) > .btn {\n  border-top-left-radius: 0;\n  border-bottom-left-radius: 0;\n}\n\n.dropdown-toggle-split {\n  padding-right: 0.5625rem;\n  padding-left: 0.5625rem;\n}\n.dropdown-toggle-split::after,\n.dropup .dropdown-toggle-split::after,\n.dropend .dropdown-toggle-split::after {\n  margin-left: 0;\n}\n.dropstart .dropdown-toggle-split::before {\n  margin-right: 0;\n}\n\n.btn-sm + .dropdown-toggle-split,\n.btn-group-sm > .btn + .dropdown-toggle-split {\n  padding-right: 0.375rem;\n  padding-left: 0.375rem;\n}\n\n.btn-lg + .dropdown-toggle-split,\n.btn-group-lg > .btn + .dropdown-toggle-split {\n  padding-right: 0.75rem;\n  padding-left: 0.75rem;\n}\n\n.btn-group-vertical {\n  flex-direction: column;\n  align-items: flex-start;\n  justify-content: center;\n}\n.btn-group-vertical > .btn,\n.btn-group-vertical > .btn-group {\n  width: 100%;\n}\n.btn-group-vertical > .btn:not(:first-child),\n.btn-group-vertical > .btn-group:not(:first-child) {\n  margin-top: -1px;\n}\n.btn-group-vertical > .btn:not(:last-child):not(.dropdown-toggle),\n.btn-group-vertical > .btn-group:not(:last-child) > .btn {\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0;\n}\n.btn-group-vertical > .btn ~ .btn,\n.btn-group-vertical > .btn-group:not(:first-child) > .btn {\n  border-top-left-radius: 0;\n  border-top-right-radius: 0;\n}\n\n// Table\n.table {\n  --bs-table-bg: transparent;\n  --bs-table-accent-bg: transparent;\n  --bs-table-striped-color: #212529;\n  --bs-table-striped-bg: rgba(0, 0, 0, 0.05);\n  --bs-table-active-color: #212529;\n  --bs-table-active-bg: rgba(0, 0, 0, 0.1);\n  --bs-table-hover-color: #212529;\n  --bs-table-hover-bg: rgba(0, 0, 0, 0.075);\n  width: 100%;\n  margin-bottom: 1rem;\n  color: #212529;\n  vertical-align: top;\n  border-color: #dee2e6;\n}\n.table > :not(caption) > * > * {\n  padding: 0.5rem 0.5rem;\n  background-color: var(--bs-table-bg);\n  border-bottom-width: 1px;\n  box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg);\n}\n.table > tbody {\n  vertical-align: inherit;\n}\n.table > thead {\n  vertical-align: bottom;\n}\n.table > :not(:first-child) {\n  border-top: 2px solid currentColor;\n}\n\n.caption-top {\n  caption-side: top;\n}\n\n.table-sm > :not(caption) > * > * {\n  padding: 0.25rem 0.25rem;\n}\n\n.table-bordered > :not(caption) > * {\n  border-width: 1px 0;\n}\n.table-bordered > :not(caption) > * > * {\n  border-width: 0 1px;\n}\n\n.table-borderless > :not(caption) > * > * {\n  border-bottom-width: 0;\n}\n.table-borderless > :not(:first-child) {\n  border-top-width: 0;\n}\n\n.table-striped > tbody > tr:nth-of-type(odd) > * {\n  --bs-table-accent-bg: var(--bs-table-striped-bg);\n  color: var(--bs-table-striped-color);\n}\n\n.table-active {\n  --bs-table-accent-bg: var(--bs-table-active-bg);\n  color: var(--bs-table-active-color);\n}\n\n.table-hover > tbody > tr:hover > * {\n  --bs-table-accent-bg: var(--bs-table-hover-bg);\n  color: var(--bs-table-hover-color);\n}\n\n.table-primary {\n  --bs-table-bg: #cfe2ff;\n  --bs-table-striped-bg: #c5d7f2;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #bacbe6;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #bfd1ec;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #bacbe6;\n}\n\n.table-secondary {\n  --bs-table-bg: #e2e3e5;\n  --bs-table-striped-bg: #d7d8da;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #cbccce;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #d1d2d4;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #cbccce;\n}\n\n.table-success {\n  --bs-table-bg: #d1e7dd;\n  --bs-table-striped-bg: #c7dbd2;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #bcd0c7;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #c1d6cc;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #bcd0c7;\n}\n\n.table-info {\n  --bs-table-bg: #cff4fc;\n  --bs-table-striped-bg: #c5e8ef;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #badce3;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #bfe2e9;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #badce3;\n}\n\n.table-warning {\n  --bs-table-bg: #fff3cd;\n  --bs-table-striped-bg: #f2e7c3;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #e6dbb9;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #ece1be;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #e6dbb9;\n}\n\n.table-danger {\n  --bs-table-bg: #f8d7da;\n  --bs-table-striped-bg: #eccccf;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #dfc2c4;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #e5c7ca;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #dfc2c4;\n}\n\n.table-light {\n  --bs-table-bg: #f8f9fa;\n  --bs-table-striped-bg: #ecedee;\n  --bs-table-striped-color: #000;\n  --bs-table-active-bg: #dfe0e1;\n  --bs-table-active-color: #000;\n  --bs-table-hover-bg: #e5e6e7;\n  --bs-table-hover-color: #000;\n  color: #000;\n  border-color: #dfe0e1;\n}\n\n.table-dark {\n  --bs-table-bg: #212529;\n  --bs-table-striped-bg: #2c3034;\n  --bs-table-striped-color: #fff;\n  --bs-table-active-bg: #373b3e;\n  --bs-table-active-color: #fff;\n  --bs-table-hover-bg: #323539;\n  --bs-table-hover-color: #fff;\n  color: #fff;\n  border-color: #373b3e;\n}\n\n.table-responsive {\n  overflow-x: auto;\n  -webkit-overflow-scrolling: touch;\n}\n\n@media (max-width: 575.98px) {\n  .table-responsive-sm {\n    overflow-x: auto;\n    -webkit-overflow-scrolling: touch;\n  }\n}\n@media (max-width: 767.98px) {\n  .table-responsive-md {\n    overflow-x: auto;\n    -webkit-overflow-scrolling: touch;\n  }\n}\n@media (max-width: 991.98px) {\n  .table-responsive-lg {\n    overflow-x: auto;\n    -webkit-overflow-scrolling: touch;\n  }\n}\n@media (max-width: 1199.98px) {\n  .table-responsive-xl {\n    overflow-x: auto;\n    -webkit-overflow-scrolling: touch;\n  }\n}\n@media (max-width: 1399.98px) {\n  .table-responsive-xxl {\n    overflow-x: auto;\n    -webkit-overflow-scrolling: touch;\n  }\n}\n\n// Tabs\n\n.nav {\n  display: -ms-flexbox;\n  display: flex;\n  -ms-flex-wrap: wrap;\n  flex-wrap: wrap;\n  padding-left: 0;\n  margin-bottom: 0;\n  list-style: none;\n}\n\n.nav-link {\n  display: block;\n  padding: 0.5rem 1rem;\n  text-decoration: none;\n}\n\n.nav-link:hover,\n.nav-link:focus {\n  text-decoration: none;\n}\n\n.nav-link.disabled {\n  color: #6c757d;\n  pointer-events: none;\n  cursor: default;\n}\n\n.nav-tabs {\n  border-bottom: 1px solid #dee2e6;\n}\n.nav-tabs .nav-link {\n  margin-bottom: -1px;\n  background: none;\n  border: 1px solid transparent;\n  border-top-left-radius: 0.25rem;\n  border-top-right-radius: 0.25rem;\n}\n.nav-tabs .nav-link:hover,\n.nav-tabs .nav-link:focus {\n  border-color: #e9ecef #e9ecef #dee2e6;\n  isolation: isolate;\n}\n.nav-tabs .nav-link.disabled {\n  color: #6c757d;\n  background-color: transparent;\n  border-color: transparent;\n}\n.nav-tabs .nav-link.active,\n.nav-tabs .nav-item.show .nav-link {\n  color: #495057;\n  background-color: #fff;\n  border-color: #dee2e6 #dee2e6 #fff;\n}\n.nav-tabs .dropdown-menu {\n  margin-top: -1px;\n  border-top-left-radius: 0;\n  border-top-right-radius: 0;\n}\n\n.nav-pills .nav-link {\n  background-color: transparent;\n  border: 0;\n  border-radius: 6px;\n  color: #eee;\n  -webkit-user-drag: none;\n  font-weight: 500;\n  margin: 0px 4px;\n  &:hover {\n    // transition: transform .35s var(--appleEase), background-color 0s var(--appleEase);\n    background-color: var(--hover);\n  }\n}\n.nav-pills .nav-link.active,\n.nav-pills .show > .nav-link {\n  color: #fff;\n  background-color: var(--selected);\n  // outline:2px solid var(--keyColor);\n}\n\n.nav-fill > .nav-link,\n.nav-fill .nav-item {\n  flex: 1 1 auto;\n  text-align: center;\n}\n\n.nav-justified > .nav-link,\n.nav-justified .nav-item {\n  flex-basis: 0;\n  flex-grow: 1;\n  text-align: center;\n}\n\n.nav-fill .nav-item .nav-link,\n.nav-justified .nav-item .nav-link {\n  width: 100%;\n}\n\n.tab-content > .tab-pane {\n  display: none;\n}\n.tab-content > .active {\n  display: block;\n}\n\n/*!\n * Bootstrap Grid v5.1.1 (https://getbootstrap.com/)\n * Copyright 2011-2021 The Bootstrap Authors\n * Copyright 2011-2021 Twitter, Inc.\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n */\n:root {\n  --bs-blue: #0d6efd;\n  --bs-indigo: #6610f2;\n  --bs-purple: #6f42c1;\n  --bs-pink: #d63384;\n  --bs-red: #dc3545;\n  --bs-orange: #fd7e14;\n  --bs-yellow: #ffc107;\n  --bs-green: #198754;\n  --bs-teal: #20c997;\n  --bs-cyan: #0dcaf0;\n  --bs-white: #fff;\n  --bs-gray: #6c757d;\n  --bs-gray-dark: #343a40;\n  --bs-gray-100: #f8f9fa;\n  --bs-gray-200: #e9ecef;\n  --bs-gray-300: #dee2e6;\n  --bs-gray-400: #ced4da;\n  --bs-gray-500: #adb5bd;\n  --bs-gray-600: #6c757d;\n  --bs-gray-700: #495057;\n  --bs-gray-800: #343a40;\n  --bs-gray-900: #212529;\n  --bs-primary: #0d6efd;\n  --bs-secondary: #6c757d;\n  --bs-success: #198754;\n  --bs-info: #0dcaf0;\n  --bs-warning: #ffc107;\n  --bs-danger: #dc3545;\n  --bs-light: #f8f9fa;\n  --bs-dark: #212529;\n  --bs-primary-rgb: 13, 110, 253;\n  --bs-secondary-rgb: 108, 117, 125;\n  --bs-success-rgb: 25, 135, 84;\n  --bs-info-rgb: 13, 202, 240;\n  --bs-warning-rgb: 255, 193, 7;\n  --bs-danger-rgb: 220, 53, 69;\n  --bs-light-rgb: 248, 249, 250;\n  --bs-dark-rgb: 33, 37, 41;\n  --bs-white-rgb: 255, 255, 255;\n  --bs-black-rgb: 0, 0, 0;\n  --bs-body-color-rgb: 33, 37, 41;\n  --bs-body-bg-rgb: 255, 255, 255;\n  --bs-font-sans-serif: inherit;\n  --bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n  --bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));\n  --bs-body-font-family: inherit;\n  --bs-body-font-size: 1rem;\n  --bs-body-font-weight: 400;\n  --bs-body-line-height: 1.5;\n  --bs-body-color: #212529;\n  --bs-body-bg: #fff;\n}\n\n.container,\n.container-fluid,\n.container-xxl,\n.container-xl,\n.container-lg,\n.container-md,\n.container-sm {\n  width: 100%;\n  padding-right: var(--bs-gutter-x, 0.75rem);\n  padding-left: var(--bs-gutter-x, 0.75rem);\n  margin-right: auto;\n  margin-left: auto;\n}\n\n@media (min-width: 576px) {\n  .container-sm,\n  .container {\n    max-width: 540px;\n  }\n}\n\n@media (min-width: 768px) {\n  .container-md,\n  .container-sm,\n  .container {\n    max-width: 720px;\n  }\n}\n\n@media (min-width: 992px) {\n  .container-lg,\n  .container-md,\n  .container-sm,\n  .container {\n    max-width: 960px;\n  }\n}\n\n@media (min-width: 1200px) {\n  .container-xl,\n  .container-lg,\n  .container-md,\n  .container-sm,\n  .container {\n    max-width: 1140px;\n  }\n}\n\n@media (min-width: 1400px) {\n  .container-xxl,\n  .container-xl,\n  .container-lg,\n  .container-md,\n  .container-sm,\n  .container {\n    max-width: 1320px;\n  }\n}\n\n.col {\n  flex: 1 0 0%;\n}\n\n.row-cols-auto > * {\n  flex: 0 0 auto;\n  width: auto;\n}\n\n.row-cols-1 > * {\n  flex: 0 0 auto;\n  width: 100%;\n}\n\n.row-cols-2 > * {\n  flex: 0 0 auto;\n  width: 50%;\n}\n\n.row-cols-3 > * {\n  flex: 0 0 auto;\n  width: 33.3333333333%;\n}\n\n.row-cols-4 > * {\n  flex: 0 0 auto;\n  width: 25%;\n}\n\n.row-cols-5 > * {\n  flex: 0 0 auto;\n  width: 20%;\n}\n\n.row-cols-6 > * {\n  flex: 0 0 auto;\n  width: 16.6666666667%;\n}\n\n.col-auto {\n  flex: 0 0 auto;\n  width: auto;\n}\n\n@media only screen and (min-width: 1133px) and (max-width: 1233px) {\n  .about-page {\n    .row .col-auto {\n      display: none !important;\n    }\n  }\n}\n\n.col-1 {\n  flex: 0 0 auto;\n  width: 8.33333333%;\n}\n\n.col-2 {\n  flex: 0 0 auto;\n  width: 16.66666667%;\n}\n\n.col-3 {\n  flex: 0 0 auto;\n  width: 25%;\n}\n\n.col-4 {\n  flex: 0 0 auto;\n  width: 33.33333333%;\n}\n\n.col-5 {\n  flex: 0 0 auto;\n  width: 41.66666667%;\n}\n\n.col-6 {\n  flex: 0 0 auto;\n  width: 50%;\n}\n\n.col-7 {\n  flex: 0 0 auto;\n  width: 58.33333333%;\n}\n\n.col-8 {\n  flex: 0 0 auto;\n  width: 66.66666667%;\n}\n\n.col-9 {\n  flex: 0 0 auto;\n  width: 75%;\n}\n\n.col-10 {\n  flex: 0 0 auto;\n  width: 83.33333333%;\n}\n\n.col-11 {\n  flex: 0 0 auto;\n  width: 91.66666667%;\n}\n\n.col-12 {\n  flex: 0 0 auto;\n  width: 100%;\n}\n\n.offset-1 {\n  margin-left: 8.33333333%;\n}\n\n.offset-2 {\n  margin-left: 16.66666667%;\n}\n\n.offset-3 {\n  margin-left: 25%;\n}\n\n.offset-4 {\n  margin-left: 33.33333333%;\n}\n\n.offset-5 {\n  margin-left: 41.66666667%;\n}\n\n.offset-6 {\n  margin-left: 50%;\n}\n\n.offset-7 {\n  margin-left: 58.33333333%;\n}\n\n.offset-8 {\n  margin-left: 66.66666667%;\n}\n\n.offset-9 {\n  margin-left: 75%;\n}\n\n.offset-10 {\n  margin-left: 83.33333333%;\n}\n\n.offset-11 {\n  margin-left: 91.66666667%;\n}\n\n.g-0,\n.gx-0 {\n  --bs-gutter-x: 0;\n}\n\n.g-0,\n.gy-0 {\n  --bs-gutter-y: 0;\n}\n\n.g-1,\n.gx-1 {\n  --bs-gutter-x: 0.25rem;\n}\n\n.g-1,\n.gy-1 {\n  --bs-gutter-y: 0.25rem;\n}\n\n.g-2,\n.gx-2 {\n  --bs-gutter-x: 0.5rem;\n}\n\n.g-2,\n.gy-2 {\n  --bs-gutter-y: 0.5rem;\n}\n\n.g-3,\n.gx-3 {\n  --bs-gutter-x: 1rem;\n}\n\n.g-3,\n.gy-3 {\n  --bs-gutter-y: 1rem;\n}\n\n.g-4,\n.gx-4 {\n  --bs-gutter-x: 1.5rem;\n}\n\n.g-4,\n.gy-4 {\n  --bs-gutter-y: 1.5rem;\n}\n\n.g-5,\n.gx-5 {\n  --bs-gutter-x: 3rem;\n}\n\n.g-5,\n.gy-5 {\n  --bs-gutter-y: 3rem;\n}\n\n@media (min-width: 576px) {\n  .col-sm {\n    flex: 1 0 0%;\n  }\n\n  .row-cols-sm-auto > * {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .row-cols-sm-1 > * {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .row-cols-sm-2 > * {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .row-cols-sm-3 > * {\n    flex: 0 0 auto;\n    width: 33.3333333333%;\n  }\n\n  .row-cols-sm-4 > * {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .row-cols-sm-5 > * {\n    flex: 0 0 auto;\n    width: 20%;\n  }\n\n  .row-cols-sm-6 > * {\n    flex: 0 0 auto;\n    width: 16.6666666667%;\n  }\n\n  .col-sm-auto {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .col-sm-1 {\n    flex: 0 0 auto;\n    width: 8.33333333%;\n  }\n\n  .col-sm-2 {\n    flex: 0 0 auto;\n    width: 16.66666667%;\n  }\n\n  .col-sm-3 {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .col-sm-4 {\n    flex: 0 0 auto;\n    width: 33.33333333%;\n  }\n\n  .col-sm-5 {\n    flex: 0 0 auto;\n    width: 41.66666667%;\n  }\n\n  .col-sm-6 {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .col-sm-7 {\n    flex: 0 0 auto;\n    width: 58.33333333%;\n  }\n\n  .col-sm-8 {\n    flex: 0 0 auto;\n    width: 66.66666667%;\n  }\n\n  .col-sm-9 {\n    flex: 0 0 auto;\n    width: 75%;\n  }\n\n  .col-sm-10 {\n    flex: 0 0 auto;\n    width: 83.33333333%;\n  }\n\n  .col-sm-11 {\n    flex: 0 0 auto;\n    width: 91.66666667%;\n  }\n\n  .col-sm-12 {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .offset-sm-0 {\n    margin-left: 0;\n  }\n\n  .offset-sm-1 {\n    margin-left: 8.33333333%;\n  }\n\n  .offset-sm-2 {\n    margin-left: 16.66666667%;\n  }\n\n  .offset-sm-3 {\n    margin-left: 25%;\n  }\n\n  .offset-sm-4 {\n    margin-left: 33.33333333%;\n  }\n\n  .offset-sm-5 {\n    margin-left: 41.66666667%;\n  }\n\n  .offset-sm-6 {\n    margin-left: 50%;\n  }\n\n  .offset-sm-7 {\n    margin-left: 58.33333333%;\n  }\n\n  .offset-sm-8 {\n    margin-left: 66.66666667%;\n  }\n\n  .offset-sm-9 {\n    margin-left: 75%;\n  }\n\n  .offset-sm-10 {\n    margin-left: 83.33333333%;\n  }\n\n  .offset-sm-11 {\n    margin-left: 91.66666667%;\n  }\n\n  .g-sm-0,\n  .gx-sm-0 {\n    --bs-gutter-x: 0;\n  }\n\n  .g-sm-0,\n  .gy-sm-0 {\n    --bs-gutter-y: 0;\n  }\n\n  .g-sm-1,\n  .gx-sm-1 {\n    --bs-gutter-x: 0.25rem;\n  }\n\n  .g-sm-1,\n  .gy-sm-1 {\n    --bs-gutter-y: 0.25rem;\n  }\n\n  .g-sm-2,\n  .gx-sm-2 {\n    --bs-gutter-x: 0.5rem;\n  }\n\n  .g-sm-2,\n  .gy-sm-2 {\n    --bs-gutter-y: 0.5rem;\n  }\n\n  .g-sm-3,\n  .gx-sm-3 {\n    --bs-gutter-x: 1rem;\n  }\n\n  .g-sm-3,\n  .gy-sm-3 {\n    --bs-gutter-y: 1rem;\n  }\n\n  .g-sm-4,\n  .gx-sm-4 {\n    --bs-gutter-x: 1.5rem;\n  }\n\n  .g-sm-4,\n  .gy-sm-4 {\n    --bs-gutter-y: 1.5rem;\n  }\n\n  .g-sm-5,\n  .gx-sm-5 {\n    --bs-gutter-x: 3rem;\n  }\n\n  .g-sm-5,\n  .gy-sm-5 {\n    --bs-gutter-y: 3rem;\n  }\n}\n\n@media (min-width: 768px) {\n  .col-md {\n    flex: 1 0 0%;\n  }\n\n  .row-cols-md-auto > * {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .row-cols-md-1 > * {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .row-cols-md-2 > * {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .row-cols-md-3 > * {\n    flex: 0 0 auto;\n    width: 33.3333333333%;\n  }\n\n  .row-cols-md-4 > * {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .row-cols-md-5 > * {\n    flex: 0 0 auto;\n    width: 20%;\n  }\n\n  .row-cols-md-6 > * {\n    flex: 0 0 auto;\n    width: 16.6666666667%;\n  }\n\n  .col-md-auto {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .col-md-1 {\n    flex: 0 0 auto;\n    width: 8.33333333%;\n  }\n\n  .col-md-2 {\n    flex: 0 0 auto;\n    width: 16.66666667%;\n  }\n\n  .col-md-3 {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .col-md-4 {\n    flex: 0 0 auto;\n    width: 33.33333333%;\n  }\n\n  .col-md-5 {\n    flex: 0 0 auto;\n    width: 41.66666667%;\n  }\n\n  .col-md-6 {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .col-md-7 {\n    flex: 0 0 auto;\n    width: 58.33333333%;\n  }\n\n  .col-md-8 {\n    flex: 0 0 auto;\n    width: 66.66666667%;\n  }\n\n  .col-md-9 {\n    flex: 0 0 auto;\n    width: 75%;\n  }\n\n  .col-md-10 {\n    flex: 0 0 auto;\n    width: 83.33333333%;\n  }\n\n  .col-md-11 {\n    flex: 0 0 auto;\n    width: 91.66666667%;\n  }\n\n  .col-md-12 {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .offset-md-0 {\n    margin-left: 0;\n  }\n\n  .offset-md-1 {\n    margin-left: 8.33333333%;\n  }\n\n  .offset-md-2 {\n    margin-left: 16.66666667%;\n  }\n\n  .offset-md-3 {\n    margin-left: 25%;\n  }\n\n  .offset-md-4 {\n    margin-left: 33.33333333%;\n  }\n\n  .offset-md-5 {\n    margin-left: 41.66666667%;\n  }\n\n  .offset-md-6 {\n    margin-left: 50%;\n  }\n\n  .offset-md-7 {\n    margin-left: 58.33333333%;\n  }\n\n  .offset-md-8 {\n    margin-left: 66.66666667%;\n  }\n\n  .offset-md-9 {\n    margin-left: 75%;\n  }\n\n  .offset-md-10 {\n    margin-left: 83.33333333%;\n  }\n\n  .offset-md-11 {\n    margin-left: 91.66666667%;\n  }\n\n  .g-md-0,\n  .gx-md-0 {\n    --bs-gutter-x: 0;\n  }\n\n  .g-md-0,\n  .gy-md-0 {\n    --bs-gutter-y: 0;\n  }\n\n  .g-md-1,\n  .gx-md-1 {\n    --bs-gutter-x: 0.25rem;\n  }\n\n  .g-md-1,\n  .gy-md-1 {\n    --bs-gutter-y: 0.25rem;\n  }\n\n  .g-md-2,\n  .gx-md-2 {\n    --bs-gutter-x: 0.5rem;\n  }\n\n  .g-md-2,\n  .gy-md-2 {\n    --bs-gutter-y: 0.5rem;\n  }\n\n  .g-md-3,\n  .gx-md-3 {\n    --bs-gutter-x: 1rem;\n  }\n\n  .g-md-3,\n  .gy-md-3 {\n    --bs-gutter-y: 1rem;\n  }\n\n  .g-md-4,\n  .gx-md-4 {\n    --bs-gutter-x: 1.5rem;\n  }\n\n  .g-md-4,\n  .gy-md-4 {\n    --bs-gutter-y: 1.5rem;\n  }\n\n  .g-md-5,\n  .gx-md-5 {\n    --bs-gutter-x: 3rem;\n  }\n\n  .g-md-5,\n  .gy-md-5 {\n    --bs-gutter-y: 3rem;\n  }\n}\n\n@media (min-width: 992px) {\n  .col-lg {\n    flex: 1 0 0%;\n  }\n\n  .row-cols-lg-auto > * {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .row-cols-lg-1 > * {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .row-cols-lg-2 > * {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .row-cols-lg-3 > * {\n    flex: 0 0 auto;\n    width: 33.3333333333%;\n  }\n\n  .row-cols-lg-4 > * {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .row-cols-lg-5 > * {\n    flex: 0 0 auto;\n    width: 20%;\n  }\n\n  .row-cols-lg-6 > * {\n    flex: 0 0 auto;\n    width: 16.6666666667%;\n  }\n\n  .col-lg-auto {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .col-lg-1 {\n    flex: 0 0 auto;\n    width: 8.33333333%;\n  }\n\n  .col-lg-2 {\n    flex: 0 0 auto;\n    width: 16.66666667%;\n  }\n\n  .col-lg-3 {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .col-lg-4 {\n    flex: 0 0 auto;\n    width: 33.33333333%;\n  }\n\n  .col-lg-5 {\n    flex: 0 0 auto;\n    width: 41.66666667%;\n  }\n\n  .col-lg-6 {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .col-lg-7 {\n    flex: 0 0 auto;\n    width: 58.33333333%;\n  }\n\n  .col-lg-8 {\n    flex: 0 0 auto;\n    width: 66.66666667%;\n  }\n\n  .col-lg-9 {\n    flex: 0 0 auto;\n    width: 75%;\n  }\n\n  .col-lg-10 {\n    flex: 0 0 auto;\n    width: 83.33333333%;\n  }\n\n  .col-lg-11 {\n    flex: 0 0 auto;\n    width: 91.66666667%;\n  }\n\n  .col-lg-12 {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .offset-lg-0 {\n    margin-left: 0;\n  }\n\n  .offset-lg-1 {\n    margin-left: 8.33333333%;\n  }\n\n  .offset-lg-2 {\n    margin-left: 16.66666667%;\n  }\n\n  .offset-lg-3 {\n    margin-left: 25%;\n  }\n\n  .offset-lg-4 {\n    margin-left: 33.33333333%;\n  }\n\n  .offset-lg-5 {\n    margin-left: 41.66666667%;\n  }\n\n  .offset-lg-6 {\n    margin-left: 50%;\n  }\n\n  .offset-lg-7 {\n    margin-left: 58.33333333%;\n  }\n\n  .offset-lg-8 {\n    margin-left: 66.66666667%;\n  }\n\n  .offset-lg-9 {\n    margin-left: 75%;\n  }\n\n  .offset-lg-10 {\n    margin-left: 83.33333333%;\n  }\n\n  .offset-lg-11 {\n    margin-left: 91.66666667%;\n  }\n\n  .g-lg-0,\n  .gx-lg-0 {\n    --bs-gutter-x: 0;\n  }\n\n  .g-lg-0,\n  .gy-lg-0 {\n    --bs-gutter-y: 0;\n  }\n\n  .g-lg-1,\n  .gx-lg-1 {\n    --bs-gutter-x: 0.25rem;\n  }\n\n  .g-lg-1,\n  .gy-lg-1 {\n    --bs-gutter-y: 0.25rem;\n  }\n\n  .g-lg-2,\n  .gx-lg-2 {\n    --bs-gutter-x: 0.5rem;\n  }\n\n  .g-lg-2,\n  .gy-lg-2 {\n    --bs-gutter-y: 0.5rem;\n  }\n\n  .g-lg-3,\n  .gx-lg-3 {\n    --bs-gutter-x: 1rem;\n  }\n\n  .g-lg-3,\n  .gy-lg-3 {\n    --bs-gutter-y: 1rem;\n  }\n\n  .g-lg-4,\n  .gx-lg-4 {\n    --bs-gutter-x: 1.5rem;\n  }\n\n  .g-lg-4,\n  .gy-lg-4 {\n    --bs-gutter-y: 1.5rem;\n  }\n\n  .g-lg-5,\n  .gx-lg-5 {\n    --bs-gutter-x: 3rem;\n  }\n\n  .g-lg-5,\n  .gy-lg-5 {\n    --bs-gutter-y: 3rem;\n  }\n}\n\n@media (min-width: 1200px) {\n  .col-xl {\n    flex: 1 0 0%;\n  }\n\n  .row-cols-xl-auto > * {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .row-cols-xl-1 > * {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .row-cols-xl-2 > * {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .row-cols-xl-3 > * {\n    flex: 0 0 auto;\n    width: 33.3333333333%;\n  }\n\n  .row-cols-xl-4 > * {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .row-cols-xl-5 > * {\n    flex: 0 0 auto;\n    width: 20%;\n  }\n\n  .row-cols-xl-6 > * {\n    flex: 0 0 auto;\n    width: 16.6666666667%;\n  }\n\n  .col-xl-auto {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .col-xl-1 {\n    flex: 0 0 auto;\n    width: 8.33333333%;\n  }\n\n  .col-xl-2 {\n    flex: 0 0 auto;\n    width: 16.66666667%;\n  }\n\n  .col-xl-3 {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .col-xl-4 {\n    flex: 0 0 auto;\n    width: 33.33333333%;\n  }\n\n  .col-xl-5 {\n    flex: 0 0 auto;\n    width: 41.66666667%;\n  }\n\n  .col-xl-6 {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .col-xl-7 {\n    flex: 0 0 auto;\n    width: 58.33333333%;\n  }\n\n  .col-xl-8 {\n    flex: 0 0 auto;\n    width: 66.66666667%;\n  }\n\n  .col-xl-9 {\n    flex: 0 0 auto;\n    width: 75%;\n  }\n\n  .col-xl-10 {\n    flex: 0 0 auto;\n    width: 83.33333333%;\n  }\n\n  .col-xl-11 {\n    flex: 0 0 auto;\n    width: 91.66666667%;\n  }\n\n  .col-xl-12 {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .offset-xl-0 {\n    margin-left: 0;\n  }\n\n  .offset-xl-1 {\n    margin-left: 8.33333333%;\n  }\n\n  .offset-xl-2 {\n    margin-left: 16.66666667%;\n  }\n\n  .offset-xl-3 {\n    margin-left: 25%;\n  }\n\n  .offset-xl-4 {\n    margin-left: 33.33333333%;\n  }\n\n  .offset-xl-5 {\n    margin-left: 41.66666667%;\n  }\n\n  .offset-xl-6 {\n    margin-left: 50%;\n  }\n\n  .offset-xl-7 {\n    margin-left: 58.33333333%;\n  }\n\n  .offset-xl-8 {\n    margin-left: 66.66666667%;\n  }\n\n  .offset-xl-9 {\n    margin-left: 75%;\n  }\n\n  .offset-xl-10 {\n    margin-left: 83.33333333%;\n  }\n\n  .offset-xl-11 {\n    margin-left: 91.66666667%;\n  }\n\n  .g-xl-0,\n  .gx-xl-0 {\n    --bs-gutter-x: 0;\n  }\n\n  .g-xl-0,\n  .gy-xl-0 {\n    --bs-gutter-y: 0;\n  }\n\n  .g-xl-1,\n  .gx-xl-1 {\n    --bs-gutter-x: 0.25rem;\n  }\n\n  .g-xl-1,\n  .gy-xl-1 {\n    --bs-gutter-y: 0.25rem;\n  }\n\n  .g-xl-2,\n  .gx-xl-2 {\n    --bs-gutter-x: 0.5rem;\n  }\n\n  .g-xl-2,\n  .gy-xl-2 {\n    --bs-gutter-y: 0.5rem;\n  }\n\n  .g-xl-3,\n  .gx-xl-3 {\n    --bs-gutter-x: 1rem;\n  }\n\n  .g-xl-3,\n  .gy-xl-3 {\n    --bs-gutter-y: 1rem;\n  }\n\n  .g-xl-4,\n  .gx-xl-4 {\n    --bs-gutter-x: 1.5rem;\n  }\n\n  .g-xl-4,\n  .gy-xl-4 {\n    --bs-gutter-y: 1.5rem;\n  }\n\n  .g-xl-5,\n  .gx-xl-5 {\n    --bs-gutter-x: 3rem;\n  }\n\n  .g-xl-5,\n  .gy-xl-5 {\n    --bs-gutter-y: 3rem;\n  }\n}\n\n@media (min-width: 1400px) {\n  .col-xxl {\n    flex: 1 0 0%;\n  }\n\n  .row-cols-xxl-auto > * {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .row-cols-xxl-1 > * {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .row-cols-xxl-2 > * {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .row-cols-xxl-3 > * {\n    flex: 0 0 auto;\n    width: 33.3333333333%;\n  }\n\n  .row-cols-xxl-4 > * {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .row-cols-xxl-5 > * {\n    flex: 0 0 auto;\n    width: 20%;\n  }\n\n  .row-cols-xxl-6 > * {\n    flex: 0 0 auto;\n    width: 16.6666666667%;\n  }\n\n  .col-xxl-auto {\n    flex: 0 0 auto;\n    width: auto;\n  }\n\n  .col-xxl-1 {\n    flex: 0 0 auto;\n    width: 8.33333333%;\n  }\n\n  .col-xxl-2 {\n    flex: 0 0 auto;\n    width: 16.66666667%;\n  }\n\n  .col-xxl-3 {\n    flex: 0 0 auto;\n    width: 25%;\n  }\n\n  .col-xxl-4 {\n    flex: 0 0 auto;\n    width: 33.33333333%;\n  }\n\n  .col-xxl-5 {\n    flex: 0 0 auto;\n    width: 41.66666667%;\n  }\n\n  .col-xxl-6 {\n    flex: 0 0 auto;\n    width: 50%;\n  }\n\n  .col-xxl-7 {\n    flex: 0 0 auto;\n    width: 58.33333333%;\n  }\n\n  .col-xxl-8 {\n    flex: 0 0 auto;\n    width: 66.66666667%;\n  }\n\n  .col-xxl-9 {\n    flex: 0 0 auto;\n    width: 75%;\n  }\n\n  .col-xxl-10 {\n    flex: 0 0 auto;\n    width: 83.33333333%;\n  }\n\n  .col-xxl-11 {\n    flex: 0 0 auto;\n    width: 91.66666667%;\n  }\n\n  .col-xxl-12 {\n    flex: 0 0 auto;\n    width: 100%;\n  }\n\n  .offset-xxl-0 {\n    margin-left: 0;\n  }\n\n  .offset-xxl-1 {\n    margin-left: 8.33333333%;\n  }\n\n  .offset-xxl-2 {\n    margin-left: 16.66666667%;\n  }\n\n  .offset-xxl-3 {\n    margin-left: 25%;\n  }\n\n  .offset-xxl-4 {\n    margin-left: 33.33333333%;\n  }\n\n  .offset-xxl-5 {\n    margin-left: 41.66666667%;\n  }\n\n  .offset-xxl-6 {\n    margin-left: 50%;\n  }\n\n  .offset-xxl-7 {\n    margin-left: 58.33333333%;\n  }\n\n  .offset-xxl-8 {\n    margin-left: 66.66666667%;\n  }\n\n  .offset-xxl-9 {\n    margin-left: 75%;\n  }\n\n  .offset-xxl-10 {\n    margin-left: 83.33333333%;\n  }\n\n  .offset-xxl-11 {\n    margin-left: 91.66666667%;\n  }\n\n  .g-xxl-0,\n  .gx-xxl-0 {\n    --bs-gutter-x: 0;\n  }\n\n  .g-xxl-0,\n  .gy-xxl-0 {\n    --bs-gutter-y: 0;\n  }\n\n  .g-xxl-1,\n  .gx-xxl-1 {\n    --bs-gutter-x: 0.25rem;\n  }\n\n  .g-xxl-1,\n  .gy-xxl-1 {\n    --bs-gutter-y: 0.25rem;\n  }\n\n  .g-xxl-2,\n  .gx-xxl-2 {\n    --bs-gutter-x: 0.5rem;\n  }\n\n  .g-xxl-2,\n  .gy-xxl-2 {\n    --bs-gutter-y: 0.5rem;\n  }\n\n  .g-xxl-3,\n  .gx-xxl-3 {\n    --bs-gutter-x: 1rem;\n  }\n\n  .g-xxl-3,\n  .gy-xxl-3 {\n    --bs-gutter-y: 1rem;\n  }\n\n  .g-xxl-4,\n  .gx-xxl-4 {\n    --bs-gutter-x: 1.5rem;\n  }\n\n  .g-xxl-4,\n  .gy-xxl-4 {\n    --bs-gutter-y: 1.5rem;\n  }\n\n  .g-xxl-5,\n  .gx-xxl-5 {\n    --bs-gutter-x: 3rem;\n  }\n\n  .g-xxl-5,\n  .gy-xxl-5 {\n    --bs-gutter-y: 3rem;\n  }\n}\n\n.d-inline {\n  display: inline !important;\n}\n\n.d-inline-block {\n  display: inline-block !important;\n}\n\n.d-block {\n  display: block !important;\n}\n\n.d-grid {\n  display: grid !important;\n}\n\n.d-table {\n  display: table !important;\n}\n\n.d-table-row {\n  display: table-row !important;\n}\n\n.d-table-cell {\n  display: table-cell !important;\n}\n\n.d-flex {\n  display: flex !important;\n}\n\n.d-inline-flex {\n  display: inline-flex !important;\n}\n\n.d-none {\n  display: none !important;\n}\n\n.flex-fill {\n  flex: 1 1 auto !important;\n}\n\n.flex-row {\n  flex-direction: row !important;\n}\n\n.flex-column {\n  flex-direction: column !important;\n}\n\n.flex-row-reverse {\n  flex-direction: row-reverse !important;\n}\n\n.flex-column-reverse {\n  flex-direction: column-reverse !important;\n}\n\n.flex-grow-0 {\n  flex-grow: 0 !important;\n}\n\n.flex-grow-1 {\n  flex-grow: 1 !important;\n}\n\n.flex-shrink-0 {\n  flex-shrink: 0 !important;\n}\n\n.flex-shrink-1 {\n  flex-shrink: 1 !important;\n}\n\n.flex-wrap {\n  flex-wrap: wrap !important;\n}\n\n.flex-nowrap {\n  flex-wrap: nowrap !important;\n}\n\n.flex-wrap-reverse {\n  flex-wrap: wrap-reverse !important;\n}\n\n.justify-content-start {\n  justify-content: flex-start !important;\n}\n\n.justify-content-end {\n  justify-content: flex-end !important;\n}\n\n.justify-content-center {\n  justify-content: center !important;\n}\n\n.justify-content-between {\n  justify-content: space-between !important;\n}\n\n.justify-content-around {\n  justify-content: space-around !important;\n}\n\n.justify-content-evenly {\n  justify-content: space-evenly !important;\n}\n\n.align-items-start {\n  align-items: flex-start !important;\n}\n\n.align-items-end {\n  align-items: flex-end !important;\n}\n\n.align-items-center {\n  align-items: center !important;\n}\n\n.align-items-baseline {\n  align-items: baseline !important;\n}\n\n.align-items-stretch {\n  align-items: stretch !important;\n}\n\n.align-content-start {\n  align-content: flex-start !important;\n}\n\n.align-content-end {\n  align-content: flex-end !important;\n}\n\n.align-content-center {\n  align-content: center !important;\n}\n\n.align-content-between {\n  align-content: space-between !important;\n}\n\n.align-content-around {\n  align-content: space-around !important;\n}\n\n.align-content-stretch {\n  align-content: stretch !important;\n}\n\n.align-self-auto {\n  align-self: auto !important;\n}\n\n.align-self-start {\n  align-self: flex-start !important;\n}\n\n.align-self-end {\n  align-self: flex-end !important;\n}\n\n.align-self-center {\n  align-self: center !important;\n}\n\n.align-self-baseline {\n  align-self: baseline !important;\n}\n\n.align-self-stretch {\n  align-self: stretch !important;\n}\n\n.order-first {\n  order: -1 !important;\n}\n\n.order-0 {\n  order: 0 !important;\n}\n\n.order-1 {\n  order: 1 !important;\n}\n\n.order-2 {\n  order: 2 !important;\n}\n\n.order-3 {\n  order: 3 !important;\n}\n\n.order-4 {\n  order: 4 !important;\n}\n\n.order-5 {\n  order: 5 !important;\n}\n\n.order-last {\n  order: 6 !important;\n}\n\n.m-0 {\n  margin: 0 !important;\n}\n\n.m-1 {\n  margin: 0.25rem !important;\n}\n\n.m-2 {\n  margin: 0.5rem !important;\n}\n\n.m-3 {\n  margin: 1rem !important;\n}\n\n.m-4 {\n  margin: 1.5rem !important;\n}\n\n.m-5 {\n  margin: 3rem !important;\n}\n\n.m-auto {\n  margin: auto !important;\n}\n\n.mx-0 {\n  margin-right: 0 !important;\n  margin-left: 0 !important;\n}\n\n.mx-1 {\n  margin-right: 0.25rem !important;\n  margin-left: 0.25rem !important;\n}\n\n.mx-2 {\n  margin-right: 0.5rem !important;\n  margin-left: 0.5rem !important;\n}\n\n.mx-3 {\n  margin-right: 1rem !important;\n  margin-left: 1rem !important;\n}\n\n.mx-4 {\n  margin-right: 1.5rem !important;\n  margin-left: 1.5rem !important;\n}\n\n.mx-5 {\n  margin-right: 3rem !important;\n  margin-left: 3rem !important;\n}\n\n.mx-auto {\n  margin-right: auto !important;\n  margin-left: auto !important;\n}\n\n.my-0 {\n  margin-top: 0 !important;\n  margin-bottom: 0 !important;\n}\n\n.my-1 {\n  margin-top: 0.25rem !important;\n  margin-bottom: 0.25rem !important;\n}\n\n.my-2 {\n  margin-top: 0.5rem !important;\n  margin-bottom: 0.5rem !important;\n}\n\n.my-3 {\n  margin-top: 1rem !important;\n  margin-bottom: 1rem !important;\n}\n\n.my-4 {\n  margin-top: 1.5rem !important;\n  margin-bottom: 1.5rem !important;\n}\n\n.my-5 {\n  margin-top: 3rem !important;\n  margin-bottom: 3rem !important;\n}\n\n.my-auto {\n  margin-top: auto !important;\n  margin-bottom: auto !important;\n}\n\n.mt-0 {\n  margin-top: 0 !important;\n}\n\n.mt-1 {\n  margin-top: 0.25rem !important;\n}\n\n.mt-2 {\n  margin-top: 0.5rem !important;\n}\n\n.mt-3 {\n  margin-top: 1rem !important;\n}\n\n.mt-4 {\n  margin-top: 1.5rem !important;\n}\n\n.mt-5 {\n  margin-top: 3rem !important;\n}\n\n.mt-auto {\n  margin-top: auto !important;\n}\n\n.me-0 {\n  margin-right: 0 !important;\n}\n\n.me-1 {\n  margin-right: 0.25rem !important;\n}\n\n.me-2 {\n  margin-right: 0.5rem !important;\n}\n\n.me-3 {\n  margin-right: 1rem !important;\n}\n\n.me-4 {\n  margin-right: 1.5rem !important;\n}\n\n.me-5 {\n  margin-right: 3rem !important;\n}\n\n.me-auto {\n  margin-right: auto !important;\n}\n\n.mb-0 {\n  margin-bottom: 0 !important;\n}\n\n.mb-1 {\n  margin-bottom: 0.25rem !important;\n}\n\n.mb-2 {\n  margin-bottom: 0.5rem !important;\n}\n\n.mb-3 {\n  margin-bottom: 1rem !important;\n}\n\n.mb-4 {\n  margin-bottom: 1.5rem !important;\n}\n\n.mb-5 {\n  margin-bottom: 3rem !important;\n}\n\n.mb-auto {\n  margin-bottom: auto !important;\n}\n\n.ms-0 {\n  margin-left: 0 !important;\n}\n\n.ms-1 {\n  margin-left: 0.25rem !important;\n}\n\n.ms-2 {\n  margin-left: 0.5rem !important;\n}\n\n.ms-3 {\n  margin-left: 1rem !important;\n}\n\n.ms-4 {\n  margin-left: 1.5rem !important;\n}\n\n.ms-5 {\n  margin-left: 3rem !important;\n}\n\n.ms-auto {\n  margin-left: auto !important;\n}\n\n.p-0 {\n  padding: 0 !important;\n}\n\n.p-1 {\n  padding: 0.25rem !important;\n}\n\n.p-2 {\n  padding: 0.5rem !important;\n}\n\n.p-3 {\n  padding: 1rem !important;\n}\n\n.p-4 {\n  padding: 1.5rem !important;\n}\n\n.p-5 {\n  padding: 3rem !important;\n}\n\n.px-0 {\n  padding-right: 0 !important;\n  padding-left: 0 !important;\n}\n\n.px-1 {\n  padding-right: 0.25rem !important;\n  padding-left: 0.25rem !important;\n}\n\n.px-2 {\n  padding-right: 0.5rem !important;\n  padding-left: 0.5rem !important;\n}\n\n.px-3 {\n  padding-right: 1rem !important;\n  padding-left: 1rem !important;\n}\n\n.px-4 {\n  padding-right: 1.5rem !important;\n  padding-left: 1.5rem !important;\n}\n\n.px-5 {\n  padding-right: 3rem !important;\n  padding-left: 3rem !important;\n}\n\n.py-0 {\n  padding-top: 0 !important;\n  padding-bottom: 0 !important;\n}\n\n.py-1 {\n  padding-top: 0.25rem !important;\n  padding-bottom: 0.25rem !important;\n}\n\n.py-2 {\n  padding-top: 0.5rem !important;\n  padding-bottom: 0.5rem !important;\n}\n\n.py-3 {\n  padding-top: 1rem !important;\n  padding-bottom: 1rem !important;\n}\n\n.py-4 {\n  padding-top: 1.5rem !important;\n  padding-bottom: 1.5rem !important;\n}\n\n.py-5 {\n  padding-top: 3rem !important;\n  padding-bottom: 3rem !important;\n}\n\n.pt-0 {\n  padding-top: 0 !important;\n}\n\n.pt-1 {\n  padding-top: 0.25rem !important;\n}\n\n.pt-2 {\n  padding-top: 0.5rem !important;\n}\n\n.pt-3 {\n  padding-top: 1rem !important;\n}\n\n.pt-4 {\n  padding-top: 1.5rem !important;\n}\n\n.pt-5 {\n  padding-top: 3rem !important;\n}\n\n.pe-0 {\n  padding-right: 0 !important;\n}\n\n.pe-1 {\n  padding-right: 0.25rem !important;\n}\n\n.pe-2 {\n  padding-right: 0.5rem !important;\n}\n\n.pe-3 {\n  padding-right: 1rem !important;\n}\n\n.pe-4 {\n  padding-right: 1.5rem !important;\n}\n\n.pe-5 {\n  padding-right: 3rem !important;\n}\n\n.pb-0 {\n  padding-bottom: 0 !important;\n}\n\n.pb-1 {\n  padding-bottom: 0.25rem !important;\n}\n\n.pb-2 {\n  padding-bottom: 0.5rem !important;\n}\n\n.pb-3 {\n  padding-bottom: 1rem !important;\n}\n\n.pb-4 {\n  padding-bottom: 1.5rem !important;\n}\n\n.pb-5 {\n  padding-bottom: 3rem !important;\n}\n\n.ps-0 {\n  padding-left: 0 !important;\n}\n\n.ps-1 {\n  padding-left: 0.25rem !important;\n}\n\n.ps-2 {\n  padding-left: 0.5rem !important;\n}\n\n.ps-3 {\n  padding-left: 1rem !important;\n}\n\n.ps-4 {\n  padding-left: 1.5rem !important;\n}\n\n.ps-5 {\n  padding-left: 3rem !important;\n}\n\n@media (min-width: 576px) {\n  .d-sm-inline {\n    display: inline !important;\n  }\n\n  .d-sm-inline-block {\n    display: inline-block !important;\n  }\n\n  .d-sm-block {\n    display: block !important;\n  }\n\n  .d-sm-grid {\n    display: grid !important;\n  }\n\n  .d-sm-table {\n    display: table !important;\n  }\n\n  .d-sm-table-row {\n    display: table-row !important;\n  }\n\n  .d-sm-table-cell {\n    display: table-cell !important;\n  }\n\n  .d-sm-flex {\n    display: flex !important;\n  }\n\n  .d-sm-inline-flex {\n    display: inline-flex !important;\n  }\n\n  .d-sm-none {\n    display: none !important;\n  }\n\n  .flex-sm-fill {\n    flex: 1 1 auto !important;\n  }\n\n  .flex-sm-row {\n    flex-direction: row !important;\n  }\n\n  .flex-sm-column {\n    flex-direction: column !important;\n  }\n\n  .flex-sm-row-reverse {\n    flex-direction: row-reverse !important;\n  }\n\n  .flex-sm-column-reverse {\n    flex-direction: column-reverse !important;\n  }\n\n  .flex-sm-grow-0 {\n    flex-grow: 0 !important;\n  }\n\n  .flex-sm-grow-1 {\n    flex-grow: 1 !important;\n  }\n\n  .flex-sm-shrink-0 {\n    flex-shrink: 0 !important;\n  }\n\n  .flex-sm-shrink-1 {\n    flex-shrink: 1 !important;\n  }\n\n  .flex-sm-wrap {\n    flex-wrap: wrap !important;\n  }\n\n  .flex-sm-nowrap {\n    flex-wrap: nowrap !important;\n  }\n\n  .flex-sm-wrap-reverse {\n    flex-wrap: wrap-reverse !important;\n  }\n\n  .justify-content-sm-start {\n    justify-content: flex-start !important;\n  }\n\n  .justify-content-sm-end {\n    justify-content: flex-end !important;\n  }\n\n  .justify-content-sm-center {\n    justify-content: center !important;\n  }\n\n  .justify-content-sm-between {\n    justify-content: space-between !important;\n  }\n\n  .justify-content-sm-around {\n    justify-content: space-around !important;\n  }\n\n  .justify-content-sm-evenly {\n    justify-content: space-evenly !important;\n  }\n\n  .align-items-sm-start {\n    align-items: flex-start !important;\n  }\n\n  .align-items-sm-end {\n    align-items: flex-end !important;\n  }\n\n  .align-items-sm-center {\n    align-items: center !important;\n  }\n\n  .align-items-sm-baseline {\n    align-items: baseline !important;\n  }\n\n  .align-items-sm-stretch {\n    align-items: stretch !important;\n  }\n\n  .align-content-sm-start {\n    align-content: flex-start !important;\n  }\n\n  .align-content-sm-end {\n    align-content: flex-end !important;\n  }\n\n  .align-content-sm-center {\n    align-content: center !important;\n  }\n\n  .align-content-sm-between {\n    align-content: space-between !important;\n  }\n\n  .align-content-sm-around {\n    align-content: space-around !important;\n  }\n\n  .align-content-sm-stretch {\n    align-content: stretch !important;\n  }\n\n  .align-self-sm-auto {\n    align-self: auto !important;\n  }\n\n  .align-self-sm-start {\n    align-self: flex-start !important;\n  }\n\n  .align-self-sm-end {\n    align-self: flex-end !important;\n  }\n\n  .align-self-sm-center {\n    align-self: center !important;\n  }\n\n  .align-self-sm-baseline {\n    align-self: baseline !important;\n  }\n\n  .align-self-sm-stretch {\n    align-self: stretch !important;\n  }\n\n  .order-sm-first {\n    order: -1 !important;\n  }\n\n  .order-sm-0 {\n    order: 0 !important;\n  }\n\n  .order-sm-1 {\n    order: 1 !important;\n  }\n\n  .order-sm-2 {\n    order: 2 !important;\n  }\n\n  .order-sm-3 {\n    order: 3 !important;\n  }\n\n  .order-sm-4 {\n    order: 4 !important;\n  }\n\n  .order-sm-5 {\n    order: 5 !important;\n  }\n\n  .order-sm-last {\n    order: 6 !important;\n  }\n\n  .m-sm-0 {\n    margin: 0 !important;\n  }\n\n  .m-sm-1 {\n    margin: 0.25rem !important;\n  }\n\n  .m-sm-2 {\n    margin: 0.5rem !important;\n  }\n\n  .m-sm-3 {\n    margin: 1rem !important;\n  }\n\n  .m-sm-4 {\n    margin: 1.5rem !important;\n  }\n\n  .m-sm-5 {\n    margin: 3rem !important;\n  }\n\n  .m-sm-auto {\n    margin: auto !important;\n  }\n\n  .mx-sm-0 {\n    margin-right: 0 !important;\n    margin-left: 0 !important;\n  }\n\n  .mx-sm-1 {\n    margin-right: 0.25rem !important;\n    margin-left: 0.25rem !important;\n  }\n\n  .mx-sm-2 {\n    margin-right: 0.5rem !important;\n    margin-left: 0.5rem !important;\n  }\n\n  .mx-sm-3 {\n    margin-right: 1rem !important;\n    margin-left: 1rem !important;\n  }\n\n  .mx-sm-4 {\n    margin-right: 1.5rem !important;\n    margin-left: 1.5rem !important;\n  }\n\n  .mx-sm-5 {\n    margin-right: 3rem !important;\n    margin-left: 3rem !important;\n  }\n\n  .mx-sm-auto {\n    margin-right: auto !important;\n    margin-left: auto !important;\n  }\n\n  .my-sm-0 {\n    margin-top: 0 !important;\n    margin-bottom: 0 !important;\n  }\n\n  .my-sm-1 {\n    margin-top: 0.25rem !important;\n    margin-bottom: 0.25rem !important;\n  }\n\n  .my-sm-2 {\n    margin-top: 0.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .my-sm-3 {\n    margin-top: 1rem !important;\n    margin-bottom: 1rem !important;\n  }\n\n  .my-sm-4 {\n    margin-top: 1.5rem !important;\n    margin-bottom: 1.5rem !important;\n  }\n\n  .my-sm-5 {\n    margin-top: 3rem !important;\n    margin-bottom: 3rem !important;\n  }\n\n  .my-sm-auto {\n    margin-top: auto !important;\n    margin-bottom: auto !important;\n  }\n\n  .mt-sm-0 {\n    margin-top: 0 !important;\n  }\n\n  .mt-sm-1 {\n    margin-top: 0.25rem !important;\n  }\n\n  .mt-sm-2 {\n    margin-top: 0.5rem !important;\n  }\n\n  .mt-sm-3 {\n    margin-top: 1rem !important;\n  }\n\n  .mt-sm-4 {\n    margin-top: 1.5rem !important;\n  }\n\n  .mt-sm-5 {\n    margin-top: 3rem !important;\n  }\n\n  .mt-sm-auto {\n    margin-top: auto !important;\n  }\n\n  .me-sm-0 {\n    margin-right: 0 !important;\n  }\n\n  .me-sm-1 {\n    margin-right: 0.25rem !important;\n  }\n\n  .me-sm-2 {\n    margin-right: 0.5rem !important;\n  }\n\n  .me-sm-3 {\n    margin-right: 1rem !important;\n  }\n\n  .me-sm-4 {\n    margin-right: 1.5rem !important;\n  }\n\n  .me-sm-5 {\n    margin-right: 3rem !important;\n  }\n\n  .me-sm-auto {\n    margin-right: auto !important;\n  }\n\n  .mb-sm-0 {\n    margin-bottom: 0 !important;\n  }\n\n  .mb-sm-1 {\n    margin-bottom: 0.25rem !important;\n  }\n\n  .mb-sm-2 {\n    margin-bottom: 0.5rem !important;\n  }\n\n  .mb-sm-3 {\n    margin-bottom: 1rem !important;\n  }\n\n  .mb-sm-4 {\n    margin-bottom: 1.5rem !important;\n  }\n\n  .mb-sm-5 {\n    margin-bottom: 3rem !important;\n  }\n\n  .mb-sm-auto {\n    margin-bottom: auto !important;\n  }\n\n  .ms-sm-0 {\n    margin-left: 0 !important;\n  }\n\n  .ms-sm-1 {\n    margin-left: 0.25rem !important;\n  }\n\n  .ms-sm-2 {\n    margin-left: 0.5rem !important;\n  }\n\n  .ms-sm-3 {\n    margin-left: 1rem !important;\n  }\n\n  .ms-sm-4 {\n    margin-left: 1.5rem !important;\n  }\n\n  .ms-sm-5 {\n    margin-left: 3rem !important;\n  }\n\n  .ms-sm-auto {\n    margin-left: auto !important;\n  }\n\n  .p-sm-0 {\n    padding: 0 !important;\n  }\n\n  .p-sm-1 {\n    padding: 0.25rem !important;\n  }\n\n  .p-sm-2 {\n    padding: 0.5rem !important;\n  }\n\n  .p-sm-3 {\n    padding: 1rem !important;\n  }\n\n  .p-sm-4 {\n    padding: 1.5rem !important;\n  }\n\n  .p-sm-5 {\n    padding: 3rem !important;\n  }\n\n  .px-sm-0 {\n    padding-right: 0 !important;\n    padding-left: 0 !important;\n  }\n\n  .px-sm-1 {\n    padding-right: 0.25rem !important;\n    padding-left: 0.25rem !important;\n  }\n\n  .px-sm-2 {\n    padding-right: 0.5rem !important;\n    padding-left: 0.5rem !important;\n  }\n\n  .px-sm-3 {\n    padding-right: 1rem !important;\n    padding-left: 1rem !important;\n  }\n\n  .px-sm-4 {\n    padding-right: 1.5rem !important;\n    padding-left: 1.5rem !important;\n  }\n\n  .px-sm-5 {\n    padding-right: 3rem !important;\n    padding-left: 3rem !important;\n  }\n\n  .py-sm-0 {\n    padding-top: 0 !important;\n    padding-bottom: 0 !important;\n  }\n\n  .py-sm-1 {\n    padding-top: 0.25rem !important;\n    padding-bottom: 0.25rem !important;\n  }\n\n  .py-sm-2 {\n    padding-top: 0.5rem !important;\n    padding-bottom: 0.5rem !important;\n  }\n\n  .py-sm-3 {\n    padding-top: 1rem !important;\n    padding-bottom: 1rem !important;\n  }\n\n  .py-sm-4 {\n    padding-top: 1.5rem !important;\n    padding-bottom: 1.5rem !important;\n  }\n\n  .py-sm-5 {\n    padding-top: 3rem !important;\n    padding-bottom: 3rem !important;\n  }\n\n  .pt-sm-0 {\n    padding-top: 0 !important;\n  }\n\n  .pt-sm-1 {\n    padding-top: 0.25rem !important;\n  }\n\n  .pt-sm-2 {\n    padding-top: 0.5rem !important;\n  }\n\n  .pt-sm-3 {\n    padding-top: 1rem !important;\n  }\n\n  .pt-sm-4 {\n    padding-top: 1.5rem !important;\n  }\n\n  .pt-sm-5 {\n    padding-top: 3rem !important;\n  }\n\n  .pe-sm-0 {\n    padding-right: 0 !important;\n  }\n\n  .pe-sm-1 {\n    padding-right: 0.25rem !important;\n  }\n\n  .pe-sm-2 {\n    padding-right: 0.5rem !important;\n  }\n\n  .pe-sm-3 {\n    padding-right: 1rem !important;\n  }\n\n  .pe-sm-4 {\n    padding-right: 1.5rem !important;\n  }\n\n  .pe-sm-5 {\n    padding-right: 3rem !important;\n  }\n\n  .pb-sm-0 {\n    padding-bottom: 0 !important;\n  }\n\n  .pb-sm-1 {\n    padding-bottom: 0.25rem !important;\n  }\n\n  .pb-sm-2 {\n    padding-bottom: 0.5rem !important;\n  }\n\n  .pb-sm-3 {\n    padding-bottom: 1rem !important;\n  }\n\n  .pb-sm-4 {\n    padding-bottom: 1.5rem !important;\n  }\n\n  .pb-sm-5 {\n    padding-bottom: 3rem !important;\n  }\n\n  .ps-sm-0 {\n    padding-left: 0 !important;\n  }\n\n  .ps-sm-1 {\n    padding-left: 0.25rem !important;\n  }\n\n  .ps-sm-2 {\n    padding-left: 0.5rem !important;\n  }\n\n  .ps-sm-3 {\n    padding-left: 1rem !important;\n  }\n\n  .ps-sm-4 {\n    padding-left: 1.5rem !important;\n  }\n\n  .ps-sm-5 {\n    padding-left: 3rem !important;\n  }\n}\n\n@media (min-width: 768px) {\n  .d-md-inline {\n    display: inline !important;\n  }\n\n  .d-md-inline-block {\n    display: inline-block !important;\n  }\n\n  .d-md-block {\n    display: block !important;\n  }\n\n  .d-md-grid {\n    display: grid !important;\n  }\n\n  .d-md-table {\n    display: table !important;\n  }\n\n  .d-md-table-row {\n    display: table-row !important;\n  }\n\n  .d-md-table-cell {\n    display: table-cell !important;\n  }\n\n  .d-md-flex {\n    display: flex !important;\n  }\n\n  .d-md-inline-flex {\n    display: inline-flex !important;\n  }\n\n  .d-md-none {\n    display: none !important;\n  }\n\n  .flex-md-fill {\n    flex: 1 1 auto !important;\n  }\n\n  .flex-md-row {\n    flex-direction: row !important;\n  }\n\n  .flex-md-column {\n    flex-direction: column !important;\n  }\n\n  .flex-md-row-reverse {\n    flex-direction: row-reverse !important;\n  }\n\n  .flex-md-column-reverse {\n    flex-direction: column-reverse !important;\n  }\n\n  .flex-md-grow-0 {\n    flex-grow: 0 !important;\n  }\n\n  .flex-md-grow-1 {\n    flex-grow: 1 !important;\n  }\n\n  .flex-md-shrink-0 {\n    flex-shrink: 0 !important;\n  }\n\n  .flex-md-shrink-1 {\n    flex-shrink: 1 !important;\n  }\n\n  .flex-md-wrap {\n    flex-wrap: wrap !important;\n  }\n\n  .flex-md-nowrap {\n    flex-wrap: nowrap !important;\n  }\n\n  .flex-md-wrap-reverse {\n    flex-wrap: wrap-reverse !important;\n  }\n\n  .justify-content-md-start {\n    justify-content: flex-start !important;\n  }\n\n  .justify-content-md-end {\n    justify-content: flex-end !important;\n  }\n\n  .justify-content-md-center {\n    justify-content: center !important;\n  }\n\n  .justify-content-md-between {\n    justify-content: space-between !important;\n  }\n\n  .justify-content-md-around {\n    justify-content: space-around !important;\n  }\n\n  .justify-content-md-evenly {\n    justify-content: space-evenly !important;\n  }\n\n  .align-items-md-start {\n    align-items: flex-start !important;\n  }\n\n  .align-items-md-end {\n    align-items: flex-end !important;\n  }\n\n  .align-items-md-center {\n    align-items: center !important;\n  }\n\n  .align-items-md-baseline {\n    align-items: baseline !important;\n  }\n\n  .align-items-md-stretch {\n    align-items: stretch !important;\n  }\n\n  .align-content-md-start {\n    align-content: flex-start !important;\n  }\n\n  .align-content-md-end {\n    align-content: flex-end !important;\n  }\n\n  .align-content-md-center {\n    align-content: center !important;\n  }\n\n  .align-content-md-between {\n    align-content: space-between !important;\n  }\n\n  .align-content-md-around {\n    align-content: space-around !important;\n  }\n\n  .align-content-md-stretch {\n    align-content: stretch !important;\n  }\n\n  .align-self-md-auto {\n    align-self: auto !important;\n  }\n\n  .align-self-md-start {\n    align-self: flex-start !important;\n  }\n\n  .align-self-md-end {\n    align-self: flex-end !important;\n  }\n\n  .align-self-md-center {\n    align-self: center !important;\n  }\n\n  .align-self-md-baseline {\n    align-self: baseline !important;\n  }\n\n  .align-self-md-stretch {\n    align-self: stretch !important;\n  }\n\n  .order-md-first {\n    order: -1 !important;\n  }\n\n  .order-md-0 {\n    order: 0 !important;\n  }\n\n  .order-md-1 {\n    order: 1 !important;\n  }\n\n  .order-md-2 {\n    order: 2 !important;\n  }\n\n  .order-md-3 {\n    order: 3 !important;\n  }\n\n  .order-md-4 {\n    order: 4 !important;\n  }\n\n  .order-md-5 {\n    order: 5 !important;\n  }\n\n  .order-md-last {\n    order: 6 !important;\n  }\n\n  .m-md-0 {\n    margin: 0 !important;\n  }\n\n  .m-md-1 {\n    margin: 0.25rem !important;\n  }\n\n  .m-md-2 {\n    margin: 0.5rem !important;\n  }\n\n  .m-md-3 {\n    margin: 1rem !important;\n  }\n\n  .m-md-4 {\n    margin: 1.5rem !important;\n  }\n\n  .m-md-5 {\n    margin: 3rem !important;\n  }\n\n  .m-md-auto {\n    margin: auto !important;\n  }\n\n  .mx-md-0 {\n    margin-right: 0 !important;\n    margin-left: 0 !important;\n  }\n\n  .mx-md-1 {\n    margin-right: 0.25rem !important;\n    margin-left: 0.25rem !important;\n  }\n\n  .mx-md-2 {\n    margin-right: 0.5rem !important;\n    margin-left: 0.5rem !important;\n  }\n\n  .mx-md-3 {\n    margin-right: 1rem !important;\n    margin-left: 1rem !important;\n  }\n\n  .mx-md-4 {\n    margin-right: 1.5rem !important;\n    margin-left: 1.5rem !important;\n  }\n\n  .mx-md-5 {\n    margin-right: 3rem !important;\n    margin-left: 3rem !important;\n  }\n\n  .mx-md-auto {\n    margin-right: auto !important;\n    margin-left: auto !important;\n  }\n\n  .my-md-0 {\n    margin-top: 0 !important;\n    margin-bottom: 0 !important;\n  }\n\n  .my-md-1 {\n    margin-top: 0.25rem !important;\n    margin-bottom: 0.25rem !important;\n  }\n\n  .my-md-2 {\n    margin-top: 0.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .my-md-3 {\n    margin-top: 1rem !important;\n    margin-bottom: 1rem !important;\n  }\n\n  .my-md-4 {\n    margin-top: 1.5rem !important;\n    margin-bottom: 1.5rem !important;\n  }\n\n  .my-md-5 {\n    margin-top: 3rem !important;\n    margin-bottom: 3rem !important;\n  }\n\n  .my-md-auto {\n    margin-top: auto !important;\n    margin-bottom: auto !important;\n  }\n\n  .mt-md-0 {\n    margin-top: 0 !important;\n  }\n\n  .mt-md-1 {\n    margin-top: 0.25rem !important;\n  }\n\n  .mt-md-2 {\n    margin-top: 0.5rem !important;\n  }\n\n  .mt-md-3 {\n    margin-top: 1rem !important;\n  }\n\n  .mt-md-4 {\n    margin-top: 1.5rem !important;\n  }\n\n  .mt-md-5 {\n    margin-top: 3rem !important;\n  }\n\n  .mt-md-auto {\n    margin-top: auto !important;\n  }\n\n  .me-md-0 {\n    margin-right: 0 !important;\n  }\n\n  .me-md-1 {\n    margin-right: 0.25rem !important;\n  }\n\n  .me-md-2 {\n    margin-right: 0.5rem !important;\n  }\n\n  .me-md-3 {\n    margin-right: 1rem !important;\n  }\n\n  .me-md-4 {\n    margin-right: 1.5rem !important;\n  }\n\n  .me-md-5 {\n    margin-right: 3rem !important;\n  }\n\n  .me-md-auto {\n    margin-right: auto !important;\n  }\n\n  .mb-md-0 {\n    margin-bottom: 0 !important;\n  }\n\n  .mb-md-1 {\n    margin-bottom: 0.25rem !important;\n  }\n\n  .mb-md-2 {\n    margin-bottom: 0.5rem !important;\n  }\n\n  .mb-md-3 {\n    margin-bottom: 1rem !important;\n  }\n\n  .mb-md-4 {\n    margin-bottom: 1.5rem !important;\n  }\n\n  .mb-md-5 {\n    margin-bottom: 3rem !important;\n  }\n\n  .mb-md-auto {\n    margin-bottom: auto !important;\n  }\n\n  .ms-md-0 {\n    margin-left: 0 !important;\n  }\n\n  .ms-md-1 {\n    margin-left: 0.25rem !important;\n  }\n\n  .ms-md-2 {\n    margin-left: 0.5rem !important;\n  }\n\n  .ms-md-3 {\n    margin-left: 1rem !important;\n  }\n\n  .ms-md-4 {\n    margin-left: 1.5rem !important;\n  }\n\n  .ms-md-5 {\n    margin-left: 3rem !important;\n  }\n\n  .ms-md-auto {\n    margin-left: auto !important;\n  }\n\n  .p-md-0 {\n    padding: 0 !important;\n  }\n\n  .p-md-1 {\n    padding: 0.25rem !important;\n  }\n\n  .p-md-2 {\n    padding: 0.5rem !important;\n  }\n\n  .p-md-3 {\n    padding: 1rem !important;\n  }\n\n  .p-md-4 {\n    padding: 1.5rem !important;\n  }\n\n  .p-md-5 {\n    padding: 3rem !important;\n  }\n\n  .px-md-0 {\n    padding-right: 0 !important;\n    padding-left: 0 !important;\n  }\n\n  .px-md-1 {\n    padding-right: 0.25rem !important;\n    padding-left: 0.25rem !important;\n  }\n\n  .px-md-2 {\n    padding-right: 0.5rem !important;\n    padding-left: 0.5rem !important;\n  }\n\n  .px-md-3 {\n    padding-right: 1rem !important;\n    padding-left: 1rem !important;\n  }\n\n  .px-md-4 {\n    padding-right: 1.5rem !important;\n    padding-left: 1.5rem !important;\n  }\n\n  .px-md-5 {\n    padding-right: 3rem !important;\n    padding-left: 3rem !important;\n  }\n\n  .py-md-0 {\n    padding-top: 0 !important;\n    padding-bottom: 0 !important;\n  }\n\n  .py-md-1 {\n    padding-top: 0.25rem !important;\n    padding-bottom: 0.25rem !important;\n  }\n\n  .py-md-2 {\n    padding-top: 0.5rem !important;\n    padding-bottom: 0.5rem !important;\n  }\n\n  .py-md-3 {\n    padding-top: 1rem !important;\n    padding-bottom: 1rem !important;\n  }\n\n  .py-md-4 {\n    padding-top: 1.5rem !important;\n    padding-bottom: 1.5rem !important;\n  }\n\n  .py-md-5 {\n    padding-top: 3rem !important;\n    padding-bottom: 3rem !important;\n  }\n\n  .pt-md-0 {\n    padding-top: 0 !important;\n  }\n\n  .pt-md-1 {\n    padding-top: 0.25rem !important;\n  }\n\n  .pt-md-2 {\n    padding-top: 0.5rem !important;\n  }\n\n  .pt-md-3 {\n    padding-top: 1rem !important;\n  }\n\n  .pt-md-4 {\n    padding-top: 1.5rem !important;\n  }\n\n  .pt-md-5 {\n    padding-top: 3rem !important;\n  }\n\n  .pe-md-0 {\n    padding-right: 0 !important;\n  }\n\n  .pe-md-1 {\n    padding-right: 0.25rem !important;\n  }\n\n  .pe-md-2 {\n    padding-right: 0.5rem !important;\n  }\n\n  .pe-md-3 {\n    padding-right: 1rem !important;\n  }\n\n  .pe-md-4 {\n    padding-right: 1.5rem !important;\n  }\n\n  .pe-md-5 {\n    padding-right: 3rem !important;\n  }\n\n  .pb-md-0 {\n    padding-bottom: 0 !important;\n  }\n\n  .pb-md-1 {\n    padding-bottom: 0.25rem !important;\n  }\n\n  .pb-md-2 {\n    padding-bottom: 0.5rem !important;\n  }\n\n  .pb-md-3 {\n    padding-bottom: 1rem !important;\n  }\n\n  .pb-md-4 {\n    padding-bottom: 1.5rem !important;\n  }\n\n  .pb-md-5 {\n    padding-bottom: 3rem !important;\n  }\n\n  .ps-md-0 {\n    padding-left: 0 !important;\n  }\n\n  .ps-md-1 {\n    padding-left: 0.25rem !important;\n  }\n\n  .ps-md-2 {\n    padding-left: 0.5rem !important;\n  }\n\n  .ps-md-3 {\n    padding-left: 1rem !important;\n  }\n\n  .ps-md-4 {\n    padding-left: 1.5rem !important;\n  }\n\n  .ps-md-5 {\n    padding-left: 3rem !important;\n  }\n}\n\n@media (min-width: 992px) {\n  .d-lg-inline {\n    display: inline !important;\n  }\n\n  .d-lg-inline-block {\n    display: inline-block !important;\n  }\n\n  .d-lg-block {\n    display: block !important;\n  }\n\n  .d-lg-grid {\n    display: grid !important;\n  }\n\n  .d-lg-table {\n    display: table !important;\n  }\n\n  .d-lg-table-row {\n    display: table-row !important;\n  }\n\n  .d-lg-table-cell {\n    display: table-cell !important;\n  }\n\n  .d-lg-flex {\n    display: flex !important;\n  }\n\n  .d-lg-inline-flex {\n    display: inline-flex !important;\n  }\n\n  .d-lg-none {\n    display: none !important;\n  }\n\n  .flex-lg-fill {\n    flex: 1 1 auto !important;\n  }\n\n  .flex-lg-row {\n    flex-direction: row !important;\n  }\n\n  .flex-lg-column {\n    flex-direction: column !important;\n  }\n\n  .flex-lg-row-reverse {\n    flex-direction: row-reverse !important;\n  }\n\n  .flex-lg-column-reverse {\n    flex-direction: column-reverse !important;\n  }\n\n  .flex-lg-grow-0 {\n    flex-grow: 0 !important;\n  }\n\n  .flex-lg-grow-1 {\n    flex-grow: 1 !important;\n  }\n\n  .flex-lg-shrink-0 {\n    flex-shrink: 0 !important;\n  }\n\n  .flex-lg-shrink-1 {\n    flex-shrink: 1 !important;\n  }\n\n  .flex-lg-wrap {\n    flex-wrap: wrap !important;\n  }\n\n  .flex-lg-nowrap {\n    flex-wrap: nowrap !important;\n  }\n\n  .flex-lg-wrap-reverse {\n    flex-wrap: wrap-reverse !important;\n  }\n\n  .justify-content-lg-start {\n    justify-content: flex-start !important;\n  }\n\n  .justify-content-lg-end {\n    justify-content: flex-end !important;\n  }\n\n  .justify-content-lg-center {\n    justify-content: center !important;\n  }\n\n  .justify-content-lg-between {\n    justify-content: space-between !important;\n  }\n\n  .justify-content-lg-around {\n    justify-content: space-around !important;\n  }\n\n  .justify-content-lg-evenly {\n    justify-content: space-evenly !important;\n  }\n\n  .align-items-lg-start {\n    align-items: flex-start !important;\n  }\n\n  .align-items-lg-end {\n    align-items: flex-end !important;\n  }\n\n  .align-items-lg-center {\n    align-items: center !important;\n  }\n\n  .align-items-lg-baseline {\n    align-items: baseline !important;\n  }\n\n  .align-items-lg-stretch {\n    align-items: stretch !important;\n  }\n\n  .align-content-lg-start {\n    align-content: flex-start !important;\n  }\n\n  .align-content-lg-end {\n    align-content: flex-end !important;\n  }\n\n  .align-content-lg-center {\n    align-content: center !important;\n  }\n\n  .align-content-lg-between {\n    align-content: space-between !important;\n  }\n\n  .align-content-lg-around {\n    align-content: space-around !important;\n  }\n\n  .align-content-lg-stretch {\n    align-content: stretch !important;\n  }\n\n  .align-self-lg-auto {\n    align-self: auto !important;\n  }\n\n  .align-self-lg-start {\n    align-self: flex-start !important;\n  }\n\n  .align-self-lg-end {\n    align-self: flex-end !important;\n  }\n\n  .align-self-lg-center {\n    align-self: center !important;\n  }\n\n  .align-self-lg-baseline {\n    align-self: baseline !important;\n  }\n\n  .align-self-lg-stretch {\n    align-self: stretch !important;\n  }\n\n  .order-lg-first {\n    order: -1 !important;\n  }\n\n  .order-lg-0 {\n    order: 0 !important;\n  }\n\n  .order-lg-1 {\n    order: 1 !important;\n  }\n\n  .order-lg-2 {\n    order: 2 !important;\n  }\n\n  .order-lg-3 {\n    order: 3 !important;\n  }\n\n  .order-lg-4 {\n    order: 4 !important;\n  }\n\n  .order-lg-5 {\n    order: 5 !important;\n  }\n\n  .order-lg-last {\n    order: 6 !important;\n  }\n\n  .m-lg-0 {\n    margin: 0 !important;\n  }\n\n  .m-lg-1 {\n    margin: 0.25rem !important;\n  }\n\n  .m-lg-2 {\n    margin: 0.5rem !important;\n  }\n\n  .m-lg-3 {\n    margin: 1rem !important;\n  }\n\n  .m-lg-4 {\n    margin: 1.5rem !important;\n  }\n\n  .m-lg-5 {\n    margin: 3rem !important;\n  }\n\n  .m-lg-auto {\n    margin: auto !important;\n  }\n\n  .mx-lg-0 {\n    margin-right: 0 !important;\n    margin-left: 0 !important;\n  }\n\n  .mx-lg-1 {\n    margin-right: 0.25rem !important;\n    margin-left: 0.25rem !important;\n  }\n\n  .mx-lg-2 {\n    margin-right: 0.5rem !important;\n    margin-left: 0.5rem !important;\n  }\n\n  .mx-lg-3 {\n    margin-right: 1rem !important;\n    margin-left: 1rem !important;\n  }\n\n  .mx-lg-4 {\n    margin-right: 1.5rem !important;\n    margin-left: 1.5rem !important;\n  }\n\n  .mx-lg-5 {\n    margin-right: 3rem !important;\n    margin-left: 3rem !important;\n  }\n\n  .mx-lg-auto {\n    margin-right: auto !important;\n    margin-left: auto !important;\n  }\n\n  .my-lg-0 {\n    margin-top: 0 !important;\n    margin-bottom: 0 !important;\n  }\n\n  .my-lg-1 {\n    margin-top: 0.25rem !important;\n    margin-bottom: 0.25rem !important;\n  }\n\n  .my-lg-2 {\n    margin-top: 0.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .my-lg-3 {\n    margin-top: 1rem !important;\n    margin-bottom: 1rem !important;\n  }\n\n  .my-lg-4 {\n    margin-top: 1.5rem !important;\n    margin-bottom: 1.5rem !important;\n  }\n\n  .my-lg-5 {\n    margin-top: 3rem !important;\n    margin-bottom: 3rem !important;\n  }\n\n  .my-lg-auto {\n    margin-top: auto !important;\n    margin-bottom: auto !important;\n  }\n\n  .mt-lg-0 {\n    margin-top: 0 !important;\n  }\n\n  .mt-lg-1 {\n    margin-top: 0.25rem !important;\n  }\n\n  .mt-lg-2 {\n    margin-top: 0.5rem !important;\n  }\n\n  .mt-lg-3 {\n    margin-top: 1rem !important;\n  }\n\n  .mt-lg-4 {\n    margin-top: 1.5rem !important;\n  }\n\n  .mt-lg-5 {\n    margin-top: 3rem !important;\n  }\n\n  .mt-lg-auto {\n    margin-top: auto !important;\n  }\n\n  .me-lg-0 {\n    margin-right: 0 !important;\n  }\n\n  .me-lg-1 {\n    margin-right: 0.25rem !important;\n  }\n\n  .me-lg-2 {\n    margin-right: 0.5rem !important;\n  }\n\n  .me-lg-3 {\n    margin-right: 1rem !important;\n  }\n\n  .me-lg-4 {\n    margin-right: 1.5rem !important;\n  }\n\n  .me-lg-5 {\n    margin-right: 3rem !important;\n  }\n\n  .me-lg-auto {\n    margin-right: auto !important;\n  }\n\n  .mb-lg-0 {\n    margin-bottom: 0 !important;\n  }\n\n  .mb-lg-1 {\n    margin-bottom: 0.25rem !important;\n  }\n\n  .mb-lg-2 {\n    margin-bottom: 0.5rem !important;\n  }\n\n  .mb-lg-3 {\n    margin-bottom: 1rem !important;\n  }\n\n  .mb-lg-4 {\n    margin-bottom: 1.5rem !important;\n  }\n\n  .mb-lg-5 {\n    margin-bottom: 3rem !important;\n  }\n\n  .mb-lg-auto {\n    margin-bottom: auto !important;\n  }\n\n  .ms-lg-0 {\n    margin-left: 0 !important;\n  }\n\n  .ms-lg-1 {\n    margin-left: 0.25rem !important;\n  }\n\n  .ms-lg-2 {\n    margin-left: 0.5rem !important;\n  }\n\n  .ms-lg-3 {\n    margin-left: 1rem !important;\n  }\n\n  .ms-lg-4 {\n    margin-left: 1.5rem !important;\n  }\n\n  .ms-lg-5 {\n    margin-left: 3rem !important;\n  }\n\n  .ms-lg-auto {\n    margin-left: auto !important;\n  }\n\n  .p-lg-0 {\n    padding: 0 !important;\n  }\n\n  .p-lg-1 {\n    padding: 0.25rem !important;\n  }\n\n  .p-lg-2 {\n    padding: 0.5rem !important;\n  }\n\n  .p-lg-3 {\n    padding: 1rem !important;\n  }\n\n  .p-lg-4 {\n    padding: 1.5rem !important;\n  }\n\n  .p-lg-5 {\n    padding: 3rem !important;\n  }\n\n  .px-lg-0 {\n    padding-right: 0 !important;\n    padding-left: 0 !important;\n  }\n\n  .px-lg-1 {\n    padding-right: 0.25rem !important;\n    padding-left: 0.25rem !important;\n  }\n\n  .px-lg-2 {\n    padding-right: 0.5rem !important;\n    padding-left: 0.5rem !important;\n  }\n\n  .px-lg-3 {\n    padding-right: 1rem !important;\n    padding-left: 1rem !important;\n  }\n\n  .px-lg-4 {\n    padding-right: 1.5rem !important;\n    padding-left: 1.5rem !important;\n  }\n\n  .px-lg-5 {\n    padding-right: 3rem !important;\n    padding-left: 3rem !important;\n  }\n\n  .py-lg-0 {\n    padding-top: 0 !important;\n    padding-bottom: 0 !important;\n  }\n\n  .py-lg-1 {\n    padding-top: 0.25rem !important;\n    padding-bottom: 0.25rem !important;\n  }\n\n  .py-lg-2 {\n    padding-top: 0.5rem !important;\n    padding-bottom: 0.5rem !important;\n  }\n\n  .py-lg-3 {\n    padding-top: 1rem !important;\n    padding-bottom: 1rem !important;\n  }\n\n  .py-lg-4 {\n    padding-top: 1.5rem !important;\n    padding-bottom: 1.5rem !important;\n  }\n\n  .py-lg-5 {\n    padding-top: 3rem !important;\n    padding-bottom: 3rem !important;\n  }\n\n  .pt-lg-0 {\n    padding-top: 0 !important;\n  }\n\n  .pt-lg-1 {\n    padding-top: 0.25rem !important;\n  }\n\n  .pt-lg-2 {\n    padding-top: 0.5rem !important;\n  }\n\n  .pt-lg-3 {\n    padding-top: 1rem !important;\n  }\n\n  .pt-lg-4 {\n    padding-top: 1.5rem !important;\n  }\n\n  .pt-lg-5 {\n    padding-top: 3rem !important;\n  }\n\n  .pe-lg-0 {\n    padding-right: 0 !important;\n  }\n\n  .pe-lg-1 {\n    padding-right: 0.25rem !important;\n  }\n\n  .pe-lg-2 {\n    padding-right: 0.5rem !important;\n  }\n\n  .pe-lg-3 {\n    padding-right: 1rem !important;\n  }\n\n  .pe-lg-4 {\n    padding-right: 1.5rem !important;\n  }\n\n  .pe-lg-5 {\n    padding-right: 3rem !important;\n  }\n\n  .pb-lg-0 {\n    padding-bottom: 0 !important;\n  }\n\n  .pb-lg-1 {\n    padding-bottom: 0.25rem !important;\n  }\n\n  .pb-lg-2 {\n    padding-bottom: 0.5rem !important;\n  }\n\n  .pb-lg-3 {\n    padding-bottom: 1rem !important;\n  }\n\n  .pb-lg-4 {\n    padding-bottom: 1.5rem !important;\n  }\n\n  .pb-lg-5 {\n    padding-bottom: 3rem !important;\n  }\n\n  .ps-lg-0 {\n    padding-left: 0 !important;\n  }\n\n  .ps-lg-1 {\n    padding-left: 0.25rem !important;\n  }\n\n  .ps-lg-2 {\n    padding-left: 0.5rem !important;\n  }\n\n  .ps-lg-3 {\n    padding-left: 1rem !important;\n  }\n\n  .ps-lg-4 {\n    padding-left: 1.5rem !important;\n  }\n\n  .ps-lg-5 {\n    padding-left: 3rem !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .d-xl-inline {\n    display: inline !important;\n  }\n\n  .d-xl-inline-block {\n    display: inline-block !important;\n  }\n\n  .d-xl-block {\n    display: block !important;\n  }\n\n  .d-xl-grid {\n    display: grid !important;\n  }\n\n  .d-xl-table {\n    display: table !important;\n  }\n\n  .d-xl-table-row {\n    display: table-row !important;\n  }\n\n  .d-xl-table-cell {\n    display: table-cell !important;\n  }\n\n  .d-xl-flex {\n    display: flex !important;\n  }\n\n  .d-xl-inline-flex {\n    display: inline-flex !important;\n  }\n\n  .d-xl-none {\n    display: none !important;\n  }\n\n  .flex-xl-fill {\n    flex: 1 1 auto !important;\n  }\n\n  .flex-xl-row {\n    flex-direction: row !important;\n  }\n\n  .flex-xl-column {\n    flex-direction: column !important;\n  }\n\n  .flex-xl-row-reverse {\n    flex-direction: row-reverse !important;\n  }\n\n  .flex-xl-column-reverse {\n    flex-direction: column-reverse !important;\n  }\n\n  .flex-xl-grow-0 {\n    flex-grow: 0 !important;\n  }\n\n  .flex-xl-grow-1 {\n    flex-grow: 1 !important;\n  }\n\n  .flex-xl-shrink-0 {\n    flex-shrink: 0 !important;\n  }\n\n  .flex-xl-shrink-1 {\n    flex-shrink: 1 !important;\n  }\n\n  .flex-xl-wrap {\n    flex-wrap: wrap !important;\n  }\n\n  .flex-xl-nowrap {\n    flex-wrap: nowrap !important;\n  }\n\n  .flex-xl-wrap-reverse {\n    flex-wrap: wrap-reverse !important;\n  }\n\n  .justify-content-xl-start {\n    justify-content: flex-start !important;\n  }\n\n  .justify-content-xl-end {\n    justify-content: flex-end !important;\n  }\n\n  .justify-content-xl-center {\n    justify-content: center !important;\n  }\n\n  .justify-content-xl-between {\n    justify-content: space-between !important;\n  }\n\n  .justify-content-xl-around {\n    justify-content: space-around !important;\n  }\n\n  .justify-content-xl-evenly {\n    justify-content: space-evenly !important;\n  }\n\n  .align-items-xl-start {\n    align-items: flex-start !important;\n  }\n\n  .align-items-xl-end {\n    align-items: flex-end !important;\n  }\n\n  .align-items-xl-center {\n    align-items: center !important;\n  }\n\n  .align-items-xl-baseline {\n    align-items: baseline !important;\n  }\n\n  .align-items-xl-stretch {\n    align-items: stretch !important;\n  }\n\n  .align-content-xl-start {\n    align-content: flex-start !important;\n  }\n\n  .align-content-xl-end {\n    align-content: flex-end !important;\n  }\n\n  .align-content-xl-center {\n    align-content: center !important;\n  }\n\n  .align-content-xl-between {\n    align-content: space-between !important;\n  }\n\n  .align-content-xl-around {\n    align-content: space-around !important;\n  }\n\n  .align-content-xl-stretch {\n    align-content: stretch !important;\n  }\n\n  .align-self-xl-auto {\n    align-self: auto !important;\n  }\n\n  .align-self-xl-start {\n    align-self: flex-start !important;\n  }\n\n  .align-self-xl-end {\n    align-self: flex-end !important;\n  }\n\n  .align-self-xl-center {\n    align-self: center !important;\n  }\n\n  .align-self-xl-baseline {\n    align-self: baseline !important;\n  }\n\n  .align-self-xl-stretch {\n    align-self: stretch !important;\n  }\n\n  .order-xl-first {\n    order: -1 !important;\n  }\n\n  .order-xl-0 {\n    order: 0 !important;\n  }\n\n  .order-xl-1 {\n    order: 1 !important;\n  }\n\n  .order-xl-2 {\n    order: 2 !important;\n  }\n\n  .order-xl-3 {\n    order: 3 !important;\n  }\n\n  .order-xl-4 {\n    order: 4 !important;\n  }\n\n  .order-xl-5 {\n    order: 5 !important;\n  }\n\n  .order-xl-last {\n    order: 6 !important;\n  }\n\n  .m-xl-0 {\n    margin: 0 !important;\n  }\n\n  .m-xl-1 {\n    margin: 0.25rem !important;\n  }\n\n  .m-xl-2 {\n    margin: 0.5rem !important;\n  }\n\n  .m-xl-3 {\n    margin: 1rem !important;\n  }\n\n  .m-xl-4 {\n    margin: 1.5rem !important;\n  }\n\n  .m-xl-5 {\n    margin: 3rem !important;\n  }\n\n  .m-xl-auto {\n    margin: auto !important;\n  }\n\n  .mx-xl-0 {\n    margin-right: 0 !important;\n    margin-left: 0 !important;\n  }\n\n  .mx-xl-1 {\n    margin-right: 0.25rem !important;\n    margin-left: 0.25rem !important;\n  }\n\n  .mx-xl-2 {\n    margin-right: 0.5rem !important;\n    margin-left: 0.5rem !important;\n  }\n\n  .mx-xl-3 {\n    margin-right: 1rem !important;\n    margin-left: 1rem !important;\n  }\n\n  .mx-xl-4 {\n    margin-right: 1.5rem !important;\n    margin-left: 1.5rem !important;\n  }\n\n  .mx-xl-5 {\n    margin-right: 3rem !important;\n    margin-left: 3rem !important;\n  }\n\n  .mx-xl-auto {\n    margin-right: auto !important;\n    margin-left: auto !important;\n  }\n\n  .my-xl-0 {\n    margin-top: 0 !important;\n    margin-bottom: 0 !important;\n  }\n\n  .my-xl-1 {\n    margin-top: 0.25rem !important;\n    margin-bottom: 0.25rem !important;\n  }\n\n  .my-xl-2 {\n    margin-top: 0.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .my-xl-3 {\n    margin-top: 1rem !important;\n    margin-bottom: 1rem !important;\n  }\n\n  .my-xl-4 {\n    margin-top: 1.5rem !important;\n    margin-bottom: 1.5rem !important;\n  }\n\n  .my-xl-5 {\n    margin-top: 3rem !important;\n    margin-bottom: 3rem !important;\n  }\n\n  .my-xl-auto {\n    margin-top: auto !important;\n    margin-bottom: auto !important;\n  }\n\n  .mt-xl-0 {\n    margin-top: 0 !important;\n  }\n\n  .mt-xl-1 {\n    margin-top: 0.25rem !important;\n  }\n\n  .mt-xl-2 {\n    margin-top: 0.5rem !important;\n  }\n\n  .mt-xl-3 {\n    margin-top: 1rem !important;\n  }\n\n  .mt-xl-4 {\n    margin-top: 1.5rem !important;\n  }\n\n  .mt-xl-5 {\n    margin-top: 3rem !important;\n  }\n\n  .mt-xl-auto {\n    margin-top: auto !important;\n  }\n\n  .me-xl-0 {\n    margin-right: 0 !important;\n  }\n\n  .me-xl-1 {\n    margin-right: 0.25rem !important;\n  }\n\n  .me-xl-2 {\n    margin-right: 0.5rem !important;\n  }\n\n  .me-xl-3 {\n    margin-right: 1rem !important;\n  }\n\n  .me-xl-4 {\n    margin-right: 1.5rem !important;\n  }\n\n  .me-xl-5 {\n    margin-right: 3rem !important;\n  }\n\n  .me-xl-auto {\n    margin-right: auto !important;\n  }\n\n  .mb-xl-0 {\n    margin-bottom: 0 !important;\n  }\n\n  .mb-xl-1 {\n    margin-bottom: 0.25rem !important;\n  }\n\n  .mb-xl-2 {\n    margin-bottom: 0.5rem !important;\n  }\n\n  .mb-xl-3 {\n    margin-bottom: 1rem !important;\n  }\n\n  .mb-xl-4 {\n    margin-bottom: 1.5rem !important;\n  }\n\n  .mb-xl-5 {\n    margin-bottom: 3rem !important;\n  }\n\n  .mb-xl-auto {\n    margin-bottom: auto !important;\n  }\n\n  .ms-xl-0 {\n    margin-left: 0 !important;\n  }\n\n  .ms-xl-1 {\n    margin-left: 0.25rem !important;\n  }\n\n  .ms-xl-2 {\n    margin-left: 0.5rem !important;\n  }\n\n  .ms-xl-3 {\n    margin-left: 1rem !important;\n  }\n\n  .ms-xl-4 {\n    margin-left: 1.5rem !important;\n  }\n\n  .ms-xl-5 {\n    margin-left: 3rem !important;\n  }\n\n  .ms-xl-auto {\n    margin-left: auto !important;\n  }\n\n  .p-xl-0 {\n    padding: 0 !important;\n  }\n\n  .p-xl-1 {\n    padding: 0.25rem !important;\n  }\n\n  .p-xl-2 {\n    padding: 0.5rem !important;\n  }\n\n  .p-xl-3 {\n    padding: 1rem !important;\n  }\n\n  .p-xl-4 {\n    padding: 1.5rem !important;\n  }\n\n  .p-xl-5 {\n    padding: 3rem !important;\n  }\n\n  .px-xl-0 {\n    padding-right: 0 !important;\n    padding-left: 0 !important;\n  }\n\n  .px-xl-1 {\n    padding-right: 0.25rem !important;\n    padding-left: 0.25rem !important;\n  }\n\n  .px-xl-2 {\n    padding-right: 0.5rem !important;\n    padding-left: 0.5rem !important;\n  }\n\n  .px-xl-3 {\n    padding-right: 1rem !important;\n    padding-left: 1rem !important;\n  }\n\n  .px-xl-4 {\n    padding-right: 1.5rem !important;\n    padding-left: 1.5rem !important;\n  }\n\n  .px-xl-5 {\n    padding-right: 3rem !important;\n    padding-left: 3rem !important;\n  }\n\n  .py-xl-0 {\n    padding-top: 0 !important;\n    padding-bottom: 0 !important;\n  }\n\n  .py-xl-1 {\n    padding-top: 0.25rem !important;\n    padding-bottom: 0.25rem !important;\n  }\n\n  .py-xl-2 {\n    padding-top: 0.5rem !important;\n    padding-bottom: 0.5rem !important;\n  }\n\n  .py-xl-3 {\n    padding-top: 1rem !important;\n    padding-bottom: 1rem !important;\n  }\n\n  .py-xl-4 {\n    padding-top: 1.5rem !important;\n    padding-bottom: 1.5rem !important;\n  }\n\n  .py-xl-5 {\n    padding-top: 3rem !important;\n    padding-bottom: 3rem !important;\n  }\n\n  .pt-xl-0 {\n    padding-top: 0 !important;\n  }\n\n  .pt-xl-1 {\n    padding-top: 0.25rem !important;\n  }\n\n  .pt-xl-2 {\n    padding-top: 0.5rem !important;\n  }\n\n  .pt-xl-3 {\n    padding-top: 1rem !important;\n  }\n\n  .pt-xl-4 {\n    padding-top: 1.5rem !important;\n  }\n\n  .pt-xl-5 {\n    padding-top: 3rem !important;\n  }\n\n  .pe-xl-0 {\n    padding-right: 0 !important;\n  }\n\n  .pe-xl-1 {\n    padding-right: 0.25rem !important;\n  }\n\n  .pe-xl-2 {\n    padding-right: 0.5rem !important;\n  }\n\n  .pe-xl-3 {\n    padding-right: 1rem !important;\n  }\n\n  .pe-xl-4 {\n    padding-right: 1.5rem !important;\n  }\n\n  .pe-xl-5 {\n    padding-right: 3rem !important;\n  }\n\n  .pb-xl-0 {\n    padding-bottom: 0 !important;\n  }\n\n  .pb-xl-1 {\n    padding-bottom: 0.25rem !important;\n  }\n\n  .pb-xl-2 {\n    padding-bottom: 0.5rem !important;\n  }\n\n  .pb-xl-3 {\n    padding-bottom: 1rem !important;\n  }\n\n  .pb-xl-4 {\n    padding-bottom: 1.5rem !important;\n  }\n\n  .pb-xl-5 {\n    padding-bottom: 3rem !important;\n  }\n\n  .ps-xl-0 {\n    padding-left: 0 !important;\n  }\n\n  .ps-xl-1 {\n    padding-left: 0.25rem !important;\n  }\n\n  .ps-xl-2 {\n    padding-left: 0.5rem !important;\n  }\n\n  .ps-xl-3 {\n    padding-left: 1rem !important;\n  }\n\n  .ps-xl-4 {\n    padding-left: 1.5rem !important;\n  }\n\n  .ps-xl-5 {\n    padding-left: 3rem !important;\n  }\n}\n\n@media (min-width: 1400px) {\n  .d-xxl-inline {\n    display: inline !important;\n  }\n\n  .d-xxl-inline-block {\n    display: inline-block !important;\n  }\n\n  .d-xxl-block {\n    display: block !important;\n  }\n\n  .d-xxl-grid {\n    display: grid !important;\n  }\n\n  .d-xxl-table {\n    display: table !important;\n  }\n\n  .d-xxl-table-row {\n    display: table-row !important;\n  }\n\n  .d-xxl-table-cell {\n    display: table-cell !important;\n  }\n\n  .d-xxl-flex {\n    display: flex !important;\n  }\n\n  .d-xxl-inline-flex {\n    display: inline-flex !important;\n  }\n\n  .d-xxl-none {\n    display: none !important;\n  }\n\n  .flex-xxl-fill {\n    flex: 1 1 auto !important;\n  }\n\n  .flex-xxl-row {\n    flex-direction: row !important;\n  }\n\n  .flex-xxl-column {\n    flex-direction: column !important;\n  }\n\n  .flex-xxl-row-reverse {\n    flex-direction: row-reverse !important;\n  }\n\n  .flex-xxl-column-reverse {\n    flex-direction: column-reverse !important;\n  }\n\n  .flex-xxl-grow-0 {\n    flex-grow: 0 !important;\n  }\n\n  .flex-xxl-grow-1 {\n    flex-grow: 1 !important;\n  }\n\n  .flex-xxl-shrink-0 {\n    flex-shrink: 0 !important;\n  }\n\n  .flex-xxl-shrink-1 {\n    flex-shrink: 1 !important;\n  }\n\n  .flex-xxl-wrap {\n    flex-wrap: wrap !important;\n  }\n\n  .flex-xxl-nowrap {\n    flex-wrap: nowrap !important;\n  }\n\n  .flex-xxl-wrap-reverse {\n    flex-wrap: wrap-reverse !important;\n  }\n\n  .justify-content-xxl-start {\n    justify-content: flex-start !important;\n  }\n\n  .justify-content-xxl-end {\n    justify-content: flex-end !important;\n  }\n\n  .justify-content-xxl-center {\n    justify-content: center !important;\n  }\n\n  .justify-content-xxl-between {\n    justify-content: space-between !important;\n  }\n\n  .justify-content-xxl-around {\n    justify-content: space-around !important;\n  }\n\n  .justify-content-xxl-evenly {\n    justify-content: space-evenly !important;\n  }\n\n  .align-items-xxl-start {\n    align-items: flex-start !important;\n  }\n\n  .align-items-xxl-end {\n    align-items: flex-end !important;\n  }\n\n  .align-items-xxl-center {\n    align-items: center !important;\n  }\n\n  .align-items-xxl-baseline {\n    align-items: baseline !important;\n  }\n\n  .align-items-xxl-stretch {\n    align-items: stretch !important;\n  }\n\n  .align-content-xxl-start {\n    align-content: flex-start !important;\n  }\n\n  .align-content-xxl-end {\n    align-content: flex-end !important;\n  }\n\n  .align-content-xxl-center {\n    align-content: center !important;\n  }\n\n  .align-content-xxl-between {\n    align-content: space-between !important;\n  }\n\n  .align-content-xxl-around {\n    align-content: space-around !important;\n  }\n\n  .align-content-xxl-stretch {\n    align-content: stretch !important;\n  }\n\n  .align-self-xxl-auto {\n    align-self: auto !important;\n  }\n\n  .align-self-xxl-start {\n    align-self: flex-start !important;\n  }\n\n  .align-self-xxl-end {\n    align-self: flex-end !important;\n  }\n\n  .align-self-xxl-center {\n    align-self: center !important;\n  }\n\n  .align-self-xxl-baseline {\n    align-self: baseline !important;\n  }\n\n  .align-self-xxl-stretch {\n    align-self: stretch !important;\n  }\n\n  .order-xxl-first {\n    order: -1 !important;\n  }\n\n  .order-xxl-0 {\n    order: 0 !important;\n  }\n\n  .order-xxl-1 {\n    order: 1 !important;\n  }\n\n  .order-xxl-2 {\n    order: 2 !important;\n  }\n\n  .order-xxl-3 {\n    order: 3 !important;\n  }\n\n  .order-xxl-4 {\n    order: 4 !important;\n  }\n\n  .order-xxl-5 {\n    order: 5 !important;\n  }\n\n  .order-xxl-last {\n    order: 6 !important;\n  }\n\n  .m-xxl-0 {\n    margin: 0 !important;\n  }\n\n  .m-xxl-1 {\n    margin: 0.25rem !important;\n  }\n\n  .m-xxl-2 {\n    margin: 0.5rem !important;\n  }\n\n  .m-xxl-3 {\n    margin: 1rem !important;\n  }\n\n  .m-xxl-4 {\n    margin: 1.5rem !important;\n  }\n\n  .m-xxl-5 {\n    margin: 3rem !important;\n  }\n\n  .m-xxl-auto {\n    margin: auto !important;\n  }\n\n  .mx-xxl-0 {\n    margin-right: 0 !important;\n    margin-left: 0 !important;\n  }\n\n  .mx-xxl-1 {\n    margin-right: 0.25rem !important;\n    margin-left: 0.25rem !important;\n  }\n\n  .mx-xxl-2 {\n    margin-right: 0.5rem !important;\n    margin-left: 0.5rem !important;\n  }\n\n  .mx-xxl-3 {\n    margin-right: 1rem !important;\n    margin-left: 1rem !important;\n  }\n\n  .mx-xxl-4 {\n    margin-right: 1.5rem !important;\n    margin-left: 1.5rem !important;\n  }\n\n  .mx-xxl-5 {\n    margin-right: 3rem !important;\n    margin-left: 3rem !important;\n  }\n\n  .mx-xxl-auto {\n    margin-right: auto !important;\n    margin-left: auto !important;\n  }\n\n  .my-xxl-0 {\n    margin-top: 0 !important;\n    margin-bottom: 0 !important;\n  }\n\n  .my-xxl-1 {\n    margin-top: 0.25rem !important;\n    margin-bottom: 0.25rem !important;\n  }\n\n  .my-xxl-2 {\n    margin-top: 0.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .my-xxl-3 {\n    margin-top: 1rem !important;\n    margin-bottom: 1rem !important;\n  }\n\n  .my-xxl-4 {\n    margin-top: 1.5rem !important;\n    margin-bottom: 1.5rem !important;\n  }\n\n  .my-xxl-5 {\n    margin-top: 3rem !important;\n    margin-bottom: 3rem !important;\n  }\n\n  .my-xxl-auto {\n    margin-top: auto !important;\n    margin-bottom: auto !important;\n  }\n\n  .mt-xxl-0 {\n    margin-top: 0 !important;\n  }\n\n  .mt-xxl-1 {\n    margin-top: 0.25rem !important;\n  }\n\n  .mt-xxl-2 {\n    margin-top: 0.5rem !important;\n  }\n\n  .mt-xxl-3 {\n    margin-top: 1rem !important;\n  }\n\n  .mt-xxl-4 {\n    margin-top: 1.5rem !important;\n  }\n\n  .mt-xxl-5 {\n    margin-top: 3rem !important;\n  }\n\n  .mt-xxl-auto {\n    margin-top: auto !important;\n  }\n\n  .me-xxl-0 {\n    margin-right: 0 !important;\n  }\n\n  .me-xxl-1 {\n    margin-right: 0.25rem !important;\n  }\n\n  .me-xxl-2 {\n    margin-right: 0.5rem !important;\n  }\n\n  .me-xxl-3 {\n    margin-right: 1rem !important;\n  }\n\n  .me-xxl-4 {\n    margin-right: 1.5rem !important;\n  }\n\n  .me-xxl-5 {\n    margin-right: 3rem !important;\n  }\n\n  .me-xxl-auto {\n    margin-right: auto !important;\n  }\n\n  .mb-xxl-0 {\n    margin-bottom: 0 !important;\n  }\n\n  .mb-xxl-1 {\n    margin-bottom: 0.25rem !important;\n  }\n\n  .mb-xxl-2 {\n    margin-bottom: 0.5rem !important;\n  }\n\n  .mb-xxl-3 {\n    margin-bottom: 1rem !important;\n  }\n\n  .mb-xxl-4 {\n    margin-bottom: 1.5rem !important;\n  }\n\n  .mb-xxl-5 {\n    margin-bottom: 3rem !important;\n  }\n\n  .mb-xxl-auto {\n    margin-bottom: auto !important;\n  }\n\n  .ms-xxl-0 {\n    margin-left: 0 !important;\n  }\n\n  .ms-xxl-1 {\n    margin-left: 0.25rem !important;\n  }\n\n  .ms-xxl-2 {\n    margin-left: 0.5rem !important;\n  }\n\n  .ms-xxl-3 {\n    margin-left: 1rem !important;\n  }\n\n  .ms-xxl-4 {\n    margin-left: 1.5rem !important;\n  }\n\n  .ms-xxl-5 {\n    margin-left: 3rem !important;\n  }\n\n  .ms-xxl-auto {\n    margin-left: auto !important;\n  }\n\n  .p-xxl-0 {\n    padding: 0 !important;\n  }\n\n  .p-xxl-1 {\n    padding: 0.25rem !important;\n  }\n\n  .p-xxl-2 {\n    padding: 0.5rem !important;\n  }\n\n  .p-xxl-3 {\n    padding: 1rem !important;\n  }\n\n  .p-xxl-4 {\n    padding: 1.5rem !important;\n  }\n\n  .p-xxl-5 {\n    padding: 3rem !important;\n  }\n\n  .px-xxl-0 {\n    padding-right: 0 !important;\n    padding-left: 0 !important;\n  }\n\n  .px-xxl-1 {\n    padding-right: 0.25rem !important;\n    padding-left: 0.25rem !important;\n  }\n\n  .px-xxl-2 {\n    padding-right: 0.5rem !important;\n    padding-left: 0.5rem !important;\n  }\n\n  .px-xxl-3 {\n    padding-right: 1rem !important;\n    padding-left: 1rem !important;\n  }\n\n  .px-xxl-4 {\n    padding-right: 1.5rem !important;\n    padding-left: 1.5rem !important;\n  }\n\n  .px-xxl-5 {\n    padding-right: 3rem !important;\n    padding-left: 3rem !important;\n  }\n\n  .py-xxl-0 {\n    padding-top: 0 !important;\n    padding-bottom: 0 !important;\n  }\n\n  .py-xxl-1 {\n    padding-top: 0.25rem !important;\n    padding-bottom: 0.25rem !important;\n  }\n\n  .py-xxl-2 {\n    padding-top: 0.5rem !important;\n    padding-bottom: 0.5rem !important;\n  }\n\n  .py-xxl-3 {\n    padding-top: 1rem !important;\n    padding-bottom: 1rem !important;\n  }\n\n  .py-xxl-4 {\n    padding-top: 1.5rem !important;\n    padding-bottom: 1.5rem !important;\n  }\n\n  .py-xxl-5 {\n    padding-top: 3rem !important;\n    padding-bottom: 3rem !important;\n  }\n\n  .pt-xxl-0 {\n    padding-top: 0 !important;\n  }\n\n  .pt-xxl-1 {\n    padding-top: 0.25rem !important;\n  }\n\n  .pt-xxl-2 {\n    padding-top: 0.5rem !important;\n  }\n\n  .pt-xxl-3 {\n    padding-top: 1rem !important;\n  }\n\n  .pt-xxl-4 {\n    padding-top: 1.5rem !important;\n  }\n\n  .pt-xxl-5 {\n    padding-top: 3rem !important;\n  }\n\n  .pe-xxl-0 {\n    padding-right: 0 !important;\n  }\n\n  .pe-xxl-1 {\n    padding-right: 0.25rem !important;\n  }\n\n  .pe-xxl-2 {\n    padding-right: 0.5rem !important;\n  }\n\n  .pe-xxl-3 {\n    padding-right: 1rem !important;\n  }\n\n  .pe-xxl-4 {\n    padding-right: 1.5rem !important;\n  }\n\n  .pe-xxl-5 {\n    padding-right: 3rem !important;\n  }\n\n  .pb-xxl-0 {\n    padding-bottom: 0 !important;\n  }\n\n  .pb-xxl-1 {\n    padding-bottom: 0.25rem !important;\n  }\n\n  .pb-xxl-2 {\n    padding-bottom: 0.5rem !important;\n  }\n\n  .pb-xxl-3 {\n    padding-bottom: 1rem !important;\n  }\n\n  .pb-xxl-4 {\n    padding-bottom: 1.5rem !important;\n  }\n\n  .pb-xxl-5 {\n    padding-bottom: 3rem !important;\n  }\n\n  .ps-xxl-0 {\n    padding-left: 0 !important;\n  }\n\n  .ps-xxl-1 {\n    padding-left: 0.25rem !important;\n  }\n\n  .ps-xxl-2 {\n    padding-left: 0.5rem !important;\n  }\n\n  .ps-xxl-3 {\n    padding-left: 1rem !important;\n  }\n\n  .ps-xxl-4 {\n    padding-left: 1.5rem !important;\n  }\n\n  .ps-xxl-5 {\n    padding-left: 3rem !important;\n  }\n}\n\n@media print {\n  .d-print-inline {\n    display: inline !important;\n  }\n\n  .d-print-inline-block {\n    display: inline-block !important;\n  }\n\n  .d-print-block {\n    display: block !important;\n  }\n\n  .d-print-grid {\n    display: grid !important;\n  }\n\n  .d-print-table {\n    display: table !important;\n  }\n\n  .d-print-table-row {\n    display: table-row !important;\n  }\n\n  .d-print-table-cell {\n    display: table-cell !important;\n  }\n\n  .d-print-flex {\n    display: flex !important;\n  }\n\n  .d-print-inline-flex {\n    display: inline-flex !important;\n  }\n\n  .d-print-none {\n    display: none !important;\n  }\n}\n\n// Tooltips\n.tooltip {\n  position: absolute;\n  z-index: 999999;\n  display: block;\n  margin: 0;\n  font-family: var(--bs-font-sans-serif);\n  font-style: normal;\n  font-weight: 400;\n  line-height: 1.5;\n  text-align: left;\n  text-align: start;\n  text-decoration: none;\n  text-shadow: none;\n  text-transform: none;\n  letter-spacing: normal;\n  word-break: normal;\n  word-spacing: normal;\n  white-space: normal;\n  line-break: auto;\n  font-size: 0.875rem;\n  word-wrap: break-word;\n  opacity: 0;\n  pointer-events: none;\n}\n\n.tooltip.show {\n  opacity: 0.9;\n}\n\n.tooltip .tooltip-arrow {\n  position: absolute;\n  display: block;\n  width: 0.8rem;\n  height: 0.4rem;\n}\n\n.tooltip .tooltip-arrow::before {\n  position: absolute;\n  content: \"\";\n  border-color: transparent;\n  border-style: solid;\n}\n\n.bs-tooltip-top,\n.bs-tooltip-auto[data-popper-placement^=\"top\"] {\n  padding: 0.4rem 0;\n}\n\n.bs-tooltip-top .tooltip-arrow,\n.bs-tooltip-auto[data-popper-placement^=\"top\"] .tooltip-arrow {\n  bottom: 0;\n}\n\n.bs-tooltip-top .tooltip-arrow::before,\n.bs-tooltip-auto[data-popper-placement^=\"top\"] .tooltip-arrow::before {\n  top: -1px;\n  border-width: 0.4rem 0.4rem 0;\n  border-top-color: #000;\n}\n\n.bs-tooltip-end,\n.bs-tooltip-auto[data-popper-placement^=\"right\"] {\n  padding: 0 0.4rem;\n}\n\n.bs-tooltip-end .tooltip-arrow,\n.bs-tooltip-auto[data-popper-placement^=\"right\"] .tooltip-arrow {\n  left: 0;\n  width: 0.4rem;\n  height: 0.8rem;\n}\n\n.bs-tooltip-end .tooltip-arrow::before,\n.bs-tooltip-auto[data-popper-placement^=\"right\"] .tooltip-arrow::before {\n  right: -1px;\n  border-width: 0.4rem 0.4rem 0.4rem 0;\n  border-right-color: #000;\n}\n\n.bs-tooltip-bottom,\n.bs-tooltip-auto[data-popper-placement^=\"bottom\"] {\n  padding: 0.4rem 0;\n}\n\n.bs-tooltip-bottom .tooltip-arrow,\n.bs-tooltip-auto[data-popper-placement^=\"bottom\"] .tooltip-arrow {\n  top: 0;\n}\n\n.bs-tooltip-bottom .tooltip-arrow::before,\n.bs-tooltip-auto[data-popper-placement^=\"bottom\"] .tooltip-arrow::before {\n  bottom: -1px;\n  border-width: 0 0.4rem 0.4rem;\n  border-bottom-color: #000;\n}\n\n.bs-tooltip-start,\n.bs-tooltip-auto[data-popper-placement^=\"left\"] {\n  padding: 0 0.4rem;\n}\n\n.bs-tooltip-start .tooltip-arrow,\n.bs-tooltip-auto[data-popper-placement^=\"left\"] .tooltip-arrow {\n  right: 0;\n  width: 0.4rem;\n  height: 0.8rem;\n}\n\n.bs-tooltip-start .tooltip-arrow::before,\n.bs-tooltip-auto[data-popper-placement^=\"left\"] .tooltip-arrow::before {\n  left: -1px;\n  border-width: 0.4rem 0 0.4rem 0.4rem;\n  border-left-color: #000;\n}\n\n.tooltip-inner {\n  max-width: 200px;\n  padding: 0.25rem 0.5rem;\n  color: #fff;\n  text-align: center;\n  background-color: #000;\n  border-radius: 0.25rem;\n  -webkit-user-select: none;\n  user-select: none;\n  pointer-events: none;\n}\n\n.popover {\n  position: absolute;\n  top: 0;\n  left: 0 /* rtl:ignore */;\n  z-index: 1070;\n  display: block;\n  max-width: 276px;\n  font-family: var(--bs-font-sans-serif);\n  font-style: normal;\n  font-weight: 400;\n  line-height: 1.5;\n  text-align: left;\n  text-align: start;\n  text-decoration: none;\n  text-shadow: none;\n  text-transform: none;\n  letter-spacing: normal;\n  word-break: normal;\n  word-spacing: normal;\n  white-space: normal;\n  line-break: auto;\n  font-size: 0.875rem;\n  word-wrap: break-word;\n  background-color: var(--modalBackground);\n  background-clip: padding-box;\n  box-shadow: var(--mediaItemShadow), var(--mediaItemShadow-Shadow);\n  border-radius: var(--mediaItemRadius);\n}\n.popover .popover-arrow {\n  position: absolute;\n  display: block;\n  width: 1rem;\n  height: 0.5rem;\n}\n.popover .popover-arrow::before,\n.popover .popover-arrow::after {\n  position: absolute;\n  display: block;\n  content: \"\";\n  border-color: transparent;\n  border-style: solid;\n}\n\n.bs-popover-top > .popover-arrow,\n.bs-popover-auto[data-popper-placement^=\"top\"] > .popover-arrow {\n  bottom: calc(-0.5rem - 1px);\n}\n.bs-popover-top > .popover-arrow::before,\n.bs-popover-auto[data-popper-placement^=\"top\"] > .popover-arrow::before {\n  bottom: 0;\n  border-width: 0.5rem 0.5rem 0;\n  border-top-color: rgba(0, 0, 0, 0.25);\n}\n.bs-popover-top > .popover-arrow::after,\n.bs-popover-auto[data-popper-placement^=\"top\"] > .popover-arrow::after {\n  bottom: 1px;\n  border-width: 0.5rem 0.5rem 0;\n  border-top-color: #fff;\n}\n\n.bs-popover-end > .popover-arrow,\n.bs-popover-auto[data-popper-placement^=\"right\"] > .popover-arrow {\n  left: calc(-0.5rem - 1px);\n  width: 0.5rem;\n  height: 1rem;\n}\n.bs-popover-end > .popover-arrow::before,\n.bs-popover-auto[data-popper-placement^=\"right\"] > .popover-arrow::before {\n  left: 0;\n  border-width: 0.5rem 0.5rem 0.5rem 0;\n  border-right-color: rgba(0, 0, 0, 0.25);\n}\n.bs-popover-end > .popover-arrow::after,\n.bs-popover-auto[data-popper-placement^=\"right\"] > .popover-arrow::after {\n  left: 1px;\n  border-width: 0.5rem 0.5rem 0.5rem 0;\n  border-right-color: #fff;\n}\n\n.bs-popover-bottom > .popover-arrow,\n.bs-popover-auto[data-popper-placement^=\"bottom\"] > .popover-arrow {\n  top: calc(-0.5rem - 1px);\n}\n.bs-popover-bottom > .popover-arrow::before,\n.bs-popover-auto[data-popper-placement^=\"bottom\"] > .popover-arrow::before {\n  top: 0;\n  border-width: 0 0.5rem 0.5rem 0.5rem;\n  border-bottom-color: rgba(0, 0, 0, 0.25);\n}\n.bs-popover-bottom > .popover-arrow::after,\n.bs-popover-auto[data-popper-placement^=\"bottom\"] > .popover-arrow::after {\n  top: 1px;\n  border-width: 0 0.5rem 0.5rem 0.5rem;\n  border-bottom-color: #fff;\n}\n.bs-popover-bottom .popover-header::before,\n.bs-popover-auto[data-popper-placement^=\"bottom\"] .popover-header::before {\n  position: absolute;\n  top: 0;\n  left: 50%;\n  display: block;\n  width: 1rem;\n  margin-left: -0.5rem;\n  content: \"\";\n  border-bottom: 1px solid #f0f0f0;\n}\n\n.bs-popover-start > .popover-arrow,\n.bs-popover-auto[data-popper-placement^=\"left\"] > .popover-arrow {\n  right: calc(-0.5rem - 1px);\n  width: 0.5rem;\n  height: 1rem;\n}\n.bs-popover-start > .popover-arrow::before,\n.bs-popover-auto[data-popper-placement^=\"left\"] > .popover-arrow::before {\n  right: 0;\n  border-width: 0.5rem 0 0.5rem 0.5rem;\n  border-left-color: rgba(0, 0, 0, 0.25);\n}\n.bs-popover-start > .popover-arrow::after,\n.bs-popover-auto[data-popper-placement^=\"left\"] > .popover-arrow::after {\n  right: 1px;\n  border-width: 0.5rem 0 0.5rem 0.5rem;\n  border-left-color: #fff;\n}\n\n.popover-header {\n  padding: 0.5rem 1rem;\n  margin-bottom: 0;\n  font-size: 1rem;\n  background-color: #f0f0f0;\n  border-bottom: 1px solid rgba(0, 0, 0, 0.2);\n  border-top-left-radius: calc(0.3rem - 1px);\n  border-top-right-radius: calc(0.3rem - 1px);\n}\n.popover-header:empty {\n  display: none;\n}\n\n.popover-body {\n  padding: 1rem 1rem;\n  color: var(--textColor);\n}\n\n// carousel\n.carousel {\n  position: relative;\n}\n\n.carousel.pointer-event {\n  -ms-touch-action: pan-y;\n  touch-action: pan-y;\n}\n\n.carousel-inner {\n  position: relative;\n  width: 100%;\n  overflow: hidden;\n}\n\n.carousel-inner::after {\n  display: block;\n  clear: both;\n  content: \"\";\n}\n\n.carousel-item {\n  position: relative;\n  display: none;\n  float: left;\n  width: 100%;\n  margin-right: -100%;\n  -webkit-backface-visibility: hidden;\n  backface-visibility: hidden;\n  transition: -webkit-transform 0.6s ease-in-out;\n  transition: transform 0.6s ease-in-out;\n  transition:\n    transform 0.6s ease-in-out,\n    -webkit-transform 0.6s ease-in-out;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .carousel-item {\n    transition: none;\n  }\n}\n\n.carousel-item.active,\n.carousel-item-next,\n.carousel-item-prev {\n  display: block;\n}\n\n.carousel-item-next:not(.carousel-item-left),\n.active.carousel-item-right {\n  -webkit-transform: translateX(100%);\n  transform: translateX(100%);\n}\n\n.carousel-item-prev:not(.carousel-item-right),\n.active.carousel-item-left {\n  -webkit-transform: translateX(-100%);\n  transform: translateX(-100%);\n}\n\n.carousel-fade .carousel-item {\n  opacity: 0;\n  transition-property: opacity;\n  -webkit-transform: none;\n  transform: none;\n}\n\n.carousel-fade .carousel-item.active,\n.carousel-fade .carousel-item-next.carousel-item-left,\n.carousel-fade .carousel-item-prev.carousel-item-right {\n  z-index: 1;\n  opacity: 1;\n}\n\n.carousel-fade .active.carousel-item-left,\n.carousel-fade .active.carousel-item-right {\n  z-index: 0;\n  opacity: 0;\n  transition: opacity 0s 0.6s;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .carousel-fade .active.carousel-item-left,\n  .carousel-fade .active.carousel-item-right {\n    transition: none;\n  }\n}\n\n.carousel-control-prev,\n.carousel-control-next {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  z-index: 1;\n  display: -ms-flexbox;\n  display: flex;\n  -ms-flex-align: center;\n  align-items: center;\n  -ms-flex-pack: center;\n  justify-content: center;\n  width: 15%;\n  padding: 0;\n  color: #fff;\n  text-align: center;\n  background: none;\n  border: 0;\n  opacity: 0.5;\n  transition: opacity 0.15s ease;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .carousel-control-prev,\n  .carousel-control-next {\n    transition: none;\n  }\n}\n\n.carousel-control-prev:hover,\n.carousel-control-prev:focus,\n.carousel-control-next:hover,\n.carousel-control-next:focus {\n  color: #fff;\n  text-decoration: none;\n  outline: 0;\n  opacity: 0.9;\n}\n\n.carousel-control-prev {\n  left: 0;\n}\n\n.carousel-control-next {\n  right: 0;\n}\n\n.carousel-control-prev-icon,\n.carousel-control-next-icon {\n  display: inline-block;\n  width: 20px;\n  height: 20px;\n  background: 50% / 100% 100% no-repeat;\n}\n\n.carousel-control-prev-icon {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e\");\n}\n\n.carousel-control-next-icon {\n  background-image: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5L3.75 4l-2.5 2.5L2.75 8l4-4-4-4z'/%3e%3c/svg%3e\");\n}\n\n.carousel-indicators {\n  position: absolute;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 15;\n  display: -ms-flexbox;\n  display: flex;\n  -ms-flex-pack: center;\n  justify-content: center;\n  padding-left: 0;\n  margin-right: 15%;\n  margin-left: 15%;\n  list-style: none;\n}\n\n.carousel-indicators li {\n  box-sizing: content-box;\n  -ms-flex: 0 1 auto;\n  flex: 0 1 auto;\n  width: 30px;\n  height: 3px;\n  margin-right: 3px;\n  margin-left: 3px;\n  text-indent: -999px;\n  cursor: pointer;\n  background-color: #fff;\n  background-clip: padding-box;\n  border-top: 10px solid transparent;\n  border-bottom: 10px solid transparent;\n  opacity: 0.5;\n  transition: opacity 0.6s ease;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .carousel-indicators li {\n    transition: none;\n  }\n}\n\n.carousel-indicators .active {\n  opacity: 1;\n}\n\n.carousel-caption {\n  position: absolute;\n  right: 15%;\n  bottom: 20px;\n  left: 15%;\n  z-index: 10;\n  padding-top: 20px;\n  padding-bottom: 20px;\n  color: #fff;\n  text-align: center;\n}\n"
  },
  {
    "path": "src/renderer/less/codicon.css",
    "content": "/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n@font-face {\n  font-family: \"codicon\";\n  font-display: block;\n  src: url(\"./codicon.ttf?f06865699f1720ee6ca6e0a4aa084d76\") format(\"truetype\");\n}\n\n.codicon[class*=\"codicon-\"] {\n  font: normal normal normal 16px/1 codicon;\n  display: inline-block;\n  text-decoration: none;\n  text-rendering: auto;\n  text-align: center;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  user-select: none;\n  -webkit-user-select: none;\n  -ms-user-select: none;\n}\n\n/*---------------------\n *  Modifiers\n *-------------------*/\n\n@keyframes codicon-spin {\n  100% {\n    transform: rotate(360deg);\n  }\n}\n\n.codicon-sync.codicon-modifier-spin,\n.codicon-loading.codicon-modifier-spin,\n.codicon-gear.codicon-modifier-spin {\n  /* Use steps to throttle FPS to reduce CPU usage */\n  animation: codicon-spin 1.5s steps(30) infinite;\n}\n\n.codicon-modifier-disabled {\n  opacity: 0.5;\n}\n\n.codicon-modifier-hidden {\n  opacity: 0;\n}\n\n/* custom speed & easing for loading icon */\n.codicon-loading {\n  animation-duration: 1s !important;\n  animation-timing-function: cubic-bezier(0.53, 0.21, 0.29, 0.67) !important;\n}\n\n/*---------------------\n *  Icons\n *-------------------*/\n\n.codicon-add:before {\n  content: \"\\ea60\";\n}\n.codicon-plus:before {\n  content: \"\\ea60\";\n}\n.codicon-gist-new:before {\n  content: \"\\ea60\";\n}\n.codicon-repo-create:before {\n  content: \"\\ea60\";\n}\n.codicon-lightbulb:before {\n  content: \"\\ea61\";\n}\n.codicon-light-bulb:before {\n  content: \"\\ea61\";\n}\n.codicon-repo:before {\n  content: \"\\ea62\";\n}\n.codicon-repo-delete:before {\n  content: \"\\ea62\";\n}\n.codicon-gist-fork:before {\n  content: \"\\ea63\";\n}\n.codicon-repo-forked:before {\n  content: \"\\ea63\";\n}\n.codicon-git-pull-request:before {\n  content: \"\\ea64\";\n}\n.codicon-git-pull-request-abandoned:before {\n  content: \"\\ea64\";\n}\n.codicon-record-keys:before {\n  content: \"\\ea65\";\n}\n.codicon-keyboard:before {\n  content: \"\\ea65\";\n}\n.codicon-tag:before {\n  content: \"\\ea66\";\n}\n.codicon-tag-add:before {\n  content: \"\\ea66\";\n}\n.codicon-tag-remove:before {\n  content: \"\\ea66\";\n}\n.codicon-person:before {\n  content: \"\\ea67\";\n}\n.codicon-person-follow:before {\n  content: \"\\ea67\";\n}\n.codicon-person-outline:before {\n  content: \"\\ea67\";\n}\n.codicon-person-filled:before {\n  content: \"\\ea67\";\n}\n.codicon-git-branch:before {\n  content: \"\\ea68\";\n}\n.codicon-git-branch-create:before {\n  content: \"\\ea68\";\n}\n.codicon-git-branch-delete:before {\n  content: \"\\ea68\";\n}\n.codicon-source-control:before {\n  content: \"\\ea68\";\n}\n.codicon-mirror:before {\n  content: \"\\ea69\";\n}\n.codicon-mirror-public:before {\n  content: \"\\ea69\";\n}\n.codicon-star:before {\n  content: \"\\ea6a\";\n}\n.codicon-star-add:before {\n  content: \"\\ea6a\";\n}\n.codicon-star-delete:before {\n  content: \"\\ea6a\";\n}\n.codicon-star-empty:before {\n  content: \"\\ea6a\";\n}\n.codicon-comment:before {\n  content: \"\\ea6b\";\n}\n.codicon-comment-add:before {\n  content: \"\\ea6b\";\n}\n.codicon-alert:before {\n  content: \"\\ea6c\";\n}\n.codicon-warning:before {\n  content: \"\\ea6c\";\n}\n.codicon-search:before {\n  content: \"\\ea6d\";\n}\n.codicon-search-save:before {\n  content: \"\\ea6d\";\n}\n.codicon-log-out:before {\n  content: \"\\ea6e\";\n}\n.codicon-sign-out:before {\n  content: \"\\ea6e\";\n}\n.codicon-log-in:before {\n  content: \"\\ea6f\";\n}\n.codicon-sign-in:before {\n  content: \"\\ea6f\";\n}\n.codicon-eye:before {\n  content: \"\\ea70\";\n}\n.codicon-eye-unwatch:before {\n  content: \"\\ea70\";\n}\n.codicon-eye-watch:before {\n  content: \"\\ea70\";\n}\n.codicon-circle-filled:before {\n  content: \"\\ea71\";\n}\n.codicon-primitive-dot:before {\n  content: \"\\ea71\";\n}\n.codicon-close-dirty:before {\n  content: \"\\ea71\";\n}\n.codicon-debug-breakpoint:before {\n  content: \"\\ea71\";\n}\n.codicon-debug-breakpoint-disabled:before {\n  content: \"\\ea71\";\n}\n.codicon-debug-hint:before {\n  content: \"\\ea71\";\n}\n.codicon-primitive-square:before {\n  content: \"\\ea72\";\n}\n.codicon-edit:before {\n  content: \"\\ea73\";\n}\n.codicon-pencil:before {\n  content: \"\\ea73\";\n}\n.codicon-info:before {\n  content: \"\\ea74\";\n}\n.codicon-issue-opened:before {\n  content: \"\\ea74\";\n}\n.codicon-gist-private:before {\n  content: \"\\ea75\";\n}\n.codicon-git-fork-private:before {\n  content: \"\\ea75\";\n}\n.codicon-lock:before {\n  content: \"\\ea75\";\n}\n.codicon-mirror-private:before {\n  content: \"\\ea75\";\n}\n.codicon-close:before {\n  content: \"\\ea76\";\n}\n.codicon-remove-close:before {\n  content: \"\\ea76\";\n}\n.codicon-x:before {\n  content: \"\\ea76\";\n}\n.codicon-repo-sync:before {\n  content: \"\\ea77\";\n}\n.codicon-sync:before {\n  content: \"\\ea77\";\n}\n.codicon-clone:before {\n  content: \"\\ea78\";\n}\n.codicon-desktop-download:before {\n  content: \"\\ea78\";\n}\n.codicon-beaker:before {\n  content: \"\\ea79\";\n}\n.codicon-microscope:before {\n  content: \"\\ea79\";\n}\n.codicon-vm:before {\n  content: \"\\ea7a\";\n}\n.codicon-device-desktop:before {\n  content: \"\\ea7a\";\n}\n.codicon-file:before {\n  content: \"\\ea7b\";\n}\n.codicon-file-text:before {\n  content: \"\\ea7b\";\n}\n.codicon-more:before {\n  content: \"\\ea7c\";\n}\n.codicon-ellipsis:before {\n  content: \"\\ea7c\";\n}\n.codicon-kebab-horizontal:before {\n  content: \"\\ea7c\";\n}\n.codicon-mail-reply:before {\n  content: \"\\ea7d\";\n}\n.codicon-reply:before {\n  content: \"\\ea7d\";\n}\n.codicon-organization:before {\n  content: \"\\ea7e\";\n}\n.codicon-organization-filled:before {\n  content: \"\\ea7e\";\n}\n.codicon-organization-outline:before {\n  content: \"\\ea7e\";\n}\n.codicon-new-file:before {\n  content: \"\\ea7f\";\n}\n.codicon-file-add:before {\n  content: \"\\ea7f\";\n}\n.codicon-new-folder:before {\n  content: \"\\ea80\";\n}\n.codicon-file-directory-create:before {\n  content: \"\\ea80\";\n}\n.codicon-trash:before {\n  content: \"\\ea81\";\n}\n.codicon-trashcan:before {\n  content: \"\\ea81\";\n}\n.codicon-history:before {\n  content: \"\\ea82\";\n}\n.codicon-clock:before {\n  content: \"\\ea82\";\n}\n.codicon-folder:before {\n  content: \"\\ea83\";\n}\n.codicon-file-directory:before {\n  content: \"\\ea83\";\n}\n.codicon-symbol-folder:before {\n  content: \"\\ea83\";\n}\n.codicon-logo-github:before {\n  content: \"\\ea84\";\n}\n.codicon-mark-github:before {\n  content: \"\\ea84\";\n}\n.codicon-github:before {\n  content: \"\\ea84\";\n}\n.codicon-terminal:before {\n  content: \"\\ea85\";\n}\n.codicon-console:before {\n  content: \"\\ea85\";\n}\n.codicon-repl:before {\n  content: \"\\ea85\";\n}\n.codicon-zap:before {\n  content: \"\\ea86\";\n}\n.codicon-symbol-event:before {\n  content: \"\\ea86\";\n}\n.codicon-error:before {\n  content: \"\\ea87\";\n}\n.codicon-stop:before {\n  content: \"\\ea87\";\n}\n.codicon-variable:before {\n  content: \"\\ea88\";\n}\n.codicon-symbol-variable:before {\n  content: \"\\ea88\";\n}\n.codicon-array:before {\n  content: \"\\ea8a\";\n}\n.codicon-symbol-array:before {\n  content: \"\\ea8a\";\n}\n.codicon-symbol-module:before {\n  content: \"\\ea8b\";\n}\n.codicon-symbol-package:before {\n  content: \"\\ea8b\";\n}\n.codicon-symbol-namespace:before {\n  content: \"\\ea8b\";\n}\n.codicon-symbol-object:before {\n  content: \"\\ea8b\";\n}\n.codicon-symbol-method:before {\n  content: \"\\ea8c\";\n}\n.codicon-symbol-function:before {\n  content: \"\\ea8c\";\n}\n.codicon-symbol-constructor:before {\n  content: \"\\ea8c\";\n}\n.codicon-symbol-boolean:before {\n  content: \"\\ea8f\";\n}\n.codicon-symbol-null:before {\n  content: \"\\ea8f\";\n}\n.codicon-symbol-numeric:before {\n  content: \"\\ea90\";\n}\n.codicon-symbol-number:before {\n  content: \"\\ea90\";\n}\n.codicon-symbol-structure:before {\n  content: \"\\ea91\";\n}\n.codicon-symbol-struct:before {\n  content: \"\\ea91\";\n}\n.codicon-symbol-parameter:before {\n  content: \"\\ea92\";\n}\n.codicon-symbol-type-parameter:before {\n  content: \"\\ea92\";\n}\n.codicon-symbol-key:before {\n  content: \"\\ea93\";\n}\n.codicon-symbol-text:before {\n  content: \"\\ea93\";\n}\n.codicon-symbol-reference:before {\n  content: \"\\ea94\";\n}\n.codicon-go-to-file:before {\n  content: \"\\ea94\";\n}\n.codicon-symbol-enum:before {\n  content: \"\\ea95\";\n}\n.codicon-symbol-value:before {\n  content: \"\\ea95\";\n}\n.codicon-symbol-ruler:before {\n  content: \"\\ea96\";\n}\n.codicon-symbol-unit:before {\n  content: \"\\ea96\";\n}\n.codicon-activate-breakpoints:before {\n  content: \"\\ea97\";\n}\n.codicon-archive:before {\n  content: \"\\ea98\";\n}\n.codicon-arrow-both:before {\n  content: \"\\ea99\";\n}\n.codicon-arrow-down:before {\n  content: \"\\ea9a\";\n}\n.codicon-arrow-left:before {\n  content: \"\\ea9b\";\n}\n.codicon-arrow-right:before {\n  content: \"\\ea9c\";\n}\n.codicon-arrow-small-down:before {\n  content: \"\\ea9d\";\n}\n.codicon-arrow-small-left:before {\n  content: \"\\ea9e\";\n}\n.codicon-arrow-small-right:before {\n  content: \"\\ea9f\";\n}\n.codicon-arrow-small-up:before {\n  content: \"\\eaa0\";\n}\n.codicon-arrow-up:before {\n  content: \"\\eaa1\";\n}\n.codicon-bell:before {\n  content: \"\\eaa2\";\n}\n.codicon-bold:before {\n  content: \"\\eaa3\";\n}\n.codicon-book:before {\n  content: \"\\eaa4\";\n}\n.codicon-bookmark:before {\n  content: \"\\eaa5\";\n}\n.codicon-debug-breakpoint-conditional-unverified:before {\n  content: \"\\eaa6\";\n}\n.codicon-debug-breakpoint-conditional:before {\n  content: \"\\eaa7\";\n}\n.codicon-debug-breakpoint-conditional-disabled:before {\n  content: \"\\eaa7\";\n}\n.codicon-debug-breakpoint-data-unverified:before {\n  content: \"\\eaa8\";\n}\n.codicon-debug-breakpoint-data:before {\n  content: \"\\eaa9\";\n}\n.codicon-debug-breakpoint-data-disabled:before {\n  content: \"\\eaa9\";\n}\n.codicon-debug-breakpoint-log-unverified:before {\n  content: \"\\eaaa\";\n}\n.codicon-debug-breakpoint-log:before {\n  content: \"\\eaab\";\n}\n.codicon-debug-breakpoint-log-disabled:before {\n  content: \"\\eaab\";\n}\n.codicon-briefcase:before {\n  content: \"\\eaac\";\n}\n.codicon-broadcast:before {\n  content: \"\\eaad\";\n}\n.codicon-browser:before {\n  content: \"\\eaae\";\n}\n.codicon-bug:before {\n  content: \"\\eaaf\";\n}\n.codicon-calendar:before {\n  content: \"\\eab0\";\n}\n.codicon-case-sensitive:before {\n  content: \"\\eab1\";\n}\n.codicon-check:before {\n  content: \"\\eab2\";\n}\n.codicon-checklist:before {\n  content: \"\\eab3\";\n}\n.codicon-chevron-down:before {\n  content: \"\\eab4\";\n}\n.codicon-chevron-left:before {\n  content: \"\\eab5\";\n}\n.codicon-chevron-right:before {\n  content: \"\\eab6\";\n}\n.codicon-chevron-up:before {\n  content: \"\\eab7\";\n}\n.codicon-chrome-close:before {\n  content: \"\\eab8\";\n}\n.codicon-chrome-maximize:before {\n  content: \"\\eab9\";\n}\n.codicon-chrome-minimize:before {\n  content: \"\\eaba\";\n}\n.codicon-chrome-restore:before {\n  content: \"\\eabb\";\n}\n.codicon-circle-outline:before {\n  content: \"\\eabc\";\n}\n.codicon-debug-breakpoint-unverified:before {\n  content: \"\\eabc\";\n}\n.codicon-circle-slash:before {\n  content: \"\\eabd\";\n}\n.codicon-circuit-board:before {\n  content: \"\\eabe\";\n}\n.codicon-clear-all:before {\n  content: \"\\eabf\";\n}\n.codicon-clippy:before {\n  content: \"\\eac0\";\n}\n.codicon-close-all:before {\n  content: \"\\eac1\";\n}\n.codicon-cloud-download:before {\n  content: \"\\eac2\";\n}\n.codicon-cloud-upload:before {\n  content: \"\\eac3\";\n}\n.codicon-code:before {\n  content: \"\\eac4\";\n}\n.codicon-collapse-all:before {\n  content: \"\\eac5\";\n}\n.codicon-color-mode:before {\n  content: \"\\eac6\";\n}\n.codicon-comment-discussion:before {\n  content: \"\\eac7\";\n}\n.codicon-credit-card:before {\n  content: \"\\eac9\";\n}\n.codicon-dash:before {\n  content: \"\\eacc\";\n}\n.codicon-dashboard:before {\n  content: \"\\eacd\";\n}\n.codicon-database:before {\n  content: \"\\eace\";\n}\n.codicon-debug-continue:before {\n  content: \"\\eacf\";\n}\n.codicon-debug-disconnect:before {\n  content: \"\\ead0\";\n}\n.codicon-debug-pause:before {\n  content: \"\\ead1\";\n}\n.codicon-debug-restart:before {\n  content: \"\\ead2\";\n}\n.codicon-debug-start:before {\n  content: \"\\ead3\";\n}\n.codicon-debug-step-into:before {\n  content: \"\\ead4\";\n}\n.codicon-debug-step-out:before {\n  content: \"\\ead5\";\n}\n.codicon-debug-step-over:before {\n  content: \"\\ead6\";\n}\n.codicon-debug-stop:before {\n  content: \"\\ead7\";\n}\n.codicon-debug:before {\n  content: \"\\ead8\";\n}\n.codicon-device-camera-video:before {\n  content: \"\\ead9\";\n}\n.codicon-device-camera:before {\n  content: \"\\eada\";\n}\n.codicon-device-mobile:before {\n  content: \"\\eadb\";\n}\n.codicon-diff-added:before {\n  content: \"\\eadc\";\n}\n.codicon-diff-ignored:before {\n  content: \"\\eadd\";\n}\n.codicon-diff-modified:before {\n  content: \"\\eade\";\n}\n.codicon-diff-removed:before {\n  content: \"\\eadf\";\n}\n.codicon-diff-renamed:before {\n  content: \"\\eae0\";\n}\n.codicon-diff:before {\n  content: \"\\eae1\";\n}\n.codicon-discard:before {\n  content: \"\\eae2\";\n}\n.codicon-editor-layout:before {\n  content: \"\\eae3\";\n}\n.codicon-empty-window:before {\n  content: \"\\eae4\";\n}\n.codicon-exclude:before {\n  content: \"\\eae5\";\n}\n.codicon-extensions:before {\n  content: \"\\eae6\";\n}\n.codicon-eye-closed:before {\n  content: \"\\eae7\";\n}\n.codicon-file-binary:before {\n  content: \"\\eae8\";\n}\n.codicon-file-code:before {\n  content: \"\\eae9\";\n}\n.codicon-file-media:before {\n  content: \"\\eaea\";\n}\n.codicon-file-pdf:before {\n  content: \"\\eaeb\";\n}\n.codicon-file-submodule:before {\n  content: \"\\eaec\";\n}\n.codicon-file-symlink-directory:before {\n  content: \"\\eaed\";\n}\n.codicon-file-symlink-file:before {\n  content: \"\\eaee\";\n}\n.codicon-file-zip:before {\n  content: \"\\eaef\";\n}\n.codicon-files:before {\n  content: \"\\eaf0\";\n}\n.codicon-filter:before {\n  content: \"\\eaf1\";\n}\n.codicon-flame:before {\n  content: \"\\eaf2\";\n}\n.codicon-fold-down:before {\n  content: \"\\eaf3\";\n}\n.codicon-fold-up:before {\n  content: \"\\eaf4\";\n}\n.codicon-fold:before {\n  content: \"\\eaf5\";\n}\n.codicon-folder-active:before {\n  content: \"\\eaf6\";\n}\n.codicon-folder-opened:before {\n  content: \"\\eaf7\";\n}\n.codicon-gear:before {\n  content: \"\\eaf8\";\n}\n.codicon-gift:before {\n  content: \"\\eaf9\";\n}\n.codicon-gist-secret:before {\n  content: \"\\eafa\";\n}\n.codicon-gist:before {\n  content: \"\\eafb\";\n}\n.codicon-git-commit:before {\n  content: \"\\eafc\";\n}\n.codicon-git-compare:before {\n  content: \"\\eafd\";\n}\n.codicon-compare-changes:before {\n  content: \"\\eafd\";\n}\n.codicon-git-merge:before {\n  content: \"\\eafe\";\n}\n.codicon-github-action:before {\n  content: \"\\eaff\";\n}\n.codicon-github-alt:before {\n  content: \"\\eb00\";\n}\n.codicon-globe:before {\n  content: \"\\eb01\";\n}\n.codicon-grabber:before {\n  content: \"\\eb02\";\n}\n.codicon-graph:before {\n  content: \"\\eb03\";\n}\n.codicon-gripper:before {\n  content: \"\\eb04\";\n}\n.codicon-heart:before {\n  content: \"\\eb05\";\n}\n.codicon-home:before {\n  content: \"\\eb06\";\n}\n.codicon-horizontal-rule:before {\n  content: \"\\eb07\";\n}\n.codicon-hubot:before {\n  content: \"\\eb08\";\n}\n.codicon-inbox:before {\n  content: \"\\eb09\";\n}\n.codicon-issue-reopened:before {\n  content: \"\\eb0b\";\n}\n.codicon-issues:before {\n  content: \"\\eb0c\";\n}\n.codicon-italic:before {\n  content: \"\\eb0d\";\n}\n.codicon-jersey:before {\n  content: \"\\eb0e\";\n}\n.codicon-json:before {\n  content: \"\\eb0f\";\n}\n.codicon-kebab-vertical:before {\n  content: \"\\eb10\";\n}\n.codicon-key:before {\n  content: \"\\eb11\";\n}\n.codicon-law:before {\n  content: \"\\eb12\";\n}\n.codicon-lightbulb-autofix:before {\n  content: \"\\eb13\";\n}\n.codicon-link-external:before {\n  content: \"\\eb14\";\n}\n.codicon-link:before {\n  content: \"\\eb15\";\n}\n.codicon-list-ordered:before {\n  content: \"\\eb16\";\n}\n.codicon-list-unordered:before {\n  content: \"\\eb17\";\n}\n.codicon-live-share:before {\n  content: \"\\eb18\";\n}\n.codicon-loading:before {\n  content: \"\\eb19\";\n}\n.codicon-location:before {\n  content: \"\\eb1a\";\n}\n.codicon-mail-read:before {\n  content: \"\\eb1b\";\n}\n.codicon-mail:before {\n  content: \"\\eb1c\";\n}\n.codicon-markdown:before {\n  content: \"\\eb1d\";\n}\n.codicon-megaphone:before {\n  content: \"\\eb1e\";\n}\n.codicon-mention:before {\n  content: \"\\eb1f\";\n}\n.codicon-milestone:before {\n  content: \"\\eb20\";\n}\n.codicon-mortar-board:before {\n  content: \"\\eb21\";\n}\n.codicon-move:before {\n  content: \"\\eb22\";\n}\n.codicon-multiple-windows:before {\n  content: \"\\eb23\";\n}\n.codicon-mute:before {\n  content: \"\\eb24\";\n}\n.codicon-no-newline:before {\n  content: \"\\eb25\";\n}\n.codicon-note:before {\n  content: \"\\eb26\";\n}\n.codicon-octoface:before {\n  content: \"\\eb27\";\n}\n.codicon-open-preview:before {\n  content: \"\\eb28\";\n}\n.codicon-package:before {\n  content: \"\\eb29\";\n}\n.codicon-paintcan:before {\n  content: \"\\eb2a\";\n}\n.codicon-pin:before {\n  content: \"\\eb2b\";\n}\n.codicon-play:before {\n  content: \"\\eb2c\";\n}\n.codicon-run:before {\n  content: \"\\eb2c\";\n}\n.codicon-plug:before {\n  content: \"\\eb2d\";\n}\n.codicon-preserve-case:before {\n  content: \"\\eb2e\";\n}\n.codicon-preview:before {\n  content: \"\\eb2f\";\n}\n.codicon-project:before {\n  content: \"\\eb30\";\n}\n.codicon-pulse:before {\n  content: \"\\eb31\";\n}\n.codicon-question:before {\n  content: \"\\eb32\";\n}\n.codicon-quote:before {\n  content: \"\\eb33\";\n}\n.codicon-radio-tower:before {\n  content: \"\\eb34\";\n}\n.codicon-reactions:before {\n  content: \"\\eb35\";\n}\n.codicon-references:before {\n  content: \"\\eb36\";\n}\n.codicon-refresh:before {\n  content: \"\\eb37\";\n}\n.codicon-regex:before {\n  content: \"\\eb38\";\n}\n.codicon-remote-explorer:before {\n  content: \"\\eb39\";\n}\n.codicon-remote:before {\n  content: \"\\eb3a\";\n}\n.codicon-remove:before {\n  content: \"\\eb3b\";\n}\n.codicon-replace-all:before {\n  content: \"\\eb3c\";\n}\n.codicon-replace:before {\n  content: \"\\eb3d\";\n}\n.codicon-repo-clone:before {\n  content: \"\\eb3e\";\n}\n.codicon-repo-force-push:before {\n  content: \"\\eb3f\";\n}\n.codicon-repo-pull:before {\n  content: \"\\eb40\";\n}\n.codicon-repo-push:before {\n  content: \"\\eb41\";\n}\n.codicon-report:before {\n  content: \"\\eb42\";\n}\n.codicon-request-changes:before {\n  content: \"\\eb43\";\n}\n.codicon-rocket:before {\n  content: \"\\eb44\";\n}\n.codicon-root-folder-opened:before {\n  content: \"\\eb45\";\n}\n.codicon-root-folder:before {\n  content: \"\\eb46\";\n}\n.codicon-rss:before {\n  content: \"\\eb47\";\n}\n.codicon-ruby:before {\n  content: \"\\eb48\";\n}\n.codicon-save-all:before {\n  content: \"\\eb49\";\n}\n.codicon-save-as:before {\n  content: \"\\eb4a\";\n}\n.codicon-save:before {\n  content: \"\\eb4b\";\n}\n.codicon-screen-full:before {\n  content: \"\\eb4c\";\n}\n.codicon-screen-normal:before {\n  content: \"\\eb4d\";\n}\n.codicon-search-stop:before {\n  content: \"\\eb4e\";\n}\n.codicon-server:before {\n  content: \"\\eb50\";\n}\n.codicon-settings-gear:before {\n  content: \"\\eb51\";\n}\n.codicon-settings:before {\n  content: \"\\eb52\";\n}\n.codicon-shield:before {\n  content: \"\\eb53\";\n}\n.codicon-smiley:before {\n  content: \"\\eb54\";\n}\n.codicon-sort-precedence:before {\n  content: \"\\eb55\";\n}\n.codicon-split-horizontal:before {\n  content: \"\\eb56\";\n}\n.codicon-split-vertical:before {\n  content: \"\\eb57\";\n}\n.codicon-squirrel:before {\n  content: \"\\eb58\";\n}\n.codicon-star-full:before {\n  content: \"\\eb59\";\n}\n.codicon-star-half:before {\n  content: \"\\eb5a\";\n}\n.codicon-symbol-class:before {\n  content: \"\\eb5b\";\n}\n.codicon-symbol-color:before {\n  content: \"\\eb5c\";\n}\n.codicon-symbol-constant:before {\n  content: \"\\eb5d\";\n}\n.codicon-symbol-enum-member:before {\n  content: \"\\eb5e\";\n}\n.codicon-symbol-field:before {\n  content: \"\\eb5f\";\n}\n.codicon-symbol-file:before {\n  content: \"\\eb60\";\n}\n.codicon-symbol-interface:before {\n  content: \"\\eb61\";\n}\n.codicon-symbol-keyword:before {\n  content: \"\\eb62\";\n}\n.codicon-symbol-misc:before {\n  content: \"\\eb63\";\n}\n.codicon-symbol-operator:before {\n  content: \"\\eb64\";\n}\n.codicon-symbol-property:before {\n  content: \"\\eb65\";\n}\n.codicon-wrench:before {\n  content: \"\\eb65\";\n}\n.codicon-wrench-subaction:before {\n  content: \"\\eb65\";\n}\n.codicon-symbol-snippet:before {\n  content: \"\\eb66\";\n}\n.codicon-tasklist:before {\n  content: \"\\eb67\";\n}\n.codicon-telescope:before {\n  content: \"\\eb68\";\n}\n.codicon-text-size:before {\n  content: \"\\eb69\";\n}\n.codicon-three-bars:before {\n  content: \"\\eb6a\";\n}\n.codicon-thumbsdown:before {\n  content: \"\\eb6b\";\n}\n.codicon-thumbsup:before {\n  content: \"\\eb6c\";\n}\n.codicon-tools:before {\n  content: \"\\eb6d\";\n}\n.codicon-triangle-down:before {\n  content: \"\\eb6e\";\n}\n.codicon-triangle-left:before {\n  content: \"\\eb6f\";\n}\n.codicon-triangle-right:before {\n  content: \"\\eb70\";\n}\n.codicon-triangle-up:before {\n  content: \"\\eb71\";\n}\n.codicon-twitter:before {\n  content: \"\\eb72\";\n}\n.codicon-unfold:before {\n  content: \"\\eb73\";\n}\n.codicon-unlock:before {\n  content: \"\\eb74\";\n}\n.codicon-unmute:before {\n  content: \"\\eb75\";\n}\n.codicon-unverified:before {\n  content: \"\\eb76\";\n}\n.codicon-verified:before {\n  content: \"\\eb77\";\n}\n.codicon-versions:before {\n  content: \"\\eb78\";\n}\n.codicon-vm-active:before {\n  content: \"\\eb79\";\n}\n.codicon-vm-outline:before {\n  content: \"\\eb7a\";\n}\n.codicon-vm-running:before {\n  content: \"\\eb7b\";\n}\n.codicon-watch:before {\n  content: \"\\eb7c\";\n}\n.codicon-whitespace:before {\n  content: \"\\eb7d\";\n}\n.codicon-whole-word:before {\n  content: \"\\eb7e\";\n}\n.codicon-window:before {\n  content: \"\\eb7f\";\n}\n.codicon-word-wrap:before {\n  content: \"\\eb80\";\n}\n.codicon-zoom-in:before {\n  content: \"\\eb81\";\n}\n.codicon-zoom-out:before {\n  content: \"\\eb82\";\n}\n.codicon-list-filter:before {\n  content: \"\\eb83\";\n}\n.codicon-list-flat:before {\n  content: \"\\eb84\";\n}\n.codicon-list-selection:before {\n  content: \"\\eb85\";\n}\n.codicon-selection:before {\n  content: \"\\eb85\";\n}\n.codicon-list-tree:before {\n  content: \"\\eb86\";\n}\n.codicon-debug-breakpoint-function-unverified:before {\n  content: \"\\eb87\";\n}\n.codicon-debug-breakpoint-function:before {\n  content: \"\\eb88\";\n}\n.codicon-debug-breakpoint-function-disabled:before {\n  content: \"\\eb88\";\n}\n.codicon-debug-stackframe-active:before {\n  content: \"\\eb89\";\n}\n.codicon-debug-stackframe-dot:before {\n  content: \"\\eb8a\";\n}\n.codicon-debug-stackframe:before {\n  content: \"\\eb8b\";\n}\n.codicon-debug-stackframe-focused:before {\n  content: \"\\eb8b\";\n}\n.codicon-debug-breakpoint-unsupported:before {\n  content: \"\\eb8c\";\n}\n.codicon-symbol-string:before {\n  content: \"\\eb8d\";\n}\n.codicon-debug-reverse-continue:before {\n  content: \"\\eb8e\";\n}\n.codicon-debug-step-back:before {\n  content: \"\\eb8f\";\n}\n.codicon-debug-restart-frame:before {\n  content: \"\\eb90\";\n}\n.codicon-debug-alt:before {\n  content: \"\\eb91\";\n}\n.codicon-call-incoming:before {\n  content: \"\\eb92\";\n}\n.codicon-call-outgoing:before {\n  content: \"\\eb93\";\n}\n.codicon-menu:before {\n  content: \"\\eb94\";\n}\n.codicon-expand-all:before {\n  content: \"\\eb95\";\n}\n.codicon-feedback:before {\n  content: \"\\eb96\";\n}\n.codicon-group-by-ref-type:before {\n  content: \"\\eb97\";\n}\n.codicon-ungroup-by-ref-type:before {\n  content: \"\\eb98\";\n}\n.codicon-account:before {\n  content: \"\\eb99\";\n}\n.codicon-bell-dot:before {\n  content: \"\\eb9a\";\n}\n.codicon-debug-console:before {\n  content: \"\\eb9b\";\n}\n.codicon-library:before {\n  content: \"\\eb9c\";\n}\n.codicon-output:before {\n  content: \"\\eb9d\";\n}\n.codicon-run-all:before {\n  content: \"\\eb9e\";\n}\n.codicon-sync-ignored:before {\n  content: \"\\eb9f\";\n}\n.codicon-pinned:before {\n  content: \"\\eba0\";\n}\n.codicon-github-inverted:before {\n  content: \"\\eba1\";\n}\n.codicon-server-process:before {\n  content: \"\\eba2\";\n}\n.codicon-server-environment:before {\n  content: \"\\eba3\";\n}\n.codicon-pass:before {\n  content: \"\\eba4\";\n}\n.codicon-issue-closed:before {\n  content: \"\\eba4\";\n}\n.codicon-stop-circle:before {\n  content: \"\\eba5\";\n}\n.codicon-play-circle:before {\n  content: \"\\eba6\";\n}\n.codicon-record:before {\n  content: \"\\eba7\";\n}\n.codicon-debug-alt-small:before {\n  content: \"\\eba8\";\n}\n.codicon-vm-connect:before {\n  content: \"\\eba9\";\n}\n.codicon-cloud:before {\n  content: \"\\ebaa\";\n}\n.codicon-merge:before {\n  content: \"\\ebab\";\n}\n.codicon-export:before {\n  content: \"\\ebac\";\n}\n.codicon-graph-left:before {\n  content: \"\\ebad\";\n}\n.codicon-magnet:before {\n  content: \"\\ebae\";\n}\n.codicon-notebook:before {\n  content: \"\\ebaf\";\n}\n.codicon-redo:before {\n  content: \"\\ebb0\";\n}\n.codicon-check-all:before {\n  content: \"\\ebb1\";\n}\n.codicon-pinned-dirty:before {\n  content: \"\\ebb2\";\n}\n.codicon-pass-filled:before {\n  content: \"\\ebb3\";\n}\n.codicon-circle-large-filled:before {\n  content: \"\\ebb4\";\n}\n.codicon-circle-large-outline:before {\n  content: \"\\ebb5\";\n}\n.codicon-combine:before {\n  content: \"\\ebb6\";\n}\n.codicon-gather:before {\n  content: \"\\ebb6\";\n}\n.codicon-table:before {\n  content: \"\\ebb7\";\n}\n.codicon-variable-group:before {\n  content: \"\\ebb8\";\n}\n.codicon-type-hierarchy:before {\n  content: \"\\ebb9\";\n}\n.codicon-type-hierarchy-sub:before {\n  content: \"\\ebba\";\n}\n.codicon-type-hierarchy-super:before {\n  content: \"\\ebbb\";\n}\n.codicon-git-pull-request-create:before {\n  content: \"\\ebbc\";\n}\n.codicon-run-above:before {\n  content: \"\\ebbd\";\n}\n.codicon-run-below:before {\n  content: \"\\ebbe\";\n}\n.codicon-notebook-template:before {\n  content: \"\\ebbf\";\n}\n.codicon-debug-rerun:before {\n  content: \"\\ebc0\";\n}\n.codicon-workspace-trusted:before {\n  content: \"\\ebc1\";\n}\n.codicon-workspace-untrusted:before {\n  content: \"\\ebc2\";\n}\n.codicon-workspace-unknown:before {\n  content: \"\\ebc3\";\n}\n.codicon-terminal-cmd:before {\n  content: \"\\ebc4\";\n}\n.codicon-terminal-debian:before {\n  content: \"\\ebc5\";\n}\n.codicon-terminal-linux:before {\n  content: \"\\ebc6\";\n}\n.codicon-terminal-powershell:before {\n  content: \"\\ebc7\";\n}\n.codicon-terminal-tmux:before {\n  content: \"\\ebc8\";\n}\n.codicon-terminal-ubuntu:before {\n  content: \"\\ebc9\";\n}\n.codicon-terminal-bash:before {\n  content: \"\\ebca\";\n}\n.codicon-arrow-swap:before {\n  content: \"\\ebcb\";\n}\n.codicon-copy:before {\n  content: \"\\ebcc\";\n}\n.codicon-person-add:before {\n  content: \"\\ebcd\";\n}\n.codicon-filter-filled:before {\n  content: \"\\ebce\";\n}\n.codicon-wand:before {\n  content: \"\\ebcf\";\n}\n.codicon-debug-line-by-line:before {\n  content: \"\\ebd0\";\n}\n.codicon-inspect:before {\n  content: \"\\ebd1\";\n}\n.codicon-layers:before {\n  content: \"\\ebd2\";\n}\n.codicon-layers-dot:before {\n  content: \"\\ebd3\";\n}\n.codicon-layers-active:before {\n  content: \"\\ebd4\";\n}\n.codicon-compass:before {\n  content: \"\\ebd5\";\n}\n.codicon-compass-dot:before {\n  content: \"\\ebd6\";\n}\n.codicon-compass-active:before {\n  content: \"\\ebd7\";\n}\n.codicon-azure:before {\n  content: \"\\ebd8\";\n}\n.codicon-issue-draft:before {\n  content: \"\\ebd9\";\n}\n.codicon-git-pull-request-closed:before {\n  content: \"\\ebda\";\n}\n.codicon-git-pull-request-draft:before {\n  content: \"\\ebdb\";\n}\n.codicon-debug-all:before {\n  content: \"\\ebdc\";\n}\n.codicon-debug-coverage:before {\n  content: \"\\ebdd\";\n}\n.codicon-run-errors:before {\n  content: \"\\ebde\";\n}\n.codicon-folder-library:before {\n  content: \"\\ebdf\";\n}\n.codicon-debug-continue-small:before {\n  content: \"\\ebe0\";\n}\n.codicon-beaker-stop:before {\n  content: \"\\ebe1\";\n}\n.codicon-graph-line:before {\n  content: \"\\ebe2\";\n}\n.codicon-graph-scatter:before {\n  content: \"\\ebe3\";\n}\n.codicon-pie-chart:before {\n  content: \"\\ebe4\";\n}\n.codicon-bracket:before {\n  content: \"\\eb0f\";\n}\n.codicon-bracket-dot:before {\n  content: \"\\ebe5\";\n}\n.codicon-bracket-error:before {\n  content: \"\\ebe6\";\n}\n.codicon-lock-small:before {\n  content: \"\\ebe7\";\n}\n.codicon-azure-devops:before {\n  content: \"\\ebe8\";\n}\n.codicon-verified-filled:before {\n  content: \"\\ebe9\";\n}\n.codicon-newline:before {\n  content: \"\\ebea\";\n}\n.codicon-layout:before {\n  content: \"\\ebeb\";\n}\n.codicon-layout-activitybar-left:before {\n  content: \"\\ebec\";\n}\n.codicon-layout-activitybar-right:before {\n  content: \"\\ebed\";\n}\n.codicon-layout-panel-left:before {\n  content: \"\\ebee\";\n}\n.codicon-layout-panel-center:before {\n  content: \"\\ebef\";\n}\n.codicon-layout-panel-justify:before {\n  content: \"\\ebf0\";\n}\n.codicon-layout-panel-right:before {\n  content: \"\\ebf1\";\n}\n.codicon-layout-panel:before {\n  content: \"\\ebf2\";\n}\n.codicon-layout-sidebar-left:before {\n  content: \"\\ebf3\";\n}\n.codicon-layout-sidebar-right:before {\n  content: \"\\ebf4\";\n}\n.codicon-layout-statusbar:before {\n  content: \"\\ebf5\";\n}\n.codicon-layout-menubar:before {\n  content: \"\\ebf6\";\n}\n.codicon-layout-centered:before {\n  content: \"\\ebf7\";\n}\n.codicon-target:before {\n  content: \"\\ebf8\";\n}\n.codicon-indent:before {\n  content: \"\\ebf9\";\n}\n.codicon-record-small:before {\n  content: \"\\ebfa\";\n}\n.codicon-error-small:before {\n  content: \"\\ebfb\";\n}\n.codicon-arrow-circle-down:before {\n  content: \"\\ebfc\";\n}\n.codicon-arrow-circle-left:before {\n  content: \"\\ebfd\";\n}\n.codicon-arrow-circle-right:before {\n  content: \"\\ebfe\";\n}\n.codicon-arrow-circle-up:before {\n  content: \"\\ebff\";\n}\n.codicon-layout-sidebar-right-off:before {\n  content: \"\\ec00\";\n}\n.codicon-layout-panel-off:before {\n  content: \"\\ec01\";\n}\n.codicon-layout-sidebar-left-off:before {\n  content: \"\\ec02\";\n}\n.codicon-blank:before {\n  content: \"\\ec03\";\n}\n"
  },
  {
    "path": "src/renderer/less/compact.less",
    "content": "#app.compact {\n  .content-inner {\n    zoom: 0.95;\n  }\n  .app-sidebar-content {\n    padding: 0px;\n\n    .app-sidebar-header-text {\n      padding: 6px 10px;\n      margin: 0px;\n    }\n    .app-sidebar-item {\n      display: flex;\n      width: 100%;\n      padding: 8px 12px;\n      font-size: 13px;\n      margin: 0px;\n      border: 1px solid transparent;\n      border-radius: 0px;\n      transition: unset;\n      transform: unset;\n\n      &:active {\n        background: var(--selected-click);\n      }\n\n      &::after {\n        display: none;\n      }\n\n      &.active {\n        background: var(--keyColor-disabled);\n      }\n    }\n    .sidebar-icon {\n      width: 14px;\n      height: 16px;\n      margin-right: 8px;\n    }\n\n    .folder-body {\n      border-radius: 0px;\n      padding: 0px;\n    }\n  }\n\n  @media (max-width: 951px) {\n    #app-content {\n      // zoom: 0.8;\n    }\n  }\n}\n\n// if page width is less than 951px\n@media (max-width: 951px) {\n  #app-content {\n    // zoom: 0.8;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/directives.less",
    "content": "#app.navbar {\n  --navigationBarHeight: 38px;\n}\n\n#app.twopanel {\n  --chromeHeight1: 46px;\n  --chromeHeight2: 90px;\n  --chromeHeight: calc(var(--chromeHeight1) + var(--chromeHeight2));\n\n  .modular-fs .app-drawer .lyric-footer {\n    bottom: var(--chromeHeight2);\n  }\n\n  .app-chrome {\n    &:not(.chrome-bottom) {\n      .app-chrome--center {\n        flex: 1;\n\n        .top-nav-group {\n          background: #1e1e1e99;\n          border: 1px solid lighten(@baseColor, 8);\n          border-radius: 12px;\n          display: flex;\n          height: 32px;\n\n          .app-sidebar-item {\n            background-color: #1e1e1e00;\n            border-radius: 10px !important;\n            border: 0px;\n            min-width: 120px;\n            padding: 6px;\n            justify-content: center;\n            align-items: center;\n            margin: 0px;\n            height: 100%;\n            position: relative;\n            white-space: nowrap;\n\n            ._svg-icon {\n              flex: 0 0 auto;\n            }\n\n            &:before {\n              --dist: 1px;\n              content: \"\";\n              position: absolute;\n              top: var(--dist);\n              left: var(--dist);\n              right: var(--dist);\n              bottom: var(--dist);\n              background-color: #fff;\n              opacity: 0;\n              border-radius: 10px;\n              transform: scale(0.5);\n              transition:\n                transform 0.2s ease-in-out,\n                opacity 0.2s ease-in-out;\n            }\n\n            &:after {\n              display: none;\n            }\n\n            &:hover {\n              background-color: transparent;\n\n              &:before {\n                transition:\n                  transform 0.1s ease-in-out,\n                  opacity 0.1s ease-in-out;\n                opacity: 0.1;\n                transform: scale(1);\n              }\n            }\n\n            &.active {\n              background-color: transparent;\n\n              &:before {\n                opacity: 0.2;\n                transform: scale(1);\n              }\n            }\n\n            &.md-btn-primary {\n              box-shadow: 0px 0px 0px 1px lighten(@baseColor, @colorMixRate * 8);\n              background-color: lighten(@baseColor, @colorMixRate * 5);\n              z-index: 1;\n            }\n          }\n        }\n      }\n    }\n\n    .app-mainmenu {\n      width: 30px;\n      height: 30px;\n    }\n\n    .search-input {\n      width: 180px;\n    }\n\n    height: var(--chromeHeight1);\n\n    &.chrome-bottom {\n      background: var(--color2);\n      -webkit-app-region: no-drag;\n      height: var(--chromeHeight2);\n      box-shadow:\n        0px -2px 6px rgb(20 20 20 / 12%),\n        0px -1px 0px 0px rgb(200 200 200 / 12%);\n      z-index: 4;\n\n      .app-chrome-playback-duration-bottom {\n        width: 100%;\n\n        .col {\n          display: flex;\n        }\n\n        .col-sm-auto {\n          width: 4em;\n          display: flex;\n          justify-content: center;\n          align-items: center;\n          font-size: 0.8em;\n        }\n\n        input[type=\"range\"] {\n          appearance: none;\n          width: 100%;\n          height: 5px;\n          background-color: rgb(200 200 200 / 10%);\n          border-radius: 6px;\n          box-shadow: 0px 0px 0px 1px rgba(0 0 0 / 10%);\n          align-self: center;\n\n          &::-webkit-slider-thumb {\n            opacity: 0;\n            transform: scale(1);\n            -webkit-appearance: none;\n            appearance: none;\n            width: 16px;\n            height: 16px;\n            border-radius: 100%;\n            background: var(--keyColor);\n            cursor: default;\n            transition:\n              opacity 0.1s var(--appleEase),\n              transform 0.1s var(--appleEase);\n          }\n\n          &:hover {\n            &::-webkit-slider-thumb {\n              opacity: 1;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  .app-sidebar-footer--controls {\n    display: none !important;\n  }\n\n  .app-chrome.chrome-bottom {\n    .app-playback-controls .actions {\n      align-self: center;\n    }\n\n    -webkit-app-region: no-drag;\n\n    .playback-button.play,\n    .playback-button.pause,\n    .playback-button.stop {\n      width: 42px;\n      height: 42px;\n      border-radius: 50%;\n      margin: 6px;\n    }\n\n    .app-chrome--center {\n      display: flex;\n      flex-direction: column;\n\n      .app-chrome-playback-controls {\n        display: flex;\n        z-index: 1;\n        // margin-bottom: 12px;\n      }\n\n      .app-chrome-playback-duration {\n        position: relative;\n        width: 80%;\n        -webkit-app-region: no-drag;\n        height: 16px;\n\n        .song-progress {\n          @bgColor: transparent;\n          height: 16px;\n          position: absolute;\n          bottom: 4px;\n          left: 0px;\n          right: 4px;\n          background: @bgColor;\n          z-index: 0;\n\n          .song-duration {\n            display: flex;\n          }\n\n          .song-duration p {\n            font-weight: 400;\n            font-size: 10px;\n            height: 1.2em;\n            line-height: 1.3em;\n            overflow: hidden;\n            margin: 0 0 0 0.25em;\n          }\n\n          &:hover {\n            > input[type=\"range\"] {\n              &::-webkit-slider-thumb {\n                opacity: 1;\n                transform: scale(1);\n                z-index: 1;\n              }\n            }\n          }\n\n          input[type=\"range\"] {\n            appearance: none;\n            width: 100%;\n            height: 4px;\n            background-color: rgb(200 200 200 / 10%);\n            border-radius: 2px;\n\n            &::-webkit-slider-thumb {\n              opacity: 0;\n              transform: scale(0.5);\n              -webkit-appearance: none;\n              appearance: none;\n              width: 12px;\n              height: 12px;\n              border-radius: 100%;\n              background: var(--keyColor);\n              cursor: default;\n              transition:\n                opacity 0.1s var(--appleEase),\n                transform 0.1s var(--appleEase);\n            }\n          }\n        }\n      }\n    }\n\n    .app-chrome--left {\n      width: 30%;\n      justify-content: flex-start;\n      align-items: flex-start;\n      -webkit-app-region: no-drag !important;\n\n      .playback-controls {\n        -webkit-app-region: no-drag !important;\n\n        .artwork {\n          --offset: 20px;\n          --marginOffset: 2;\n          --size: calc(var(--chromeHeight2) - var(--offset));\n          width: var(--size);\n          height: var(--size);\n          margin: 0 calc(var(--offset) / var(--marginOffset)) 0 calc(var(--offset) / var(--marginOffset));\n\n          .mediaitem-artwork,\n          img {\n            border-radius: calc(var(--mediaItemRadius) / 2);\n          }\n        }\n\n        .playback-info {\n          align-items: flex-start;\n          margin: 8px;\n\n          .song-name {\n            text-align: left;\n            font-size: 0.8em;\n            font-weight: 500;\n            width: 100%;\n            -webkit-mask-image: linear-gradient(-90deg, transparent 0%, transparent 10%, black 20%);\n          }\n\n          .song-artist,\n          .song-album {\n            font-size: 0.75em;\n            opacity: 0.8;\n            cursor: pointer;\n            white-space: nowrap;\n            max-width: 360px;\n            -webkit-mask-image: linear-gradient(-90deg, transparent 0%, transparent 10%, black 20%);\n            width: 100%;\n\n            &:hover {\n              text-decoration: underline;\n            }\n          }\n\n          .audio-type {\n            margin: 0px;\n          }\n\n          .song-artist-album-content {\n            text-align: left;\n            font-size: 12px;\n          }\n        }\n\n        width: 100%;\n        height: 100%;\n        max-width: 100%;\n        border: 0px;\n      }\n\n      flex: 0 0 auto;\n    }\n\n    .app-chrome--right {\n      width: 30%;\n      flex: 0 0 auto;\n      padding-right: 8px;\n    }\n  }\n\n  .collection-page {\n    .top-fab {\n      bottom: 96px;\n    }\n  }\n}\n\n// screen width is less than 768px\n@media (max-width: 1100px) {\n  #app.twopanel .app-chrome:not(.chrome-bottom) .app-chrome--center {\n    flex: unset;\n  }\n\n  #app.twopanel .app-chrome:not(.chrome-bottom) .app-chrome--center .top-nav-group .app-sidebar-item {\n    min-width: 110px;\n    .sidebar-item-text {\n      display: none;\n    }\n\n    .sidebar-icon {\n      margin: 0px;\n    }\n  }\n}\n\n@media (max-width: 1000px) {\n  #app.twopanel .app-chrome:not(.chrome-bottom) .app-chrome--center {\n    flex: unset;\n  }\n\n  #app.twopanel .app-chrome:not(.chrome-bottom) .app-chrome--center .top-nav-group .app-sidebar-item {\n    min-width: 60px;\n    .sidebar-item-text {\n      display: none;\n    }\n\n    .sidebar-icon {\n      margin: 0px;\n    }\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/elements.less",
    "content": "// Form\n\n.md-select {\n  padding: 6px;\n  border-radius: 6px;\n  border: 1px solid rgba(200, 200, 200, 0.1);\n  border-top: 1px solid rgba(100, 100, 100, 0.5);\n  font-family: inherit;\n  font-size: 14px;\n  background: rgba(100, 100, 100, 0.25);\n  color: #eee;\n\n  option {\n    font-size: 1em;\n    font-family: inherit;\n    padding: 8px 16px;\n    background: #404040;\n  }\n\n  optgroup {\n    background: #2c2c2c;\n  }\n\n  &:focus {\n    outline: solid 1px var(--selected);\n  }\n}\n\n// Buttons\n.md-btn {\n  font-family: inherit;\n  background: rgb(100 100 100 / 25%);\n  padding: 8px 14px;\n  border-radius: 6px;\n  font-size: 14px;\n  border: 1px solid rgba(100, 100, 100, 0.35);\n  border-top: 1px solid rgba(100, 100, 100, 0.5);\n  color: #eee;\n  white-space: nowrap;\n  transition:\n    transform 0.2s var(--appleEase),\n    box-shadow 0.2s var(--appleEase);\n\n  &.md-btn-block {\n    display: block;\n    width: 100%;\n  }\n\n  &.md-btn-glyph {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    width: 100%;\n  }\n\n  &.md-btn-primary {\n    background: #ff2b52a6;\n    color: white;\n    border: 1px solid rgb(220 53 69 / 25%);\n    border-top: 1px solid rgb(220 53 69 / 50%);\n  }\n\n  &.md-btn-small {\n    padding: 6px 8px;\n    font-size: 13px;\n  }\n\n  &:hover {\n    filter: brightness(125%);\n  }\n\n  &:active {\n    filter: brightness(75%);\n    transform: scale(0.98);\n    transition:\n      transform 0s var(--appleEase),\n      box-shadow 0.2s var(--appleEase);\n  }\n\n  &.md-btn-icon {\n    display: inline-flex;\n    vertical-align: middle;\n    justify-content: center;\n\n    > img {\n      margin: 0px 16px 0px 0px;\n      pointer-events: none;\n    }\n\n    > .md-btn-text {\n      margin: 0px;\n    }\n  }\n}\n\n.btn-group {\n  display: inline-flex;\n  justify-content: center;\n  align-items: center;\n\n  > .md-btn {\n    border-radius: 0px;\n    width: 100%;\n  }\n\n  > .md-btn:first-child {\n    border-top-left-radius: 6px;\n    border-bottom-left-radius: 6px;\n  }\n\n  > .md-btn:last-child {\n    border-top-right-radius: 6px;\n    border-bottom-right-radius: 6px;\n  }\n\n  > .md-btn:not(:first-child):not(:last-child) {\n    border-radius: 0px;\n  }\n}\n\n.md-close-btn {\n  -webkit-mask-image: url(\"ameres://icons/webui/close.svg\");\n  -webkit-mask-repeat: no-repeat;\n  -webkit-mask-position: center;\n  background-color: white;\n  opacity: 0.75;\n  -webkit-mask-size: contain;\n  height: 18px;\n  width: 18px;\n}\n\n.md-ico-play {\n  content: url(\"./assets/play.svg\");\n  width: 10px;\n  height: 12px;\n  margin-right: 1px;\n  align-self: center;\n}\n\n.md-ico-shuffle {\n  content: url(\"./assets/shuffle.svg\");\n  width: 1em;\n  height: 1em;\n  margin-right: 1px;\n  margin-bottom: -2px;\n  align-self: center;\n}\n\n.md-ico-remove {\n  content: url(\"./assets/feather/x-circle-white.svg\");\n  width: 16px;\n  height: 16px;\n  margin-right: 1px;\n  margin-bottom: -1.5px;\n  align-self: center;\n}\n\n.md-ico-add {\n  content: url(\"./assets/feather/plus-circle-white.svg\");\n  width: 1em;\n  height: 1em;\n  margin-right: 1px;\n  margin-bottom: -1.5px;\n  align-self: center;\n}\n\n.page-btn {\n  align-self: center;\n  height: 32px;\n  width: max-content;\n}\n\n.page-btn img {\n  height: 100%;\n  align-self: center;\n}\n\n.md-ico-first {\n  content: url(\"./assets/angles-left.svg\");\n}\n\n.md-ico-prev {\n  content: url(\"./assets/chevron-left.svg\");\n}\n\n.md-ico-next {\n  content: url(\"./assets/chevron-right.svg\");\n}\n\n.md-ico-last {\n  content: url(\"./assets/angles-right.svg\");\n}\n\n.reload-btn {\n  background: rgb(86 86 86 / 52%);\n  border-radius: 100%;\n  width: 32px;\n  height: 32px;\n  border: 0px;\n  appearance: none;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.reload-btn:hover {\n  background: rgb(86 86 86 / 80%);\n  cursor: pointer;\n}\n\n.reload-btn > svg {\n  height: 50%;\n  color: #eee;\n}\n\n.wr-btn {\n  font-family: inherit;\n  appearance: none;\n  border: 0px;\n  border-radius: 6px;\n  padding: 8px;\n  font-weight: 600;\n  background: rgb(80 80 80 / 70%);\n  color: white;\n}\n\n.cd-btn-seeall {\n  background: transparent;\n  border: 0px;\n  color: var(--keyColor);\n  font-family: inherit;\n  font-weight: 500;\n  font-size: 16px;\n  border-radius: 4px;\n  padding: 6px;\n\n  &:hover {\n    cursor: pointer;\n    background: rgb(200 200 200 / 10%);\n  }\n}\n\n// Media Item Elements\n\n.mediaitem-artwork {\n  border-radius: var(--mediaItemRadius);\n  overflow: hidden;\n  flex: 0 0 auto;\n  position: relative;\n  width: 100%;\n  height: 100%;\n\n  .animatedartwork-view-box {\n    position: absolute;\n    top: 0px;\n    width: 100%;\n    height: 100%;\n\n    .animated {\n      position: absolute;\n      top: 0px;\n      width: 100%;\n      height: 100%;\n\n      video {\n        width: 100%;\n        height: 100%;\n      }\n    }\n  }\n\n  &.rounded {\n    border-radius: 100%;\n\n    &::after {\n      border-radius: 100%;\n    }\n  }\n\n  &::after {\n    content: \"\";\n    box-shadow: var(--mediaItemShadow);\n    z-index: 1;\n    width: 100%;\n    height: 100%;\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: inherit;\n  }\n\n  img {\n    width: 100%;\n    height: 100%;\n    object-fit: cover;\n    image-rendering: -webkit-optimize-contrast;\n    pointer-events: none;\n    background-image: url(\"./assets/MissingArtwork.svg\");\n    background-size: cover;\n    background-position: center;\n  }\n\n  &.no-shadow {\n    box-shadow: none;\n\n    &::after {\n      display: none;\n    }\n  }\n\n  &.subtle-shadow {\n    box-shadow: var(--mediaItemShadow-ShadowSubtle);\n  }\n\n  &.shadow {\n    box-shadow: var(--mediaItemShadow-Shadow);\n  }\n}\n\n#artworkLCD img {\n  image-rendering: auto;\n}\n\n/* queue item */\n.cd-queue-item {\n  border-bottom: 0px solid rgb(200 200 200 / 10%);\n  padding: 1px;\n  padding-bottom: 9px;\n  padding-top: 9px;\n\n  .row,\n  .col {\n    padding: 0px;\n    margin: 0px;\n  }\n\n  .artwork {\n    width: 42px;\n    height: 42px;\n    flex: 0 0 auto;\n    &.circle {\n      border-radius: 50%;\n      .mediaitem-artwork {\n        border-radius: 50%;\n      }\n      img {\n        border-radius: 50%;\n      }\n    }\n  }\n\n  &:hover {\n    background: var(--selected);\n  }\n\n  &.selected {\n    background: var(--selected);\n  }\n\n  &:active {\n    background: var(--selected-click);\n    color: #eee;\n  }\n\n  &.hintactive {\n    background: var(--keyColor);\n    border-radius: 6px;\n  }\n\n  .queue-info {\n    justify-content: center;\n    display: flex;\n    flex-direction: column;\n    flex-grow: 1;\n\n    .queue-title {\n      font-size: 14px;\n    }\n\n    .queue-subtitle {\n      font-size: 0.7em;\n      opacity: 0.7;\n    }\n  }\n\n  .queue-duration-info {\n    display: flex;\n    flex-grow: 0;\n  }\n\n  .queue-duration {\n    font-size: 14px;\n    justify-content: center;\n    min-width: 60px;\n    height: 100%;\n  }\n\n  .queue-explicit-icon {\n    display: flex;\n    width: 24px;\n    padding: 0px;\n  }\n\n  .explicit-icon {\n    background-image: url(\"./assets/explicit.svg\");\n    height: 12px;\n    width: 36px;\n    filter: contrast(0);\n    background-repeat: no-repeat;\n  }\n}\n\n.search-hints .cd-queue-item {\n  &:hover {\n    background: var(--selected);\n    border-radius: 6px;\n\n    .circular-play-button {\n      opacity: 1;\n    }\n  }\n  &:active {\n    background: var(--selected-click);\n    color: #eee;\n    border-radius: 6px;\n  }\n}\n\n/* Circle Play Button */\n.circular-play-button {\n  position: relative;\n  opacity: 0;\n  top: -34px;\n  z-index: 5;\n  left: 8px;\n  align-items: center;\n  background: rgba(100, 100, 100, 0.5);\n  border: none;\n  cursor: pointer;\n  border-radius: 100%;\n  height: 26px;\n  box-shadow: var(--ciderShadow-Generic);\n}\n\n/* horizontal media scroller */\n.cd-hmedia-scroller {\n  &::-webkit-scrollbar-thumb {\n    box-shadow: none;\n  }\n\n  &:hover::-webkit-scrollbar-thumb {\n    box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n  }\n\n  &.hmedia-scroller-card {\n    .mediaitem-card {\n      margin: 16px;\n    }\n  }\n}\n\n/* mediaitem-list-item */\n.cd-mediaitem-list-item {\n  width: 100%;\n  height: 60px;\n  display: flex;\n  flex: 0 0 auto;\n  flex-direction: row;\n  font-size: 14px;\n  justify-content: center-between;\n  align-items: center;\n  border-radius: var(--mediaItemRadius);\n  position: relative;\n\n  .listitem-content {\n    width: 100%;\n    height: 60px;\n    display: flex;\n    flex: 0 0 auto;\n    flex-direction: row;\n    font-size: 14px;\n    justify-content: center-between;\n    align-items: center;\n    border-radius: var(--mediaItemRadius);\n    position: relative;\n  }\n\n  &:hover {\n    .heart-icon {\n      display: none;\n    }\n  }\n\n  .popular {\n    background-image: url(assets/star.svg);\n    background-repeat: no-repeat;\n    background-size: 10px;\n    width: 10px;\n    height: 10px;\n    position: absolute;\n    left: 3px;\n  }\n\n  .artwork {\n    height: 42px;\n    width: 42px;\n    object-fit: cover;\n    object-position: center;\n    flex: 0 0 auto;\n    background-repeat: no-repeat;\n    margin: 12px;\n    border: 0px;\n    outline: none;\n    position: relative;\n    overflow: hidden;\n    border-radius: var(--mediaItemRadiusSmall);\n\n    .mediaitem-artwork {\n      border-radius: var(--mediaItemRadiusSmall);\n    }\n\n    .overlay-play {\n      background: rgba(0, 0, 0, 0.5);\n      opacity: 0;\n      appearance: none;\n      border: 0;\n      position: absolute;\n      top: 0;\n      left: 0;\n      width: 100%;\n      height: 100%;\n      padding: 0px;\n      z-index: 5;\n      cursor: pointer;\n\n      &:hover {\n        opacity: 1;\n      }\n\n      &:active {\n        background: var(--selected-click);\n      }\n    }\n  }\n\n  .artwork.round {\n    border-radius: var(--mediaItemRadiusRound);\n  }\n\n  .info-rect {\n    height: 100%;\n    display: flex;\n    flex-flow: column;\n    justify-content: center;\n    flex-grow: 1;\n  }\n\n  .title {\n    width: 100%;\n  }\n\n  .subtitle {\n    width: 90%;\n    font-size: 0.8em;\n    opacity: 0.7;\n  }\n\n  .duration {\n    min-width: 60px;\n    text-align: center;\n    height: 100%;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n  }\n\n  .metainfo {\n    min-width: 145px;\n    text-align: center;\n    height: 100%;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n  }\n\n  .heart-unfilled {\n    -webkit-mask-image: url(\"assets/feather/heart.svg\");\n    height: 12px;\n    width: 12px;\n    background-repeat: no-repeat;\n    background-color: #999;\n  }\n\n  .heart-filled {\n    -webkit-mask-image: url(\"assets/feather/heart-fill.svg\");\n    height: 12px;\n    width: 12px;\n    background-repeat: no-repeat;\n    background-color: #999;\n  }\n\n  .explicit-icon {\n    background-image: url(\"./assets/explicit.svg\");\n    height: 12px;\n    width: 36px;\n    filter: contrast(0);\n    background-repeat: no-repeat;\n  }\n\n  .heart-icon {\n    display: flex;\n    position: absolute;\n    left: 20px;\n  }\n\n  /* CSS.gg\n  */\n  @keyframes load-bar {\n    10% {\n      box-shadow: inset 0 -4px 0;\n    }\n\n    20% {\n      box-shadow: inset 0 -10px 0;\n    }\n\n    30% {\n      box-shadow: inset 0 -12px 0;\n    }\n\n    40% {\n      box-shadow: inset 0 -8px 0;\n    }\n\n    50% {\n      box-shadow: inset 0 -4px 0;\n    }\n\n    60% {\n      box-shadow: inset 0 -6px 0;\n    }\n\n    80% {\n      box-shadow: inset 0 -12px 0;\n    }\n\n    90% {\n      box-shadow: inset 0 -6px 0;\n    }\n\n    to {\n      box-shadow: inset 0 -2px 0;\n    }\n  }\n\n  .loadbar-sound,\n  .loadbar-sound::after,\n  .loadbar-sound::before {\n    animation: load-bar 1.3s ease infinite alternate;\n    box-sizing: border-box;\n    width: 3px;\n    height: 28px;\n    box-shadow: inset 0 -12px 0;\n  }\n\n  .loadbar-sound {\n    margin-left: 22px;\n    margin-top: -16px;\n    position: relative;\n    transform: scale(var(--load-bar, 1));\n    color: var(--keyColor);\n    display: block;\n  }\n\n  .loadbar-sound::after,\n  .loadbar-sound::before {\n    content: \"\";\n    position: absolute;\n    bottom: 0;\n  }\n\n  .loadbar-sound::before {\n    left: -4.5px;\n    animation-delay: -2.4s;\n  }\n\n  .loadbar-sound::after {\n    right: -4.2px;\n    animation-delay: -3.7s;\n  }\n\n  .isLibrary {\n    flex: 0 0 auto;\n    width: 40px;\n    text-align: center;\n\n    button {\n      appearance: none;\n      border: 0px;\n      background: transparent;\n      cursor: pointer;\n      filter: contrast(0.8);\n    }\n  }\n\n  &:hover {\n    background: rgb(200 200 200 / 10%);\n    box-shadow: var(--mediaItemShadow);\n\n    .overlay-play {\n      opacity: 1;\n    }\n  }\n\n  &.mediaitem-selected {\n    background: var(--selected);\n    box-shadow: var(--mediaItemShadow);\n  }\n\n  &:active {\n    background: var(--selected-click);\n    box-shadow: var(--mediaItemShadow);\n    color: #eee;\n  }\n\n  &.disabled {\n    opacity: 0.5;\n    pointer-events: none;\n  }\n\n  //  list item compact\n  &.compact {\n    height: 40px;\n    font-size: 13px;\n\n    .artwork {\n      display: none;\n    }\n\n    .info-rect {\n      padding-left: 1em;\n    }\n  }\n}\n\n/* mediaitem-hrect */\n.cd-mediaitem-hrect {\n  background: rgb(255 255 255 / 18%);\n  width: 264px;\n  height: 100px;\n  display: inline-flex;\n  flex: 0 0 auto;\n  flex-direction: row;\n  font-size: 14px;\n  justify-content: center;\n  align-items: center;\n  border-radius: 6px;\n  cursor: pointer;\n\n  .artwork {\n    height: 70px;\n    width: 70px;\n    background: blue;\n    border-radius: var(--mediaItemRadius);\n    background: var(--artwork);\n    background-size: contain;\n    flex: 0 0 auto;\n    background-repeat: no-repeat;\n    margin: 18px;\n  }\n\n  .artwork.round {\n    border-radius: var(--mediaItemRadiusRound);\n  }\n\n  .info-rect {\n    width: 100%;\n  }\n\n  .title {\n    width: 100%;\n    text-align: center;\n  }\n\n  .subtitle {\n    width: 100%;\n    text-align: center;\n    font-size: 12px;\n  }\n}\n\n/* mediaitem-square-sp */\n.cd-mediaitem-square-sp {\n  --spcolor: var(\"\");\n  width: 190px;\n  height: 245px;\n  display: inline-flex;\n  flex: 0 0 auto;\n  flex-direction: column;\n  font-size: 14px;\n  justify-content: flex-start;\n  align-items: center;\n  border-radius: 6px;\n  margin-left: 10px;\n  cursor: pointer;\n  background-color: var(--spcolor);\n\n  .artwork {\n    height: 190px;\n    width: 190px;\n    background: blue;\n    border-top-left-radius: 6px;\n    border-top-right-radius: 6px;\n    background: var(--artwork);\n    background-size: cover;\n    flex: 0 0 auto;\n    margin: 6px;\n    margin-top: 0px;\n\n    &.round {\n      border-radius: var(--mediaItemRadiusRound);\n    }\n\n    &:hover {\n      box-shadow: rgb(0 0 0 / 50%) 0 0 0 1000000px inset;\n    }\n  }\n\n  .title {\n    width: 90%;\n    text-align: center;\n  }\n\n  .subtitle {\n    width: 100%;\n    text-align: center;\n    font-size: 12px;\n  }\n\n  > .cd-mediaitem-square-large-overlay {\n    z-index: 3;\n\n    &:hover {\n      opacity: 1;\n    }\n  }\n\n  + .cd-mediaitem-square-large-overlay {\n    pointer-events: none;\n  }\n\n  &:hover + .cd-mediaitem-square-large-overlay {\n    opacity: 1;\n  }\n\n  &:hover {\n    box-shadow: rgb(0 0 0 / 50%) 0 0 0 1000000px inset;\n  }\n}\n\n/* mediaitem-square-large */\n.cd-mediaitem-square-large {\n  width: 190px;\n  height: 250px;\n  display: inline-flex;\n  flex: 0 0 auto;\n  flex-direction: column;\n  font-size: 14px;\n  justify-content: flex-start;\n  align-items: center;\n  border-radius: 6px;\n  margin-left: 10px;\n  cursor: pointer;\n\n  > * {\n    z-index: inherit;\n  }\n}\n\n.cd-mediaitem-square-large .artwork {\n  height: 190px;\n  width: 190px;\n  background: blue;\n  border-top-left-radius: 6px;\n  border-top-right-radius: 6px;\n  background: var(--artwork);\n  background-size: cover;\n  flex: 0 0 auto;\n  margin: 6px;\n  margin-top: 0px;\n}\n\n.cd-mediaitem-square-large-overlay {\n  position: absolute;\n  width: 190px;\n  float: right;\n  height: 250px;\n  top: 0px;\n  margin: 10px;\n  margin-top: 0px;\n  opacity: 0;\n}\n\n.cd-mediaitem-square-large-overlay > * {\n  pointer-events: auto;\n}\n\n.cd-mediaitem-square-large > .cd-mediaitem-square-large-overlay {\n  z-index: 3;\n}\n\n.cd-mediaitem-square-large > .cd-mediaitem-square-large-overlay:hover {\n  opacity: 1;\n}\n\n.cd-mediaitem-square-large + .cd-mediaitem-square-large-overlay {\n  pointer-events: none;\n}\n\n.cd-mediaitem-square-large:hover + .cd-mediaitem-square-large-overlay {\n  opacity: 1;\n}\n\n.cd-mediaitem-square-large .artwork.round {\n  border-radius: var(--mediaItemRadiusRound);\n}\n\n.cd-mediaitem-square-large .title {\n  width: 90%;\n  text-align: center;\n}\n\n.cd-mediaitem-square-large .subtitle {\n  width: 100%;\n  text-align: center;\n  font-size: 12px;\n}\n\n/* mediaitem-mvview */\n\n/* mediaitem-mvview */\n.cd-mediaitem-mvview {\n  width: 300px;\n  height: 250px;\n  display: inline-flex;\n  flex: 0 0 auto;\n  flex-direction: column;\n  font-size: 14px;\n  justify-content: flex-start;\n  align-items: center;\n  border-radius: 6px;\n  margin-left: 10px;\n  cursor: pointer;\n\n  > * {\n    z-index: inherit;\n  }\n}\n\n.cd-mediaitem-mvview .artwork {\n  height: auto;\n  width: 300px;\n  background: blue;\n  border-top-left-radius: 6px;\n  border-top-right-radius: 6px;\n  background: var(--artwork);\n  background-size: cover;\n  flex: 0 0 auto;\n  margin: 6px;\n  margin-top: 0px;\n  aspect-ratio: 1.7435897435897436;\n}\n\n.cd-mediaitem-mvview-overlay {\n  position: absolute;\n  width: 300px;\n  float: right;\n  height: 250px;\n  top: 0px;\n  margin: 10px;\n  margin-top: 0px;\n  opacity: 0;\n}\n\n.cd-mediaitem-mvview-overlay > * {\n  pointer-events: auto;\n}\n\n.cd-mediaitem-mvview > .cd-mediaitem-mvview-overlay {\n  z-index: 3;\n}\n\n.cd-mediaitem-mvview > .cd-mediaitem-mvview-overlay:hover {\n  opacity: 1;\n}\n\n.cd-mediaitem-mvview + .cd-mediaitem-mvview-overlay {\n  pointer-events: none;\n}\n\n.cd-mediaitem-mvview:hover + .cd-mediaitem-mvview-overlay {\n  opacity: 1;\n}\n\n.cd-mediaitem-mvview .artwork.round {\n  border-radius: var(--mediaItemRadiusRound);\n}\n\n.cd-mediaitem-mvview .title {\n  width: 90%;\n  text-align: center;\n}\n\n.cd-mediaitem-mvview .subtitle {\n  width: 100%;\n  text-align: center;\n  font-size: 12px;\n}\n\n/* mediaitem-square */\n.cd-mediaitem-square {\n  --transitionDuration: 0.5s;\n  --scaleRate: 1.25;\n  --scaleRateArtwork: 1;\n  width: calc(160px * var(--windowRelativeScale));\n  height: calc(200px * var(--windowRelativeScale));\n  display: inline-flex;\n  flex: 0 0 auto;\n  flex-direction: column;\n  font-size: 14px;\n  justify-content: center;\n  align-items: center;\n  border-radius: 6px;\n\n  .artwork-container {\n    position: relative;\n\n    .artwork {\n      height: calc(140px * var(--windowRelativeScale));\n      width: calc(140px * var(--windowRelativeScale));\n      background: blue;\n      border-radius: var(--mediaItemRadius);\n      background: var(--artwork);\n      background-size: cover;\n      flex: 0 0 auto;\n      margin: 6px;\n      cursor: pointer;\n\n      .mediaitem-artwork {\n        box-shadow: unset;\n      }\n\n      &.round {\n        border-radius: var(--mediaItemRadiusRound);\n      }\n    }\n\n    .badge-container {\n      transition: opacity 0.1s var(--appleEase);\n      opacity: 1;\n\n      .socialBadge {\n        width: 32px;\n        height: 32px;\n        position: absolute;\n        right: 14px;\n        bottom: 14px;\n        border-radius: 100%;\n        overflow: hidden;\n        z-index: 2;\n        pointer-events: none;\n      }\n    }\n\n    > .play-btn,\n    > .menu-btn {\n      opacity: 0;\n      appearance: none;\n      padding: 0px;\n      border: 0px;\n      width: 30px;\n      height: 30px;\n      border-radius: 50%;\n      background: rgba(50, 50, 50, 0.7);\n      cursor: pointer;\n      transition: opacity 0.1s var(--appleEase);\n\n      :hover {\n        border-radius: 50%;\n        background: rgba(250, 0, 0, 0.7);\n      }\n    }\n\n    > .play-btn {\n      position: absolute;\n      bottom: 14px;\n      left: 14px;\n      z-index: 2;\n    }\n\n    > .menu-btn {\n      position: absolute;\n      bottom: 14px;\n      right: 14px;\n      z-index: 2;\n    }\n\n    &:hover {\n      > .badge-container {\n        opacity: 0;\n      }\n\n      > .play-btn,\n      > .menu-btn {\n        opacity: 1;\n      }\n    }\n  }\n\n  // &:not(.mediaitem-card):not(.mediaitem-brick):not(.mediaitem-video):not(.noscale) {\n  //   @media (min-width: 1460px) {\n  //     --scaleRate: 1.1;\n  //     --scaleRateArtwork: 0.9;\n  //     width: calc(200px * var(--scaleRate));\n  //     height: calc(200px * var(--scaleRate));\n\n  //     .artwork-container > .artwork {\n  //       width: calc(190px * var(--scaleRateArtwork));\n  //       height: calc(190px * var(--scaleRateArtwork));\n  //     }\n  //   }\n\n  //   @media (min-width: 1550px) {\n  //     --scaleRate: 1.25;\n  //     --scaleRateArtwork: 1;\n  //     width: calc(200px * var(--scaleRate));\n  //     height: calc(200px * var(--scaleRate));\n\n  //     .artwork-container > .artwork {\n  //       width: calc(190px * var(--scaleRateArtwork));\n  //       height: calc(190px * var(--scaleRateArtwork));\n  //     }\n  //   }\n  // }\n\n  .info-rect {\n    width: 90%;\n    height: 100%;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n  }\n\n  .title {\n    width: 100%;\n    text-align: center;\n    display: flex;\n    align-content: center;\n    justify-content: center;\n  }\n\n  .subtitle {\n    width: 100%;\n    text-align: center;\n    font-size: 12px;\n  }\n\n  .unavailable-overlay {\n    position: absolute;\n    top: 0px;\n    left: 0px;\n    bottom: 0;\n    right: 0;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n    z-index: 2;\n    pointer-events: none;\n    background: rgb(0 0 0 / 40%);\n    margin: 2em;\n    border-radius: 10px;\n\n    > .codicon {\n      font-size: 4em;\n      font-weight: bold;\n      opacity: 0.5;\n    }\n  }\n\n  &.mediaitem-video {\n    height: 200px;\n    width: 240px;\n    transition:\n      width var(--transitionDuration) linear,\n      height var(--transitionDuration) linear;\n\n    .artwork {\n      height: 120px;\n      width: 212px;\n      transition:\n        width var(--transitionDuration) linear,\n        height var(--transitionDuration) linear;\n    }\n\n    &:not(.noscale) {\n      @media (min-width: 1460px) {\n        --scaleRate: 1.1;\n        --scaleRateArtwork: 1.1;\n        width: calc(240px * var(--scaleRate));\n        height: calc(200px * var(--scaleRate));\n\n        .artwork-container > .artwork {\n          width: calc(220px * var(--scaleRateArtwork));\n          height: calc(123px * var(--scaleRateArtwork));\n        }\n      }\n\n      @media (min-width: 1550px) {\n        --scaleRate: 1.25;\n        --scaleRateArtwork: 1.25;\n        width: calc(240px * var(--scaleRate));\n        height: calc(200px * var(--scaleRate));\n\n        .artwork-container > .artwork {\n          width: calc(220px * var(--scaleRateArtwork));\n          height: calc(123px * var(--scaleRateArtwork));\n        }\n      }\n    }\n  }\n\n  &.mediaitem-brick {\n    height: 200px;\n    width: 240px;\n    transition:\n      width var(--transitionDuration) linear,\n      height var(--transitionDuration) linear;\n\n    .artwork {\n      height: 123px;\n      width: 220px;\n      transition:\n        width var(--transitionDuration) linear,\n        height var(--transitionDuration) linear;\n    }\n\n    &:not(.noscale) {\n      @media (min-width: 1460px) {\n        --scaleRate: 1.1;\n        --scaleRateArtwork: 1.1;\n        width: calc(240px * var(--scaleRate));\n        height: calc(200px * var(--scaleRate));\n\n        .artwork-container > .artwork {\n          width: calc(220px * var(--scaleRateArtwork));\n          height: calc(123px * var(--scaleRateArtwork));\n        }\n      }\n\n      @media (min-width: 1550px) {\n        --scaleRate: 1.25;\n        --scaleRateArtwork: 1.25;\n        width: calc(240px * var(--scaleRate));\n        height: calc(200px * var(--scaleRate));\n\n        .artwork-container > .artwork {\n          width: calc(220px * var(--scaleRateArtwork));\n          height: calc(123px * var(--scaleRateArtwork));\n        }\n      }\n    }\n  }\n\n  &.mediaitem-small {\n    width: calc(140px, var(--windowRelativeScale));\n    height: calc(180px, var(--windowRelativeScale));\n    transition:\n      width var(--transitionDuration) linear,\n      height var(--transitionDuration) linear;\n\n    .artwork {\n      height: calc(128px, var(--windowRelativeScale));\n      width: calc(128px, var(--windowRelativeScale));\n      transition:\n        width var(--transitionDuration) linear,\n        height var(--transitionDuration) linear;\n    }\n  }\n\n  &.mediaitem-card {\n    background: #ccc;\n    background: var(--spcolor);\n    height: 302px;\n    width: 230px;\n    overflow: hidden;\n    position: relative;\n    border-radius: calc(var(--mediaItemRadius) * 2);\n    box-shadow: var(--mediaItemShadow-ShadowSubtle);\n    transition:\n      width var(--transitionDuration) linear,\n      height var(--transitionDuration) linear;\n\n    .artwork {\n      width: 230px;\n      height: 230px;\n      overflow: hidden;\n      border-radius: 0px;\n      margin: 0;\n      transition:\n        width var(--transitionDuration) linear,\n        height var(--transitionDuration) linear,\n        filter 0.2s ease-in-out;\n      .mediaitem-artwork {\n        border-radius: 0px;\n\n        &::after {\n          box-shadow: unset;\n        }\n      }\n    }\n\n    .info-rect-card {\n      padding: 10px 10px 14px;\n      position: relative;\n      width: 100%;\n      display: grid;\n      align-content: center;\n\n      &::before {\n        background: var(--bgartwork);\n        content: \"\";\n        top: 0;\n        left: 0;\n        bottom: 0;\n        right: 0;\n        position: absolute;\n        background-size: cover;\n        background-position: bottom;\n        z-index: 0;\n        opacity: 1;\n        filter: brightness(0.5) blur(50px) saturate(180%);\n        transition: filter 0.2s ease-in-out;\n      }\n    }\n\n    .title {\n      height: 100%;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      font-size: 0.9em;\n      font-weight: 500;\n      z-index: 1;\n\n      & + .subtitle {\n        max-height: none !important;\n        // margin-top: -0.5em;\n      }\n    }\n\n    .subtitle {\n      height: 100%;\n      justify-content: center;\n      align-items: center;\n      font-size: 0.75em;\n      width: 100%;\n      display: -webkit-box;\n      -webkit-box-orient: vertical;\n      -webkit-line-clamp: 3;\n      overflow: hidden;\n      max-height: 4.8em;\n      z-index: 1;\n    }\n\n    &::after {\n      box-shadow: var(--mediaItemShadow);\n      content: \"\";\n      width: 100%;\n      height: 100%;\n      position: absolute;\n      top: 0;\n      left: 0;\n      pointer-events: none;\n      border-radius: inherit;\n    }\n\n    &:hover {\n      .artwork {\n        filter: brightness(0.8);\n      }\n      .info-rect-card::before {\n        filter: brightness(0.3) blur(50px) saturate(180%);\n      }\n    }\n\n    &:not(.noscale) {\n      @media (min-width: 1200px) {\n        width: calc(230px * 1.1);\n        height: calc(298px * 1.1);\n        .artwork-container > .artwork {\n          width: calc(230px * 1.1);\n          height: calc(230px * 1.1);\n        }\n      }\n\n      @media (min-width: 1400px) {\n        width: calc(230px * 1.25);\n        height: calc(298px * 1.25);\n        .artwork-container > .artwork {\n          width: calc(230px * 1.25);\n          height: calc(230px * 1.25);\n        }\n      }\n    }\n  }\n}\n\n/* mediaitem-square */\n.albums-square-containeru > * > .cd-mediaitem-square {\n  --frame: max(220px, 15vw);\n  width: var(--frame);\n  height: calc(var(--frame) * 13 / 11);\n  display: inline-flex;\n  flex: 0 0 auto;\n  flex-direction: column;\n  font-size: calc(var(--frame) / 220 * 14);\n  justify-content: center;\n  align-items: center;\n  border-radius: calc(var(--frame) / 220 * 6);\n\n  .artwork-container {\n    position: relative;\n\n    .artwork {\n      height: calc(var(--frame) * 19 / 22);\n      width: calc(var(--frame) * 19 / 22);\n      background: blue;\n      border-radius: var(--mediaItemRadius);\n      background: var(--artwork);\n      background-size: cover;\n      flex: 0 0 auto;\n      margin: calc(var(--frame) / 220 * 6);\n      cursor: pointer;\n\n      &.round {\n        border-radius: var(--mediaItemRadiusRound);\n      }\n    }\n\n    > .play-btn,\n    > .menu-btn {\n      opacity: 0;\n      appearance: none;\n      padding: 0px;\n      border: 0px;\n      width: calc(var(--frame) / 220 * 30);\n      height: calc(var(--frame) / 220 * 30);\n      border-radius: 50%;\n      background: rgba(50, 50, 50, 0.7);\n      cursor: pointer;\n      backdrop-filter: blur(32px) saturate(180%);\n      transition: opacity 0.1s var(--appleEase);\n    }\n\n    > .play-btn {\n      position: absolute;\n      bottom: calc(var(--frame) / 220 * 14);\n      left: calc(var(--frame) / 220 * 14);\n      z-index: 2;\n    }\n\n    > .menu-btn {\n      position: absolute;\n      bottom: calc(var(--frame) / 220 * 14);\n      right: calc(var(--frame) / 220 * 14);\n      z-index: 2;\n    }\n\n    &:hover {\n      > .play-btn,\n      > .menu-btn {\n        opacity: 1;\n      }\n    }\n  }\n\n  .title {\n    width: 90%;\n    text-align: center;\n  }\n\n  .subtitle {\n    width: 100%;\n    text-align: center;\n    font-size: calc(var(--frame) / 220 * 12);\n  }\n\n  &.mediaitem-video {\n    height: calc(var(--frame) / 220 * 200);\n    width: calc(var(--frame) / 220 * 240);\n\n    .artwork {\n      height: calc(var(--frame) / 220 * 120);\n      width: calc(var(--frame) / 220 * 212);\n    }\n  }\n\n  &.mediaitem-brick {\n    height: calc(var(--frame) / 220 * 200);\n    width: calc(var(--frame) / 220 * 240);\n\n    .artwork {\n      height: calc(var(--frame) / 220 * 123);\n      width: calc(var(--frame));\n    }\n  }\n}\n\n.listitem-horizontal {\n  .cd-mediaitem-list-item {\n    width: 350px;\n    height: 60px;\n  }\n}\n\n.mediaitem-list-item__grid {\n  background: rgba(200, 200, 200, 0.05);\n  border-radius: 10px;\n  padding: var(--contentInnerPadding);\n  box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;\n  width: 100%;\n\n  .cd-mediaitem-list-item {\n    width: 350px;\n    height: 60px;\n  }\n\n  &::-webkit-scrollbar {\n    display: none;\n  }\n\n  &:hover::-webkit-scrollbar {\n    display: initial;\n  }\n}\n\n// Graphics\n\n// sidebar icon\n.svg-icon {\n  --color: #aaa;\n  --url: url(\"./assets/feather/share.svg\");\n  -webkit-mask-image: var(--url);\n  -webkit-mask-size: cover;\n  height: 18px;\n  width: 18px;\n  background: var(--color);\n\n  &.inline {\n    display: inline-block;\n  }\n}\n\n.sidebar-icon {\n  width: 18px;\n  height: 18px;\n  margin-right: 8px;\n\n  > .svg-icon {\n    width: 100%;\n    height: 100%;\n    --color: #aaa;\n  }\n\n  > svg {\n    width: 100%;\n    height: 100%;\n    color: #aaa;\n  }\n}\n\n/* Switch Checkbox */\ninput[type=\"checkbox\"][switch] {\n  width: 38px;\n  appearance: none;\n  border-radius: 32px;\n  height: 24px;\n  zoom: 1;\n  top: 0;\n  cursor: pointer;\n  left: 0;\n  position: relative;\n  transform: scale(1);\n  background: rgb(142 142 147 / 100%);\n  padding: 0;\n  margin: 0;\n}\n\ninput[type=\"checkbox\"][switch]:focus,\ninput[type=\"checkbox\"][switch]:active {\n  outline: none;\n}\n\ninput[type=\"checkbox\"][switch]:checked {\n  background: var(--keyColor);\n  border: 0 solid var(--keyColor);\n  mix-blend-mode: unset;\n\n  &:hover {\n    background: var(--keyColor-rollover);\n  }\n\n  &:active {\n    background: var(--keyColor-pressed);\n  }\n}\n\ninput[type=\"checkbox\"][switch]::before {\n  background: white;\n  width: 26px;\n  height: 26px;\n  top: -1px;\n  left: -1px;\n  position: absolute;\n  content: \" \";\n  border-radius: 32px;\n  transition: 0.1s left var(--appleEase);\n  transform: scale(0.75);\n}\n\ninput[type=\"checkbox\"][switch]:checked::before {\n  background: white;\n  top: -1px;\n  left: 13px;\n  transition: 0.1s left var(--appleEase);\n  transform: scale(0.75);\n}\n\ninput[type=\"checkbox\"][switch]:disabled::before {\n  opacity: 0.5;\n}\n\ninput[type=\"checkbox\"][switch]:active::before {\n  left: 13px;\n}\n\ninput[type=\"checkbox\"][switch]:checked:active::before {\n  left: -1px;\n}\n\n/* End Switch Checkbox */\n\n.header-text {\n  margin: 0px;\n}\n\n.media-item--small {\n  background: rgb(0 0 0 / 25%);\n  height: 162px;\n  width: 132px;\n  display: inline-flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: center;\n  border-radius: 10px;\n}\n\n.media-item--small .artwork {\n  background: red;\n  margin: 6px;\n  border-radius: 100%;\n  width: 90px;\n  height: 90px;\n  box-shadow: inset 0px 0px 0px 1px rgb(200 200 200 / 30%);\n}\n\n.playlist-artwork {\n  height: 190px;\n  width: 190px;\n  background: blue;\n  border-radius: 6px;\n  background: var(--artwork);\n  background-size: cover;\n  box-shadow: var(--mediaItemShadow);\n  flex: 0 0 auto;\n  margin: 6px;\n  margin-top: 0px;\n}\n\n.media-item--small .text {\n  font-weight: 600;\n  font-size: 0.9em;\n}\n\n.media-item--small .subtext {\n  font-size: 0.75em;\n}\n\n.player-duration-time {\n  opacity: 0.5;\n}\n\n.player-artwork-container {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.player-duration-container {\n  font-size: 0.85em;\n  font-weight: 500;\n}\n\n.media-artwork {\n  --artwork: url(\"\");\n  width: 80vw;\n  height: 80vw;\n  max-height: 500px;\n  max-width: 500px;\n  background: black;\n  background-image: var(--artwork);\n  background-size: cover;\n  background-position: center;\n  background-repeat: no-repeat;\n  border-radius: 8px;\n  box-shadow:\n    inset 0px 0px 0px 1px rgb(200 200 200 / 16%),\n    0 8px 40px rgb(0 0 0 / 0.55);\n  transition: transform 0.1s var(--appleEase);\n}\n\n.media-artwork.paused {\n  transition: transform 0.35s var(--appleEase);\n  transform: scale(0.85);\n}\n\n.playback-slider {\n  width: 90%;\n}\n\n.volume-slider {\n  width: 100%;\n}\n\n.volume-slider-container {\n  width: 90%;\n  margin: 0 auto;\n  padding: 0px;\n}\n\n.volume-slider-container .col-auto,\n.volume-slider-container .col {\n  display: flex;\n  align-items: center;\n  justify-self: center;\n  padding: 0px;\n  margin: 0px;\n}\n\n.playback-button {\n  font-size: 2em;\n  width: 40px;\n  height: 36px;\n  padding: 0px;\n  background: transparent;\n  border: 0px;\n  border-radius: 0px;\n  box-shadow: unset;\n  background-size: 12px;\n  background-position: center;\n  background-repeat: no-repeat;\n  opacity: 0.7;\n  border-radius: 6px;\n  position: relative;\n\n  &:before {\n    content: \"\";\n    display: block;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    background: var(--selected);\n    border-radius: inherit;\n    position: absolute;\n    opacity: 0;\n    z-index: -1;\n    transform: scale(0.5);\n    pointer-events: none;\n    transition:\n      opacity 0.1s var(--appleEase),\n      transform 0.1s var(--appleEase);\n  }\n\n  &:hover {\n    &:before {\n      transform: scale(1);\n      opacity: 1;\n    }\n  }\n}\n\n.playback-button--small {\n  border-radius: 6px;\n  font-size: 1em;\n  color: inherit;\n  background-size: 0.98em;\n  background-repeat: no-repeat;\n  background-position: center;\n  background-color: transparent;\n  width: 40px;\n  height: 32px;\n  border: 0px;\n  box-shadow: unset;\n  opacity: 0.7;\n  position: relative;\n\n  &:before {\n    content: \"\";\n    display: block;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    background: var(--selected);\n    border-radius: inherit;\n    position: absolute;\n    opacity: 0;\n    z-index: -1;\n    transform: scale(0.5);\n    pointer-events: none;\n    transition:\n      opacity 0.1s var(--appleEase),\n      transform 0.1s var(--appleEase);\n  }\n\n  &:hover {\n    &:before {\n      transform: scale(1);\n      opacity: 1;\n    }\n  }\n}\n\n.playback-button--small.active {\n  background-color: rgb(200 200 200 / 25%);\n}\n\n.playback-button:hover,\n.playback-button--small:hover {\n  // background-color: var(--selected);\n}\n\n.playback-button:active,\n.playback-button--small:active {\n  background-color: var(--selected-click);\n}\n\n.playback-button--small.search {\n  background-image: url(\"./assets/search.svg\");\n}\n\n.playback-button--small.cast {\n  background-image: url(\"./assets/cast_white.svg\");\n  background-size: 1.25em;\n}\n\n.playback-button--small.miniplayer {\n  background-image: url(\"./assets/pip.svg\");\n}\n\n.playback-button--small.queue {\n  background-image: url(\"./assets/list.svg\");\n}\n\n.playback-button--small.lyrics {\n  background-image: url(\"./assets/quote-right.svg\");\n}\n\n.playback-button--small.shuffle {\n  background-image: url(\"./assets/shuffle.svg\");\n}\n\n.playback-button--small.repeat {\n  background-image: url(\"./assets/repeat.svg\");\n}\n\n.playback-button--small.repeat.repeatOne {\n  background-color: rgb(200 200 200 / 25%);\n  background-image: url(\"./assets/repeatOne.svg\");\n}\n\n.playback-button.stop {\n  background-image: url(\"./assets/cider-icons/stop.svg\");\n  background-size: 38px;\n  background-position: center;\n}\n\n.playback-button.collapseLibrary {\n  font-family: \"codicon\";\n  font-size: 1em;\n  color: var(--textColor);\n  display: grid;\n  place-items: center;\n\n  span {\n    position: absolute;\n  }\n}\n\n.playback-button.pause {\n  background-image: url(\"./assets/cider-icons/pause.svg\");\n  background-size: 38px;\n  background-position: center;\n}\n\n.playback-button.stop {\n  background-image: url(\"./assets/cider-icons/stop.svg\");\n  background-size: 38px;\n  background-position: center;\n}\n\n.playback-button.play {\n  background-image: url(\"./assets/cider-icons/play.svg\");\n  background-size: 38px;\n  background-position: center;\n}\n\n.playback-button.next {\n  background-image: url(\"./assets/cider-icons/forward.svg\");\n  background-size: 60%;\n  background-position: center;\n}\n\n.playback-button.previous {\n  background-image: url(\"./assets/cider-icons/backward.svg\");\n  background-size: 60%;\n  background-position: center;\n}\n\n.playback-button.disabled,\n.playback-button--small.disabled {\n  opacity: 0.25 !important;\n  pointer-events: none;\n  transform: none !important;\n\n  &:hover {\n    background-color: transparent !important;\n    transform: none !important;\n  }\n}\n\n.playback-button {\n  &.navigation {\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    color: white;\n\n    > ._svg-icon {\n      height: 16px;\n      width: 16px;\n      pointer-events: none;\n    }\n  }\n}\n\n.playback-buttons {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.player-volume-glyph {\n  width: 32px;\n  height: 16px;\n  background-repeat: no-repeat;\n  background-size: contain;\n  background-position: center;\n}\n\n.player-volume-glyph.decrease {\n  background-image: url(\"./assets/volume.svg\");\n  opacity: 0.5;\n}\n\n.player-volume-glyph.increase {\n  background-image: url(\"./assets/volume-2.svg\");\n  opacity: 0.5;\n}\n\n.player-track-info {\n  width: 90%;\n  margin: 0 auto;\n}\n\n.player-song-title {\n  font-size: 1.25em;\n  text-align: left;\n  margin: 0 auto;\n  font-weight: 500;\n}\n\n.player-song-artist {\n  font-size: 1em;\n  text-align: left;\n  margin: 0 auto;\n  color: var(--keyColor);\n  font-weight: 400;\n}\n\n.player-song-artist:hover {\n  cursor: pointer;\n  text-decoration: underline;\n}\n\n.player-more-container {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.player-more-button {\n  appearance: none;\n  width: 32px;\n  height: 32px;\n  border-radius: 50%;\n  border: 0px;\n  background: var(--keyColor);\n  cursor: pointer;\n  box-shadow: inset 0px 0px 0px 1px rgb(200 200 200 / 16%);\n  color: white;\n  font-weight: bold;\n  padding: 0px;\n  font-size: 16px;\n}\n\n.back-button {\n  width: 40px;\n  height: 40px;\n  background-color: transparent;\n  background-size: 16px;\n  background-position: center;\n  background-repeat: no-repeat;\n  background-image: url(\"./assets/arrow-left.svg\");\n  border: 0px;\n  border-radius: 0px;\n}\n\n.header-text {\n  height: 40px;\n  display: flex;\n  align-items: center;\n}\n\n.list-entry-header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 12px;\n  font-size: 1em;\n  font-family: inherit;\n}\n\n.list-entry {\n  display: flex;\n  align-items: center;\n  /* justify-content: space-between; */\n  padding: 12px;\n  font-size: 1em;\n  font-family: inherit;\n  border-bottom: 1px solid rgba(255 255 255 / 0.1);\n  cursor: pointer;\n}\n\n.list-entry-image {\n  --artwork: url(\"\");\n  width: 64px;\n  height: 64px;\n  background: var(--artwork);\n  background-size: cover;\n  background-position: center;\n  background-repeat: no-repeat;\n  border-radius: 8px;\n  box-shadow:\n    inset 0px 0px 0px 1px rgb(200 200 200 / 16%),\n    0 8px 40px rgb(0 0 0 / 0.55);\n}\n\n.list-entry-image.artist {\n  border-radius: 50%;\n}\n\n.list-entry-body {\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: flex-start;\n  margin-left: 12px;\n}\n\n.list-entry-name {\n  font-size: 14px;\n  font-weight: 500;\n  overflow: hidden;\n  width: 100%;\n}\n\n.list-entry-artist {\n  font-size: 12px;\n  overflow: hidden;\n  width: 100%;\n}\n\n.list-entry .handle {\n  height: 100%;\n  width: 28px;\n  background: var(--keyColor);\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.artist-chip {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  margin: 12px 12px 12px 0px;\n  border-radius: 4px;\n  color: white;\n  font-size: 1em;\n  font-weight: 500;\n  cursor: pointer;\n\n  .artist-chip__follow {\n    appearance: none;\n    border: 0;\n    height: 32px;\n    width: 32px;\n    background: #ffffff0f;\n    margin: 0px 0px 0px 10px;\n    font-weight: bold;\n    color: white;\n    border-radius: 100%;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    font-size: 12px;\n    cursor: pointer;\n    flex: 0 0 32px;\n    box-shadow: var(--ciderShadow-Generic);\n\n    &:hover {\n      background: var(--selected);\n    }\n  }\n\n  .artist-chip__image {\n    width: 32px;\n    height: 32px;\n    background-size: contain;\n    background-position: center;\n    background-repeat: no-repeat;\n    border-radius: 100%;\n    overflow: hidden;\n    margin: 0px 12px 0px 0px;\n    pointer-events: none;\n    flex: 0 0 32px;\n\n    .mediaitem-artwork {\n      border-radius: inherit;\n    }\n  }\n\n  .artist-chip__name {\n    pointer-events: none;\n  }\n}\n\n.search-panel {\n  background: rgb(0 0 0 / 50%);\n}\n\n.search-header {\n  position: absolute;\n  width: 100%;\n  z-index: 1;\n  backdrop-filter: blur(16px);\n  -webkit-backdrop-filter: blur(16px);\n  border-bottom: 1px solid rgb(200 200 200 / 8%);\n}\n\n.connection-error-panel {\n  background: rgb(0 0 0 / 50%);\n}\n\n.search-type-container {\n  display: flex;\n}\n\n.search-type-button {\n  background: rgb(20 20 20 / 0.85);\n  border-radius: 50px;\n  color: white;\n  border: 0px;\n  box-shadow: unset;\n  font-family: inherit;\n  padding: 8px 16px;\n  font-size: 14px;\n  font-weight: 500;\n  margin: 8px;\n  margin-top: 0px;\n  margin-bottom: 0px;\n}\n\n.search-type-button.active {\n  background: var(--keyColor);\n}\n\n.search-tab-container {\n  overflow: auto;\n  white-space: nowrap;\n  overflow-y: hidden;\n}\n\n.search-body-container {\n  position: relative;\n  width: 100%;\n  height: 100%;\n}\n\n.search-body {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  padding-top: 220px;\n}\n\n.search-tab {\n  background: rgb(20 20 20 / 0.85);\n  border-radius: 50px;\n  color: white;\n  border: 0px;\n  box-shadow: unset;\n  font-family: inherit;\n  padding: 8px 16px;\n  font-size: 14px;\n  font-weight: 500;\n}\n\n.search-tab.active {\n  background: var(--keyColor);\n}\n\n// fancy pills\n.fancy-pills {\n  .nav-pills {\n    position: relative;\n\n    .nav-link {\n      transition: transform 0.3s var(--appleEase);\n      position: relative;\n      background-color: transparent;\n      border: 0;\n      border-radius: 50px;\n      color: #eee;\n      -webkit-user-drag: none;\n      font-weight: 500;\n      margin: 0px 4px;\n\n      &:after {\n        --dist: 1px;\n        content: \"\";\n        position: absolute;\n        top: var(--dist);\n        bottom: var(--dist);\n        left: var(--dist);\n        right: var(--dist);\n        // width   : 100%;\n        // height  : 100%;\n        background-color: transparent;\n        border-radius: 50px;\n        z-index: -1;\n        opacity: 0;\n        transition:\n          background-color 0.5s var(--appleEase),\n          opacity 0.25s var(--appleEase),\n          border-radius 0.32s var(--appleEase);\n      }\n\n      &:hover {\n        outline: none;\n        transform: scale(1.1);\n        // background: #eee;\n        background: transparent;\n        color: #333;\n\n        &:after {\n          opacity: 1;\n          background-color: #eee;\n          transition:\n            background-color 0.25s var(--appleEase),\n            border-radius 0.25s var(--appleEase),\n            color 0s var(--appleEase),\n            opacity 0s var(--appleEase);\n        }\n      }\n\n      &.active {\n        outline: none;\n        transform: scale(1.1);\n        // background: #eee;\n        background: transparent;\n        color: #333;\n        font-weight: 600;\n\n        &:after {\n          opacity: 1;\n          background-color: #eee;\n        }\n      }\n    }\n\n    &:hover {\n      .nav-link.active {\n        outline: none;\n        transform: scale(1);\n        background: transparent;\n        color: #eee;\n        transform: scale(1);\n\n        &:after {\n          background: rgb(200 200 200 / 15%);\n          opacity: 1;\n          transition: color 0s;\n          // border-radius: 5px;\n          --dist: 4px;\n        }\n\n        &:hover {\n          transform: scale(1.1);\n          z-index: 1;\n          color: #333;\n\n          &:after {\n            background: #eee;\n            border-radius: inherit;\n            --dist: 1px;\n          }\n        }\n      }\n    }\n\n    &:after {\n      content: \"\";\n      position: absolute;\n      top: 0;\n      left: 0;\n      bottom: 0;\n      right: 0;\n      background: rgb(200 200 200 / 10%);\n      border-radius: 50px;\n      z-index: 0;\n      pointer-events: none;\n    }\n  }\n}\n\n.grouping-container {\n  display: grid;\n  grid-template-columns: repeat(3, 1fr);\n  gap: 16px;\n\n  .grouping-btn {\n    padding: 16px;\n    appearance: none;\n    border: 0px;\n    border-radius: 10px;\n    background: var(--color1);\n    color: var(--keyColor);\n    width: 100%;\n    text-align: left;\n    font-family: inherit;\n    cursor: pointer;\n    flex: 1 0 21%;\n    position: relative;\n\n    &:after {\n      content: \"\";\n      position: absolute;\n      top: 0;\n      right: 0;\n      bottom: 0;\n      font-family: \"codicon\";\n      display: flex;\n      align-items: center;\n      width: 28px;\n      font-weight: bold;\n      font-size: 1.2em;\n      pointer-events: none;\n    }\n  }\n}\n\n.app-sidebar-header .search-input-container .search-hints-container {\n  top: 38px;\n  padding: 3px;\n}\n\n.content-inner {\n  &.library-page {\n    .heart-icon {\n      left: 7px;\n    }\n\n    .cd-mediaitem-list-item {\n      padding-left: 25px;\n    }\n  }\n\n  &.library-artists-page {\n    .inner-container .list-container .podcasts-list {\n      background: rgba(27, 27, 27);\n      padding-top: 14px;\n      width: 272px;\n\n      .cd-mediaitem-list-item {\n        margin-left: 10px;\n      }\n\n      .cd-mediaitem-list-item:hover {\n        width: 96%;\n      }\n    }\n  }\n}\n\n.listennow-chip.circle {\n  border-radius: 50%;\n  div {\n    border-radius: 50%;\n  }\n  img {\n    border-radius: 50%;\n  }\n}\n\n.pagination-container {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  gap: 0.5rem;\n  margin-bottom: 16px;\n  .md-input-number {\n    min-width: 12em;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/fullscreen.less",
    "content": ".fullscreen-view-container {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: black;\n  z-index: 99;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  opacity: 1;\n}\n\n.fullscreen-view {\n  width: 100%;\n  height: 100%;\n  background: black;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  --chromeHeight1: 70px;\n\n  .app-content-container {\n    width: 100%;\n    height: 100%;\n    #app-content {\n      width: 100%;\n      height: 100%;\n\n      .fs-search {\n        .search-input--icon {\n          width: 4em;\n          background-size: 40%;\n          background-position: center;\n        }\n        input {\n          padding-left: 2em;\n          font-size: 2em;\n          border-radius: var(--mediaItemRadius);\n        }\n      }\n    }\n  }\n\n  .fs-header {\n    position: fixed;\n    top: 0;\n    left: 0;\n    right: 0;\n    height: var(--chromeHeight1);\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    z-index: 9999;\n\n    .top-nav-group {\n      background: #1e1e1e99;\n      border: 1px solid lighten(@baseColor, 8);\n      border-radius: 12px;\n      display: flex;\n      height: 55px;\n      width: 90%;\n      backdrop-filter: var(--glassFilter);\n\n      .app-sidebar-item {\n        background-color: #1e1e1e00;\n        border-radius: 10px !important;\n        border: 0px;\n        min-width: 120px;\n        padding: 6px;\n        justify-content: center;\n        align-items: center;\n        margin: 0px;\n        height: 100%;\n        position: relative;\n        font-size: 1.1em;\n        font-weight: 500;\n\n        &:before {\n          --dist: 1px;\n          content: \"\";\n          position: absolute;\n          top: var(--dist);\n          left: var(--dist);\n          right: var(--dist);\n          bottom: var(--dist);\n          background-color: #fff;\n          opacity: 0;\n          border-radius: 10px;\n          transform: scale(0.5);\n          transition:\n            transform 0.2s ease-in-out,\n            opacity 0.2s ease-in-out;\n        }\n\n        &:after {\n          display: none;\n        }\n\n        &:hover {\n          background-color: transparent;\n\n          &:before {\n            transition:\n              transform 0.1s ease-in-out,\n              opacity 0.1s ease-in-out;\n            opacity: 0.1;\n            transform: scale(1);\n          }\n        }\n\n        &.active {\n          background-color: transparent;\n\n          &:before {\n            opacity: 0.2;\n            transform: scale(1);\n          }\n        }\n\n        &.md-btn-primary {\n          box-shadow: 0px 0px 0px 1px lighten(@baseColor, @colorMixRate * 8);\n          background-color: lighten(@baseColor, @colorMixRate * 5);\n          z-index: 1;\n        }\n      }\n    }\n  }\n\n  .fs-row {\n    flex-grow: 0.5;\n  }\n\n  .playback-button--small.active {\n    background-color: rgb(200 200 200 / 25%);\n  }\n\n  .playback-button--small {\n    opacity: 0.7;\n  }\n\n  .right-col {\n    height: 50vh;\n  }\n\n  .bg-artwork-container {\n    display: block !important;\n  }\n\n  @media only screen and (max-width: 1121px) {\n    .display--large {\n      display: flex !important;\n    }\n  }\n\n  .display--large {\n    display: flex;\n\n    .slider {\n      width: 100%;\n      z-index: 1;\n    }\n\n    .input-container {\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      width: 100%;\n    }\n\n    .volume-button--small {\n      border-radius: 6px;\n      color: inherit;\n      background-size: 16px;\n      background-repeat: no-repeat;\n      background-position: center;\n      background-color: transparent;\n      height: 15px;\n      width: 30px;\n      border: 0px;\n      box-shadow: unset;\n      opacity: 0.7;\n      background-image: url(\"./assets/feather/volume-2.svg\");\n    }\n\n    .volume-button--small:active {\n      transform: scale(0.9);\n    }\n\n    .volume-button--small.active {\n      background-image: url(\"./assets/feather/volume.svg\");\n    }\n\n    input[type=\"range\"] {\n      -webkit-appearance: none;\n      height: 4px;\n      background: rgba(255, 255, 255, 0.4);\n      border-radius: 5px;\n      background-size: 70% 100%;\n      background-repeat: no-repeat;\n\n      &::-webkit-slider-thumb {\n        -webkit-appearance: none;\n        height: 14px;\n        width: 14px;\n        border-radius: 50%;\n        background: rgb(50 50 50);\n        cursor: default;\n        box-shadow: inset 0px 0px 0px 1px rgba(255, 255, 255, 0.4);\n        transition: all var(--appleTransition);\n      }\n\n      &::-webkit-slider-thumb:hover {\n        background-image: radial-gradient(var(--songProgressColor) 2px, transparent 3px, transparent 10px);\n        transform: scale(1.2);\n      }\n\n      &::-webkit-slider-thumb:active {\n        background-image: radial-gradient(var(--songProgressColor) 3px, transparent 4px, transparent 10px);\n        transform: scale(1);\n      }\n\n      &::-webkit-slider-runnable-track {\n        -webkit-appearance: none;\n        box-shadow: none;\n        border: none;\n        background: transparent;\n      }\n    }\n  }\n\n  .background {\n    position: absolute;\n    background-size: cover;\n    width: 100%;\n    height: 100%;\n\n    .bgArtworkMaterial {\n      position: absolute;\n      width: 100%;\n      height: 100%;\n\n      .bg-artwork-container {\n        z-index: unset;\n      }\n\n      .bg-artwork-container .bg-artwork {\n        filter: brightness(85%) saturate(95%) blur(180px) contrast(0.9) opacity(0.9);\n      }\n    }\n  }\n\n  .lyrics-col {\n    height: 62vh;\n    display: flex;\n    justify-content: center;\n    align-content: center;\n    width: 80%;\n\n    ::-webkit-scrollbar-thumb {\n      box-shadow: unset;\n    }\n\n    &:hover ::-webkit-scrollbar-thumb {\n      box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n    }\n\n    .no-lyrics {\n      width: 100%;\n      height: 100%;\n      display: flex;\n      justify-content: center;\n    }\n\n    .lyric-line {\n      font-size: 35px;\n    }\n  }\n\n  .queue-col {\n    width: 60vh;\n    height: 62vh;\n\n    .queue-title {\n      opacity: 0.6;\n    }\n\n    .queue-panel > * {\n      z-index: 3;\n    }\n\n    ::-webkit-scrollbar-thumb {\n      box-shadow: unset;\n    }\n\n    &:hover ::-webkit-scrollbar-thumb {\n      box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n    }\n  }\n\n  .tab-toggles {\n    display: flex;\n    position: absolute;\n    bottom: 0;\n    right: 0;\n    width: 15vh;\n    height: 5vh;\n    justify-content: space-evenly;\n\n    .volume {\n      background-image: url(\"./assets/feathers/volume.svg\");\n      padding: 0.5vh;\n      width: 2vh;\n      height: 2vh;\n      background-origin: content-box;\n      background-repeat: no-repeat;\n    }\n\n    .queue {\n      background-image: url(\"./assets/list.svg\");\n      padding: 0.5vh;\n      width: 2.5vh;\n      height: 2.5vh;\n      background-origin: content-box;\n      background-repeat: no-repeat;\n    }\n\n    .lyrics {\n      background-image: url(\"./assets/quote-right.svg\");\n      padding: 0.5vh;\n      width: 2.5vh;\n      height: 2.5vh;\n      background-origin: content-box;\n      background-repeat: no-repeat;\n    }\n\n    .active {\n      background-color: rgba(200, 200, 200, 0.7);\n      border-radius: 3px;\n    }\n  }\n\n  .artwork-col {\n    justify-content: center;\n    align-items: center;\n    display: flex;\n    flex-direction: column;\n\n    .artwork {\n      width: 50vh;\n      height: 50vh;\n    }\n\n    .controls-parents {\n      width: 50vh;\n    }\n\n    .app-playback-controls {\n      .song-artist,\n      .song-name {\n        font-weight: 600;\n        text-align: center;\n        font-size: 0.9em;\n        height: 1.2em;\n        line-height: 0.9em;\n        overflow: hidden;\n        text-overflow: ellipsis;\n        max-width: 360px;\n\n        .song-name-normal {\n          height: inherit;\n        }\n\n        &.song-artist-marquee {\n          > marquee {\n            //margin-bottom: -3px;\n          }\n        }\n      }\n\n      .song-artist {\n        font-size: 0.875em;\n        font-weight: 400;\n      }\n\n      .song-name {\n        width: unset !important;\n        margin-top: 0.15vh;\n        display: -webkit-box;\n        line-height: 1.2;\n        text-overflow: ellipsis;\n        text-align: center;\n      }\n    }\n\n    .app-playback-controls .playback-info {\n      margin-top: 0.5vh;\n      width: 100%;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      flex-direction: column;\n      position: relative;\n\n      input[type=\"range\"] {\n        width: 100%;\n      }\n\n      > div {\n        width: 100%;\n        text-align: center;\n      }\n    }\n\n    .app-playback-controls .song-progress {\n      @bgColor: transparent;\n      //height: 16px;\n      position: absolute;\n      bottom: -1.5vh;\n      left: 0px;\n      background: @bgColor;\n\n      .song-duration p {\n        font-weight: 400;\n        font-size: 10px;\n        height: 1.2em;\n        line-height: 1.3em;\n        overflow: hidden;\n        margin: 0 0 0 0.25em;\n      }\n\n      &:hover {\n        > input[type=\"range\"] {\n          &::-webkit-slider-thumb {\n            opacity: 1;\n            transform: scale(1);\n            z-index: 1;\n          }\n        }\n      }\n\n      input[type=\"range\"] {\n        appearance: none;\n        width: 100%;\n        height: 4px;\n        background-color: rgb(200 200 200 / 10%);\n        border-radius: 2px;\n\n        &::-webkit-slider-thumb {\n          opacity: 0;\n          transform: scale(0.5);\n          -webkit-appearance: none;\n          appearance: none;\n          width: 12px;\n          height: 12px;\n          border-radius: 100%;\n          background: var(--songProgressColor);\n          cursor: default;\n          transition:\n            opacity 0.1s var(--appleEase),\n            transform 0.1s var(--appleEase);\n        }\n\n        &::-moz-range-thumb {\n          width: 8px;\n          height: 8px;\n          border-radius: 100%;\n          background: var(--songProgressColor);\n          cursor: default;\n        }\n      }\n    }\n\n    .control-buttons {\n      margin-top: 2vh;\n      display: inline-flex;\n      width: 100%;\n      justify-content: center;\n      align-items: center;\n    }\n  }\n\n  .cd-mediaitem-square {\n    font-size: 17px;\n    font-weight: 500;\n  }\n\n  .cd-mediaitem-square .artwork-container .artwork {\n    box-shadow: var(--mediaItemShadow-Shadow);\n  }\n\n  .cd-mediaitem-list-item {\n    height: 80px;\n  }\n\n  .cd-mediaitem-list-item .title {\n    font-size: 1.2em;\n    font-weight: 450;\n  }\n\n  .cd-mediaitem-list-item .subtitle {\n    font-size: 1.1em;\n    font-weight: 380;\n  }\n\n  .cd-mediaitem-list-item .duration {\n    font-size: 1.2em;\n  }\n\n  .cd-mediaitem-list-item .artwork {\n    width: 50px;\n    height: 50px;\n  }\n\n  .cd-btn-seeall {\n    font-size: 1.2em;\n  }\n\n  h1 {\n    font-size: 3em;\n  }\n\n  h3 {\n    font-size: 1.5rem;\n  }\n\n  .home-page .well.artistfeed-well {\n    height: 512px;\n  }\n\n  .header-text {\n    font-size: 3em;\n    height: 3em;\n    padding-left: 0.2em;\n  }\n\n  .grouping-container .grouping-btn {\n    font-size: 1.3em;\n    color: var(--textColor);\n    background-color: var(--sidebarColor);\n    font-weight: 600;\n    padding: 32px;\n    //box-shadow: var(--ciderShadow-Generic);\n  }\n\n  .content-inner.playlist-page {\n    display: flex;\n    flex-direction: row;\n  }\n\n  .playlist-page .playlist-display {\n    width: 100%;\n    max-width: 500px;\n    flex: 1;\n    text-align: center;\n\n    .playlistInfo {\n      > .row {\n        justify-content: center;\n      }\n    }\n\n    .playlist-controls {\n      div {\n        width: 100%;\n      }\n    }\n  }\n  .playlist-page .mediaContainer {\n    width: 30vh;\n    height: 30vh;\n    aspect-ratio: 1;\n  }\n  .playlist-page .playlist-display .playlistInfo .playlist-info {\n    gap: 16px;\n    margin-top: 40px;\n  }\n\n  .playlist-page .playlist-display .playlistInfo .playlist-hero {\n    transform: unset;\n  }\n\n  .artist-page .artist-header {\n    min-height: 60vh;\n  }\n\n  .artist-page .artist-image {\n    width: 20vh;\n    height: 20vh;\n    aspect-ratio: 1;\n  }\n\n  .artist-page.animated .artist-header {\n    min-height: 80vh;\n  }\n\n  .playlist-page .playlist-body {\n    flex: 1;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/helpers.css",
    "content": ".notyf__toast {\n  -webkit-app-region: no-drag;\n  cursor: pointer;\n}\n.notyf-info {\n  background: var(--keyColor);\n}\n.tooltip-inner {\n  background: #2f2f2f;\n  opacity: 1;\n  border: 1px solid rgba(0, 0, 0, 0.35);\n  transition: all 0.3s ease-in-out;\n  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);\n}\n.modal-fullscreen {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  position: fixed;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: rgba(0, 0, 0, 0.3);\n  z-index: 1000;\n}\n.modal-fullscreen .modal-window {\n  background: #333;\n  border-radius: 10px;\n  box-shadow: var(--mediaItemShadow-Shadow);\n  display: flex;\n  flex-flow: column;\n  max-height: 500px;\n  max-width: 360px;\n  background: #121212;\n  width: 100%;\n  position: relative;\n}\n.modal-fullscreen .modal-window:after {\n  content: \"\";\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  pointer-events: none;\n  box-shadow: var(--mediaItemShadow);\n  z-index: 1;\n  border-radius: inherit;\n}\n.modal-fullscreen .modal-window .modal-header {\n  width: 100%;\n  padding: 6px;\n}\n.modal-fullscreen .modal-window .modal-content {\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n  overflow-y: overlay;\n}\n.spatialproperties-panel .modal-window {\n  overflow: hidden;\n}\n.spatialproperties-panel .modal-window:not(.airplay-modal) {\n  height: 700px;\n  max-height: 700px;\n  width: 800px;\n  max-width: 800px;\n}\n.spatialproperties-panel .modal-window .info-header {\n  padding-left: 12px;\n}\n.spatialproperties-panel .modal-window .visual-container {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  overflow: hidden;\n}\n.spatialproperties-panel .modal-window .visual {\n  position: relative;\n  height: 250px;\n  width: 300px;\n  display: inline-flex;\n  align-items: flex-end;\n  justify-content: center;\n  filter: drop-shadow(2px 12px 6px rgba(0, 0, 0, 0.25));\n  margin: 0 auto;\n}\n.spatialproperties-panel .modal-window .visual .face {\n  position: absolute;\n  width: calc(12px * 6);\n  height: calc(12px * 6);\n  border-radius: 6px;\n  transform: rotateX(60deg) rotateZ(-45deg);\n  transition: transform 0.2s linear, width 0.2s linear, height 0.2s linear;\n}\n.spatialproperties-panel .modal-window .visual .listener {\n  position: absolute;\n  width: 32px;\n  height: 32px;\n  border-radius: 6px;\n  transform: rotateX(60deg) rotateZ(-45deg);\n  transition: transform 0.2s linear, width 0.2s linear, height 0.2s linear;\n  background: white;\n  color: black;\n  z-index: 2;\n}\n.spatialproperties-panel .modal-window .visual .audiosource {\n  position: absolute;\n  width: 32px;\n  height: 32px;\n  border-radius: 6px;\n  transform: rotateX(60deg) rotateZ(-45deg);\n  transition: transform 0.2s linear, width 0.2s linear, height 0.2s linear;\n  background: yellow;\n  z-index: 2;\n}\n.spatialproperties-panel .modal-window .visual .face:nth-of-type(1) {\n  background: linear-gradient(45deg, #28223a, #1f2038);\n  z-index: 1;\n}\n.spatialproperties-panel .modal-window .visual .face:nth-of-type(2) {\n  background: linear-gradient(45deg, #7d53ad, #5763ff);\n  transform: rotateX(60deg) rotateZ(-45deg) translateZ(30px);\n  opacity: 0.7;\n  z-index: 3;\n}\n.spatialproperties-panel .modal-window .modal-header {\n  padding: 16px;\n  position: relative;\n  overflow: hidden;\n}\n.spatialproperties-panel .modal-window .modal-header .modal-title {\n  text-align: center;\n}\n.spatialproperties-panel .modal-window .modal-header .close-btn {\n  width: 36px;\n  height: 36px;\n  background-position: center;\n  background-repeat: no-repeat;\n  -webkit-app-region: no-drag;\n  appearance: none;\n  border: 0;\n  background-color: transparent;\n  position: absolute;\n  top: 10px;\n  right: 10px;\n  border-radius: 50px;\n  display: grid;\n  align-content: center;\n}\n.spatialproperties-panel .modal-window .modal-header .close-btn:before {\n  content: \"\";\n  font-family: \"codicon\";\n  color: var(--textColor);\n  font-size: 20px;\n}\n.spatialproperties-panel .modal-window .modal-header .close-btn:hover {\n  background-color: #c42b1c;\n}\n.addtoplaylist-panel .modal-window {\n  max-height: 600px;\n  max-width: 400px;\n  background: rgba(18, 18, 18, 0.9);\n  overflow: hidden;\n  backdrop-filter: blur(16px) saturate(180%);\n}\n.addtoplaylist-panel .modal-window .modal-header {\n  padding: 16px;\n  position: relative;\n}\n.addtoplaylist-panel .modal-window .modal-header .modal-title {\n  text-align: center;\n}\n.addtoplaylist-panel .modal-window .modal-header .close-btn {\n  width: 36px;\n  height: 36px;\n  background-position: center;\n  background-repeat: no-repeat;\n  -webkit-app-region: no-drag;\n  appearance: none;\n  border: 0;\n  background-color: transparent;\n  position: absolute;\n  top: 10px;\n  right: 10px;\n  border-radius: 50px;\n  display: grid;\n  align-content: center;\n}\n.addtoplaylist-panel .modal-window .modal-header .close-btn:before {\n  content: \"\";\n  font-family: \"codicon\";\n  color: var(--textColor);\n  font-size: 20px;\n}\n.addtoplaylist-panel .modal-window .modal-header .close-btn:hover {\n  background-color: #c42b1c;\n}\n.addtoplaylist-panel .modal-window .modal-search {\n  width: 100%;\n  padding: 0px 16px;\n  position: relative;\n}\n.addtoplaylist-panel .modal-window .playlist-item {\n  appearance: none;\n  border: 0px;\n  text-align: left;\n  width: 100%;\n  margin: 0;\n  display: flex;\n  background: rgba(32, 32, 32, 0.46);\n  color: #eee;\n  font-family: inherit;\n  font-size: 0.98em;\n  padding: 6px 12px;\n  align-items: center;\n  flex-flow: row;\n}\n.addtoplaylist-panel .modal-window .playlist-item .icon {\n  pointer-events: none;\n  width: 32px;\n  height: 32px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  margin-right: 6px;\n}\n.addtoplaylist-panel .modal-window .playlist-item .name {\n  position: relative;\n}\n.addtoplaylist-panel .modal-window .playlist-item:hover {\n  background: var(--selected);\n}\n.addtoplaylist-panel .modal-window .playlist-item:active {\n  background: var(--selected-click);\n}\n.addtoplaylist-panel .modal-window .playlist-item.focused {\n  background: var(--keyColor);\n}\n.addtoplaylist-panel .modal-window .playlist-item:last-child {\n  border-bottom: 0px;\n}\n.menu-panel {\n  width: 100%;\n  height: 100%;\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 100001;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  -webkit-app-region: no-drag;\n}\n.menu-panel .menu-header-body {\n  padding: 6px;\n  display: flex;\n  background: rgba(200, 200, 200, 0.1);\n}\n.menu-panel .menu-header-body .menu-option-header {\n  width: 40px;\n  height: 40px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  border-radius: var(--mediaItemRadius);\n  appearance: none;\n  border: 0;\n  background: transparent;\n}\n.menu-panel .menu-header-body .menu-option-header.active .sidebar-icon > .svg-icon {\n  --color: var(--keyColor);\n}\n.menu-panel .menu-header-body .menu-option-header:hover {\n  background: var(--selected);\n}\n.menu-panel .menu-header-body .menu-option-header:active {\n  background: var(--selected-click);\n}\n.menu-panel .menu-panel-body {\n  display: flex;\n  flex-flow: column;\n  background: rgba(30, 30, 30, 0.45);\n  backdrop-filter: blur(32px) saturate(180%);\n  position: relative;\n  min-width: 200px;\n  box-shadow: var(--ciderShadow-Generic);\n  border-radius: var(--panelRadius);\n  overflow: hidden;\n  font-size: 13px;\n}\n.menu-panel .menu-panel-body .menu-option {\n  text-align: left;\n  display: flex;\n  appearance: none;\n  border: 0px;\n  font: inherit;\n  background: transparent;\n  color: inherit;\n  margin: 0 auto;\n  position: relative;\n  width: 100%;\n  padding: 9px 14px;\n  align-items: center;\n}\n.menu-panel .menu-panel-body .menu-option::before {\n  background: var(--hover);\n  border-radius: 6px;\n  content: \"\";\n  --sizeY: 3px;\n  --sizeX: 4px;\n  top: var(--sizeY);\n  left: var(--sizeX);\n  bottom: var(--sizeY);\n  right: var(--sizeX);\n  position: absolute;\n  opacity: 0;\n  transform: scale(0.98);\n  z-index: -1;\n  transition: transform 0.25s ease-out, opacity 0.25s ease-out;\n}\n.menu-panel .menu-panel-body .menu-option:hover::before {\n  transition: transform 0s ease-in, opacity 0s ease-in;\n  opacity: 1;\n  transform: scale(1);\n}\n.menu-panel .menu-panel-body .menu-option:active::before {\n  transition: transform 0.1s ease-in-out, opacity 0.1s ease-in-out;\n  opacity: 1;\n  transform: scale(0.98);\n  background: var(--selected-click);\n}\n.menu-panel .menu-header-text {\n  margin: 18px 6px;\n}\n.menu-panel .menu-header-text .close-btn {\n  width: 36px;\n  height: 36px;\n  background-position: center;\n  background-repeat: no-repeat;\n  -webkit-app-region: no-drag;\n  appearance: none;\n  border: 0;\n  background-color: transparent;\n  position: absolute;\n  top: 10px;\n  right: 10px;\n  border-radius: 50px;\n  display: grid;\n  align-content: center;\n}\n.menu-panel .menu-header-text .close-btn:before {\n  content: \"\";\n  font-family: \"codicon\";\n  color: var(--textColor);\n  font-size: 20px;\n}\n.menu-panel .menu-header-text .close-btn:hover {\n  background-color: #c42b1c;\n}\n.menu-panel .menu-body {\n  overflow: overlay;\n  height: 100%;\n  display: flex;\n  flex-flow: column;\n  gap: 0px;\n  padding: 0px;\n  position: relative;\n}\n.menu-panel .menu-footer {\n  width: 100%;\n  padding: 12px;\n}\n.queue-panel {\n  height: 100%;\n  width: 100%;\n  display: flex;\n  flex-flow: column;\n}\n.queue-panel .queue-header-text {\n  margin: 18px 6px;\n}\n.queue-panel .queue-body {\n  overflow: overlay;\n  height: 100%;\n}\n.queue-panel .queue-footer {\n  width: 100%;\n  padding: 12px;\n}\n.queue-panel .autoplay {\n  background: rgba(200, 200, 200, 0.15);\n  display: flex;\n  justify-content: center;\n  appearance: none;\n  border: 0;\n  border-radius: 6px;\n  height: 32px;\n  width: 32px;\n}\n.queue-panel .infinity {\n  content: url(\"assets/infinity.svg\");\n  margin: auto;\n}\n.moreinfo-modal .modal-window {\n  height: 70%;\n  max-height: 100%;\n  width: 45%;\n  max-width: 100%;\n  overflow: hidden;\n  line-height: 1.25;\n}\n.moreinfo-modal .modal-content {\n  padding: 1em;\n  font-size: 0.8rem;\n}\n.moreinfo-modal .modal-content br {\n  display: block;\n  /* makes it have a width */\n  content: \"\";\n  /* clears default height */\n  margin: 2em;\n  margin-bottom: -0.6rem;\n}\n.moreinfo-modal .modal-header {\n  flex-direction: column;\n}\n.moreinfo-modal .modal-header .modal-title {\n  text-align: unset !important;\n  width: 100%;\n}\n.moreinfo-modal .modal-header .modal-title:not(.modal-subtitle) {\n  font-size: 25px;\n}\n.mediainfo-popover {\n  user-select: none;\n  background-color: #000000;\n  overflow: hidden;\n}\n.mediainfo-popover .content .shadow-artwork {\n  height: 100%;\n  width: 100%;\n  position: absolute;\n  top: 0;\n  left: 0;\n  z-index: -1;\n  filter: blur(32px) brightness(50%) saturate(280%);\n}\n.mediainfo-popover .content .popover-artwork {\n  width: 200px;\n  height: 200px;\n  margin: 0 auto;\n  margin-bottom: 20px;\n}\n.mediainfo-popover .content .song-name {\n  font-weight: 600;\n}\n.mediainfo-popover .content .song-artist,\n.mediainfo-popover .content .song-album {\n  opacity: 0.75;\n  cursor: pointer;\n}\n.mediainfo-popover .content .song-artist:hover,\n.mediainfo-popover .content .song-album:hover {\n  text-decoration: underline;\n}\n._svg-icon {\n  --icon: url(\"assets/chevron-left.svg\");\n  --size: 1em;\n  width: var(--size);\n  height: var(--size);\n  -webkit-mask-image: var(--icon);\n  -webkit-mask-position: center;\n  -webkit-mask-size: contain;\n  background: rgba(255, 255, 255, 0.76);\n  -webkit-mask-repeat: no-repeat;\n}\n._svg-icon.svg-md {\n  --size: 1.2em;\n}\n"
  },
  {
    "path": "src/renderer/less/helpers.less",
    "content": ".notyf__toast {\n  -webkit-app-region: no-drag;\n  cursor: pointer;\n}\n\n.notyf-info {\n  background: var(--keyColor);\n}\n\n.tooltip-inner {\n  background: #2f2f2f;\n  opacity: 1;\n  border: 1px solid rgb(0 0 0 / 35%);\n  transition: all 0.3s ease-in-out;\n  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);\n}\n\n.modal-fullscreen {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  position: fixed;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: rgba(0, 0, 0, 0.3);\n  z-index: 1000;\n\n  .modal-window {\n    background: #333;\n    border-radius: 10px;\n    box-shadow: var(--mediaItemShadow-Shadow);\n    display: flex;\n    flex-flow: column;\n    max-height: 500px;\n    max-width: 360px;\n    background: #121212;\n    width: 100%;\n    position: relative;\n\n    &:after {\n      content: \"\";\n      position: absolute;\n      top: 0;\n      left: 0;\n      width: 100%;\n      height: 100%;\n      pointer-events: none;\n      box-shadow: var(--mediaItemShadow);\n      z-index: 1;\n      border-radius: inherit;\n    }\n\n    .modal-header {\n      width: 100%;\n      padding: 6px;\n    }\n\n    .modal-content {\n      width: 100%;\n      height: 100%;\n      overflow: hidden;\n      overflow-y: overlay;\n    }\n\n    .modal-footer {\n    }\n  }\n}\n\n.spatialproperties-panel {\n  .modal-window {\n    &:not(.airplay-modal) {\n      height: 700px;\n      max-height: 700px;\n      width: 800px;\n      max-width: 800px;\n    }\n\n    overflow: hidden;\n\n    .info-header {\n      padding-left: 12px;\n    }\n\n    .visual-container {\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      overflow: hidden;\n    }\n\n    .visual {\n      position: relative;\n      height: 250px;\n      width: 300px;\n      display: inline-flex;\n      align-items: flex-end;\n      justify-content: center;\n      filter: drop-shadow(2px 12px 6px rgb(0 0 0 / 25%));\n      margin: 0 auto;\n\n      .face {\n        position: absolute;\n        width: calc(12px * 6);\n        height: calc(12px * 6);\n        border-radius: 6px;\n        transform: rotateX(60deg) rotateZ(-45deg);\n        transition:\n          transform 0.2s linear,\n          width 0.2s linear,\n          height 0.2s linear;\n      }\n\n      .listener {\n        position: absolute;\n        width: 32px;\n        height: 32px;\n        border-radius: 6px;\n        transform: rotateX(60deg) rotateZ(-45deg);\n        transition:\n          transform 0.2s linear,\n          width 0.2s linear,\n          height 0.2s linear;\n        background: white;\n        color: black;\n        z-index: 2;\n      }\n\n      .audiosource {\n        position: absolute;\n        width: 32px;\n        height: 32px;\n        border-radius: 6px;\n        transform: rotateX(60deg) rotateZ(-45deg);\n        transition:\n          transform 0.2s linear,\n          width 0.2s linear,\n          height 0.2s linear;\n        background: yellow;\n        z-index: 2;\n      }\n\n      .face:nth-of-type(1) {\n        background: linear-gradient(45deg, #28223a, #1f2038);\n        z-index: 1;\n      }\n\n      .face:nth-of-type(2) {\n        background: linear-gradient(45deg, #7d53ad, #5763ff);\n        transform: rotateX(60deg) rotateZ(-45deg) translateZ(30px);\n        opacity: 0.7;\n        z-index: 3;\n      }\n    }\n\n    .modal-header {\n      padding: 16px;\n      position: relative;\n      overflow: hidden;\n\n      .modal-title {\n        text-align: center;\n      }\n\n      .close-btn {\n        .menu-panel.menu-header-text.close-btn;\n      }\n    }\n  }\n}\n\n.addtoplaylist-panel {\n  .modal-window {\n    max-height: 600px;\n    max-width: 400px;\n    background: rgb(18 18 18 / 90%);\n    overflow: hidden;\n    backdrop-filter: blur(16px) saturate(180%);\n\n    .modal-header {\n      padding: 16px;\n      position: relative;\n\n      .modal-title {\n        text-align: center;\n      }\n\n      .close-btn {\n        .menu-panel.menu-header-text.close-btn;\n      }\n    }\n\n    .modal-search {\n      width: 100%;\n      padding: 0px 16px;\n      position: relative;\n    }\n\n    .playlist-item {\n      appearance: none;\n      border: 0px;\n      text-align: left;\n      width: 100%;\n      margin: 0;\n      display: flex;\n      background: rgba(32, 32, 32, 0.46);\n      color: #eee;\n      font-family: inherit;\n      font-size: 0.98em;\n      padding: 6px 12px;\n      align-items: center;\n      flex-flow: row;\n\n      .icon {\n        pointer-events: none;\n        width: 32px;\n        height: 32px;\n        display: flex;\n        justify-content: center;\n        align-items: center;\n        margin-right: 6px;\n      }\n\n      .name {\n        position: relative;\n      }\n\n      &:hover {\n        background: var(--selected);\n      }\n\n      &:active {\n        background: var(--selected-click);\n      }\n\n      &.focused {\n        background: var(--keyColor);\n      }\n    }\n\n    .playlist-item:last-child {\n      border-bottom: 0px;\n    }\n  }\n}\n\n.menu-panel {\n  width: 100%;\n  height: 100%;\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 100001;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  -webkit-app-region: no-drag;\n\n  .menu-header-body {\n    padding: 6px;\n    display: flex;\n    background: rgb(200 200 200 / 10%);\n\n    .menu-option-header {\n      width: 40px;\n      height: 40px;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      border-radius: var(--mediaItemRadius);\n      appearance: none;\n      border: 0;\n      background: transparent;\n\n      &.active {\n        .sidebar-icon > .svg-icon {\n          --color: var(--keyColor);\n        }\n      }\n\n      &:hover {\n        background: var(--selected);\n      }\n\n      &:active {\n        background: var(--selected-click);\n      }\n    }\n  }\n\n  .menu-panel-body {\n    display: flex;\n    flex-flow: column;\n    background: rgb(30 30 30 / 45%);\n    backdrop-filter: blur(32px) saturate(180%);\n    position: relative;\n    min-width: 200px;\n    box-shadow: var(--ciderShadow-Generic);\n    border-radius: var(--panelRadius);\n    overflow: hidden;\n    font-size: 13px;\n\n    .menu-option {\n      text-align: left;\n      display: flex;\n      appearance: none;\n      border: 0px;\n      font: inherit;\n      background: transparent;\n      color: inherit;\n      margin: 0 auto;\n      position: relative;\n      width: 100%;\n      padding: 9px 14px;\n      align-items: center;\n\n      &::before {\n        background: var(--hover);\n        border-radius: 6px;\n        content: \"\";\n        --sizeY: 3px;\n        --sizeX: 4px;\n        top: var(--sizeY);\n        left: var(--sizeX);\n        bottom: var(--sizeY);\n        right: var(--sizeX);\n        position: absolute;\n        opacity: 0;\n        transform: scale(0.98);\n        z-index: -1;\n        transition:\n          transform 0.25s ease-out,\n          opacity 0.25s ease-out;\n      }\n\n      &:hover {\n        &::before {\n          transition:\n            transform 0s ease-in,\n            opacity 0s ease-in;\n          opacity: 1;\n          transform: scale(1);\n        }\n      }\n\n      &:active {\n        &::before {\n          transition:\n            transform 0.1s ease-in-out,\n            opacity 0.1s ease-in-out;\n          opacity: 1;\n          transform: scale(0.98);\n          background: var(--selected-click);\n        }\n      }\n    }\n  }\n\n  .menu-header-text {\n    margin: 18px 6px;\n\n    .close-btn {\n      width: 36px;\n      height: 36px;\n      background-position: center;\n      background-repeat: no-repeat;\n      -webkit-app-region: no-drag;\n      appearance: none;\n      border: 0;\n      background-color: transparent;\n      position: absolute;\n      top: 10px;\n      right: 10px;\n      border-radius: 50px;\n      display: grid;\n      align-content: center;\n\n      &:before {\n        content: \"\";\n        font-family: \"codicon\";\n        color: var(--textColor);\n        font-size: 20px;\n      }\n\n      &:hover {\n        background-color: rgb(196, 43, 28);\n      }\n    }\n  }\n\n  .menu-body {\n    overflow: overlay;\n    height: 100%;\n    display: flex;\n    flex-flow: column;\n    gap: 0px;\n    padding: 0px;\n    position: relative;\n  }\n\n  .menu-footer {\n    width: 100%;\n    padding: 12px;\n  }\n}\n\n.queue-panel {\n  height: 100%;\n  width: 100%;\n  display: flex;\n  flex-flow: column;\n\n  .queue-header-text {\n    margin: 18px 6px;\n  }\n\n  .queue-body {\n    overflow: overlay;\n    height: 100%;\n  }\n\n  .queue-footer {\n    width: 100%;\n    padding: 12px;\n  }\n\n  .autoplay {\n    background: rgb(200 200 200 / 15%);\n    display: flex;\n    justify-content: center;\n    appearance: none;\n    border: 0;\n    border-radius: 6px;\n    height: 32px;\n    width: 32px;\n  }\n\n  .infinity {\n    content: url(\"./assets/infinity.svg\");\n    margin: auto;\n  }\n}\n\n.moreinfo-modal {\n  .modal-window {\n    height: 70%;\n    max-height: 100%;\n    width: 45%;\n    max-width: 100%;\n    overflow: hidden;\n    line-height: 1.25;\n  }\n\n  .modal-content {\n    padding: 1em;\n    font-size: 0.8rem;\n\n    br {\n      display: block;\n      /* makes it have a width */\n      content: \"\";\n      /* clears default height */\n      margin: 2em;\n      margin-bottom: -0.6rem;\n    }\n  }\n\n  .modal-header {\n    flex-direction: column;\n\n    .modal-title {\n      text-align: unset !important;\n      width: 100%;\n\n      &:not(.modal-subtitle) {\n        font-size: 25px;\n      }\n    }\n  }\n}\n\n.mediainfo-popover {\n  user-select: none;\n  background-color: rgb(0 0 0 / 100%);\n  overflow: hidden;\n\n  .content {\n    .shadow-artwork {\n      height: 100%;\n      width: 100%;\n      position: absolute;\n      top: 0;\n      left: 0;\n      z-index: -1;\n      filter: blur(32px) brightness(50%) saturate(280%);\n    }\n\n    .popover-artwork {\n      width: 200px;\n      height: 200px;\n      margin: 0 auto;\n      margin-bottom: 20px;\n    }\n\n    .song-name {\n      font-weight: 600;\n    }\n\n    .song-artist,\n    .song-album {\n      opacity: 0.75;\n      cursor: pointer;\n\n      &:hover {\n        text-decoration: underline;\n      }\n    }\n  }\n}\n\n._svg-icon {\n  --icon: url(\"./assets/chevron-left.svg\");\n  --size: 1em;\n  width: var(--size);\n  height: var(--size);\n  -webkit-mask-image: var(--icon);\n  -webkit-mask-position: center;\n  -webkit-mask-size: contain;\n  background: rgb(255 255 255 / 76%);\n  -webkit-mask-repeat: no-repeat;\n\n  &.svg-md {\n    --size: 1.2em;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/linux.less",
    "content": "// Linux\nbody[platform=\"linux\"] {\n  #window-controls-container {\n    //display: none;\n  }\n\n  .window-controls {\n    justify-content: flex-end;\n    align-items: center;\n    padding-right: 6px;\n\n    > div {\n      --iconSize: 16px;\n\n      &.close,\n      &.minmax,\n      &.minimize,\n      &.minmax.restore {\n        background-image: unset !important;\n        position: relative;\n        display: grid;\n        align-content: center;\n        text-align: center;\n        height: 36px !important;\n        width: 36px !important;\n        border-radius: 50px;\n        transition: background-color 0.1s ease-in-out;\n\n        &:hover {\n          background: rgb(200 200 200 / 10%) !important;\n        }\n      }\n\n      &.close::before {\n        font-family: \"codicon\";\n        font-size: var(--iconSize);\n        content: \"\";\n      }\n\n      &.minmax::before {\n        font-family: \"codicon\";\n        font-size: var(--iconSize);\n        content: \"\";\n      }\n\n      &.minimize::before {\n        font-family: \"codicon\";\n        font-size: var(--iconSize);\n        content: \"\";\n      }\n\n      &.restore::before {\n        font-family: \"codicon\";\n        font-size: var(--iconSize);\n        content: \"\";\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/macos.less",
    "content": "body[platform=\"darwin\"] {\n  html {\n    background: transparent !important;\n  }\n\n  &.notransparency::before {\n    display: none;\n  }\n\n  #app {\n    &.simplebg {\n      background: transparent;\n    }\n\n    &::before {\n      display: none;\n    }\n\n    .app-chrome {\n      background-color: var(--macOSChromeColor);\n    }\n\n    &.twopanel {\n      --chromeHeight1: 55px;\n      --chromeHeight: calc(var(--chromeHeight1) + var(--chromeHeight2));\n\n      .app-chrome .app-chrome-item.search {\n        margin-right: 12px;\n      }\n\n      .app-chrome .app-mainmenu {\n        width: 46px;\n      }\n\n      .app-chrome.chrome-bottom {\n        background-color: var(--macOSChromeColor);\n      }\n    }\n\n    &[window-state=\"normal\"] {\n      &::after {\n        position: fixed;\n        top: 0;\n        left: 0;\n        right: 0;\n        bottom: 0;\n        box-shadow: inset 0px 0px 0.5px 1px rgb(200 200 200 / 40%);\n        border-radius: 10px;\n        content: \" \";\n        z-index: 999999;\n        pointer-events: none;\n      }\n    }\n  }\n\n  #app-main {\n    background-color: transparent;\n\n    .app-navigation {\n      background: transparent;\n    }\n\n    #app-content {\n      background-color: #1e1e1e6b;\n    }\n  }\n\n  .settings-window.maxed {\n    .tabs > .col-auto {\n      transition: padding-top 0.3s linear;\n      padding-top: var(--chromeHeight1);\n    }\n  }\n\n  #apple-music-video-player-controls #player-exit {\n    margin-top: 18px;\n    left: 70px;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/macosemu.less",
    "content": "#app.macosemu {\n  .app-chrome .app-chrome-item > .window-controls-macos {\n    @controlSize: 12px;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    width: 96px;\n    @closeClr: rgb(255, 92, 92);\n    @minmaxClr: rgb(77, 202, 77);\n    @minClr: rgb(255, 189, 76);\n    @borderDarken: 55%;\n\n    div {\n      margin: 4px;\n      background-color: red;\n      border-radius: 100%;\n      flex: 0 0 auto;\n      background-image: unset !important;\n      //border: 1px solid white;\n      &.close {\n        box-shadow: 0px 0px 0px 1px darken(@closeClr, @borderDarken);\n        background-color: @closeClr;\n        width: @controlSize;\n        height: @controlSize;\n      }\n\n      &.minimize {\n        box-shadow: 0px 0px 0px 1px darken(@minClr, @borderDarken);\n        background-color: @minClr;\n        width: @controlSize;\n        height: @controlSize;\n      }\n\n      &.minmax {\n        box-shadow: 0px 0px 0px 1px darken(@minmaxClr, 45%);\n        background-color: @minmaxClr;\n        width: @controlSize;\n        height: @controlSize;\n      }\n    }\n  }\n  .usermenu-body {\n    left: calc(100vw - 260px);\n    position: relative;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/miniplayer.less",
    "content": ".mini-view {\n  width: 100%;\n  height: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n\n  .fs-row {\n    flex-grow: 1;\n  }\n\n  .playback-button--small.active {\n    background-color: rgb(200 200 200 / 25%);\n  }\n\n  .player-exit {\n    z-index: 3;\n    position: absolute;\n    top: 5px;\n    right: 5px;\n    -webkit-app-region: no-drag;\n  }\n\n  .player-pin {\n    z-index: 3;\n    position: absolute;\n    min-width: 20px;\n    min-height: 20px;\n    top: 5px;\n    right: 30px;\n    -webkit-app-region: no-drag;\n  }\n\n  #mini-pin {\n    display: none;\n  }\n\n  .player-pin:hover #mini-pin {\n    display: block;\n  }\n\n  .playback-button--small {\n    opacity: 0.7;\n  }\n\n  .right-col {\n    height: 50vh;\n  }\n\n  @media only screen and (max-width: 1121px) {\n    .display--large {\n      display: flex !important;\n    }\n  }\n\n  .display--large {\n    display: flex;\n\n    .slider {\n      width: 100%;\n      z-index: 1;\n    }\n\n    .input-container {\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      width: 100%;\n    }\n\n    .volume-button--small {\n      border-radius: 6px;\n      color: inherit;\n      background-size: 16px;\n      background-repeat: no-repeat;\n      background-position: center;\n      background-color: transparent;\n      height: 15px;\n      width: 30px;\n      border: 0px;\n      box-shadow: unset;\n      opacity: 0.7;\n      background-image: url(\"./assets/feather/volume-2.svg\");\n    }\n\n    .volume-button--small:active {\n      transform: scale(0.9);\n    }\n\n    .volume-button--small.active {\n      background-image: url(\"./assets/feather/volume.svg\");\n    }\n\n    input[type=\"range\"] {\n      -webkit-appearance: none;\n      height: 4px;\n      background: rgba(255, 255, 255, 0.4);\n      border-radius: 5px;\n      background-size: 70% 100%;\n      background-repeat: no-repeat;\n\n      &::-webkit-slider-thumb {\n        -webkit-appearance: none;\n        height: 14px;\n        width: 14px;\n        border-radius: 50%;\n        background: rgb(50 50 50);\n        cursor: default;\n        box-shadow: inset 0px 0px 0px 1px rgba(255, 255, 255, 0.4);\n        transition: all var(--appleTransition);\n      }\n\n      &::-webkit-slider-thumb:hover {\n        background-image: radial-gradient(var(--songProgressColor) 2px, transparent 3px, transparent 10px);\n        transform: scale(1.2);\n      }\n\n      &::-webkit-slider-thumb:active {\n        background-image: radial-gradient(var(--songProgressColor) 3px, transparent 4px, transparent 10px);\n        transform: scale(1);\n      }\n\n      &::-webkit-slider-runnable-track {\n        -webkit-appearance: none;\n        box-shadow: none;\n        border: none;\n        background: transparent;\n      }\n    }\n  }\n\n  .background {\n    position: absolute;\n    background-size: cover;\n    width: 100%;\n    height: 100%;\n    -webkit-user-select: none;\n    -webkit-app-region: drag;\n\n    .bgArtworkMaterial {\n      position: absolute;\n      width: 100%;\n      height: 100%;\n\n      .bg-artwork-container {\n        z-index: unset;\n      }\n\n      .bg-artwork-container .bg-artwork {\n        filter: brightness(85%) saturate(95%) blur(180px) contrast(0.9) opacity(0.9);\n      }\n\n      .no-animation {\n        animation: unset;\n      }\n    }\n  }\n\n  .lyrics-col {\n    height: 62vh;\n    display: flex;\n    justify-content: center;\n    align-content: center;\n    width: 80%;\n\n    ::-webkit-scrollbar-thumb {\n      box-shadow: unset;\n    }\n\n    &:hover ::-webkit-scrollbar-thumb {\n      box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n    }\n\n    .no-lyrics {\n      width: 100%;\n      height: 100%;\n      display: flex;\n      justify-content: center;\n    }\n\n    .lyric-line {\n      font-size: 35px;\n    }\n  }\n\n  .queue-col {\n    width: 60vh;\n    height: 50vh;\n\n    .queue-title {\n      opacity: 0.6;\n    }\n\n    .queue-panel > * {\n      z-index: 3;\n    }\n\n    ::-webkit-scrollbar-thumb {\n      box-shadow: unset;\n    }\n\n    &:hover ::-webkit-scrollbar-thumb {\n      box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n    }\n  }\n\n  .tab-toggles {\n    display: flex;\n    position: absolute;\n    bottom: 0;\n    right: 0;\n    width: 15vh;\n    height: 5vh;\n    justify-content: space-evenly;\n\n    .volume {\n      background-image: url(\"./assets/feathers/volume.svg\");\n      padding: 0.5vh;\n      width: 2vh;\n      height: 2vh;\n      background-origin: content-box;\n      background-repeat: no-repeat;\n    }\n\n    .queue {\n      background-image: url(\"./assets/list.svg\");\n      padding: 0.5vh;\n      width: 2.5vh;\n      height: 2.5vh;\n      background-origin: content-box;\n      background-repeat: no-repeat;\n    }\n\n    .lyrics {\n      background-image: url(\"./assets/quote-right.svg\");\n      padding: 0.5vh;\n      width: 2.5vh;\n      height: 2.5vh;\n      background-origin: content-box;\n      background-repeat: no-repeat;\n    }\n\n    .active {\n      background-color: rgba(200, 200, 200, 0.7);\n      border-radius: 3px;\n    }\n  }\n\n  .artwork-col {\n    justify-content: center;\n    align-items: center;\n    display: flex;\n    flex-direction: column;\n\n    .artwork {\n      width: 100%;\n      height: 100%;\n\n      .mediaitem-artwork {\n        border-radius: unset;\n      }\n    }\n\n    .controls-parents {\n      width: 100%;\n      position: absolute;\n      background: #0000009e;\n      backdrop-filter: blur(10px);\n      bottom: 0px;\n      z-index: 3;\n      opacity: 0;\n      padding: 3%;\n\n      &:hover {\n        opacity: 1;\n      }\n    }\n\n    .app-playback-controls {\n      -webkit-app-region: no-drag;\n\n      .song-artist,\n      .song-name {\n        font-weight: 600;\n        text-align: center;\n        font-size: 0.9em;\n        height: 1.2em;\n        line-height: 0.9em;\n        overflow: hidden;\n        text-overflow: ellipsis;\n        max-width: 360px;\n\n        .song-name-normal {\n          height: inherit;\n        }\n\n        &.song-artist-marquee {\n          > marquee {\n            //margin-bottom: -3px;\n          }\n        }\n      }\n\n      .song-artist {\n        font-size: 0.875em;\n        font-weight: 400;\n      }\n\n      .song-name {\n        width: unset !important;\n        margin-top: 0.15vh;\n        display: -webkit-box;\n        line-height: 1.2;\n        text-overflow: ellipsis;\n        text-align: center;\n      }\n    }\n\n    .app-playback-controls .playback-info {\n      margin-top: 0.5vh;\n      width: 100%;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      flex-direction: column;\n      position: relative;\n\n      input[type=\"range\"] {\n        width: 100%;\n      }\n\n      > div {\n        width: 100%;\n        text-align: center;\n      }\n    }\n\n    .app-playback-controls .song-progress {\n      @bgColor: transparent;\n      //height: 16px;\n      position: absolute;\n      bottom: -3.5vh;\n      left: 0px;\n      background: @bgColor;\n\n      .song-duration p {\n        font-weight: 400;\n        font-size: 10px;\n        height: 1.2em;\n        line-height: 1.3em;\n        overflow: hidden;\n        margin: 0 0 0 0.25em;\n      }\n\n      &:hover {\n        > input[type=\"range\"] {\n          &::-webkit-slider-thumb {\n            opacity: 1;\n            transform: scale(1);\n            z-index: 1;\n          }\n        }\n      }\n\n      input[type=\"range\"] {\n        appearance: none;\n        width: 100%;\n        height: 4px;\n        background-color: rgb(200 200 200 / 10%);\n        border-radius: 2px;\n\n        &::-webkit-slider-thumb {\n          opacity: 0;\n          transform: scale(0.5);\n          -webkit-appearance: none;\n          appearance: none;\n          width: 12px;\n          height: 12px;\n          border-radius: 100%;\n          background: var(--songProgressColor);\n          cursor: default;\n          transition:\n            opacity 0.1s var(--appleEase),\n            transform 0.1s var(--appleEase);\n        }\n\n        &::-moz-range-thumb {\n          width: 8px;\n          height: 8px;\n          border-radius: 100%;\n          background: var(--songProgressColor);\n          cursor: default;\n        }\n      }\n    }\n\n    .control-buttons {\n      margin-top: 3.5vh;\n      display: inline-flex;\n      width: 100%;\n      justify-content: center;\n    }\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/notyf.less",
    "content": "@-webkit-keyframes notyf-fadeinup {\n  0% {\n    opacity: 0;\n    transform: translateY(25%);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes notyf-fadeinup {\n  0% {\n    opacity: 0;\n    transform: translateY(25%);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@-webkit-keyframes notyf-fadeinleft {\n  0% {\n    opacity: 0;\n    transform: translateX(25%);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n@keyframes notyf-fadeinleft {\n  0% {\n    opacity: 0;\n    transform: translateX(25%);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n@-webkit-keyframes notyf-fadeoutright {\n  0% {\n    opacity: 1;\n    transform: translateX(0);\n  }\n\n  to {\n    opacity: 0;\n    transform: translateX(25%);\n  }\n}\n\n@keyframes notyf-fadeoutright {\n  0% {\n    opacity: 1;\n    transform: translateX(0);\n  }\n\n  to {\n    opacity: 0;\n    transform: translateX(25%);\n  }\n}\n\n@-webkit-keyframes notyf-fadeoutdown {\n  0% {\n    opacity: 1;\n    transform: translateY(0);\n  }\n\n  to {\n    opacity: 0;\n    transform: translateY(25%);\n  }\n}\n\n@keyframes notyf-fadeoutdown {\n  0% {\n    opacity: 1;\n    transform: translateY(0);\n  }\n\n  to {\n    opacity: 0;\n    transform: translateY(25%);\n  }\n}\n\n@-webkit-keyframes ripple {\n  0% {\n    transform: scale(0) translateY(-45%) translateX(13%);\n  }\n\n  to {\n    transform: scale(1) translateY(-45%) translateX(13%);\n  }\n}\n\n@keyframes ripple {\n  0% {\n    transform: scale(0) translateY(-45%) translateX(13%);\n  }\n\n  to {\n    transform: scale(1) translateY(-45%) translateX(13%);\n  }\n}\n\n.notyf {\n  position: fixed;\n  top: 0;\n  left: 0;\n  height: 100%;\n  width: 100%;\n  color: #fff;\n  z-index: 9999;\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n  justify-content: flex-end;\n  pointer-events: none;\n  box-sizing: border-box;\n  padding: 20px;\n}\n\n.notyf__icon--error,\n.notyf__icon--success {\n  height: 21px;\n  width: 21px;\n  background: #fff;\n  border-radius: 50%;\n  display: block;\n  margin: 0 auto;\n  position: relative;\n}\n\n.notyf__icon--error:after,\n.notyf__icon--error:before {\n  content: \"\";\n  background: currentColor;\n  display: block;\n  position: absolute;\n  width: 3px;\n  border-radius: 3px;\n  left: 9px;\n  height: 12px;\n  top: 5px;\n}\n\n.notyf__icon--error:after {\n  transform: rotate(-45deg);\n}\n\n.notyf__icon--error:before {\n  transform: rotate(45deg);\n}\n\n.notyf__icon--success:after,\n.notyf__icon--success:before {\n  content: \"\";\n  background: currentColor;\n  display: block;\n  position: absolute;\n  width: 3px;\n  border-radius: 3px;\n}\n\n.notyf__icon--success:after {\n  height: 6px;\n  transform: rotate(-45deg);\n  top: 9px;\n  left: 6px;\n}\n\n.notyf__icon--success:before {\n  height: 11px;\n  transform: rotate(45deg);\n  top: 5px;\n  left: 10px;\n}\n\n.notyf__toast {\n  display: block;\n  overflow: hidden;\n  pointer-events: auto;\n  -webkit-animation: notyf-fadeinup 0.3s ease-in forwards;\n  animation: notyf-fadeinup 0.3s ease-in forwards;\n  box-shadow: 0 3px 7px 0 rgba(0, 0, 0, 0.25);\n  position: relative;\n  padding: 0 15px;\n  border-radius: 2px;\n  max-width: 300px;\n  transform: translateY(25%);\n  box-sizing: border-box;\n  flex-shrink: 0;\n}\n\n.notyf__toast--disappear {\n  transform: translateY(0);\n  -webkit-animation: notyf-fadeoutdown 0.3s forwards;\n  animation: notyf-fadeoutdown 0.3s forwards;\n  -webkit-animation-delay: 0.25s;\n  animation-delay: 0.25s;\n}\n\n.notyf__toast--disappear .notyf__icon,\n.notyf__toast--disappear .notyf__message {\n  -webkit-animation: notyf-fadeoutdown 0.3s forwards;\n  animation: notyf-fadeoutdown 0.3s forwards;\n  opacity: 1;\n  transform: translateY(0);\n}\n\n.notyf__toast--disappear .notyf__dismiss {\n  -webkit-animation: notyf-fadeoutright 0.3s forwards;\n  animation: notyf-fadeoutright 0.3s forwards;\n  opacity: 1;\n  transform: translateX(0);\n}\n\n.notyf__toast--disappear .notyf__message {\n  -webkit-animation-delay: 0.05s;\n  animation-delay: 0.05s;\n}\n\n.notyf__toast--upper {\n  margin-bottom: 20px;\n}\n\n.notyf__toast--lower {\n  margin-top: 20px;\n}\n\n.notyf__toast--dismissible .notyf__wrapper {\n  padding-right: 30px;\n}\n\n.notyf__ripple {\n  height: 400px;\n  width: 400px;\n  position: absolute;\n  transform-origin: bottom right;\n  right: 0;\n  top: 0;\n  border-radius: 50%;\n  transform: scale(0) translateY(-51%) translateX(13%);\n  z-index: 5;\n  -webkit-animation: ripple 0.4s ease-out forwards;\n  animation: ripple 0.4s ease-out forwards;\n}\n\n.notyf__wrapper {\n  display: flex;\n  align-items: center;\n  padding-top: 17px;\n  padding-bottom: 17px;\n  padding-right: 15px;\n  border-radius: 3px;\n  position: relative;\n  z-index: 10;\n}\n\n.notyf__icon {\n  width: 22px;\n  text-align: center;\n  font-size: 1.3em;\n  opacity: 0;\n  -webkit-animation: notyf-fadeinup 0.3s forwards;\n  animation: notyf-fadeinup 0.3s forwards;\n  -webkit-animation-delay: 0.3s;\n  animation-delay: 0.3s;\n  margin-right: 13px;\n}\n\n.notyf__dismiss {\n  position: absolute;\n  top: 0;\n  right: 0;\n  height: 100%;\n  width: 26px;\n  margin-right: -15px;\n  -webkit-animation: notyf-fadeinleft 0.3s forwards;\n  animation: notyf-fadeinleft 0.3s forwards;\n  -webkit-animation-delay: 0.35s;\n  animation-delay: 0.35s;\n  opacity: 0;\n}\n\n.notyf__dismiss-btn {\n  background-color: rgba(0, 0, 0, 0.25);\n  border: none;\n  cursor: pointer;\n  transition:\n    opacity 0.2s ease,\n    background-color 0.2s ease;\n  outline: none;\n  opacity: 0.35;\n  height: 100%;\n  width: 100%;\n}\n\n.notyf__dismiss-btn:after,\n.notyf__dismiss-btn:before {\n  content: \"\";\n  background: #fff;\n  height: 12px;\n  width: 2px;\n  border-radius: 3px;\n  position: absolute;\n  left: calc(50% - 1px);\n  top: calc(50% - 5px);\n}\n\n.notyf__dismiss-btn:after {\n  transform: rotate(-45deg);\n}\n\n.notyf__dismiss-btn:before {\n  transform: rotate(45deg);\n}\n\n.notyf__dismiss-btn:hover {\n  opacity: 0.7;\n  background-color: rgba(0, 0, 0, 0.15);\n}\n\n.notyf__dismiss-btn:active {\n  opacity: 0.8;\n}\n\n.notyf__message {\n  vertical-align: middle;\n  position: relative;\n  opacity: 0;\n  -webkit-animation: notyf-fadeinup 0.3s forwards;\n  animation: notyf-fadeinup 0.3s forwards;\n  -webkit-animation-delay: 0.25s;\n  animation-delay: 0.25s;\n  line-height: 1.5em;\n}\n\n@media only screen and (max-width: 480px) {\n  .notyf {\n    padding: 0;\n  }\n\n  .notyf__ripple {\n    height: 600px;\n    width: 600px;\n    -webkit-animation-duration: 0.5s;\n    animation-duration: 0.5s;\n  }\n\n  .notyf__toast {\n    max-width: none;\n    border-radius: 0;\n    box-shadow: 0 -2px 7px 0 rgba(0, 0, 0, 0.13);\n    width: 100%;\n  }\n\n  .notyf__dismiss {\n    width: 56px;\n  }\n}\n"
  },
  {
    "path": "src/renderer/less/pages.css",
    "content": ".content-inner {\n  position: absolute;\n  top: var(--navigationBarHeight);\n  left: 0;\n  padding: 32px;\n  width: 100%;\n  transition: zoom 1s;\n  zoom: 1;\n  max-width: 1680px;\n  right: 0;\n  margin: 0 auto;\n}\n.content-inner.centered {\n  height: 100%;\n  display: flex;\n  flex-flow: column;\n  justify-content: center;\n  align-items: center;\n}\n.github-themes-page {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n}\n.github-themes-page .github-avatar {\n  height: 42px;\n  width: 42px;\n  margin: 6px;\n  border-radius: 32px;\n}\n.github-themes-page .repo-name {\n  margin: 0px;\n  font-weight: 500;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: break-spaces;\n}\n.github-themes-page .repo-url {\n  color: var(--textColor);\n  font-size: 0.8em;\n}\n.github-themes-page .repo-preview-name {\n  margin: 0px;\n}\n.github-themes-page .repos-list {\n  height: 100%;\n  width: 320px;\n  font-size: 14px;\n  overflow: overlay;\n  padding-bottom: 16px;\n  flex: 0 0 auto;\n}\n.github-themes-page .repos-list > .list-group {\n  margin: 0px;\n}\n.github-themes-page .repos-list .list-group-item {\n  padding: 12px 6px;\n}\n.github-themes-page .repos-list .list-group-item:hover {\n  filter: brightness(1.2);\n}\n.github-themes-page .repos-list .list-group-item:active {\n  filter: brightness(0.8);\n}\n.github-themes-page .github-preview {\n  height: 100%;\n  flex: 1;\n  padding: 16px 32px;\n  overflow: auto;\n  padding-bottom: 16px;\n}\n.github-themes-page .gh-content {\n  display: flex;\n  flex-direction: row;\n  flex: 1;\n  overflow: hidden;\n}\n.github-themes-page .gh-header {\n  padding: 16px;\n  height: 64px;\n  display: grid;\n  align-content: center;\n  flex: 0 0 auto;\n}\n.github-themes-page .gh-header .header-text {\n  position: initial !important;\n  justify-content: left !important;\n}\n.github-themes-page .installed-themes-page .style-editor-container {\n  height: 100%;\n  flex: 1;\n  background: var(--color2);\n  padding: 0px;\n  overflow-y: overlay;\n}\n.github-themes-page .installed-themes-page .style-editor-container .list-group-item {\n  border-radius: 0px;\n}\n.installed-themes-page {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: hidden;\n}\n.installed-themes-page .themeContextMenu {\n  background: transparent;\n  color: var(--keyColor);\n  border: 0px;\n}\n.installed-themes-page .list-group-item.addon {\n  background: rgba(86, 86, 86, 0.2);\n}\n.installed-themes-page .list-group-item.applied {\n  background: var(--keyColor-disabled);\n  pointer-events: none;\n}\n.installed-themes-page .repo-header {\n  font-size: 16px;\n  position: sticky;\n  top: 0;\n  left: 0;\n  right: 0;\n  width: 100%;\n  height: 50px;\n  z-index: 1;\n  background: rgba(36, 36, 36, 0.5);\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  backdrop-filter: var(--glassFilter);\n  overflow: hidden;\n  border-bottom: 1px solid rgba(0, 0, 0, 0.18);\n  border-top: 1px solid rgba(135, 135, 135, 0.18);\n}\n.installed-themes-page .gh-header {\n  z-index: 5;\n  padding: 16px;\n  flex: 0 0 auto;\n  height: 64px;\n  display: grid;\n  align-content: center;\n}\n.installed-themes-page .gh-header .header-text {\n  position: initial !important;\n  justify-content: left !important;\n}\n.installed-themes-page .gh-content {\n  display: flex;\n  flex-direction: row;\n  padding: 0px;\n  height: 100%;\n  flex: 0 0 auto;\n}\n.installed-themes-page .gh-content .repos-list {\n  width: 320px;\n  overflow: overlay;\n  height: 90%;\n  font-size: 14px;\n  white-space: nowrap;\n}\n.installed-themes-page .gh-content .repos-list > .list-group {\n  margin: 0px;\n  padding-bottom: 16px;\n}\n.installed-themes-page .gh-content .repos-list .list-group-item {\n  padding: 12px 6px;\n}\n.installed-themes-page .gh-content .repos-list .list-group-item:hover {\n  filter: brightness(1.2);\n}\n.installed-themes-page .gh-content .repos-list .list-group-item:active {\n  filter: brightness(0.8);\n}\n.installed-themes-page .gh-content .style-editor-container {\n  height: 100%;\n  flex: 1;\n  padding: 0px;\n  width: 100%;\n  overflow: hidden;\n}\n.installed-themes-page .gh-content .style-editor-container .stylestack-editor {\n  padding-bottom: 16px;\n}\n.installed-themes-page .gh-content .style-editor-container .list-group-item {\n  border-radius: 0px;\n}\n.installed-themes-page .stylestack-editor {\n  width: 100%;\n}\n.installed-themes-page .stylestack-editor .btn,\n.installed-themes-page .stylestack-editor .btn-group {\n  width: 100%;\n}\n.installed-themes-page .stylestack-editor .themeLabel {\n  display: flex;\n  align-items: center;\n}\n.installed-themes-page .stylestack-editor .handle {\n  height: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n.installed-themes-page .stylestack-editor .list-group-item:hover {\n  cursor: grab;\n}\n.installed-themes-page .stylestack-editor .list-group-item:active {\n  cursor: grabbing;\n}\n.installed-themes-page .stylestack-editor .removeItem {\n  border: 0px;\n  background: transparent;\n  height: 32px;\n  font-weight: bold;\n  color: var(--textColor);\n  cursor: pointer;\n}\n.installed-themes-page .stylestack-editor .stylesDropdown > .dropdown-menu {\n  height: 300px;\n  overflow-y: overlay;\n}\n.library-page {\n  padding: 0px;\n}\n.library-page .library-header {\n  position: sticky;\n  top: 0;\n  left: 0;\n  border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n  z-index: 6;\n  background: black;\n  padding: 0px 2em;\n  backdrop-filter: blur(32px);\n  background: rgba(0, 0, 0, 0.25);\n  top: var(--navigationBarHeight);\n}\n.library-page .well {\n  margin: 2em;\n}\n.search-page .searchToggle {\n  float: right;\n}\n.search-page .searchToggle > button {\n  min-width: 120px;\n}\n.search-page .cd-mediaitem-square.mediaitem-brick {\n  width: 530px !important;\n}\n.search-page .cd-mediaitem-square.mediaitem-brick .artwork-container .artwork {\n  height: 168px !important;\n  width: 507px !important;\n  z-index: 1;\n}\n.search-page .cd-mediaitem-square.mediaitem-brick .title {\n  font-weight: bold;\n  justify-content: left;\n  font-size: 18px;\n  margin-top: -40px;\n  z-index: 5;\n  pointer-events: none;\n}\n.content-inner.podcasts-page {\n  display: flex;\n  height: calc(100% - var(--navigationBarHeight));\n  padding: 0px;\n}\n.content-inner.podcasts-page .list-flat {\n  border-radius: 0px;\n}\n.content-inner.podcasts-page .podcast-artwork {\n  width: 200px;\n  margin: 16px auto;\n  height: 200px;\n}\n.content-inner.podcasts-page .podcasts-list {\n  height: 100%;\n  width: 280px;\n  background: rgba(200, 200, 200, 0.1);\n  overflow-y: overlay;\n  border-right: 1px solid var(--color2);\n  flex: none;\n  overflow-x: hidden;\n}\n.content-inner.podcasts-page .podcasts-list .podcast-list-header {\n  border-bottom: 1px solid var(--color2);\n  font-size: 0.7em;\n  padding: 6px;\n  background: #ffffff17;\n  text-transform: uppercase;\n  font-weight: 600;\n  opacity: 0.5;\n}\n.content-inner.podcasts-page .podcasts-list .podcasts-search {\n  padding: 10px;\n  position: sticky;\n  top: 0;\n  left: 0;\n  width: 100%;\n  border-bottom: 1px solid var(--color2);\n  z-index: 2;\n  background: #303030;\n}\n.content-inner.podcasts-page .episodes-list {\n  height: 100%;\n  width: 100%;\n  background: rgba(200, 200, 200, 0.06);\n  overflow-y: overlay;\n  overflow-x: hidden;\n}\n.content-inner.podcasts-page .episodes-list .episodes-inline-info {\n  padding: 14px 14px 0px 14px;\n}\n.content-inner.podcasts-page .episodes-list .episodes-inline-info .podcast-show-info {\n  display: flex;\n  justify-content: center;\n  flex-direction: column;\n}\n.content-inner.podcasts-page .episodes-list .episodes-inline-info .podcast-show-description {\n  margin: 32px 6px;\n  font-size: 0.8rem;\n  white-space: pre-wrap;\n  display: block;\n}\n.content-inner.podcasts-page .episodes-list .episodes-inline-info .podcast-artwork {\n  width: 120px;\n  margin: 0px auto;\n  height: 120px;\n}\n.content-inner.podcasts-page .episodes-list .podcast-no-search-results {\n  text-align: center;\n  margin-top: 40px;\n}\n.content-inner.podcasts-page .podcasts-details {\n  width: 300px;\n  flex: none;\n  background: rgba(255, 255, 255, 0.05);\n  overflow-y: overlay;\n  overflow-x: hidden;\n  top: 2%;\n  z-index: 2;\n  border-left: 1px solid var(--color2);\n  padding-bottom: 1em;\n}\n.content-inner.podcasts-page .podcasts-details .meta-btn {\n  font-size: 0.75em;\n}\n.content-inner.podcasts-page .podcasts-details .podcasts-details-header {\n  display: flex;\n  justify-content: end;\n  align-items: center;\n  position: sticky;\n  top: 0;\n  z-index: 2;\n}\n.content-inner.podcasts-page .podcasts-details .close-btn {\n  width: 50px;\n  height: 42px;\n  background-image: var(--gfx-closeBtn);\n  background-position: center;\n  background-repeat: no-repeat;\n  -webkit-app-region: no-drag;\n  appearance: none;\n  border: 0;\n  background-color: transparent;\n  position: absolute;\n  top: 0;\n  right: 0;\n}\n.content-inner.podcasts-page .podcasts-details .close-btn:hover {\n  background-color: #c42b1c;\n}\n.content-inner.podcasts-page .podcasts-details .podcast-genre {\n  text-align: center;\n  margin: 6px;\n  font-size: 0.8em;\n  font-weight: 500;\n  opacity: 0.8;\n}\n.content-inner.podcasts-page .podcasts-details .podcast-metainfo {\n  text-align: center;\n  font-size: 0.7em;\n  opacity: 0.8;\n}\n.content-inner.podcasts-page .podcasts-details .podcast-header {\n  text-align: center;\n  padding: 0 1rem;\n}\n.content-inner.podcasts-page .podcasts-details .podcast-play-btn {\n  width: 50%;\n  display: block;\n  margin: 0 auto;\n}\n.content-inner.podcasts-page .podcasts-details .podcast-description {\n  margin: 12px;\n  font-size: 0.75em;\n  white-space: pre-wrap;\n  display: block;\n  line-break: anywhere;\n}\n.content-inner.library-artists-page {\n  height: calc(100% - 60px - var(--navigationBarHeight));\n  padding: 0px;\n}\n.content-inner.library-artists-page .inner-container {\n  display: flex;\n  height: calc(100% - var(--navigationBarHeight));\n  padding: 0px;\n  height: 100%;\n}\n.content-inner.library-artists-page .inner-container .list-flat {\n  border-radius: 0px;\n}\n.content-inner.library-artists-page .inner-container .podcast-artwork {\n  width: 200px;\n  margin: 16px auto;\n  height: 200px;\n}\n.content-inner.library-artists-page .inner-container .podcasts-list {\n  height: 100%;\n  width: 280px;\n  background: rgba(200, 200, 200, 0.1);\n  overflow-y: overlay;\n  border-right: 1px solid var(--color2);\n  flex: none;\n  overflow-x: hidden;\n}\n.content-inner.library-artists-page .inner-container .podcasts-list .podcast-list-header {\n  border-bottom: 1px solid var(--color2);\n  font-size: 0.7em;\n  padding: 6px;\n  background: #ffffff17;\n  text-transform: uppercase;\n  font-weight: 600;\n  opacity: 0.5;\n}\n.content-inner.library-artists-page .inner-container .podcasts-list .podcasts-search {\n  padding: 10px;\n  position: sticky;\n  top: 0;\n  left: 0;\n  width: 100%;\n  border-bottom: 1px solid var(--color2);\n  z-index: 2;\n  background: #303030;\n}\n.content-inner.library-artists-page .inner-container .episodes-list {\n  height: calc(100% + 60px);\n  width: 100%;\n  background: rgba(200, 200, 200, 0.06);\n  overflow-y: overlay;\n  overflow-x: hidden;\n}\n.content-inner.library-artists-page .inner-container .episodes-list .episodes-inline-info {\n  padding: 14px 14px 0px 14px;\n}\n.content-inner.library-artists-page .inner-container .episodes-list .episodes-inline-info .podcast-show-info {\n  display: flex;\n  justify-content: center;\n  flex-direction: column;\n}\n.content-inner.library-artists-page .inner-container .episodes-list .episodes-inline-info .podcast-show-description {\n  margin: 32px 6px;\n  font-size: 0.8rem;\n  white-space: pre-wrap;\n  display: block;\n}\n.content-inner.library-artists-page .inner-container .episodes-list .episodes-inline-info .podcast-artwork {\n  width: 120px;\n  margin: 0px auto;\n  height: 120px;\n}\n.content-inner.library-artists-page .inner-container .episodes-list .podcast-no-search-results {\n  text-align: center;\n  margin-top: 40px;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details {\n  width: 300px;\n  flex: none;\n  background: rgba(255, 255, 255, 0.05);\n  overflow-y: overlay;\n  overflow-x: hidden;\n  top: 2%;\n  z-index: 2;\n  border-left: 1px solid var(--color2);\n  padding-bottom: 1em;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .meta-btn {\n  font-size: 0.75em;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .podcasts-details-header {\n  display: flex;\n  justify-content: end;\n  align-items: center;\n  position: sticky;\n  top: 0;\n  z-index: 2;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .close-btn {\n  width: 50px;\n  height: 42px;\n  background-image: var(--gfx-closeBtn);\n  background-position: center;\n  background-repeat: no-repeat;\n  -webkit-app-region: no-drag;\n  appearance: none;\n  border: 0;\n  background-color: transparent;\n  position: absolute;\n  top: 0;\n  right: 0;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .close-btn:hover {\n  background-color: #c42b1c;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .podcast-genre {\n  text-align: center;\n  margin: 6px;\n  font-size: 0.8em;\n  font-weight: 500;\n  opacity: 0.8;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .podcast-metainfo {\n  text-align: center;\n  font-size: 0.7em;\n  opacity: 0.8;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .podcast-header {\n  text-align: center;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .podcast-play-btn {\n  width: 50%;\n  display: block;\n  margin: 0 auto;\n}\n.content-inner.library-artists-page .inner-container .podcasts-details .podcast-description {\n  margin: 12px;\n  font-size: 0.75em;\n  white-space: pre-wrap;\n  display: block;\n  line-break: anywhere;\n}\n@media only screen and (max-width: 1230px) {\n  .content-inner.library-artists-page .content-inner.podcasts-page .podcasts-details {\n    height: 96%;\n    width: 300px;\n    flex: none;\n    background: rgba(20, 20, 20, 0.97);\n    overflow-y: overlay;\n    overflow-x: hidden;\n    position: absolute;\n    right: 2%;\n    top: 2%;\n    border-radius: 10px;\n    box-shadow: var(--ciderShadow-Generic);\n    z-index: 2;\n  }\n}\n@media only screen and (max-width: 1230px) {\n  .content-inner.podcasts-page .podcasts-details {\n    height: 96%;\n    width: 300px;\n    flex: none;\n    background: rgba(20, 20, 20, 0.97);\n    overflow-y: overlay;\n    overflow-x: hidden;\n    position: absolute;\n    right: 2%;\n    top: 2%;\n    border-radius: 10px;\n    box-shadow: var(--ciderShadow-Generic);\n    z-index: 2;\n  }\n}\n/* Album / Playlist Page */\n.album-header {\n  position: sticky;\n  left: 0;\n  z-index: 6;\n  padding: 0px 2em;\n  backdrop-filter: blur(32px);\n  background: rgba(0, 0, 0, 0.25);\n  top: var(--navigationBarHeight);\n  --bs-gutter-x: 4rem;\n  --bs-gutter-y: 0;\n  display: flex;\n  flex-wrap: wrap;\n  margin-top: calc(-1 * var(--bs-gutter-y));\n  margin-right: calc(-0.5 * var(--bs-gutter-x));\n  margin-left: calc(-0.5 * var(--bs-gutter-x));\n  border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n}\n.playlist-page {\n  --bgColor: transparent;\n  padding: 0px;\n  top: 0;\n  padding-top: var(--navigationBarHeight);\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: hidden;\n}\n.playlist-page .cd-mediaitem-list-item:hover .heart-icon {\n  display: flex;\n}\n.playlist-page .cd-mediaitem-list-item .heart-icon {\n  left: -25px;\n}\n.playlist-page .editTracksBtn {\n  position: absolute;\n  top: 20px;\n  right: 20px;\n  z-index: 1;\n}\n.playlist-page .editTracksBtn > span {\n  display: flex;\n  gap: 8px;\n}\n.playlist-page .mediaContainer {\n  transition: width 0.5s ease-in-out, height 0.5s ease-in-out;\n  width: 260px;\n  height: 260px;\n}\n.playlist-page .playlist-body {\n  padding: 32px;\n  overflow-y: overlay;\n  height: 100%;\n  padding: 0px;\n  background-color: var(--color3);\n}\n.playlist-page .playlist-body.scrollbody .tabs {\n  display: flex;\n  flex-flow: column;\n  height: 100%;\n}\n.playlist-page .playlist-body.scrollbody .tabs .nav-link {\n  text-transform: capitalize;\n}\n.playlist-page .playlist-body.scrollbody .tabs .tab-content {\n  height: 100%;\n  overflow: hidden;\n  margin: 0px;\n}\n.playlist-page .playlist-body.scrollbody .tabs .tab-content .tab-pane {\n  height: 100%;\n  overflow-y: overlay;\n  overflow-x: hidden;\n  padding: var(--contentInnerPadding);\n  padding-inline: 40px;\n  -webkit-mask-image: linear-gradient(180deg, transparent, white 20px);\n}\n.playlist-page .playlist-body.scrollbody .tabs .tab-content .tab-pane .well {\n  margin: 0px;\n}\n.playlist-page .playlist-body .search-input-container {\n  height: 2.5rem;\n  margin: 1rem;\n  margin-top: 0;\n  scroll-margin-top: 1rem;\n}\n.playlist-page .playlist-body .search-input-container .search-input {\n  width: 100%;\n  height: 100%;\n}\n.playlist-page .floating-header {\n  position: sticky;\n  top: 0;\n  left: 0;\n  border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n  z-index: 6;\n  padding: 0px 1em;\n  backdrop-filter: blur(32px);\n  background: rgba(0, 0, 0, 0.25);\n  top: var(--navigationBarHeight);\n  transition: opacity 0.1s var(--appleEase);\n  display: none;\n}\n.playlist-page .playlist-display {\n  padding: var(--contentInnerPadding);\n  min-height: 300px;\n  position: relative;\n  box-shadow: 0px 4px 6px 3px rgba(0, 0, 0, 0.1);\n  transition: min-height 0.5s ease-in-out;\n}\n.playlist-page .playlist-display .artworkContainer {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  margin: 0;\n  margin-top: calc(var(--navigationBarHeight) * -1);\n  margin-bottom: -10px;\n  padding: 0;\n  -webkit-mask-image: radial-gradient(at top left, black, transparent 70%), radial-gradient(at top right, black, transparent 70%), linear-gradient(180deg, #c8c8c8, transparent 98%);\n  opacity: 0.7;\n  animation: playlistArtworkFadeIn 1s var(--appleEase);\n}\n.playlist-page .playlist-display .artworkContainer .artworkMaterial img {\n  filter: brightness(100%) blur(80px) saturate(100%) contrast(1);\n  object-position: center;\n  object-fit: cover;\n  width: 100%;\n  height: 100%;\n  transform: unset;\n}\n.playlist-page .playlist-display .playlistInfo {\n  z-index: 1;\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  top: 0;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  width: 100%;\n  height: 100%;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-hero {\n  width: 100%;\n  transform: translateX(25%);\n  position: absolute;\n  z-index: -1;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-hero .mediaitem-artwork {\n  -webkit-mask-image: -webkit-radial-gradient(center, circle cover, #000000 50%, rgba(0, 0, 0, 0) 75%);\n  border-radius: 0px;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-hero .hero-tint {\n  position: absolute;\n  top: 0;\n  opacity: 0.6;\n  width: 100%;\n  height: 100%;\n}\n.playlist-page .playlist-display .playlistInfo > .row {\n  width: calc(100% - 32px);\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info {\n  flex-shrink: unset;\n  display: flex;\n  flex-flow: column;\n  justify-content: flex-end;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-name {\n  font-weight: 700;\n  font-size: 1.6rem;\n  margin-right: 6px;\n  margin-bottom: 6px;\n  flex-shrink: unset;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .search-input::placeholder {\n  color: var(--heroplaceholdercolor);\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .nameEdit {\n  font-weight: 700;\n  font-size: 1.6rem;\n  flex-shrink: unset;\n  background: transparent;\n  border: 0px;\n  color: inherit;\n  font-family: inherit;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .descriptionEdit {\n  font-size: 14px;\n  flex-shrink: unset;\n  background: transparent;\n  border: 0px;\n  color: inherit;\n  font-family: inherit;\n  width: 60vw;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .descriptionEdit {\n  font-size: 14px;\n  flex-shrink: unset;\n  background: transparent;\n  border: 0px;\n  color: inherit;\n  font-family: inherit;\n  width: 60vw;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-artist {\n  font-size: 20px;\n  margin-bottom: 6px;\n  margin-right: 6px;\n  flex-shrink: unset;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-desc {\n  transition: height 0.2s ease-in-out, opacity 0.2s ease-in-out;\n  box-sizing: border-box;\n  font-size: 14px;\n  flex-shrink: unset;\n  margin-right: 5px;\n  max-height: 100px;\n  position: relative;\n  height: 4vh;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-desc .content {\n  height: 4vh;\n  -webkit-mask-image: -webkit-gradient(linear, left 50%, left 90%, from(#000000), to(rgba(0, 0, 0, 0)));\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-desc .more-btn {\n  appearance: none;\n  position: absolute;\n  right: 0;\n  bottom: 0;\n  padding: 0 5px;\n  font-size: 14px;\n  color: var(--keyColor);\n  background-color: transparent;\n  border: 0px;\n  cursor: pointer;\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n  display: flex;\n  justify-content: flex-end;\n  align-items: flex-end;\n  font-weight: 600;\n  font-family: inherit;\n  text-transform: uppercase;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-desc-expanded {\n  box-sizing: border-box;\n  font-size: 14px;\n  position: relative;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .playlist-desc-expanded .more-btn {\n  appearance: none;\n  position: absolute;\n  right: 0;\n  bottom: 0;\n  padding: 0 5px;\n  font-size: 14px;\n  color: var(--keyColor);\n  background-color: transparent;\n  border: 0px;\n  cursor: pointer;\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n  display: flex;\n  justify-content: flex-end;\n  align-items: flex-end;\n  font-weight: 600;\n  font-family: inherit;\n  text-transform: uppercase;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .search-btn {\n  display: flex;\n  width: 32px;\n  align-items: center;\n  margin-right: 1rem;\n  background: rgba(100, 100, 100, 0.5);\n  border: none;\n  cursor: pointer;\n  border-radius: 100vmax;\n  box-shadow: var(--ciderShadow-Generic);\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .search-btn > ._svg-icon {\n  width: 18px;\n  height: 18px;\n  margin: auto;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .search-btn.active {\n  animation: enlarge 0.5s ease-in-out;\n}\n.playlist-page .playlist-display .playlistInfo .playlist-info .search-btn:hover {\n  filter: brightness(125%);\n}\n@keyframes enlarge {\n  0% {\n    transform: scale(1);\n  }\n  50% {\n    transform: scale(1.2);\n  }\n  100% {\n    transform: scale(1);\n  }\n}\n.playlist-page .friends-info {\n  display: flex;\n  flex-flow: column;\n}\n.playlist-page .friends-info .badge-container {\n  display: flex;\n  flex-flow: wrap;\n}\n.playlist-page .friends-info .badge-container .socialBadge {\n  width: 40px;\n  height: 40px;\n  border-radius: 100%;\n  overflow: hidden;\n  box-shadow: var(--mediaItemShadow-ShadowSubtle);\n  transition: transform 0.2s var(--appleEase);\n  margin: 6px;\n}\n.playlist-page .friends-info .badge-container .socialBadge:hover {\n  transform: scale(1.2);\n}\n.playlist-page .friends-info .friends-name {\n  text-align: center;\n  font-size: 0.9em;\n  margin: 8px;\n}\n.playlist-page .playlist-time {\n  font-size: 0.9em;\n  margin: 6px;\n  opacity: 0.7;\n  transition: height 0.2s ease-in-out, opacity 0.2s ease-in-out;\n  height: 0.9em;\n}\n.playlist-page.inline-playlist {\n  overflow: hidden;\n  width: 100%;\n  height: 100%;\n  background: rgba(0, 0, 0, 0.5);\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  z-index: 10;\n  position: sticky;\n  margin-top: calc(var(--navigationBarHeight) * -1);\n}\n.playlist-page.inline-playlist .floating-header {\n  opacity: 1;\n  top: 0px;\n  z-index: 6;\n  padding: 1em;\n  backdrop-filter: unset;\n  background: black;\n}\n.playlist-page.inline-playlist .floating-header h3 {\n  display: none;\n}\n.playlist-page.inline-playlist .playlist-inner {\n  background: black;\n  width: 80%;\n  height: 100%;\n  overflow: overlay;\n  box-shadow: var(--ciderShadow-Generic);\n  border-radius: var(--mediaItemRadius) var(--mediaItemRadius) 0px 0px;\n}\n.playlist-page.inline-playlist .playlist-inner .close-btn {\n  position: sticky;\n  top: 16px;\n  left: 16px;\n  margin-left: 16px;\n  z-index: 7;\n}\n.playlist-page .pilldim .nav-pills {\n  width: max-content;\n  margin: 0 auto;\n  margin-top: 16px;\n}\n.playlist-page.plmin .playlist-display {\n  transition: min-height 0.5s ease-in-out;\n  min-height: 200px;\n}\n.playlist-page.plmin .playlist-display .mediaContainer {\n  transition: width 0.5s ease-in-out, height 0.5s ease-in-out;\n  width: 128px !important;\n  height: 128px !important;\n}\n.playlist-page.plmin .playlist-display .playlist-time {\n  transition: height 0.2s ease-in-out, opacity 0.2s ease-in-out;\n  height: 0px;\n  opacity: 0;\n}\n.playlist-page.plmin .playlist-display .playlist-desc {\n  transition: height 0.2s ease-in-out, opacity 0.2s ease-in-out;\n  height: 0px !important;\n  opacity: 0;\n}\n@keyframes playlistArtworkFadeIn {\n  0% {\n    opacity: 0;\n  }\n  100% {\n    opacity: 0.7;\n  }\n}\n.collection-page {\n  padding-bottom: 128px;\n}\n.collection-page .top-fab {\n  height: 52px;\n  width: 52px;\n  position: fixed;\n  bottom: 32px;\n  right: 32px;\n  border-radius: 100%;\n  background: #3c3c3c;\n  border: 0px;\n  appearance: none;\n  box-shadow: var(--ciderShadow-Generic);\n}\n.collection-page .top-fab > svg {\n  height: 50%;\n  color: #eee;\n  pointer-events: none;\n}\n.collection-page .top-fab:hover {\n  background: #646464;\n}\n.collection-page .top-fab:active {\n  background: var(--keyColor);\n}\n.collection-page .header-text {\n  margin-bottom: 32px;\n}\n/* Artist Page */\n.artist-page {\n  padding: 0px;\n  top: 0;\n}\n.artist-page .floating-header {\n  position: sticky;\n  top: 0;\n  left: 0;\n  border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n  z-index: 6;\n  padding: 0px 1em;\n  backdrop-filter: blur(32px);\n  background: rgba(0, 0, 0, 0.25);\n  top: var(--navigationBarHeight);\n  transition: opacity 0.1s var(--appleEase);\n}\n.artist-page.animated .artist-header .more-btn-round {\n  position: absolute;\n  bottom: 22px !important;\n  right: 28px;\n}\n.artist-page.animated .artist-header {\n  min-height: 80vh;\n}\n.artist-page .artist-header {\n  color: white;\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  min-height: 400px;\n  position: relative;\n  pointer-events: none;\n}\n.artist-page .artist-header .header-content {\n  z-index: 1;\n}\n.artist-page .artist-header .artist-hero {\n  height: 100%;\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n}\n.artist-page .artist-header .artist-hero .mediaitem-artwork {\n  border-radius: 0px;\n}\n.artist-page .artist-header .artworkContainer {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  margin: 0;\n  padding: 0;\n  -webkit-mask-image: radial-gradient(at top left, black, transparent 70%), radial-gradient(at top right, black, transparent 70%), linear-gradient(180deg, #c8c8c8, transparent 98%);\n  opacity: 0.7;\n  animation: playlistArtworkFadeIn 1s var(--appleEase);\n}\n.artist-page .artist-header .artworkContainer .artworkMaterial img {\n  filter: brightness(100%) blur(80px) saturate(100%) contrast(1);\n  object-position: center;\n  object-fit: cover;\n  width: 100%;\n  height: 100%;\n  transform: unset;\n}\n.artist-page .artist-header .more-btn-round {\n  position: absolute;\n  bottom: 82px;\n  right: 28px;\n}\n.artist-page .artist-header .social-btn {\n  border-radius: 100%;\n  background: transparent;\n  height: 17px;\n  border: 0px;\n  cursor: pointer;\n  z-index: 69;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  float: right;\n}\n@media only screen and (min-width: 1133px) and (max-width: 1277px) {\n  .artist-page .artist-header .about-page .social-btn {\n    display: none !important;\n  }\n}\n.artist-page .artist-header .animated {\n  width: 100%;\n  height: 100%;\n  align-self: center;\n  position: absolute;\n  overflow: hidden;\n  box-shadow: rgba(0, 0, 0, 0.5) 0 0 0 1000000px inset;\n  z-index: 1;\n}\n.artist-page .artist-header .animated video {\n  overflow: hidden;\n  height: 100%;\n  width: 100%;\n  min-height: 56.25vw;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  object-fit: cover;\n}\n.artist-page .artist-header .row .col.cider-flex-center {\n  z-index: 4;\n}\n.artist-page .artist-image {\n  width: 200px;\n  height: 200px;\n  margin: 32px;\n  position: relative;\n}\n.artist-page .artist-image .overlay-play {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  opacity: 0;\n  background: rgba(0, 0, 0, 0.5);\n  transition: opacity 0.1s var(--appleEase);\n  border-radius: 100%;\n  z-index: 1;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  cursor: pointer;\n  appearance: none;\n  border: 0px;\n  padding: 0px;\n}\n.artist-page .artist-image .overlay-play:hover {\n  opacity: 1;\n}\n.artist-page .artist-image .overlay-play:active {\n  background: var(--selected-click);\n}\n.artist-page .artist-image .overlay-play > svg {\n  width: 70%;\n}\n.artist-page .artist-play {\n  width: 32px;\n  height: 32px;\n  background: rgba(100, 100, 100, 0.5);\n  box-shadow: var(--ciderShadow-Generic);\n  border-radius: 100%;\n  box-shadow: var(--mediaItemShadow);\n  display: none;\n  cursor: pointer;\n  appearance: none;\n  border: 0px;\n  padding: 0px;\n}\n.artist-page .artist-play:hover {\n  filter: brightness(125%);\n}\n.artist-page .artist-play:active {\n  filter: brightness(75%);\n  transform: scale(0.98);\n  transition: transform 0s var(--appleEase), box-shadow 0.2s var(--appleEase);\n}\n.artist-page .artist-title .artist-play {\n  transform: translateY(3px);\n  margin: 14px;\n}\n.artist-page .artist-title.artist-animation-on {\n  width: 100%;\n  flex: unset;\n  margin-left: 0.5em;\n  color: whitesmoke;\n  position: absolute;\n  bottom: 0;\n}\n.artist-page .artist-title.artist-animation-on .artist-play {\n  display: block;\n}\n.artist-page .artist-body {\n  padding: 0px var(--contentInnerPadding) 0px var(--contentInnerPadding);\n  margin: -64px 20px;\n}\n.artist-page .artist-body .arow {\n  display: flex;\n  overflow: hidden;\n  padding: 16px 32px;\n}\n.artist-page .artist-body .arow > .latestRelease {\n  width: 250px;\n}\n.artist-page .artist-body .arow > .topSongs {\n  width: calc(100% - 250px);\n}\n.artist-page .artist-body .arow.arowb > .topSongs {\n  width: 100%;\n}\n.artist-page.animated > .artist-body {\n  padding: 0px var(--contentInnerPadding) 0px var(--contentInnerPadding);\n  margin-top: -57px;\n}\n.artist-page .showmoreless {\n  font-family: inherit;\n  font-size: 16px;\n  font-weight: 500;\n  background: transparent;\n  border: 0px;\n  border-radius: 6px;\n  appearance: none;\n  color: var(--keyColor);\n  padding: 8px 12px;\n  cursor: pointer;\n  margin-top: 12px;\n  float: right;\n}\n.artist-page .showmoreless:hover {\n  background: rgba(200, 200, 200, 0.1);\n}\n/* Artist Page End */\n.settings-page {\n  padding: 0px;\n}\n.settings-page .nav {\n  width: 90%;\n  margin: 16px auto 0px;\n}\n.audiolabs-page {\n  padding: 0px;\n}\n.audiolabs-page .md-option-header {\n  padding: 1.25em 1.25em;\n  border-bottom: unset;\n  border-top: unset;\n  font-weight: 600;\n  font-size: 1em;\n  background: rgba(255, 255, 255, 0.03);\n}\n.audiolabs-page .carousel-item > img {\n  object-fit: cover;\n  width: 100%;\n}\n.audiolabs-page .spprofile-line {\n  height: 300px;\n  width: 100%;\n  max-width: 1024px;\n  padding: 16px;\n  margin: 0 auto;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport {\n  height: 100%;\n  position: relative;\n  border-radius: var(--mediaItemRadius);\n  overflow: hidden;\n  box-shadow: var(--mediaItemShadow-Shadow);\n  background: black;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spprev,\n.audiolabs-page .spprofile-line .spprofile-viewport .nextprev {\n  position: absolute;\n  height: 100%;\n  width: 64px;\n  top: 0;\n  background: rgba(0, 0, 0, 0.2);\n  z-index: 1;\n  border: 0px;\n  transition: background 0.2s var(--appleEase), transform 0.2s var(--appleEase);\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spprev:hover,\n.audiolabs-page .spprofile-line .spprofile-viewport .nextprev:hover {\n  background: var(--selected);\n  transform: scale(1.1);\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spprev:active,\n.audiolabs-page .spprofile-line .spprofile-viewport .nextprev:active {\n  transition: background 0s var(--appleEase);\n  background: var(--selected-click);\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spprev:before,\n.audiolabs-page .spprofile-line .spprofile-viewport .nextprev:before {\n  content: \"\";\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: #eee;\n  opacity: 1;\n  -webkit-mask-position: center;\n  -webkit-mask-repeat: no-repeat;\n  -webkit-mask-size: 1em;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spprev {\n  left: 0;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spprev:before {\n  -webkit-mask-image: url(\"views/svg/chevron-left.svg\");\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .nextprev {\n  right: 0;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .nextprev:before {\n  -webkit-mask-image: url(\"views/svg/chevron-right.svg\");\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spslide {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n  background: black;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spslide > img {\n  width: 100%;\n  height: 100%;\n  object-fit: cover;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spslide .sptitle {\n  position: absolute;\n  bottom: 0px;\n  left: 0;\n  width: 100%;\n  text-align: center;\n  font-size: 18px;\n  text-shadow: 0px 2px 4px #00000033;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spfade-enter-active,\n.audiolabs-page .spprofile-line .spprofile-viewport .spfade-leave-active {\n  --transitionTime: 0.2s;\n  transition: opacity var(--transitionTime) var(--appleEase), transform var(--transitionTime) var(--appleEase);\n  will-change: opacity, transform;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spfade-enter {\n  opacity: 0;\n  transform: scale(1.2) translate3d(0, 0, 0);\n  will-change: opacity, transform;\n}\n.audiolabs-page .spprofile-line .spprofile-viewport .spfade-leave-to {\n  opacity: 1;\n  transform: scale(1) translate3d(0, 0, 0);\n  will-change: opacity, transform;\n}\n.audiolabs-page .settings-option-body {\n  margin: 16px;\n}\n@keyframes gradient-animation {\n  0% {\n    background-position: 0% 0%;\n  }\n  50% {\n    background-position: 100% 0%;\n  }\n  100% {\n    background-position: 0% 0%;\n  }\n}\n.home-page .md-btn-replay {\n  background-image: linear-gradient(-45deg, #2e2173, #925042);\n  animation: gradient-animation 5s ease-in-out infinite;\n  background-size: 400% 400%;\n  border: 0px;\n  box-shadow: inset 0px 0px 0px 1px rgba(200, 200, 200, 0.2);\n  text-transform: uppercase;\n  font-weight: bold;\n}\n.home-page .md-btn-replay--hero {\n  font-size: 1em;\n  padding: 16px;\n  background-image: linear-gradient(-45deg, #2e2173, #925042);\n  animation: gradient-animation 5s ease-in-out infinite;\n  background-size: 400% 400%;\n  border: 0px;\n  box-shadow: inset 0px 0px 0px 1px rgba(200, 200, 200, 0.2);\n  margin-top: 1em;\n  font-size: 0.9em;\n  text-transform: uppercase;\n  font-weight: bold;\n}\n.home-page .artist-feed-card {\n  position: absolute;\n  bottom: 0;\n  left: 10%;\n  z-index: 1;\n  background: black;\n  width: 80%;\n  height: 96%;\n  overflow: scroll;\n  border-radius: 10px;\n}\n.home-page .col.madeforyou-col {\n  width: 420px;\n  min-width: 0px;\n  max-width: 420px;\n}\n.home-page .well.artistfeed-well {\n  margin-top: 0px;\n  height: 392px;\n  align-content: flex-start;\n}\n.home-page .hint-text {\n  font-size: 0.9rem;\n  color: rgba(200, 200, 200, 0.7);\n}\n.home-page .user-icon {\n  border-radius: 100%;\n  width: 128px;\n  height: 128px;\n  overflow: hidden;\n  box-shadow: var(--mediaItemShadow-Shadow);\n  margin: 16px;\n}\n.home-page .well.profile-well {\n  flex-direction: column;\n  justify-content: center;\n  align-items: center;\n}\n.home-page .well.profile-well .name {\n  margin: 4px;\n  font-weight: 500;\n}\n.home-page .well.profile-well .handle {\n  margin: 4px;\n  opacity: 0.7;\n  font-weight: 500;\n}\n.replay-page {\n  --replayTextShadow: 0px 3px 2px #6f3f52;\n}\n.replay-page .replay-period {\n  height: 200px;\n  width: 200px;\n  margin: 6px;\n  border-radius: var(--mediaItemRadius);\n  overflow: hidden;\n  cursor: pointer;\n  transition: transform 0.2s var(--appleEase);\n  transition-delay: 0.1s;\n  align-self: center;\n}\n.replay-page .replay-period:hover {\n  transform: translateY(-6px);\n  transition-delay: 0s;\n}\n.replay-page .replay-period .artwork-container {\n  height: 200px;\n  width: 200px;\n}\n.replay-page .replay-playlist-container .cd-mediaitem-square {\n  height: 230px;\n  width: 230px;\n}\n.replay-page .replay-playlist-container .cd-mediaitem-square .info-rect {\n  display: none;\n}\n.replay-page .replay-video {\n  max-height: 300px;\n  max-width: 800px;\n  margin: 0 auto;\n}\n.replay-page .replay-video .mediaitem-artwork {\n  max-height: 300px;\n  max-width: 800px;\n}\n.replay-page .replay-video .mediaitem-artwork .animatedartwork-view-box .animated video {\n  object-fit: cover;\n}\n.replay-page .top-genres-container .genre-name {\n  font-size: 0.9em;\n  margin: 6px 0px;\n  font-weight: 500;\n}\n.replay-page .top-genres-container .genre-count {\n  width: 100%;\n  height: 32px;\n  background: #ffffff14;\n  border-radius: 10px;\n  overflow: hidden;\n}\n.replay-page .top-genres-container .genre-count .genre-count-bar {\n  height: 100%;\n  width: 0%;\n  background: var(--keyColor);\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  min-width: 32px;\n  font-size: 0.9em;\n  font-weight: 500;\n}\n.replay-page .cd-mediaitem-square {\n  transition: transform 0.2s var(--appleEase);\n  transition-delay: 0.1s;\n}\n.replay-page .cd-mediaitem-square .mediaitem-artwork {\n  animation: replayFadeIn 0.5s var(--appleEase);\n}\n.replay-page .cd-mediaitem-square:hover {\n  transform: scale(1.1);\n  transition-delay: 0s;\n}\n@keyframes replayFadeIn {\n  0% {\n    transform: translateY(10px) scale(0.9);\n    opacity: 0;\n  }\n  100% {\n    transform: scale(1);\n    opacity: 1;\n  }\n}\n.replay-page .replay-viewport {\n  background-image: linear-gradient(-45deg, #2e2173, #925042);\n  animation: gradient-animation 5s ease-in-out infinite;\n  background-size: 400% 400%;\n  padding: 16px 40px;\n  border-radius: 10px;\n  box-shadow: var(--mediaItemShadow), var(--mediaItemShadow-Shadow);\n  color: rgba(238, 238, 238, 0.86);\n}\n.replay-page .replay-viewport .replay-header {\n  text-align: center;\n  font-size: 3em;\n  text-shadow: var(--replayTextShadow);\n}\n.replay-page .replay-card {\n  background: transparent;\n  border: 0px;\n}\n.content-inner.oobe {\n  position: absolute;\n  overflow: hidden;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  display: grid;\n  place-items: center;\n  width: 100%;\n  background: #1e1e1e;\n}\n.content-inner.oobe .oobe-view {\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: center;\n  gap: 32px;\n  max-width: 1280px;\n  max-height: 720px;\n  align-self: center;\n  justify-self: center;\n  height: 100%;\n  width: 100%;\n}\n.content-inner.oobe .oobe-view .oobe-header {\n  font-size: 3em;\n  text-shadow: var(--replayTextShadow);\n  font-weight: 600;\n}\n.content-inner.oobe .oobe-view .oobe-body {\n  flex: 1;\n  width: 100%;\n  background: #ffffff0d;\n  border-radius: 20px;\n  padding: 3em;\n  overflow-y: scroll;\n  overflow-x: hidden;\n}\n@media screen and (max-width: 1161px) {\n  .content-inner.oobe .oobe-view .oobe-body {\n    font-size: 13px;\n  }\n}\n.content-inner.oobe .oobe-view .oobe-body.text {\n  white-space: pre-wrap;\n}\n.content-inner.oobe .oobe-view .oobe-body .blurb {\n  white-space: pre-wrap;\n  margin: 16px;\n  line-height: 1.5em;\n}\n.content-inner.oobe .oobe-view .oobe-body.visual {\n  padding: 1em;\n}\n.content-inner.oobe .oobe-view .oobe-body.visual .stylePicker {\n  border-radius: 10px;\n  overflow: hidden;\n  cursor: pointer;\n  transition: 0.25s all;\n  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);\n  width: 450px;\n  margin: 0 auto;\n}\n.content-inner.oobe .oobe-view .oobe-body.visual .stylePicker .visualPreview {\n  pointer-events: none;\n  transition: 0.25s all;\n  width: 100%;\n}\n.content-inner.oobe .oobe-view .oobe-body.visual .stylePicker .card-body {\n  padding: 0;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n.content-inner.oobe .oobe-view .oobe-body.visual .stylePicker .card-footer {\n  font-size: 1.25em;\n  font-weight: 500;\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  width: 100%;\n  border: 0px;\n  text-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);\n  font-weight: bold;\n}\n.content-inner.oobe .oobe-view .oobe-body.visual .stylePicker.style-active {\n  outline: 4px solid var(--keyColor);\n}\n.content-inner.oobe .oobe-view .oobe-body.visual .stylePicker:hover {\n  transform: scale(1.1) translateZ(-1px) translateY(10px);\n  z-index: 1;\n  box-shadow: 0px 12px 16px rgba(0, 0, 0, 0.25);\n}\n@media screen and (max-height: 688px) {\n  .content-inner.oobe .oobe-view .oobe-body.visual .stylePicker {\n    width: 270px;\n  }\n}\n.content-inner.oobe .oobe-view .oobe-footer {\n  display: flex;\n  flex-direction: row;\n  justify-content: center;\n  align-items: center;\n  padding: 16px;\n}\n.content-inner.oobe .oobe-view .oobe-footer .md-btn {\n  font-size: 18px;\n  min-width: 128px;\n  text-align: center;\n}\n.content-inner.oobe .oobe-titlebar {\n  position: absolute;\n  top: 0;\n  left: 0;\n  height: 46px;\n  width: 100%;\n  align-items: center;\n  justify-content: right;\n  display: flex;\n  -webkit-app-region: drag;\n}\n.content-inner.oobe .oobe-titlebar .button-group {\n  -webkit-app-region: no-drag;\n  display: flex;\n  flex-direction: row;\n  width: 100px;\n  height: 100%;\n  justify-content: center;\n  align-items: center;\n  gap: 16px;\n}\n.content-inner.oobe .oobe-titlebar .button-group > button {\n  height: 32px;\n  width: 32px;\n  font-size: 16px;\n  border-radius: 0px;\n  border: 0;\n  appearance: none;\n  position: relative;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  border-radius: 100%;\n}\n.content-inner.oobe .oobe-titlebar .button-group > button.close {\n  background-color: #fc3c44aa;\n}\n.content-inner.oobe .oobe-titlebar .button-group > button.close:hover {\n  background-color: #fc3c44;\n}\n.content-inner.oobe .oobe-titlebar .button-group > button.min {\n  background-color: rgba(200, 200, 200, 0.05);\n}\n.content-inner.oobe .oobe-titlebar .button-group > button.min:hover {\n  background-color: rgba(200, 200, 200, 0.1);\n}\n.content-inner.oobe .oobe-titlebar .button-group > button.close::before {\n  font-family: \"codicon\";\n  content: \"\";\n  color: white;\n}\n.content-inner.oobe .oobe-titlebar .button-group > button.min::before {\n  font-family: \"codicon\";\n  content: \"\";\n  color: white;\n}\n.content-inner.cider-multiroom {\n  padding: 0px;\n}\n.content-inner.cider-multiroom .detail {\n  padding: 32px;\n}\n.content-inner.cider-multiroom .header-desc {\n  font-size: 1em;\n  font-weight: 400;\n}\n.content-inner.cider-multiroom .artworkContainer {\n  height: 300px;\n  width: 100%;\n}\n.content-inner.cider-multiroom .artworkContainer img {\n  height: 100%;\n  width: 100%;\n  overflow: hidden;\n  object-fit: cover;\n  filter: unset;\n}\n.content-inner.cider-multiroom .artworkContainer img:last-child {\n  transform: unset;\n}\n.settings-panel {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: rgba(0, 0, 0, 0);\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  z-index: 16;\n}\n.settings-panel .settings-window {\n  background: var(--baseColorMix);\n  max-width: 90%;\n  max-height: 90%;\n  width: 100%;\n  height: 100%;\n  border-radius: 10px;\n  box-shadow: var(--ciderShadow-Generic);\n  overflow: hidden;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  position: relative;\n  flex: 1;\n  backdrop-filter: var(--glassFilterHeavy);\n  transition: width 0.25s ease-in-out, height 0.25s ease-in-out, max-width 0.25s ease-in-out, max-height 0.25s ease-in-out;\n}\n.settings-panel .settings-window .header-text {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  height: 48px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  font-weight: 600;\n  opacity: 0.9;\n}\n.settings-panel .settings-window .nav-pills {\n  gap: 6px;\n}\n.settings-panel .settings-window .nav-pills .nav-link {\n  display: flex;\n  gap: 10px;\n  align-items: center;\n  height: 35px;\n}\n.settings-panel .settings-window .nav-pills .nav-link :nth-child(2) {\n  white-space: nowrap;\n}\n.settings-panel .settings-window .md-option-header {\n  padding: 0px 26px;\n  border-bottom: unset;\n  border-top: unset;\n  font-weight: 600;\n  background: rgba(255, 255, 255, 0);\n  font-size: 2em;\n}\n.settings-panel .settings-window .settings-option-body-webview {\n  height: 100%;\n  width: 100%;\n}\n.settings-panel .settings-window .settings-option-body {\n  margin: 16px;\n}\n.settings-panel .settings-window.maxed {\n  width: 100%;\n  height: 100%;\n  max-height: 100%;\n  max-width: 100%;\n  border-radius: 0px;\n  box-shadow: unset;\n}\n.settings-panel .settings-window .close-btn {\n  width: 36px;\n  height: 36px;\n  background-position: center;\n  background-repeat: no-repeat;\n  -webkit-app-region: no-drag;\n  appearance: none;\n  border: 0;\n  background-color: transparent;\n  position: absolute;\n  top: 10px;\n  right: 10px;\n  border-radius: 50px;\n  display: grid;\n  align-content: center;\n  z-index: 9;\n}\n.settings-panel .settings-window .close-btn:before {\n  content: \"\";\n  font-family: \"codicon\";\n  color: var(--textColor);\n  font-size: 20px;\n}\n.settings-panel .settings-window .close-btn:hover {\n  background-color: #c42b1c;\n}\n.settings-panel .settings-window .close-btn.back-btn {\n  left: 10px;\n  right: unset;\n}\n.settings-panel .settings-window .close-btn.minmax-btn {\n  right: 52px;\n}\n.settings-panel .settings-window .close-btn.minmax-btn:before {\n  content: \"\";\n}\n.settings-panel .settings-window .close-btn.minmax-btn.min:before {\n  content: \"\";\n}\n.settings-panel .settings-window .close-btn.minmax-btn:hover {\n  background-color: var(--selected);\n}\n.settings-panel .settings-window .tabs {\n  height: 100%;\n  width: 100%;\n  margin: 0;\n  padding: 0;\n}\n.settings-panel .settings-window .tabs > .col-auto {\n  width: 230px;\n  overflow-x: hidden;\n  overflow-y: overlay;\n  transition: width 0.25s ease-in-out;\n}\n.settings-panel .settings-window .tabs .tab-content {\n  margin: 0 !important;\n}\n.settings-panel .settings-window .tab-content {\n  overflow-y: overlay;\n  height: 100%;\n  background-color: var(--panelColor2);\n  padding: 0px;\n  padding-top: 48px;\n  border-left: 1px solid var(--borderColor);\n}\n.settings-panel .settings-window .github-themes-page .header-text,\n.settings-panel .settings-window .installed-themes-page .header-text {\n  font-size: 1.25em;\n}\n.settings-panel .settings-window .tab-pane {\n  height: 100%;\n}\n.settings-panel .settings-window .settings-tab-content {\n  height: 100%;\n}\n.settings-panel .settings-window.no-sidebar .gh-header > .row:last-child {\n  padding-right: 90px;\n}\n.settings-panel .settings-window.no-sidebar .tab-content {\n  padding-top: 0px;\n}\n.settings-panel .settings-window.no-sidebar .tabs .nav-pills .nav-link {\n  width: 50px;\n}\n.settings-panel .settings-window.no-sidebar .tabs .nav-pills .nav-link :nth-child(2) {\n  opacity: 0;\n}\n.settings-panel .settings-window.no-sidebar .tabs > .col-auto {\n  width: 80px;\n}\n#hid___BV_tab_button__ {\n  display: none;\n}\n"
  },
  {
    "path": "src/renderer/less/pages.less",
    "content": "// Helpers\n.content-inner {\n  position: absolute;\n  top: var(--navigationBarHeight);\n  left: 0;\n  padding: 32px;\n  width: 100%;\n  transition: zoom 1s;\n  zoom: 1;\n}\n\n.content-inner.centered {\n  height: 100%;\n  display: flex;\n  flex-flow: column;\n  justify-content: center;\n  align-items: center;\n}\n\n// End Helpers\n\n// GitHub Themes\n.github-themes-page {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n\n  .github-avatar {\n    height: 42px;\n    width: 42px;\n    margin: 6px;\n    border-radius: 32px;\n  }\n\n  .repo-name {\n    margin: 0px;\n    font-weight: 500;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: break-spaces;\n  }\n\n  .repo-url {\n    color: var(--textColor);\n    font-size: 0.8em;\n  }\n\n  .repo-preview-name {\n    margin: 0px;\n  }\n\n  .repos-list {\n    height: 100%;\n    width: 320px;\n    font-size: 14px;\n    overflow: overlay;\n    padding-bottom: 16px;\n    flex: 0 0 auto;\n\n    > .list-group {\n      margin: 0px;\n    }\n\n    .list-group-item {\n      padding: 12px 6px;\n\n      &:hover {\n        filter: brightness(1.2);\n      }\n\n      &:active {\n        filter: brightness(0.8);\n      }\n    }\n  }\n\n  .github-preview {\n    height: 100%;\n    flex: 1;\n    padding: 16px 32px;\n    overflow: auto;\n    padding-bottom: 16px;\n  }\n\n  .gh-content {\n    display: flex;\n    flex-direction: row;\n    flex: 1;\n    overflow: hidden;\n  }\n\n  .gh-header {\n    padding: 16px;\n    height: 64px;\n    display: grid;\n    align-content: center;\n    flex: 0 0 auto;\n\n    .header-text {\n      position: initial !important;\n      justify-content: left !important;\n    }\n  }\n\n  .installed-themes-page {\n    .style-editor-container {\n      height: 100%;\n      flex: 1;\n      background: var(--color2);\n      padding: 0px;\n      overflow-y: overlay;\n\n      .list-group-item {\n        border-radius: 0px;\n      }\n    }\n  }\n}\n\n//Styles Page\n.installed-themes-page {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: hidden;\n  .themeContextMenu {\n    background: transparent;\n    color: var(--keyColor);\n    border: 0px;\n  }\n\n  .list-group-item {\n    &.addon {\n      background: rgb(86 86 86 / 20%);\n    }\n\n    &.applied {\n      background: var(--keyColor-disabled);\n      pointer-events: none;\n    }\n  }\n\n  .repo-header {\n    font-size: 16px;\n    position: sticky;\n    top: 0;\n    left: 0;\n    right: 0;\n    width: 100%;\n    height: 50px;\n    z-index: 1;\n    background: rgba(36, 36, 36, 0.5);\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    backdrop-filter: var(--glassFilter);\n    overflow: hidden;\n    border-bottom: 1px solid rgb(0 0 0 / 18%);\n    border-top: 1px solid rgb(135 135 135 / 18%);\n  }\n\n  .gh-header {\n    z-index: 5;\n    padding: 16px;\n    flex: 0 0 auto;\n    height: 64px;\n    display: grid;\n    align-content: center;\n    .header-text {\n      position: initial !important;\n      justify-content: left !important;\n    }\n  }\n\n  .gh-content {\n    display: flex;\n    flex-direction: row;\n    padding: 0px;\n    height: 100%;\n    flex: 0 0 auto;\n\n    .repos-list {\n      width: 320px;\n      overflow: overlay;\n      height: 90%;\n      font-size: 14px;\n      white-space: nowrap;\n\n      > .list-group {\n        margin: 0px;\n        padding-bottom: 16px;\n      }\n\n      .list-group-item {\n        padding: 12px 6px;\n\n        &:hover {\n          filter: brightness(1.2);\n        }\n\n        &:active {\n          filter: brightness(0.8);\n        }\n      }\n    }\n\n    .style-editor-container {\n      height: 100%;\n      flex: 1;\n      padding: 0px;\n      width: 100%;\n      overflow: hidden;\n\n      .stylestack-editor {\n        padding-bottom: 16px;\n      }\n\n      .list-group-item {\n        border-radius: 0px;\n      }\n    }\n  }\n\n  .stylestack-editor {\n    width: 100%;\n\n    .btn,\n    .btn-group {\n      width: 100%;\n    }\n\n    .themeLabel {\n      display: flex;\n      align-items: center;\n    }\n\n    .handle {\n      height: 100%;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n    }\n\n    .list-group-item {\n      &:hover {\n        cursor: grab;\n      }\n\n      &:active {\n        cursor: grabbing;\n      }\n    }\n\n    .removeItem {\n      border: 0px;\n      background: transparent;\n      height: 32px;\n      font-weight: bold;\n      color: var(--textColor);\n      cursor: pointer;\n    }\n\n    .stylesDropdown {\n      > .dropdown-menu {\n        height: 300px;\n        overflow-y: overlay;\n      }\n    }\n  }\n}\n\n// Library - Songs page\n.library-page {\n  padding: 0px;\n\n  .library-header {\n    position: sticky;\n    top: 0;\n    left: 0;\n    border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n    z-index: 6;\n    background: black;\n    padding: 0px 2em;\n    backdrop-filter: blur(32px);\n    background: rgba(0, 0, 0, 0.25);\n    top: var(--navigationBarHeight);\n  }\n\n  .well {\n    margin: 2em;\n  }\n}\n\n// Search Page\n&.search-page {\n  .searchToggle {\n    float: right;\n\n    > button {\n      min-width: 120px;\n    }\n  }\n  .categories {\n    display: grid;\n    grid-template-columns: repeat(3, minmax(200px, 1fr));\n    gap: 1rem;\n  }\n  .cd-mediaitem-square.mediaitem-brick {\n    width: 100% !important;\n    height: 168px;\n    padding-block: 0.5rem;\n    .artwork-container .artwork {\n      height: 168px !important;\n      width: 100% !important;\n      z-index: 1;\n    }\n    .info-rect {\n      height: max-content;\n    }\n    .title {\n      font-weight: bold;\n      justify-content: left;\n      font-size: 18px;\n      margin-top: -40px;\n      z-index: 5;\n      pointer-events: none;\n    }\n  }\n}\n\n// Podcast Page\n.content-inner.podcasts-page {\n  display: flex;\n  height: calc(100% - var(--navigationBarHeight));\n  padding: 0px;\n\n  .list-flat {\n    border-radius: 0px;\n  }\n\n  .podcast-artwork {\n    width: 200px;\n    margin: 16px auto;\n    height: 200px;\n  }\n\n  .podcasts-list {\n    height: 100%;\n    width: 280px;\n    background: rgb(200 200 200 / 10%);\n    overflow-y: overlay;\n    border-right: 1px solid var(--color2);\n    flex: none;\n    overflow-x: hidden;\n\n    .podcast-list-header {\n      border-bottom: 1px solid var(--color2);\n      font-size: 0.7em;\n      padding: 6px;\n      background: #ffffff17;\n      text-transform: uppercase;\n      font-weight: 600;\n      opacity: 0.5;\n    }\n\n    .podcasts-search {\n      padding: 10px;\n      position: sticky;\n      top: 0;\n      left: 0;\n      width: 100%;\n      border-bottom: 1px solid var(--color2);\n      z-index: 2;\n      background: #303030;\n    }\n  }\n\n  .episodes-list {\n    height: 100%;\n    width: 100%;\n    background: rgb(200 200 200 / 6%);\n    overflow-y: overlay;\n    overflow-x: hidden;\n\n    .episodes-inline-info {\n      padding: 14px 14px 0px 14px;\n\n      .podcast-show-info {\n        display: flex;\n        justify-content: center;\n        flex-direction: column;\n      }\n\n      .podcast-show-description {\n        margin: 32px 6px;\n        font-size: 0.8rem;\n        white-space: pre-wrap;\n        display: block;\n      }\n\n      .podcast-artwork {\n        width: 120px;\n        margin: 0px auto;\n        height: 120px;\n      }\n    }\n\n    .podcast-no-search-results {\n      text-align: center;\n      margin-top: 40px;\n    }\n  }\n\n  .podcasts-details {\n    width: 300px;\n    flex: none;\n    background: rgb(255 255 255 / 5%);\n    overflow-y: overlay;\n    overflow-x: hidden;\n    top: 2%;\n    z-index: 2;\n    border-left: 1px solid var(--color2);\n    padding-bottom: 1em;\n\n    .meta-btn {\n      font-size: 0.75em;\n    }\n\n    .podcasts-details-header {\n      display: flex;\n      justify-content: end;\n      align-items: center;\n      position: sticky;\n      top: 0;\n      z-index: 2;\n    }\n\n    .close-btn {\n      width: 50px;\n      height: 42px;\n      background-image: var(--gfx-closeBtn);\n      background-position: center;\n      background-repeat: no-repeat;\n      -webkit-app-region: no-drag;\n      appearance: none;\n      border: 0;\n      background-color: transparent;\n      position: absolute;\n      top: 0;\n      right: 0;\n\n      &:hover {\n        background-color: rgb(196, 43, 28);\n      }\n    }\n\n    .podcast-genre {\n      text-align: center;\n      margin: 6px;\n      font-size: 0.8em;\n      font-weight: 500;\n      opacity: 0.8;\n    }\n\n    .podcast-metainfo {\n      text-align: center;\n      font-size: 0.7em;\n      opacity: 0.8;\n    }\n\n    .podcast-header {\n      text-align: center;\n      padding: 0 1rem;\n    }\n\n    .podcast-play-btn {\n      width: 50%;\n      display: block;\n      margin: 0 auto;\n    }\n\n    .podcast-description {\n      margin: 12px;\n      font-size: 0.75em;\n      white-space: pre-wrap;\n      display: block;\n      line-break: anywhere;\n    }\n  }\n}\n\n// Podcast Page\n.content-inner.library-artists-page {\n  // top: 0;\n  height: calc(100% - 60px - var(--navigationBarHeight));\n  padding: 0px;\n\n  .inner-container {\n    display: flex;\n    height: calc(100% - var(--navigationBarHeight));\n    padding: 0px;\n    height: 100%;\n\n    .list-flat {\n      border-radius: 0px;\n    }\n\n    .podcast-artwork {\n      width: 200px;\n      margin: 16px auto;\n      height: 200px;\n    }\n\n    .podcasts-list {\n      height: 100%;\n      width: 280px;\n      background: rgb(200 200 200 / 10%);\n      overflow-y: overlay;\n      border-right: 1px solid var(--color2);\n      flex: none;\n      overflow-x: hidden;\n\n      .podcast-list-header {\n        border-bottom: 1px solid var(--color2);\n        font-size: 0.7em;\n        padding: 6px;\n        background: #ffffff17;\n        text-transform: uppercase;\n        font-weight: 600;\n        opacity: 0.5;\n      }\n\n      .podcasts-search {\n        padding: 10px;\n        position: sticky;\n        top: 0;\n        left: 0;\n        width: 100%;\n        border-bottom: 1px solid var(--color2);\n        z-index: 2;\n        background: #303030;\n      }\n    }\n\n    .episodes-list {\n      height: calc(100% + 60px);\n      width: 100%;\n      background: rgb(200 200 200 / 6%);\n      overflow-y: overlay;\n      overflow-x: hidden;\n\n      .episodes-inline-info {\n        padding: 14px 14px 0px 14px;\n\n        .podcast-show-info {\n          display: flex;\n          justify-content: center;\n          flex-direction: column;\n        }\n\n        .podcast-show-description {\n          margin: 32px 6px;\n          font-size: 0.8rem;\n          white-space: pre-wrap;\n          display: block;\n        }\n\n        .podcast-artwork {\n          width: 120px;\n          margin: 0px auto;\n          height: 120px;\n        }\n      }\n\n      .podcast-no-search-results {\n        text-align: center;\n        margin-top: 40px;\n      }\n    }\n\n    .podcasts-details {\n      width: 300px;\n      flex: none;\n      background: rgb(255 255 255 / 5%);\n      overflow-y: overlay;\n      overflow-x: hidden;\n      top: 2%;\n      z-index: 2;\n      border-left: 1px solid var(--color2);\n      padding-bottom: 1em;\n\n      .meta-btn {\n        font-size: 0.75em;\n      }\n\n      .podcasts-details-header {\n        display: flex;\n        justify-content: end;\n        align-items: center;\n        position: sticky;\n        top: 0;\n        z-index: 2;\n      }\n\n      .close-btn {\n        width: 50px;\n        height: 42px;\n        background-image: var(--gfx-closeBtn);\n        background-position: center;\n        background-repeat: no-repeat;\n        -webkit-app-region: no-drag;\n        appearance: none;\n        border: 0;\n        background-color: transparent;\n        position: absolute;\n        top: 0;\n        right: 0;\n\n        &:hover {\n          background-color: rgb(196, 43, 28);\n        }\n      }\n\n      .podcast-genre {\n        text-align: center;\n        margin: 6px;\n        font-size: 0.8em;\n        font-weight: 500;\n        opacity: 0.8;\n      }\n\n      .podcast-metainfo {\n        text-align: center;\n        font-size: 0.7em;\n        opacity: 0.8;\n      }\n\n      .podcast-header {\n        text-align: center;\n      }\n\n      .podcast-play-btn {\n        width: 50%;\n        display: block;\n        margin: 0 auto;\n      }\n\n      .podcast-description {\n        margin: 12px;\n        font-size: 0.75em;\n        white-space: pre-wrap;\n        display: block;\n        line-break: anywhere;\n      }\n    }\n  }\n\n  @media only screen and (max-width: 1230px) {\n    .content-inner.podcasts-page {\n      .podcasts-details {\n        height: 96%;\n        width: 300px;\n        flex: none;\n        background: rgb(20 20 20 / 97%);\n        overflow-y: overlay;\n        overflow-x: hidden;\n        position: absolute;\n        right: 2%;\n        top: 2%;\n        border-radius: 10px;\n        box-shadow: var(--ciderShadow-Generic);\n        z-index: 2;\n      }\n    }\n  }\n}\n\n@media only screen and (max-width: 1230px) {\n  .content-inner.podcasts-page {\n    .podcasts-details {\n      height: 96%;\n      width: 300px;\n      flex: none;\n      background: rgb(20 20 20 / 97%);\n      overflow-y: overlay;\n      overflow-x: hidden;\n      position: absolute;\n      right: 2%;\n      top: 2%;\n      border-radius: 10px;\n      box-shadow: var(--ciderShadow-Generic);\n      z-index: 2;\n    }\n  }\n}\n\n/* Album / Playlist Page */\n.album-header {\n  position: sticky;\n  left: 0;\n  z-index: 6;\n  padding: 0px 2em;\n  backdrop-filter: blur(32px);\n  background: rgba(0, 0, 0, 0.25);\n  top: var(--navigationBarHeight);\n  --bs-gutter-x: 4rem;\n  --bs-gutter-y: 0;\n  display: flex;\n  flex-wrap: wrap;\n  margin-top: calc(-1 * var(--bs-gutter-y));\n  margin-right: calc(-0.5 * var(--bs-gutter-x));\n  margin-left: calc(-0.5 * var(--bs-gutter-x));\n  border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n}\n.playlist-page {\n  --bgColor: transparent;\n  padding: 0px;\n  //background: linear-gradient(180deg, var(--bgColor) 32px, var(--bgColor) 18px, transparent 60px, transparent 100%);\n  top: 0;\n  padding-top: var(--navigationBarHeight);\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: hidden;\n\n  .cd-mediaitem-list-item {\n    &:hover {\n      .heart-icon {\n        display: flex;\n      }\n    }\n\n    .heart-icon {\n      left: -25px;\n    }\n  }\n\n  .editTracksBtn {\n    position: absolute;\n    top: 20px;\n    right: 20px;\n    z-index: 1;\n\n    > span {\n      display: flex;\n      gap: 8px;\n    }\n  }\n\n  .mediaContainer {\n    transition:\n      width 0.5s ease-in-out,\n      height 0.5s ease-in-out;\n    width: 260px;\n    height: 260px;\n  }\n\n  .playlist-body {\n    padding: 32px;\n    // margin-top: -75px;\n    overflow-y: overlay;\n    height: 100%;\n    padding: 0px;\n    background-color: var(--color3);\n\n    &.scrollbody {\n      .tabs {\n        display: flex;\n        flex-flow: column;\n        height: 100%;\n\n        .nav-link {\n          text-transform: capitalize;\n        }\n\n        .tab-content {\n          height: 100%;\n          overflow: hidden;\n          margin: 0px;\n\n          .tab-pane {\n            height: 100%;\n            overflow-y: overlay;\n            overflow-x: hidden;\n            padding: var(--contentInnerPadding);\n            padding-inline: 40px;\n            -webkit-mask-image: linear-gradient(180deg, transparent, white 20px);\n\n            .well {\n              margin: 0px;\n            }\n          }\n        }\n      }\n    }\n\n    .search-input-container {\n      height: 2.5rem;\n      margin: 1rem;\n      margin-top: 0;\n      scroll-margin-top: 1rem;\n\n      .search-input {\n        width: 100%;\n        height: 100%;\n      }\n    }\n  }\n\n  .floating-header {\n    position: sticky;\n    top: 0;\n    left: 0;\n    border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n    z-index: 6;\n    padding: 0px 1em;\n    backdrop-filter: blur(32px);\n    background: rgba(0, 0, 0, 0.25);\n    top: var(--navigationBarHeight);\n    transition: opacity 0.1s var(--appleEase);\n    display: none;\n  }\n\n  .playlist-display {\n    padding: var(--contentInnerPadding);\n    min-height: 300px;\n    position: relative;\n    box-shadow: 0px 4px 6px 3px rgb(0 0 0 / 10%);\n    transition: min-height 0.5s ease-in-out;\n\n    .artworkContainer {\n      position: absolute;\n      top: 0;\n      left: 0;\n      bottom: 0;\n      right: 0;\n      margin: 0;\n      margin-top: calc(var(--navigationBarHeight) * -1);\n      margin-bottom: -10px;\n      padding: 0;\n      -webkit-mask-image: radial-gradient(at top left, black, transparent 70%), radial-gradient(at top right, black, transparent 70%), linear-gradient(180deg, rgb(200 200 200), transparent 98%);\n      opacity: 0.7;\n      animation: playlistArtworkFadeIn 1s var(--appleEase);\n\n      .artworkMaterial img {\n        filter: brightness(100%) blur(80px) saturate(100%) contrast(1);\n        object-position: center;\n        object-fit: cover;\n        width: 100%;\n        height: 100%;\n        transform: unset;\n      }\n    }\n\n    .playlistInfo {\n      z-index: 1;\n      position: absolute;\n      bottom: 0;\n      left: 0;\n      right: 0;\n      top: 0;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      width: 100%;\n      height: 100%;\n\n      .playlist-hero {\n        width: 100%;\n        transform: translateX(+25%);\n        position: absolute;\n        z-index: -1;\n        top: 0;\n        left: 0;\n        right: 0;\n        bottom: 0;\n\n        .mediaitem-artwork {\n          -webkit-mask-image: -webkit-radial-gradient(center, circle cover, rgba(0, 0, 0, 1) 50%, rgba(0, 0, 0, 0) 75%);\n          border-radius: 0px;\n        }\n\n        .hero-tint {\n          position: absolute;\n          top: 0;\n          opacity: 0.6;\n          width: 100%;\n          height: 100%;\n        }\n      }\n\n      > .row {\n        width: calc(100% - 32px);\n      }\n\n      .playlist-info {\n        flex-shrink: unset;\n        display: flex;\n        flex-flow: column;\n        justify-content: flex-end;\n\n        .playlist-name {\n          font-weight: 700;\n          font-size: 1.6rem;\n          //margin-bottom: 6px;\n          margin-right: 6px;\n          margin-bottom: 6px;\n          flex-shrink: unset;\n        }\n\n        .search-input::placeholder {\n          color: var(--heroplaceholdercolor);\n        }\n\n        .nameEdit {\n          font-weight: 700;\n          font-size: 1.6rem;\n          flex-shrink: unset;\n          background: transparent;\n          border: 0px;\n          color: inherit;\n          font-family: inherit;\n        }\n\n        .descriptionEdit {\n          font-size: 14px;\n          flex-shrink: unset;\n          background: transparent;\n          border: 0px;\n          color: inherit;\n          font-family: inherit;\n          width: 60vw;\n        }\n\n        .descriptionEdit {\n          font-size: 14px;\n          flex-shrink: unset;\n          background: transparent;\n          border: 0px;\n          color: inherit;\n          font-family: inherit;\n          width: 60vw;\n        }\n\n        .playlist-artist {\n          font-size: 20px;\n          margin-bottom: 6px;\n          margin-right: 6px;\n          flex-shrink: unset;\n        }\n\n        .playlist-desc {\n          transition:\n            height 0.2s ease-in-out,\n            opacity 0.2s ease-in-out;\n          box-sizing: border-box;\n          font-size: 14px;\n          flex-shrink: unset;\n          margin-right: 5px;\n          max-height: 100px;\n          position: relative;\n          height: 4vh;\n\n          .content {\n            height: 4vh;\n            -webkit-mask-image: -webkit-gradient(linear, left 50%, left 90%, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0)));\n          }\n\n          .more-btn {\n            appearance: none;\n            position: absolute;\n            right: 0;\n            bottom: 0;\n            padding: 0 5px;\n            font-size: 14px;\n            color: var(--keyColor);\n            background-color: transparent;\n            border: 0px;\n            cursor: pointer;\n            width: 100%;\n            height: 100%;\n            overflow: hidden;\n            display: flex;\n            justify-content: flex-end;\n            align-items: flex-end;\n            font-weight: 600;\n            font-family: inherit;\n            text-transform: uppercase;\n          }\n        }\n\n        .playlist-desc-expanded {\n          box-sizing: border-box;\n          font-size: 14px;\n          position: relative;\n\n          .more-btn {\n            appearance: none;\n            position: absolute;\n            right: 0;\n            bottom: 0;\n            padding: 0 5px;\n            font-size: 14px;\n            color: var(--keyColor);\n            background-color: transparent;\n            border: 0px;\n            cursor: pointer;\n            width: 100%;\n            height: 100%;\n            overflow: hidden;\n            display: flex;\n            justify-content: flex-end;\n            align-items: flex-end;\n            font-weight: 600;\n            font-family: inherit;\n            text-transform: uppercase;\n          }\n        }\n\n        .search-btn {\n          display: flex;\n          width: 32px;\n          align-items: center;\n          margin-right: 1rem;\n          background: rgba(100, 100, 100, 0.5);\n          border: none;\n          cursor: pointer;\n          border-radius: 100vmax;\n          box-shadow: var(--ciderShadow-Generic);\n\n          > ._svg-icon {\n            width: 18px;\n            height: 18px;\n            margin: auto;\n          }\n        }\n\n        .search-btn.active {\n          animation: enlarge 0.5s ease-in-out;\n        }\n\n        .search-btn:hover {\n          filter: brightness(125%);\n        }\n\n        @keyframes enlarge {\n          0% {\n            transform: scale(1);\n          }\n          50% {\n            transform: scale(1.2);\n          }\n          100% {\n            transform: scale(1);\n          }\n        }\n      }\n    }\n  }\n\n  .friends-info {\n    display: flex;\n    flex-flow: column;\n\n    .badge-container {\n      display: flex;\n      flex-flow: wrap;\n\n      .socialBadge {\n        width: 40px;\n        height: 40px;\n        border-radius: 100%;\n        overflow: hidden;\n        box-shadow: var(--mediaItemShadow-ShadowSubtle);\n        transition: transform 0.2s var(--appleEase);\n        margin: 6px;\n\n        &:hover {\n          transform: scale(1.2);\n        }\n      }\n    }\n\n    .friends-name {\n      text-align: center;\n      font-size: 0.9em;\n      margin: 8px;\n    }\n  }\n\n  .playlist-time {\n    font-size: 0.9em;\n    margin: 6px;\n    opacity: 0.7;\n    transition:\n      height 0.2s ease-in-out,\n      opacity 0.2s ease-in-out;\n    height: 0.9em;\n  }\n\n  &.inline-playlist {\n    overflow: hidden;\n    width: 100%;\n    height: 100%;\n    background: rgba(0, 0, 0, 0.5);\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    z-index: 10;\n    position: sticky;\n    margin-top: calc(var(--navigationBarHeight) * -1);\n\n    .floating-header {\n      opacity: 1;\n      top: 0px;\n      z-index: 6;\n      padding: 1em;\n      backdrop-filter: unset;\n      background: black;\n\n      h3 {\n        display: none;\n      }\n    }\n\n    .playlist-inner {\n      background: black;\n      width: 80%;\n      height: 100%;\n      overflow: overlay;\n      box-shadow: var(--ciderShadow-Generic);\n      border-radius: var(--mediaItemRadius) var(--mediaItemRadius) 0px 0px;\n\n      .close-btn {\n        position: sticky;\n        top: 16px;\n        left: 16px;\n        margin-left: 16px;\n        z-index: 7;\n      }\n    }\n  }\n\n  .pilldim {\n    .nav-pills {\n      width: max-content;\n      margin: 0 auto;\n      margin-top: 16px;\n    }\n  }\n\n  &.plmin {\n    .playlist-display {\n      transition: min-height 0.5s ease-in-out;\n      min-height: 200px;\n\n      .playlistInfo {\n      }\n\n      .mediaContainer {\n        transition:\n          width 0.5s ease-in-out,\n          height 0.5s ease-in-out;\n        width: 128px !important;\n        height: 128px !important;\n      }\n\n      .playlist-time {\n        transition:\n          height 0.2s ease-in-out,\n          opacity 0.2s ease-in-out;\n        height: 0px;\n        opacity: 0;\n      }\n\n      .playlist-desc {\n        transition:\n          height 0.2s ease-in-out,\n          opacity 0.2s ease-in-out;\n        height: 0px !important;\n        opacity: 0;\n      }\n    }\n  }\n}\n\n@keyframes playlistArtworkFadeIn {\n  0% {\n    opacity: 0;\n  }\n\n  100% {\n    opacity: 0.7;\n  }\n}\n\n// Collection Page\n.collection-page {\n  padding-bottom: 128px;\n\n  .top-fab {\n    height: 52px;\n    width: 52px;\n    position: fixed;\n    bottom: 32px;\n    right: 32px;\n    border-radius: 100%;\n    background: rgb(60 60 60);\n    border: 0px;\n    appearance: none;\n    box-shadow: var(--ciderShadow-Generic);\n\n    > svg {\n      height: 50%;\n      color: #eee;\n      pointer-events: none;\n    }\n\n    &:hover {\n      background: rgb(100 100 100);\n    }\n\n    &:active {\n      background: var(--keyColor);\n    }\n  }\n\n  .header-text {\n    margin-bottom: 32px;\n  }\n}\n\n/* Artist Page */\n\n.artist-page {\n  padding: 0px;\n  top: 0;\n\n  .floating-header {\n    position: sticky;\n    top: 0;\n    left: 0;\n    border-bottom: 1px solid rgba(200, 200, 200, 0.05);\n    z-index: 6;\n    padding: 0px 1em;\n    backdrop-filter: blur(32px);\n    background: rgba(0, 0, 0, 0.25);\n    top: var(--navigationBarHeight);\n    transition: opacity 0.1s var(--appleEase);\n  }\n\n  &.animated .artist-header .more-btn-round {\n    position: absolute;\n    bottom: 22px !important;\n    right: 28px;\n  }\n\n  &.animated .artist-header {\n    min-height: 80vh;\n  }\n\n  &.animated .artist-header-compact {\n    min-height: 40vh;\n  }\n\n  .artist-header {\n    //background: linear-gradient(45deg, var(--keyColor), #0e0e0e);\n    color: white;\n    display: flex;\n    align-items: center;\n    justify-content: space-between;\n    min-height: 400px;\n    position: relative;\n    pointer-events: none;\n\n    .header-content {\n      z-index: 1;\n      // margin-top: -16px;\n    }\n\n    .artist-hero {\n      height: 100%;\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      bottom: 0;\n\n      .mediaitem-artwork {\n        border-radius: 0px;\n      }\n    }\n\n    .artworkContainer {\n      position: absolute;\n      top: 0;\n      left: 0;\n      bottom: 0;\n      right: 0;\n      margin: 0;\n      padding: 0;\n      -webkit-mask-image: radial-gradient(at top left, black, transparent 70%), radial-gradient(at top right, black, transparent 70%), linear-gradient(180deg, rgb(200 200 200), transparent 98%);\n      opacity: 0.7;\n      animation: playlistArtworkFadeIn 1s var(--appleEase);\n\n      .artworkMaterial img {\n        filter: brightness(100%) blur(80px) saturate(100%) contrast(1);\n        object-position: center;\n        object-fit: cover;\n        width: 100%;\n        height: 100%;\n        transform: unset;\n      }\n    }\n\n    .more-btn-round {\n      position: absolute;\n      bottom: 82px;\n      right: 28px;\n    }\n\n    .social-btn {\n      border-radius: 100%;\n      background: transparent;\n      height: 17px;\n      border: 0px;\n      cursor: pointer;\n      z-index: 69;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      float: right;\n    }\n    @media only screen and (min-width: 1133px) and (max-width: 1277px) {\n      .about-page {\n        .social-btn {\n          display: none !important;\n        }\n      }\n    }\n\n    .animated {\n      width: 100%;\n      height: 100%;\n      align-self: center;\n      position: absolute;\n      overflow: hidden;\n      box-shadow: rgb(0 0 0 / 50%) 0 0 0 1000000px inset;\n      z-index: 1;\n\n      video {\n        overflow: hidden;\n        height: 100%;\n        width: 100%;\n        min-height: 56.25vw;\n        position: absolute;\n        top: 50%;\n        left: 50%;\n        transform: translate(-50%, -50%);\n        object-fit: cover;\n      }\n    }\n\n    .row .col.cider-flex-center {\n      z-index: 4;\n    }\n  }\n\n  .artist-image {\n    width: 200px;\n    height: 200px;\n    margin: 32px;\n    position: relative;\n\n    .overlay-play {\n      position: absolute;\n      top: 0;\n      left: 0;\n      width: 100%;\n      height: 100%;\n      opacity: 0;\n      background: rgb(0 0 0 / 50%);\n      transition: opacity 0.1s var(--appleEase);\n      border-radius: 100%;\n      z-index: 1;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      cursor: pointer;\n      appearance: none;\n      border: 0px;\n      padding: 0px;\n\n      &:hover {\n        opacity: 1;\n      }\n\n      &:active {\n        background: var(--selected-click);\n      }\n\n      > svg {\n        width: 70%;\n      }\n    }\n  }\n\n  .artist-play {\n    width: 32px;\n    height: 32px;\n    background: rgba(100, 100, 100, 0.5);\n    box-shadow: var(--ciderShadow-Generic);\n    border-radius: 100%;\n    box-shadow: var(--mediaItemShadow);\n    display: none;\n    cursor: pointer;\n    appearance: none;\n    border: 0px;\n    padding: 0px;\n\n    &:hover {\n      filter: brightness(125%);\n    }\n\n    &:active {\n      filter: brightness(75%);\n      transform: scale(0.98);\n      transition:\n        transform 0s var(--appleEase),\n        box-shadow 0.2s var(--appleEase);\n    }\n  }\n\n  .artist-title {\n    .artist-play {\n      transform: translateY(3px);\n      margin: 14px;\n    }\n\n    &.artist-animation-on {\n      width: 100%;\n      flex: unset;\n      margin-left: 0.5em;\n      color: whitesmoke;\n      position: absolute;\n      bottom: 0;\n\n      .artist-play {\n        display: block;\n      }\n    }\n  }\n\n  .artist-body {\n    padding: 0px var(--contentInnerPadding) 0px var(--contentInnerPadding);\n    margin: -64px 20px;\n\n    .arow {\n      display: flex;\n      overflow: hidden;\n      padding: 16px 32px;\n\n      > .latestRelease {\n        width: 250px;\n      }\n\n      > .topSongs {\n        width: calc(100% - 250px);\n      }\n\n      &.arowb > .topSongs {\n        width: 100%;\n      }\n    }\n  }\n\n  &.animated > .artist-body {\n    padding: 0px var(--contentInnerPadding) 0px var(--contentInnerPadding);\n    margin-top: -57px;\n  }\n\n  .showmoreless {\n    font-family: inherit;\n    font-size: 16px;\n    font-weight: 500;\n    background: transparent;\n    border: 0px;\n    border-radius: 6px;\n    appearance: none;\n    color: var(--keyColor);\n    padding: 8px 12px;\n    cursor: pointer;\n    margin-top: 12px;\n    float: right;\n  }\n\n  .showmoreless:hover {\n    background: rgb(200 200 200 / 10%);\n  }\n}\n\n/* Artist Page End */\n\n// Settings page\n.settings-page {\n  padding: 0px;\n\n  .nav {\n    width: 90%;\n    margin: 16px auto 0px;\n  }\n}\n\n.i18n-page {\n  textarea {\n    background: black;\n    color: #eee;\n    font-weight: bold;\n    font-size: 1em;\n    font-family: system-ui, \"Pretendard Variable\";\n    padding: 0.5em;\n  }\n\n  .selectCol {\n    display: flex;\n    align-items: center;\n  }\n}\n\n// AudioLabs page\n.audiolabs-page {\n  padding: 0px;\n\n  .md-option-header {\n    padding: 1.25em 1.25em;\n    border-bottom: unset;\n    border-top: unset;\n    font-weight: 600;\n    font-size: 1em;\n    background: rgb(255 255 255 / 3%);\n  }\n\n  .carousel-item > img {\n    object-fit: cover;\n    width: 100%;\n  }\n\n  .spprofile-line {\n    height: 300px;\n    width: 100%;\n    max-width: 1024px;\n    padding: 16px;\n    margin: 0 auto;\n\n    .spprofile-viewport {\n      height: 100%;\n      position: relative;\n      border-radius: var(--mediaItemRadius);\n      overflow: hidden;\n      box-shadow: var(--mediaItemShadow-Shadow);\n      background: black;\n\n      .spprev,\n      .nextprev {\n        position: absolute;\n        height: 100%;\n        width: 64px;\n        top: 0;\n        background: rgb(0 0 0 / 20%);\n        z-index: 1;\n        border: 0px;\n        transition:\n          background 0.2s var(--appleEase),\n          transform 0.2s var(--appleEase);\n\n        &:hover {\n          background: var(--selected);\n          transform: scale(1.1);\n        }\n\n        &:active {\n          transition: background 0s var(--appleEase);\n          background: var(--selected-click);\n        }\n\n        &:before {\n          content: \"\";\n          position: absolute;\n          top: 0;\n          left: 0;\n          width: 100%;\n          height: 100%;\n          background: #eee;\n          opacity: 1;\n          -webkit-mask-position: center;\n          -webkit-mask-repeat: no-repeat;\n          -webkit-mask-size: 1em;\n        }\n      }\n\n      .spprev {\n        left: 0;\n\n        &:before {\n          -webkit-mask-image: url(\"./views/svg/chevron-left.svg\");\n        }\n      }\n\n      .nextprev {\n        right: 0;\n\n        &:before {\n          -webkit-mask-image: url(\"./views/svg/chevron-right.svg\");\n        }\n      }\n\n      .spslide {\n        position: absolute;\n        width: 100%;\n        height: 100%;\n        overflow: hidden;\n        background: black;\n\n        > img {\n          width: 100%;\n          height: 100%;\n          object-fit: cover;\n        }\n\n        .sptitle {\n          position: absolute;\n          bottom: 0px;\n          left: 0;\n          width: 100%;\n          text-align: center;\n          font-size: 18px;\n          text-shadow: 0px 2px 4px #00000033;\n        }\n      }\n\n      .spfade-enter-active,\n      .spfade-leave-active {\n        --transitionTime: 0.2s;\n        transition:\n          opacity var(--transitionTime) var(--appleEase),\n          transform var(--transitionTime) var(--appleEase);\n        will-change: opacity, transform;\n      }\n\n      .spfade-enter {\n        opacity: 0;\n        transform: scale(1.2) translate3d(0, 0, 0);\n        will-change: opacity, transform;\n      }\n\n      .spfade-leave-to {\n        opacity: 1;\n        transform: scale(1) translate3d(0, 0, 0);\n        will-change: opacity, transform;\n      }\n    }\n  }\n\n  .settings-option-body {\n    margin: 16px;\n  }\n}\n\n@keyframes gradient-animation {\n  0% {\n    background-position: 0% 0%;\n  }\n\n  50% {\n    background-position: 100% 0%;\n  }\n\n  100% {\n    background-position: 0% 0%;\n  }\n}\n\n//Home\n.home-page {\n  .md-btn-replay {\n    background-image: linear-gradient(-45deg, #2e2173, #925042);\n    animation: gradient-animation 5s ease-in-out infinite;\n    background-size: 400% 400%;\n    border: 0px;\n    box-shadow: inset 0px 0px 0px 1px rgba(200, 200, 200, 0.2);\n    text-transform: uppercase;\n    font-weight: bold;\n  }\n\n  .md-btn-replay--hero {\n    font-size: 1em;\n    padding: 16px;\n    background-image: linear-gradient(-45deg, #2e2173, #925042);\n    animation: gradient-animation 5s ease-in-out infinite;\n    background-size: 400% 400%;\n    border: 0px;\n    box-shadow: inset 0px 0px 0px 1px rgb(200 200 200 / 20%);\n    margin-top: 1em;\n    font-size: 0.9em;\n    text-transform: uppercase;\n    font-weight: bold;\n  }\n\n  .artist-feed-card {\n    position: absolute;\n    bottom: 0;\n    left: 10%;\n    z-index: 1;\n    background: black;\n    width: 80%;\n    height: 96%;\n    overflow: scroll;\n    border-radius: 10px;\n  }\n\n  .col.madeforyou-col {\n    width: 420px;\n    min-width: 0px;\n    max-width: 420px;\n  }\n\n  .well.artistfeed-well {\n    margin-top: 0px;\n    height: 392px;\n    align-content: flex-start;\n  }\n\n  .hint-text {\n    font-size: 0.9rem;\n    color: rgb(200 200 200 / 70%);\n  }\n\n  .user-icon {\n    border-radius: 100%;\n    width: 128px;\n    height: 128px;\n    overflow: hidden;\n    box-shadow: var(--mediaItemShadow-Shadow);\n    margin: 16px;\n  }\n\n  .well.profile-well {\n    flex-direction: column;\n    justify-content: center;\n    align-items: center;\n\n    .name {\n      margin: 4px;\n      font-weight: 500;\n    }\n\n    .handle {\n      margin: 4px;\n      opacity: 0.7;\n      font-weight: 500;\n    }\n  }\n}\n\n// Replay\n.replay-page {\n  --replayTextShadow: 0px 3px 2px #6f3f52;\n\n  .replay-period {\n    height: 200px;\n    width: 200px;\n    margin: 6px;\n    border-radius: var(--mediaItemRadius);\n    overflow: hidden;\n    cursor: pointer;\n    transition: transform 0.2s var(--appleEase);\n    transition-delay: 0.1s;\n    align-self: center;\n\n    &:hover {\n      transform: translateY(-6px);\n      transition-delay: 0s;\n    }\n\n    .artwork-container {\n      height: 200px;\n      width: 200px;\n    }\n  }\n\n  .replay-playlist-container {\n    .cd-mediaitem-square {\n      height: 230px;\n      width: 230px;\n\n      .info-rect {\n        display: none;\n      }\n    }\n  }\n\n  .replay-video {\n    max-height: 300px;\n    max-width: 800px;\n    margin: 0 auto;\n\n    .mediaitem-artwork {\n      max-height: 300px;\n      max-width: 800px;\n    }\n\n    .mediaitem-artwork .animatedartwork-view-box .animated video {\n      object-fit: cover;\n    }\n  }\n\n  .top-genres-container {\n    .genre-name {\n      font-size: 0.9em;\n      margin: 6px 0px;\n      font-weight: 500;\n    }\n\n    .genre-count {\n      width: 100%;\n      height: 32px;\n      background: #ffffff14;\n      border-radius: 10px;\n      overflow: hidden;\n\n      .genre-count-bar {\n        height: 100%;\n        width: 0%;\n        background: var(--keyColor);\n        display: flex;\n        justify-content: center;\n        align-items: center;\n        min-width: 32px;\n        font-size: 0.9em;\n        font-weight: 500;\n      }\n    }\n  }\n\n  .cd-mediaitem-square {\n    .mediaitem-artwork {\n      animation: replayFadeIn 0.5s var(--appleEase);\n    }\n\n    transition: transform 0.2s var(--appleEase);\n    transition-delay: 0.1s;\n\n    &:hover {\n      transform: scale(1.1);\n      transition-delay: 0s;\n    }\n  }\n\n  @keyframes replayFadeIn {\n    0% {\n      //border-radius: 100%;\n      transform: translateY(10px) scale(0.9);\n      opacity: 0;\n    }\n\n    100% {\n      //border-radius: var(--mediaItemRadius);\n      transform: scale(1);\n      opacity: 1;\n    }\n  }\n\n  .replay-viewport {\n    background-image: linear-gradient(-45deg, #2e2173, #925042);\n    animation: gradient-animation 5s ease-in-out infinite;\n    background-size: 400% 400%;\n    padding: 16px 40px;\n    border-radius: 10px;\n    box-shadow: var(--mediaItemShadow), var(--mediaItemShadow-Shadow);\n    color: rgb(238 238 238 / 86%);\n\n    .replay-header {\n      text-align: center;\n      font-size: 3em;\n      text-shadow: var(--replayTextShadow);\n    }\n  }\n\n  .replay-card {\n    background: transparent;\n    border: 0px;\n  }\n}\n\n.content-inner.oobe {\n  position: absolute;\n  overflow: hidden;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  display: grid;\n  place-items: center;\n  width: 100%;\n  background: #1e1e1e;\n\n  .oobe-view {\n    display: flex;\n    flex-direction: column;\n    justify-content: center;\n    align-items: center;\n    gap: 32px;\n    max-width: 1280px;\n    max-height: 720px;\n    align-self: center;\n    justify-self: center;\n    height: 100%;\n    width: 100%;\n\n    .oobe-header {\n      font-size: 3em;\n      text-shadow: var(--replayTextShadow);\n      font-weight: 600;\n    }\n\n    .oobe-body {\n      flex: 1;\n      width: 100%;\n      background: #ffffff0d;\n      border-radius: 20px;\n      padding: 3em;\n      overflow-y: scroll;\n      overflow-x: hidden;\n\n      @media screen and (max-width: 1161px) {\n        font-size: 13px;\n      }\n\n      &.text {\n        white-space: pre-wrap;\n      }\n\n      .blurb {\n        white-space: pre-wrap;\n        margin: 16px;\n        line-height: 1.5em;\n      }\n\n      &.visual {\n        padding: 1em;\n\n        .stylePicker {\n          border-radius: 10px;\n          overflow: hidden;\n          cursor: pointer;\n          transition: 0.25s all;\n          box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);\n          width: 450px;\n          margin: 0 auto;\n\n          .visualPreview {\n            pointer-events: none;\n            transition: 0.25s all;\n            width: 100%;\n          }\n\n          .card-body {\n            padding: 0;\n            display: flex;\n            justify-content: center;\n            align-items: center;\n          }\n\n          .card-footer {\n            font-size: 1.25em;\n            font-weight: 500;\n            position: absolute;\n            bottom: 0;\n            left: 0;\n            width: 100%;\n            border: 0px;\n            text-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);\n            font-weight: bold;\n          }\n\n          &.style-active {\n            outline: 4px solid var(--keyColor);\n          }\n\n          &:hover {\n            transform: scale(1.1) translateZ(-1px) translateY(10px);\n            z-index: 1;\n            box-shadow: 0px 12px 16px rgb(0 0 0 / 25%);\n          }\n\n          @media screen and (max-height: 688px) {\n            width: 270px;\n          }\n        }\n      }\n    }\n\n    .oobe-footer {\n      display: flex;\n      flex-direction: row;\n      justify-content: center;\n      align-items: center;\n      padding: 16px;\n\n      .md-btn {\n        font-size: 18px;\n        min-width: 128px;\n        text-align: center;\n      }\n    }\n  }\n\n  .oobe-titlebar {\n    position: absolute;\n    top: 0;\n    left: 0;\n    height: 46px;\n    width: 100%;\n    align-items: center;\n    justify-content: right;\n    display: flex;\n    -webkit-app-region: drag;\n\n    .button-group {\n      -webkit-app-region: no-drag;\n      display: flex;\n      flex-direction: row;\n      width: 100px;\n      height: 100%;\n      justify-content: center;\n      align-items: center;\n      gap: 16px;\n\n      > button {\n        height: 32px;\n        width: 32px;\n        font-size: 16px;\n        border-radius: 0px;\n        border: 0;\n        appearance: none;\n        position: relative;\n        display: flex;\n        justify-content: center;\n        align-items: center;\n        border-radius: 100%;\n\n        &.close {\n          background-color: #fc3c44aa;\n\n          &:hover {\n            background-color: #fc3c44;\n          }\n        }\n\n        &.min {\n          background-color: rgb(200 200 200 / 5%);\n\n          &:hover {\n            background-color: rgb(200 200 200 / 10%);\n          }\n        }\n\n        &.close::before {\n          font-family: \"codicon\";\n          content: \"\";\n          color: white;\n        }\n\n        &.min::before {\n          font-family: \"codicon\";\n          content: \"\";\n          color: white;\n        }\n      }\n    }\n  }\n}\n\n.content-inner.cider-multiroom {\n  padding: 0px;\n\n  .detail {\n    padding: 32px;\n  }\n\n  .header-desc {\n    font-size: 1em;\n    font-weight: 400;\n  }\n\n  .artworkContainer {\n    height: 300px;\n    width: 100%;\n\n    img {\n      height: 100%;\n      width: 100%;\n      overflow: hidden;\n      object-fit: cover;\n      filter: unset;\n\n      &:last-child {\n        transform: unset;\n      }\n    }\n  }\n}\n\n.settings-panel {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: rgb(0 0 0 / 0);\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  z-index: 16;\n\n  .settings-window {\n    background: var(--baseColorMix);\n    max-width: 90%;\n    max-height: 90%;\n    width: 100%;\n    height: 100%;\n    border-radius: 10px;\n    box-shadow: var(--ciderShadow-Generic);\n    overflow: hidden;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    position: relative;\n    flex: 1;\n    backdrop-filter: var(--glassFilterHeavy);\n    transition:\n      width 0.25s ease-in-out,\n      height 0.25s ease-in-out,\n      max-width 0.25s ease-in-out,\n      max-height 0.25s ease-in-out;\n\n    .header-text {\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      height: 48px;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      font-weight: 600;\n      opacity: 0.9;\n    }\n\n    .nav-pills {\n      gap: 6px;\n    }\n\n    .nav-pills .nav-link {\n      display: flex;\n      gap: 10px;\n      align-items: center;\n      height: 35px;\n\n      :nth-child(2) {\n        white-space: nowrap;\n      }\n    }\n\n    .md-option-header {\n      padding: 0px 26px;\n      border-bottom: unset;\n      border-top: unset;\n      font-weight: 600;\n      background: rgb(255 255 255 / 0%);\n      font-size: 2em;\n    }\n\n    .settings-option-body-webview {\n      height: 100%;\n      width: 100%;\n    }\n\n    .settings-option-body {\n      margin: 16px;\n    }\n\n    &.maxed {\n      width: 100%;\n      height: 100%;\n      max-height: 100%;\n      max-width: 100%;\n      border-radius: 0px;\n      box-shadow: unset;\n    }\n\n    .close-btn {\n      width: 36px;\n      height: 36px;\n      background-position: center;\n      background-repeat: no-repeat;\n      -webkit-app-region: no-drag;\n      appearance: none;\n      border: 0;\n      background-color: transparent;\n      position: absolute;\n      top: 10px;\n      right: 10px;\n      border-radius: 50px;\n      display: grid;\n      align-content: center;\n      z-index: 9;\n\n      &:before {\n        content: \"\";\n        font-family: \"codicon\";\n        color: var(--textColor);\n        font-size: 20px;\n      }\n\n      &:hover {\n        background-color: rgb(196, 43, 28);\n      }\n\n      &.back-btn {\n        left: 10px;\n        right: unset;\n      }\n\n      &.minmax-btn {\n        right: 52px;\n\n        &:before {\n          content: \"\";\n        }\n\n        &.min {\n          &:before {\n            content: \"\";\n          }\n        }\n\n        &:hover {\n          background-color: var(--selected);\n        }\n      }\n    }\n\n    .tabs {\n      height: 100%;\n      width: 100%;\n      margin: 0;\n      padding: 0;\n\n      > .col-auto {\n        width: auto;\n        overflow-x: hidden;\n        overflow-y: overlay;\n        transition: width 0.25s ease-in-out;\n      }\n\n      .tab-content {\n        margin: 0 !important;\n      }\n    }\n\n    .tab-content {\n      overflow-y: overlay;\n      height: 100%;\n      background-color: var(--panelColor2);\n      padding: 0px;\n      padding-top: 48px;\n      border-left: 1px solid var(--borderColor);\n    }\n\n    .github-themes-page,\n    .installed-themes-page {\n      .header-text {\n        font-size: 1.25em;\n      }\n    }\n\n    .tab-pane {\n      height: 100%;\n    }\n\n    .settings-tab-content {\n      height: 100%;\n    }\n\n    &.no-sidebar {\n      .gh-header {\n        > .row {\n          &:last-child {\n            padding-right: 90px;\n          }\n        }\n      }\n      .tab-content {\n        padding-top: 0px;\n      }\n\n      .tabs {\n        .nav-pills .nav-link {\n          width: 50px;\n          :nth-child(2) {\n            // font-size: 0px;\n            opacity: 0;\n          }\n        }\n        > .col-auto {\n          width: 80px;\n        }\n      }\n    }\n  }\n}\n\n#hid___BV_tab_button__ {\n  display: none;\n}\n"
  },
  {
    "path": "src/renderer/lib/fast-plural-rules.js",
    "content": "!function(n,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?e(exports):\"function\"==typeof define&&define.amd?define([\"exports\"],e):e((n=\"undefined\"!=typeof globalThis?globalThis:n||self).fastPluralRules={})}(this,(function(n){\"use strict\";var e=[function(){return 0},function(n){return 1===n?0:1},function(n){return n<=1?0:1},function(n){return n%10==1&&n%100!=11?1:n%10!=0?2:0},function(n){return 1===n||11===n?0:2===n||12===n?1:n>2&&n<20?2:3},function(n){return 1===n?0:0===n||n%100>0&&n%100<20?1:2},function(n){return n%10==1&&n%100!=11?0:n%10>=2&&(n%100<10||n%100>=20)?2:1},function(n){return n%10==1&&n%100!=11?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2},function(n){return 1===n?0:n>=2&&n<=4?1:2},function(n){return 1===n?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2},function(n){return n%100==1?0:n%100==2?1:n%100==3||n%100==4?2:3},function(n){return 1===n?0:2===n?1:n>2&&n<7?2:n>6&&n<11?3:4},function(n){return 1===n?0:2===n?1:n%100>=3&&n%100<=10?2:n%100>=11?3:0!==n?4:5},function(n){return 1===n?0:0===n||n%100>0&&n%100<11?1:n%100>10&&n%100<20?2:3},function(n){return n%10==1?0:n%10==2?1:2},function(n){return n%10==1&&n%100!=11?0:1},function(n){return n%10==1&&n%100!=11&&n%100!=71&&n%100!=91?0:n%10==2&&n%100!=12&&n%100!=72&&n%100!=92?1:n%10!=3&&n%10!=4&&n%10!=9||n%100==13||n%100==73||n%100==93||n%100==14||n%100==74||n%100==94||n%100==19||n%100==79||n%100==99?0!==n&&n%1e6==0?3:4:2},function(n){return 0!==n?1:0},function(n){return 1===n?1:2===n?2:3===n?3:6===n?4:0!==n?5:0},function(n){return 1===n?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2},function(n){return 1===n?0:2===n?1:3===n?2:3},function(n){return n%10==1&&n%100!=11?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2},function(n){return 0===n?0:1===n?1:2}],r={ach:2,af:1,ak:2,am:2,an:1,anp:1,ar:12,arn:2,as:1,ast:1,ay:0,az:1,be:7,bg:1,bn:1,bo:0,br:2,brx:1,bs:7,ca:1,cgg:0,cs:8,csb:19,cy:18,da:1,de:1,doi:1,dz:0,el:1,en:1,eo:1,es:1,\"es-ar\":1,et:1,eu:1,fa:2,ff:1,fi:1,fil:2,fo:1,fr:2,fur:1,fy:1,ga:11,gd:4,gl:1,gu:1,gun:2,ha:1,he:1,hi:1,hne:1,hr:7,hu:1,hy:1,ia:1,id:0,is:15,it:1,ja:0,jbo:0,jv:17,ka:0,kk:1,kl:1,km:0,kn:1,ko:0,ku:1,kw:20,ky:1,lb:1,ln:2,lo:0,lt:6,lv:3,mai:1,me:21,mfe:2,mg:2,mi:2,mk:15,ml:1,mn:1,mni:1,mnk:22,mr:1,ms:0,mt:13,my:0,nah:1,nap:1,nb:1,ne:1,nl:1,nn:1,no:1,nso:1,oc:2,or:1,pa:1,pap:1,pl:9,pms:1,ps:1,pt:1,\"pt-br\":2,rm:1,ro:5,ru:7,rw:1,sah:0,sat:1,sco:1,sd:1,se:1,si:1,sk:8,sl:10,so:1,son:1,sq:1,sr:7,su:0,sv:1,sw:1,ta:1,te:1,tg:2,th:0,ti:2,tk:1,tr:2,tt:0,ug:0,uk:7,ur:1,uz:2,vi:0,wa:2,wo:0,yo:1,\"zh-cn\":0,\"zh-tw\":2},o=[[\"other\"],[\"one\",\"other\"],[\"one\",\"other\"],[\"zero\",\"one\",\"other\"],[\"one\",\"two\",\"few\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"two\",\"few\",\"other\"],[\"one\",\"two\",\"few\",\"many\",\"other\"],[\"one\",\"two\",\"few\",\"many\",\"other\",\"zero\"],[\"one\",\"few\",\"many\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"other\"],[\"one\",\"two\",\"few\",\"many\",\"other\"],[\"zero\",\"other\"],[\"zero\",\"one\",\"two\",\"few\",\"many\",\"other\"],[\"one\",\"few\",\"other\"],[\"one\",\"two\",\"few\",\"other\"],[\"one\",\"few\",\"other\"],[\"zero\",\"one\",\"other\"]];function t(n){n=function(n){return n.toLowerCase().replace(\"_\",\"-\")}(n);var e=r[n];if(void 0===e){var o=function(n){var e=n.indexOf(\"-\");return e>0?n.substr(0,e):n}(n);e=r[o]}if(void 0===e)throw new Error('Unrecognized locale: \"'+n+'\".');return e}function u(n,e){var r=o[e];return function(e){return r[n(e)]}}function a(n){var r=t(n);return e[r]}function i(n){var r=e[n];if(void 0===r)throw new Error('Invalid index: \"'+n+'\".');return r}function f(n){var r=t(n);return u(e[r],r)}function l(n){if(void 0===e[n])throw new Error('Invalid index: \"'+n+'\".');return u(e[n],n)}n.getPluralFormForCardinalByIndex=function(n,e){return i(n)(e)},n.getPluralFormForCardinalByLocale=function(n,e){return a(n)(e)},n.getPluralFormNameForCardinalByIndex=function(n,e){return l(n)(e)},n.getPluralFormNameForCardinalByLocale=function(n,e){return f(n)(e)},n.getPluralRuleForCardinalsByIndex=i,n.getPluralRuleForCardinalsByLocale=a,n.getPluralRuleForNamedFormsForCardinalsByIndex=l,n.getPluralRuleForNamedFormsForCardinalsByLocale=f,Object.defineProperty(n,\"__esModule\",{value:!0})}));"
  },
  {
    "path": "src/renderer/lib/less.js",
    "content": "/**\n * Less - Leaner CSS v4.1.1\n * http://lesscss.org\n *\n * Copyright (c) 2009-2021, Alexis Sellier <self@cloudhead.net>\n * Licensed under the Apache-2.0 License.\n *\n * @license Apache-2.0\n */\n!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).less=t()}(this,(function(){\"use strict\";function e(e){return e.replace(/^[a-z-]+:\\/+?[^\\/]+/,\"\").replace(/[\\?\\&]livereload=\\w+/,\"\").replace(/^\\//,\"\").replace(/\\.[a-zA-Z]+$/,\"\").replace(/[^\\.\\w-]+/g,\"-\").replace(/\\./g,\":\")}function t(e,t){for(var i in t.dataset)if(t.dataset.hasOwnProperty(i))if(\"env\"===i||\"dumpLineNumbers\"===i||\"rootpath\"===i||\"errorReporting\"===i)e[i]=t.dataset[i];else try{e[i]=JSON.parse(t.dataset[i])}catch(e){}}var i=function(t,i,n){var r=n.href||\"\",s=\"less:\"+(n.title||e(r)),o=t.getElementById(s),a=!1,l=t.createElement(\"style\");l.setAttribute(\"type\",\"text/css\"),n.media&&l.setAttribute(\"media\",n.media),l.id=s,l.styleSheet||(l.appendChild(t.createTextNode(i)),a=null!==o&&o.childNodes.length>0&&l.childNodes.length>0&&o.firstChild.nodeValue===l.firstChild.nodeValue);var u=t.getElementsByTagName(\"head\")[0];if(null===o||!1===a){var c=n&&n.nextSibling||null;c?c.parentNode.insertBefore(l,c):u.appendChild(l)}if(o&&!1===a&&o.parentNode.removeChild(o),l.styleSheet)try{l.styleSheet.cssText=i}catch(e){throw new Error(\"Couldn't reassign styleSheet.cssText.\")}},n=function(e){var t,i=e.document;return i.currentScript||(t=i.getElementsByTagName(\"script\"))[t.length-1]},r={error:function(e){this._fireEvent(\"error\",e)},warn:function(e){this._fireEvent(\"warn\",e)},info:function(e){this._fireEvent(\"info\",e)},debug:function(e){this._fireEvent(\"debug\",e)},addListener:function(e){this._listeners.push(e)},removeListener:function(e){for(var t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)},_fireEvent:function(e,t){for(var i=0;i<this._listeners.length;i++){var n=this._listeners[i][e];n&&n(t)}},_listeners:[]},s=function(){function e(e,t){this.fileManagers=t||[],e=e||{};for(var i=[],n=i.concat([\"encodeBase64\",\"mimeLookup\",\"charsetLookup\",\"getSourceMapGenerator\"]),r=0;r<n.length;r++){var s=n[r],o=e[s];o?this[s]=o.bind(e):r<i.length&&this.warn(\"missing required function in environment - \"+s)}}return e.prototype.getFileManager=function(e,t,i,n,s){e||r.warn(\"getFileManager called with no filename.. Please report this issue. continuing.\"),null==t&&r.warn(\"getFileManager called with null directory.. Please report this issue. continuing.\");var o=this.fileManagers;i.pluginManager&&(o=[].concat(o).concat(i.pluginManager.getFileManagers()));for(var a=o.length-1;a>=0;a--){var l=o[a];if(l[s?\"supportsSync\":\"supports\"](e,t,i,n))return l}return null},e.prototype.addFileManager=function(e){this.fileManagers.push(e)},e.prototype.clearFileManagers=function(){this.fileManagers=[]},e}(),o={aliceblue:\"#f0f8ff\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",azure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\",blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",brown:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#6495ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray:\"#a9a9a9\",darkgrey:\"#a9a9a9\",darkgreen:\"#006400\",darkkhaki:\"#bdb76b\",darkmagenta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray:\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkviolet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff\",gainsboro:\"#dcdcdc\",ghostwhite:\"#f8f8ff\",gold:\"#ffd700\",goldenrod:\"#daa520\",gray:\"#808080\",grey:\"#808080\",green:\"#008000\",greenyellow:\"#adff2f\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianred:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",lavender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lemonchiffon:\"#fffacd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",lightcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3\",lightgrey:\"#d3d3d3\",lightgreen:\"#90ee90\",lightpink:\"#ffb6c1\",lightsalmon:\"#ffa07a\",lightseagreen:\"#20b2aa\",lightskyblue:\"#87cefa\",lightslategray:\"#778899\",lightslategrey:\"#778899\",lightsteelblue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediumaquamarine:\"#66cdaa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",mediumpurple:\"#9370d8\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7b68ee\",mediumspringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediumvioletred:\"#c71585\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",mistyrose:\"#ffe4e1\",moccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",navy:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23\",orange:\"#ffa500\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegoldenrod:\"#eee8aa\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palevioletred:\"#d87093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",purple:\"#800080\",rebeccapurple:\"#663399\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#4169e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\",seagreen:\"#2e8b57\",seashell:\"#fff5ee\",sienna:\"#a0522d\",silver:\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#708090\",slategrey:\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",steelblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\",tomato:\"#ff6347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yellowgreen:\"#9acd32\"},a={length:{m:1,cm:.01,mm:.001,in:.0254,px:.0254/96,pt:.0254/72,pc:.0254/72*12},duration:{s:1,ms:.001},angle:{rad:1/(2*Math.PI),deg:1/360,grad:1/400,turn:1}},l={colors:o,unitConversions:a},u=function(){function e(){this.parent=null,this.visibilityBlocks=void 0,this.nodeVisible=void 0,this.rootNode=null,this.parsed=null;var e=this;Object.defineProperty(this,\"currentFileInfo\",{get:function(){return e.fileInfo()}}),Object.defineProperty(this,\"index\",{get:function(){return e.getIndex()}})}return e.prototype.setParent=function(t,i){function n(t){t&&t instanceof e&&(t.parent=i)}Array.isArray(t)?t.forEach(n):n(t)},e.prototype.getIndex=function(){return this._index||this.parent&&this.parent.getIndex()||0},e.prototype.fileInfo=function(){return this._fileInfo||this.parent&&this.parent.fileInfo()||{}},e.prototype.isRulesetLike=function(){return!1},e.prototype.toCSS=function(e){var t=[];return this.genCSS(e,{add:function(e,i,n){t.push(e)},isEmpty:function(){return 0===t.length}}),t.join(\"\")},e.prototype.genCSS=function(e,t){t.add(this.value)},e.prototype.accept=function(e){this.value=e.visit(this.value)},e.prototype.eval=function(){return this},e.prototype._operate=function(e,t,i,n){switch(t){case\"+\":return i+n;case\"-\":return i-n;case\"*\":return i*n;case\"/\":return i/n}},e.prototype.fround=function(e,t){var i=e&&e.numPrecision;return i?Number((t+2e-16).toFixed(i)):t},e.compare=function(t,i){if(t.compare&&\"Quoted\"!==i.type&&\"Anonymous\"!==i.type)return t.compare(i);if(i.compare)return-i.compare(t);if(t.type===i.type){if(t=t.value,i=i.value,!Array.isArray(t))return t===i?0:void 0;if(t.length===i.length){for(var n=0;n<t.length;n++)if(0!==e.compare(t[n],i[n]))return;return 0}}},e.numericCompare=function(e,t){return e<t?-1:e===t?0:e>t?1:void 0},e.prototype.blocksVisibility=function(){return null==this.visibilityBlocks&&(this.visibilityBlocks=0),0!==this.visibilityBlocks},e.prototype.addVisibilityBlock=function(){null==this.visibilityBlocks&&(this.visibilityBlocks=0),this.visibilityBlocks=this.visibilityBlocks+1},e.prototype.removeVisibilityBlock=function(){null==this.visibilityBlocks&&(this.visibilityBlocks=0),this.visibilityBlocks=this.visibilityBlocks-1},e.prototype.ensureVisibility=function(){this.nodeVisible=!0},e.prototype.ensureInvisibility=function(){this.nodeVisible=!1},e.prototype.isVisible=function(){return this.nodeVisible},e.prototype.visibilityInfo=function(){return{visibilityBlocks:this.visibilityBlocks,nodeVisible:this.nodeVisible}},e.prototype.copyVisibilityInfo=function(e){e&&(this.visibilityBlocks=e.visibilityBlocks,this.nodeVisible=e.nodeVisible)},e}(),c=function(e,t,i){var n=this;Array.isArray(e)?this.rgb=e:e.length>=6?(this.rgb=[],e.match(/.{2}/g).map((function(e,t){t<3?n.rgb.push(parseInt(e,16)):n.alpha=parseInt(e,16)/255}))):(this.rgb=[],e.split(\"\").map((function(e,t){t<3?n.rgb.push(parseInt(e+e,16)):n.alpha=parseInt(e+e,16)/255}))),this.alpha=this.alpha||(\"number\"==typeof t?t:1),void 0!==i&&(this.value=i)};function h(e,t){return Math.min(Math.max(e,0),t)}function f(e){return\"#\"+e.map((function(e){return((e=h(Math.round(e),255))<16?\"0\":\"\")+e.toString(16)})).join(\"\")}c.prototype=Object.assign(new u,{type:\"Color\",luma:function(){var e=this.rgb[0]/255,t=this.rgb[1]/255,i=this.rgb[2]/255;return.2126*(e=e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t=t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(i=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))},genCSS:function(e,t){t.add(this.toCSS(e))},toCSS:function(e,t){var i,n,r,s=e&&e.compress&&!t,o=[];if(n=this.fround(e,this.alpha),this.value)if(0===this.value.indexOf(\"rgb\"))n<1&&(r=\"rgba\");else{if(0!==this.value.indexOf(\"hsl\"))return this.value;r=n<1?\"hsla\":\"hsl\"}else n<1&&(r=\"rgba\");switch(r){case\"rgba\":o=this.rgb.map((function(e){return h(Math.round(e),255)})).concat(h(n,1));break;case\"hsla\":o.push(h(n,1));case\"hsl\":i=this.toHSL(),o=[this.fround(e,i.h),this.fround(e,100*i.s)+\"%\",this.fround(e,100*i.l)+\"%\"].concat(o)}if(r)return r+\"(\"+o.join(\",\"+(s?\"\":\" \"))+\")\";if(i=this.toRGB(),s){var a=i.split(\"\");a[1]===a[2]&&a[3]===a[4]&&a[5]===a[6]&&(i=\"#\"+a[1]+a[3]+a[5])}return i},operate:function(e,t,i){for(var n=new Array(3),r=this.alpha*(1-i.alpha)+i.alpha,s=0;s<3;s++)n[s]=this._operate(e,t,this.rgb[s],i.rgb[s]);return new c(n,r)},toRGB:function(){return f(this.rgb)},toHSL:function(){var e,t,i=this.rgb[0]/255,n=this.rgb[1]/255,r=this.rgb[2]/255,s=this.alpha,o=Math.max(i,n,r),a=Math.min(i,n,r),l=(o+a)/2,u=o-a;if(o===a)e=t=0;else{switch(t=l>.5?u/(2-o-a):u/(o+a),o){case i:e=(n-r)/u+(n<r?6:0);break;case n:e=(r-i)/u+2;break;case r:e=(i-n)/u+4}e/=6}return{h:360*e,s:t,l:l,a:s}},toHSV:function(){var e,t,i=this.rgb[0]/255,n=this.rgb[1]/255,r=this.rgb[2]/255,s=this.alpha,o=Math.max(i,n,r),a=Math.min(i,n,r),l=o,u=o-a;if(t=0===o?0:u/o,o===a)e=0;else{switch(o){case i:e=(n-r)/u+(n<r?6:0);break;case n:e=(r-i)/u+2;break;case r:e=(i-n)/u+4}e/=6}return{h:360*e,s:t,v:l,a:s}},toARGB:function(){return f([255*this.alpha].concat(this.rgb))},compare:function(e){return e.rgb&&e.rgb[0]===this.rgb[0]&&e.rgb[1]===this.rgb[1]&&e.rgb[2]===this.rgb[2]&&e.alpha===this.alpha?0:void 0}}),c.fromKeyword=function(e){var t,i=e.toLowerCase();if(o.hasOwnProperty(i)?t=new c(o[i].slice(1)):\"transparent\"===i&&(t=new c([0,0,0],0)),t)return t.value=e,t};var p=function(e){this.value=e};p.prototype=Object.assign(new u,{type:\"Paren\",genCSS:function(e,t){t.add(\"(\"),this.value.genCSS(e,t),t.add(\")\")},eval:function(e){return new p(this.value.eval(e))}});var v={\"\":!0,\" \":!0,\"|\":!0},d=function(e){\" \"===e?(this.value=\" \",this.emptyOrWhitespace=!0):(this.value=e?e.trim():\"\",this.emptyOrWhitespace=\"\"===this.value)};d.prototype=Object.assign(new u,{type:\"Combinator\",genCSS:function(e,t){var i=e.compress||v[this.value]?\"\":\" \";t.add(i+this.value+i)}});var m=function(e,t,i,n,r,s){this.combinator=e instanceof d?e:new d(e),this.value=\"string\"==typeof t?t.trim():t||\"\",this.isVariable=i,this._index=n,this._fileInfo=r,this.copyVisibilityInfo(s),this.setParent(this.combinator,this)};m.prototype=Object.assign(new u,{type:\"Element\",accept:function(e){var t=this.value;this.combinator=e.visit(this.combinator),\"object\"==typeof t&&(this.value=e.visit(t))},eval:function(e){return new m(this.combinator,this.value.eval?this.value.eval(e):this.value,this.isVariable,this.getIndex(),this.fileInfo(),this.visibilityInfo())},clone:function(){return new m(this.combinator,this.value,this.isVariable,this.getIndex(),this.fileInfo(),this.visibilityInfo())},genCSS:function(e,t){t.add(this.toCSS(e),this.fileInfo(),this.getIndex())},toCSS:function(e){e=e||{};var t=this.value,i=e.firstSelector;return t instanceof p&&(e.firstSelector=!0),t=t.toCSS?t.toCSS(e):t,e.firstSelector=i,\"\"===t&&\"&\"===this.combinator.value.charAt(0)?\"\":this.combinator.toCSS(e)+t}});var g={ALWAYS:0,PARENS_DIVISION:1,PARENS:2},y=0,b=1,w=2;function x(e){return Object.prototype.toString.call(e).slice(8,-1)}function S(e){return\"Array\"===x(e)}function I(e,t){return void 0===t&&(t={}),S(e)?e.map((function(e){return I(e,t)})):\"Object\"!==x(i=e)||i.constructor!==Object||Object.getPrototypeOf(i)!==Object.prototype?e:function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var n=Array(e),r=0;for(t=0;t<i;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n}(Object.getOwnPropertyNames(e),Object.getOwnPropertySymbols(e)).reduce((function(i,n){return S(t.props)&&!t.props.includes(n)||function(e,t,i,n,r){var s={}.propertyIsEnumerable.call(n,t)?\"enumerable\":\"nonenumerable\";\"enumerable\"===s&&(e[t]=i),r&&\"nonenumerable\"===s&&Object.defineProperty(e,t,{value:i,enumerable:!1,writable:!0,configurable:!0})}(i,n,I(e[n],t),e,t.nonenumerable),i}),{});var i}function C(e,t){for(var i=e+1,n=null,r=-1;--i>=0&&\"\\n\"!==t.charAt(i);)r++;return\"number\"==typeof e&&(n=(t.slice(0,e).match(/\\n/g)||\"\").length),{line:n,column:r}}function k(e){var t,i=e.length,n=new Array(i);for(t=0;t<i;t++)n[t]=e[t];return n}function _(e){var t={};for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}function A(e,t){var i=t||{};if(!t._defaults){i={};var n=I(e);i._defaults=n;var r=t?I(t):{};Object.assign(i,n,r)}return i}function M(e,t){if(t&&t._defaults)return t;var i=A(e,t);if(i.strictMath&&(i.math=g.PARENS),i.relativeUrls&&(i.rewriteUrls=w),\"string\"==typeof i.math)switch(i.math.toLowerCase()){case\"always\":i.math=g.ALWAYS;break;case\"parens-division\":i.math=g.PARENS_DIVISION;break;case\"strict\":case\"parens\":i.math=g.PARENS;break;default:i.math=g.PARENS}if(\"string\"==typeof i.rewriteUrls)switch(i.rewriteUrls.toLowerCase()){case\"off\":i.rewriteUrls=y;break;case\"local\":i.rewriteUrls=b;break;case\"all\":i.rewriteUrls=w}return i}function E(e,t){void 0===t&&(t=[]);for(var i=0,n=e.length;i<n;i++){var r=e[i];Array.isArray(r)?E(r,t):void 0!==r&&t.push(r)}return t}var P=Object.freeze({__proto__:null,getLocation:C,copyArray:k,clone:_,defaults:A,copyOptions:M,merge:function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i]);return e},flattenArray:E}),R=/(<anonymous>|Function):(\\d+):(\\d+)/,O=function(e,t,i){Error.call(this);var n=e.filename||i;if(this.message=e.message,this.stack=e.stack,t&&n){var r=t.contents[n],s=C(e.index,r),o=s.line,a=s.column,l=e.call&&C(e.call,r).line,u=r?r.split(\"\\n\"):\"\";if(this.type=e.type||\"Syntax\",this.filename=n,this.index=e.index,this.line=\"number\"==typeof o?o+1:null,this.column=a,!this.line&&this.stack){var c=this.stack.match(R),h=new Function(\"a\",\"throw new Error()\"),f=0;try{h()}catch(e){var p=e.stack.match(R);f=1-(o=parseInt(p[2]))}c&&(c[2]&&(this.line=parseInt(c[2])+f),c[3]&&(this.column=parseInt(c[3])))}this.callLine=l+1,this.callExtract=u[l],this.extract=[u[this.line-2],u[this.line-1],u[this.line]]}};if(void 0===Object.create){var V=function(){};V.prototype=Error.prototype,O.prototype=new V}else O.prototype=Object.create(Error.prototype);O.prototype.constructor=O,O.prototype.toString=function(e){e=e||{};var t=\"\",i=this.extract||[],n=[],r=function(e){return e};if(e.stylize){var s=typeof e.stylize;if(\"function\"!==s)throw Error(\"options.stylize should be a function, got a \"+s+\"!\");r=e.stylize}if(null!==this.line){if(\"string\"==typeof i[0]&&n.push(r(this.line-1+\" \"+i[0],\"grey\")),\"string\"==typeof i[1]){var o=this.line+\" \";i[1]&&(o+=i[1].slice(0,this.column)+r(r(r(i[1].substr(this.column,1),\"bold\")+i[1].slice(this.column+1),\"red\"),\"inverse\")),n.push(o)}\"string\"==typeof i[2]&&n.push(r(this.line+1+\" \"+i[2],\"grey\")),n=n.join(\"\\n\")+r(\"\",\"reset\")+\"\\n\"}return t+=r(this.type+\"Error: \"+this.message,\"red\"),this.filename&&(t+=r(\" in \",\"red\")+this.filename),this.line&&(t+=r(\" on line \"+this.line+\", column \"+(this.column+1)+\":\",\"grey\")),t+=\"\\n\"+n,this.callLine&&(t+=r(\"from \",\"red\")+(this.filename||\"\")+\"/n\",t+=r(this.callLine,\"grey\")+\" \"+this.callExtract+\"/n\"),t};var F=function(e,t,i,n,r,s){this.extendList=t,this.condition=i,this.evaldCondition=!i,this._index=n,this._fileInfo=r,this.elements=this.getElements(e),this.mixinElements_=void 0,this.copyVisibilityInfo(s),this.setParent(this.elements,this)};F.prototype=Object.assign(new u,{type:\"Selector\",accept:function(e){this.elements&&(this.elements=e.visitArray(this.elements)),this.extendList&&(this.extendList=e.visitArray(this.extendList)),this.condition&&(this.condition=e.visit(this.condition))},createDerived:function(e,t,i){e=this.getElements(e);var n=new F(e,t||this.extendList,null,this.getIndex(),this.fileInfo(),this.visibilityInfo());return n.evaldCondition=null!=i?i:this.evaldCondition,n.mediaEmpty=this.mediaEmpty,n},getElements:function(e){return e?(\"string\"==typeof e&&this.parse.parseNode(e,[\"selector\"],this._index,this._fileInfo,(function(t,i){if(t)throw new O({index:t.index,message:t.message},this.parse.imports,this._fileInfo.filename);e=i[0].elements})),e):[new m(\"\",\"&\",!1,this._index,this._fileInfo)]},createEmptySelectors:function(){var e=new m(\"\",\"&\",!1,this._index,this._fileInfo),t=[new F([e],null,null,this._index,this._fileInfo)];return t[0].mediaEmpty=!0,t},match:function(e){var t,i,n=this.elements,r=n.length;if(0===(t=(e=e.mixinElements()).length)||r<t)return 0;for(i=0;i<t;i++)if(n[i].value!==e[i])return 0;return t},mixinElements:function(){if(this.mixinElements_)return this.mixinElements_;var e=this.elements.map((function(e){return e.combinator.value+(e.value.value||e.value)})).join(\"\").match(/[,&#\\*\\.\\w-]([\\w-]|(\\\\.))*/g);return e?\"&\"===e[0]&&e.shift():e=[],this.mixinElements_=e},isJustParentSelector:function(){return!this.mediaEmpty&&1===this.elements.length&&\"&\"===this.elements[0].value&&(\" \"===this.elements[0].combinator.value||\"\"===this.elements[0].combinator.value)},eval:function(e){var t=this.condition&&this.condition.eval(e),i=this.elements,n=this.extendList;return i=i&&i.map((function(t){return t.eval(e)})),n=n&&n.map((function(t){return t.eval(e)})),this.createDerived(i,n,t)},genCSS:function(e,t){var i;for(e&&e.firstSelector||\"\"!==this.elements[0].combinator.value||t.add(\" \",this.fileInfo(),this.getIndex()),i=0;i<this.elements.length;i++)this.elements[i].genCSS(e,t)},getIsOutput:function(){return this.evaldCondition}});var $=function(e){if(!e)throw new Error(\"Value requires an array argument\");Array.isArray(e)?this.value=e:this.value=[e]};$.prototype=Object.assign(new u,{type:\"Value\",accept:function(e){this.value&&(this.value=e.visitArray(this.value))},eval:function(e){return 1===this.value.length?this.value[0].eval(e):new $(this.value.map((function(t){return t.eval(e)})))},genCSS:function(e,t){var i;for(i=0;i<this.value.length;i++)this.value[i].genCSS(e,t),i+1<this.value.length&&t.add(e&&e.compress?\",\":\", \")}});var L=function(e){this.value=e};L.prototype=Object.assign(new u,{type:\"Keyword\",genCSS:function(e,t){if(\"%\"===this.value)throw{type:\"Syntax\",message:\"Invalid % without number\"};t.add(this.value)}}),L.True=new L(\"true\"),L.False=new L(\"false\");var j=function(e,t,i,n,r,s){this.value=e,this._index=t,this._fileInfo=i,this.mapLines=n,this.rulesetLike=void 0!==r&&r,this.allowRoot=!0,this.copyVisibilityInfo(s)};j.prototype=Object.assign(new u,{type:\"Anonymous\",eval:function(){return new j(this.value,this._index,this._fileInfo,this.mapLines,this.rulesetLike,this.visibilityInfo())},compare:function(e){return e.toCSS&&this.toCSS()===e.toCSS()?0:void 0},isRulesetLike:function(){return this.rulesetLike},genCSS:function(e,t){this.nodeVisible=Boolean(this.value),this.nodeVisible&&t.add(this.value,this._fileInfo,this._index,this.mapLines)}});var N=g;var D=function(e,t,i,n,r,s,o,a){this.name=e,this.value=t instanceof u?t:new $([t?new j(t):null]),this.important=i?\" \"+i.trim():\"\",this.merge=n,this._index=r,this._fileInfo=s,this.inline=o||!1,this.variable=void 0!==a?a:e.charAt&&\"@\"===e.charAt(0),this.allowRoot=!0,this.setParent(this.value,this)};D.prototype=Object.assign(new u,{type:\"Declaration\",genCSS:function(e,t){t.add(this.name+(e.compress?\":\":\": \"),this.fileInfo(),this.getIndex());try{this.value.genCSS(e,t)}catch(e){throw e.index=this._index,e.filename=this._fileInfo.filename,e}t.add(this.important+(this.inline||e.lastRule&&e.compress?\"\":\";\"),this._fileInfo,this._index)},eval:function(e){var t,i,n=!1,r=this.name,s=this.variable;\"string\"!=typeof r&&(r=1===r.length&&r[0]instanceof L?r[0].value:function(e,t){var i,n=\"\",r=t.length,s={add:function(e){n+=e}};for(i=0;i<r;i++)t[i].eval(e).genCSS(e,s);return n}(e,r),s=!1),\"font\"===r&&e.math===N.ALWAYS&&(n=!0,t=e.math,e.math=N.PARENS_DIVISION);try{if(e.importantScope.push({}),i=this.value.eval(e),!this.variable&&\"DetachedRuleset\"===i.type)throw{message:\"Rulesets cannot be evaluated on a property.\",index:this.getIndex(),filename:this.fileInfo().filename};var o=this.important,a=e.importantScope.pop();return!o&&a.important&&(o=a.important),new D(r,i,o,this.merge,this.getIndex(),this.fileInfo(),this.inline,s)}catch(e){throw\"number\"!=typeof e.index&&(e.index=this.getIndex(),e.filename=this.fileInfo().filename),e}finally{n&&(e.math=t)}},makeImportant:function(){return new D(this.name,this.value,\"!important\",this.merge,this.getIndex(),this.fileInfo(),this.inline)}});var B=function(){function e(t,i,n){var r=\"\";if(t.dumpLineNumbers&&!t.compress)switch(t.dumpLineNumbers){case\"comments\":r=e.asComment(i);break;case\"mediaquery\":r=e.asMediaQuery(i);break;case\"all\":r=e.asComment(i)+(n||\"\")+e.asMediaQuery(i)}return r}return e.asComment=function(e){return\"/* line \"+e.debugInfo.lineNumber+\", \"+e.debugInfo.fileName+\" */\\n\"},e.asMediaQuery=function(e){var t=e.debugInfo.fileName;return/^[a-z]+:\\/\\//i.test(t)||(t=\"file://\"+t),\"@media -sass-debug-info{filename{font-family:\"+t.replace(/([.:\\/\\\\])/g,(function(e){return\"\\\\\"==e&&(e=\"/\"),\"\\\\\"+e}))+\"}line{font-family:\\\\00003\"+e.debugInfo.lineNumber+\"}}\\n\"},e}(),U=function(e,t,i,n){this.value=e,this.isLineComment=t,this._index=i,this._fileInfo=n,this.allowRoot=!0};U.prototype=Object.assign(new u,{type:\"Comment\",genCSS:function(e,t){this.debugInfo&&t.add(B(e,this),this.fileInfo(),this.getIndex()),t.add(this.value)},isSilent:function(e){var t=e.compress&&\"!\"!==this.value[2];return this.isLineComment||t}});var q={},T=function(e,t,i){if(e)for(var n=0;n<i.length;n++)e.hasOwnProperty(i[n])&&(t[i[n]]=e[i[n]])},z=[\"paths\",\"rewriteUrls\",\"rootpath\",\"strictImports\",\"insecure\",\"dumpLineNumbers\",\"compress\",\"syncImport\",\"chunkInput\",\"mime\",\"useFileCache\",\"processImports\",\"pluginManager\"];q.Parse=function(e){T(e,this,z),\"string\"==typeof this.paths&&(this.paths=[this.paths])};var G=[\"paths\",\"compress\",\"math\",\"strictUnits\",\"sourceMap\",\"importMultiple\",\"urlArgs\",\"javascriptEnabled\",\"pluginManager\",\"importantScope\",\"rewriteUrls\"];function W(e){return!/^(?:[a-z-]+:|\\/|#)/i.test(e)}function J(e){return\".\"===e.charAt(0)}q.Eval=function(e,t){T(e,this,G),\"string\"==typeof this.paths&&(this.paths=[this.paths]),this.frames=t||[],this.importantScope=this.importantScope||[]},q.Eval.prototype.enterCalc=function(){this.calcStack||(this.calcStack=[]),this.calcStack.push(!0),this.inCalc=!0},q.Eval.prototype.exitCalc=function(){this.calcStack.pop(),this.calcStack.length||(this.inCalc=!1)},q.Eval.prototype.inParenthesis=function(){this.parensStack||(this.parensStack=[]),this.parensStack.push(!0)},q.Eval.prototype.outOfParenthesis=function(){this.parensStack.pop()},q.Eval.prototype.inCalc=!1,q.Eval.prototype.mathOn=!0,q.Eval.prototype.isMathOn=function(e){return!!this.mathOn&&(!!(\"/\"!==e||this.math===g.ALWAYS||this.parensStack&&this.parensStack.length)&&(!(this.math>g.PARENS_DIVISION)||this.parensStack&&this.parensStack.length))},q.Eval.prototype.pathRequiresRewrite=function(e){return(this.rewriteUrls===b?J:W)(e)},q.Eval.prototype.rewritePath=function(e,t){var i;return t=t||\"\",i=this.normalizePath(t+e),J(e)&&W(t)&&!1===J(i)&&(i=\"./\"+i),i},q.Eval.prototype.normalizePath=function(e){var t,i=e.split(\"/\").reverse();for(e=[];0!==i.length;)switch(t=i.pop()){case\".\":break;case\"..\":0===e.length||\"..\"===e[e.length-1]?e.push(t):e.pop();break;default:e.push(t)}return e.join(\"/\")};var H=function e(t){return{_data:{},add:function(e,t){e=e.toLowerCase(),this._data.hasOwnProperty(e),this._data[e]=t},addMultiple:function(e){var t=this;Object.keys(e).forEach((function(i){t.add(i,e[i])}))},get:function(e){return this._data[e]||t&&t.get(e)},getLocalFunctions:function(){return this._data},inherit:function(){return e(this)},create:function(t){return e(t)}}}(null),Q={eval:function(){var e=this.value_,t=this.error_;if(t)throw t;if(null!=e)return e?L.True:L.False},value:function(e){this.value_=e},error:function(e){this.error_=e},reset:function(){this.value_=this.error_=null}},K=function(e,t,i,n){this.selectors=e,this.rules=t,this._lookups={},this._variables=null,this._properties=null,this.strictImports=i,this.copyVisibilityInfo(n),this.allowRoot=!0,this.setParent(this.selectors,this),this.setParent(this.rules,this)};K.prototype=Object.assign(new u,{type:\"Ruleset\",isRuleset:!0,isRulesetLike:function(){return!0},accept:function(e){this.paths?this.paths=e.visitArray(this.paths,!0):this.selectors&&(this.selectors=e.visitArray(this.selectors)),this.rules&&this.rules.length&&(this.rules=e.visitArray(this.rules))},eval:function(e){var t,i,n,r,s,o=!1;if(this.selectors&&(i=this.selectors.length)){for(t=new Array(i),Q.error({type:\"Syntax\",message:\"it is currently only allowed in parametric mixin guards,\"}),r=0;r<i;r++){n=this.selectors[r].eval(e);for(var a=0;a<n.elements.length;a++)if(n.elements[a].isVariable){s=!0;break}t[r]=n,n.evaldCondition&&(o=!0)}if(s){var l=new Array(i);for(r=0;r<i;r++)n=t[r],l[r]=n.toCSS(e);this.parse.parseNode(l.join(\",\"),[\"selectors\"],t[0].getIndex(),t[0].fileInfo(),(function(e,i){i&&(t=E(i))}))}Q.reset()}else o=!0;var c,h,f=this.rules?k(this.rules):null,p=new K(t,f,this.strictImports,this.visibilityInfo());p.originalRuleset=this,p.root=this.root,p.firstRoot=this.firstRoot,p.allowImports=this.allowImports,this.debugInfo&&(p.debugInfo=this.debugInfo),o||(f.length=0),p.functionRegistry=function(e){for(var t,i=0,n=e.length;i!==n;++i)if(t=e[i].functionRegistry)return t;return H}(e.frames).inherit();var v=e.frames;v.unshift(p);var d=e.selectors;d||(e.selectors=d=[]),d.unshift(this.selectors),(p.root||p.allowImports||!p.strictImports)&&p.evalImports(e);var m=p.rules;for(r=0;c=m[r];r++)c.evalFirst&&(m[r]=c.eval(e));var g=e.mediaBlocks&&e.mediaBlocks.length||0;for(r=0;c=m[r];r++)\"MixinCall\"===c.type?(f=c.eval(e).filter((function(e){return!(e instanceof D&&e.variable)||!p.variable(e.name)})),m.splice.apply(m,[r,1].concat(f)),r+=f.length-1,p.resetCache()):\"VariableCall\"===c.type&&(f=c.eval(e).rules.filter((function(e){return!(e instanceof D&&e.variable)})),m.splice.apply(m,[r,1].concat(f)),r+=f.length-1,p.resetCache());for(r=0;c=m[r];r++)c.evalFirst||(m[r]=c=c.eval?c.eval(e):c);for(r=0;c=m[r];r++)if(c instanceof K&&c.selectors&&1===c.selectors.length&&c.selectors[0]&&c.selectors[0].isJustParentSelector()){m.splice(r--,1);for(a=0;h=c.rules[a];a++)h instanceof u&&(h.copyVisibilityInfo(c.visibilityInfo()),h instanceof D&&h.variable||m.splice(++r,0,h))}if(v.shift(),d.shift(),e.mediaBlocks)for(r=g;r<e.mediaBlocks.length;r++)e.mediaBlocks[r].bubbleSelectors(t);return p},evalImports:function(e){var t,i,n=this.rules;if(n)for(t=0;t<n.length;t++)\"Import\"===n[t].type&&((i=n[t].eval(e))&&(i.length||0===i.length)?(n.splice.apply(n,[t,1].concat(i)),t+=i.length-1):n.splice(t,1,i),this.resetCache())},makeImportant:function(){return new K(this.selectors,this.rules.map((function(e){return e.makeImportant?e.makeImportant():e})),this.strictImports,this.visibilityInfo())},matchArgs:function(e){return!e||0===e.length},matchCondition:function(e,t){var i=this.selectors[this.selectors.length-1];return!!i.evaldCondition&&!(i.condition&&!i.condition.eval(new q.Eval(t,t.frames)))},resetCache:function(){this._rulesets=null,this._variables=null,this._properties=null,this._lookups={}},variables:function(){return this._variables||(this._variables=this.rules?this.rules.reduce((function(e,t){if(t instanceof D&&!0===t.variable&&(e[t.name]=t),\"Import\"===t.type&&t.root&&t.root.variables){var i=t.root.variables();for(var n in i)i.hasOwnProperty(n)&&(e[n]=t.root.variable(n))}return e}),{}):{}),this._variables},properties:function(){return this._properties||(this._properties=this.rules?this.rules.reduce((function(e,t){if(t instanceof D&&!0!==t.variable){var i=1===t.name.length&&t.name[0]instanceof L?t.name[0].value:t.name;e[\"$\"+i]?e[\"$\"+i].push(t):e[\"$\"+i]=[t]}return e}),{}):{}),this._properties},variable:function(e){var t=this.variables()[e];if(t)return this.parseValue(t)},property:function(e){var t=this.properties()[e];if(t)return this.parseValue(t)},lastDeclaration:function(){for(var e=this.rules.length;e>0;e--){var t=this.rules[e-1];if(t instanceof D)return this.parseValue(t)}},parseValue:function(e){var t=this;function i(e){return e.value instanceof j&&!e.parsed?(\"string\"==typeof e.value.value?this.parse.parseNode(e.value.value,[\"value\",\"important\"],e.value.getIndex(),e.fileInfo(),(function(t,i){t&&(e.parsed=!0),i&&(e.value=i[0],e.important=i[1]||\"\",e.parsed=!0)})):e.parsed=!0,e):e}if(Array.isArray(e)){var n=[];return e.forEach((function(e){n.push(i.call(t,e))})),n}return i.call(t,e)},rulesets:function(){if(!this.rules)return[];var e,t,i=[],n=this.rules;for(e=0;t=n[e];e++)t.isRuleset&&i.push(t);return i},prependRule:function(e){var t=this.rules;t?t.unshift(e):this.rules=[e],this.setParent(e,this)},find:function(e,t,i){t=t||this;var n,r,s=[],o=e.toCSS();return o in this._lookups?this._lookups[o]:(this.rulesets().forEach((function(o){if(o!==t)for(var a=0;a<o.selectors.length;a++)if(n=e.match(o.selectors[a])){if(e.elements.length>n){if(!i||i(o)){r=o.find(new F(e.elements.slice(n)),t,i);for(var l=0;l<r.length;++l)r[l].path.push(o);Array.prototype.push.apply(s,r)}}else s.push({rule:o,path:[]});break}})),this._lookups[o]=s,s)},genCSS:function(e,t){var i,n,r,s,o,a=[];e.tabLevel=e.tabLevel||0,this.root||e.tabLevel++;var l,u=e.compress?\"\":Array(e.tabLevel+1).join(\"  \"),c=e.compress?\"\":Array(e.tabLevel).join(\"  \"),h=0,f=0;for(i=0;s=this.rules[i];i++)s instanceof U?(f===i&&f++,a.push(s)):s.isCharset&&s.isCharset()?(a.splice(h,0,s),h++,f++):\"Import\"===s.type?(a.splice(f,0,s),f++):a.push(s);if(a=[].concat(a),!this.root){(r=B(e,this,c))&&(t.add(r),t.add(c));var p=this.paths,v=p.length,d=void 0;for(l=e.compress?\",\":\",\\n\"+c,i=0;i<v;i++)if(d=(o=p[i]).length)for(i>0&&t.add(l),e.firstSelector=!0,o[0].genCSS(e,t),e.firstSelector=!1,n=1;n<d;n++)o[n].genCSS(e,t);t.add((e.compress?\"{\":\" {\\n\")+u)}for(i=0;s=a[i];i++){i+1===a.length&&(e.lastRule=!0);var m=e.lastRule;s.isRulesetLike(s)&&(e.lastRule=!1),s.genCSS?s.genCSS(e,t):s.value&&t.add(s.value.toString()),e.lastRule=m,!e.lastRule&&s.isVisible()?t.add(e.compress?\"\":\"\\n\"+u):e.lastRule=!1}this.root||(t.add(e.compress?\"}\":\"\\n\"+c+\"}\"),e.tabLevel--),t.isEmpty()||e.compress||!this.firstRoot||t.add(\"\\n\")},joinSelectors:function(e,t,i){for(var n=0;n<i.length;n++)this.joinSelector(e,t,i[n])},joinSelector:function(e,t,i){function n(e,t){var i,n;if(0===e.length)i=new p(e[0]);else{var r=new Array(e.length);for(n=0;n<e.length;n++)r[n]=new m(null,e[n],t.isVariable,t._index,t._fileInfo);i=new p(new F(r))}return i}function r(e,t){var i;return i=new m(null,e,t.isVariable,t._index,t._fileInfo),new F([i])}function s(e,t,i,n){var r,s,o;if(r=[],e.length>0?(s=(r=k(e)).pop(),o=n.createDerived(k(s.elements))):o=n.createDerived([]),t.length>0){var a=i.combinator,l=t[0].elements[0];a.emptyOrWhitespace&&!l.combinator.emptyOrWhitespace&&(a=l.combinator),o.elements.push(new m(a,l.value,i.isVariable,i._index,i._fileInfo)),o.elements=o.elements.concat(t[0].elements.slice(1))}if(0!==o.elements.length&&r.push(o),t.length>1){var u=t.slice(1);u=u.map((function(e){return e.createDerived(e.elements,[])})),r=r.concat(u)}return r}function o(e,t,i,n,r){var o;for(o=0;o<e.length;o++){var a=s(e[o],t,i,n);r.push(a)}return r}function a(e,t){var i,n;if(0!==e.length)if(0!==t.length)for(i=0;n=t[i];i++)n.length>0?n[n.length-1]=n[n.length-1].createDerived(n[n.length-1].elements.concat(e)):n.push(new F(e));else t.push([new F(e)])}function l(e,t){var i=t.createDerived(t.elements,t.extendList,t.evaldCondition);return i.copyVisibilityInfo(e),i}var u,c;if(!function e(t,i,l){var u,c,h,f,v,d,g,y,b,w,x,S,I=!1;for(f=[],v=[[]],u=0;y=l.elements[u];u++)if(\"&\"!==y.value){var C=(S=void 0,(x=y).value instanceof p&&(S=x.value.value)instanceof F?S:null);if(null!=C){a(f,v);var k,_=[],A=[];for(k=e(_,i,C),I=I||k,h=0;h<_.length;h++){o(v,[r(n(_[h],y),y)],y,l,A)}v=A,f=[]}else f.push(y)}else{for(I=!0,d=[],a(f,v),c=0;c<v.length;c++)if(g=v[c],0===i.length)g.length>0&&g[0].elements.push(new m(y.combinator,\"\",y.isVariable,y._index,y._fileInfo)),d.push(g);else for(h=0;h<i.length;h++){var M=s(g,i[h],y,l);d.push(M)}v=d,f=[]}for(a(f,v),u=0;u<v.length;u++)(b=v[u].length)>0&&(t.push(v[u]),w=v[u][b-1],v[u][b-1]=w.createDerived(w.elements,l.extendList));return I}(c=[],t,i))if(t.length>0)for(c=[],u=0;u<t.length;u++){var h=t[u].map(l.bind(this,i.visibilityInfo()));h.push(i),c.push(h)}else c=[[i]];for(u=0;u<c.length;u++)e.push(c[u])}});var Z=function(e,t,i,n,r,s,o,a){var l;if(this.name=e,this.value=t instanceof u?t:t?new j(t):t,i){for(Array.isArray(i)?this.rules=i:(this.rules=[i],this.rules[0].selectors=new F([],null,null,n,r).createEmptySelectors()),l=0;l<this.rules.length;l++)this.rules[l].allowImports=!0;this.setParent(this.rules,this)}this._index=n,this._fileInfo=r,this.debugInfo=s,this.isRooted=o||!1,this.copyVisibilityInfo(a),this.allowRoot=!0};Z.prototype=Object.assign(new u,{type:\"AtRule\",accept:function(e){var t=this.value,i=this.rules;i&&(this.rules=e.visitArray(i)),t&&(this.value=e.visit(t))},isRulesetLike:function(){return this.rules||!this.isCharset()},isCharset:function(){return\"@charset\"===this.name},genCSS:function(e,t){var i=this.value,n=this.rules;t.add(this.name,this.fileInfo(),this.getIndex()),i&&(t.add(\" \"),i.genCSS(e,t)),n?this.outputRuleset(e,t,n):t.add(\";\")},eval:function(e){var t,i,n=this.value,r=this.rules;return t=e.mediaPath,i=e.mediaBlocks,e.mediaPath=[],e.mediaBlocks=[],n&&(n=n.eval(e)),r&&((r=[r[0].eval(e)])[0].root=!0),e.mediaPath=t,e.mediaBlocks=i,new Z(this.name,n,r,this.getIndex(),this.fileInfo(),this.debugInfo,this.isRooted,this.visibilityInfo())},variable:function(e){if(this.rules)return K.prototype.variable.call(this.rules[0],e)},find:function(){if(this.rules)return K.prototype.find.apply(this.rules[0],arguments)},rulesets:function(){if(this.rules)return K.prototype.rulesets.apply(this.rules[0])},outputRuleset:function(e,t,i){var n,r=i.length;if(e.tabLevel=1+(0|e.tabLevel),e.compress){for(t.add(\"{\"),n=0;n<r;n++)i[n].genCSS(e,t);return t.add(\"}\"),void e.tabLevel--}var s=\"\\n\"+Array(e.tabLevel).join(\"  \"),o=s+\"  \";if(r){for(t.add(\" {\"+o),i[0].genCSS(e,t),n=1;n<r;n++)t.add(o),i[n].genCSS(e,t);t.add(s+\"}\")}else t.add(\" {\"+s+\"}\");e.tabLevel--}});var X=function(e,t){this.ruleset=e,this.frames=t,this.setParent(this.ruleset,this)};X.prototype=Object.assign(new u,{type:\"DetachedRuleset\",evalFirst:!0,accept:function(e){this.ruleset=e.visit(this.ruleset)},eval:function(e){var t=this.frames||k(e.frames);return new X(this.ruleset,t)},callEval:function(e){return this.ruleset.eval(this.frames?new q.Eval(e,this.frames.concat(e.frames)):e)}});var Y=function(e,t,i){this.numerator=e?k(e).sort():[],this.denominator=t?k(t).sort():[],i?this.backupUnit=i:e&&e.length&&(this.backupUnit=e[0])};Y.prototype=Object.assign(new u,{type:\"Unit\",clone:function(){return new Y(k(this.numerator),k(this.denominator),this.backupUnit)},genCSS:function(e,t){var i=e&&e.strictUnits;1===this.numerator.length?t.add(this.numerator[0]):!i&&this.backupUnit?t.add(this.backupUnit):!i&&this.denominator.length&&t.add(this.denominator[0])},toString:function(){var e,t=this.numerator.join(\"*\");for(e=0;e<this.denominator.length;e++)t+=\"/\"+this.denominator[e];return t},compare:function(e){return this.is(e.toString())?0:void 0},is:function(e){return this.toString().toUpperCase()===e.toUpperCase()},isLength:function(){return RegExp(\"^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$\",\"gi\").test(this.toCSS())},isEmpty:function(){return 0===this.numerator.length&&0===this.denominator.length},isSingular:function(){return this.numerator.length<=1&&0===this.denominator.length},map:function(e){var t;for(t=0;t<this.numerator.length;t++)this.numerator[t]=e(this.numerator[t],!1);for(t=0;t<this.denominator.length;t++)this.denominator[t]=e(this.denominator[t],!0)},usedUnits:function(){var e,t,i,n={};for(i in t=function(t){return e.hasOwnProperty(t)&&!n[i]&&(n[i]=t),t},a)a.hasOwnProperty(i)&&(e=a[i],this.map(t));return n},cancel:function(){var e,t,i={};for(t=0;t<this.numerator.length;t++)i[e=this.numerator[t]]=(i[e]||0)+1;for(t=0;t<this.denominator.length;t++)i[e=this.denominator[t]]=(i[e]||0)-1;for(e in this.numerator=[],this.denominator=[],i)if(i.hasOwnProperty(e)){var n=i[e];if(n>0)for(t=0;t<n;t++)this.numerator.push(e);else if(n<0)for(t=0;t<-n;t++)this.denominator.push(e)}this.numerator.sort(),this.denominator.sort()}});var ee=function(e,t){if(this.value=parseFloat(e),isNaN(this.value))throw new Error(\"Dimension is not a number.\");this.unit=t&&t instanceof Y?t:new Y(t?[t]:void 0),this.setParent(this.unit,this)};ee.prototype=Object.assign(new u,{type:\"Dimension\",accept:function(e){this.unit=e.visit(this.unit)},eval:function(e){return this},toColor:function(){return new c([this.value,this.value,this.value])},genCSS:function(e,t){if(e&&e.strictUnits&&!this.unit.isSingular())throw new Error(\"Multiple units in dimension. Correct the units or use the unit function. Bad unit: \"+this.unit.toString());var i=this.fround(e,this.value),n=String(i);if(0!==i&&i<1e-6&&i>-1e-6&&(n=i.toFixed(20).replace(/0+$/,\"\")),e&&e.compress){if(0===i&&this.unit.isLength())return void t.add(n);i>0&&i<1&&(n=n.substr(1))}t.add(n),this.unit.genCSS(e,t)},operate:function(e,t,i){var n=this._operate(e,t,this.value,i.value),r=this.unit.clone();if(\"+\"===t||\"-\"===t)if(0===r.numerator.length&&0===r.denominator.length)r=i.unit.clone(),this.unit.backupUnit&&(r.backupUnit=this.unit.backupUnit);else if(0===i.unit.numerator.length&&0===r.denominator.length);else{if(i=i.convertTo(this.unit.usedUnits()),e.strictUnits&&i.unit.toString()!==r.toString())throw new Error(\"Incompatible units. Change the units or use the unit function. Bad units: '\"+r.toString()+\"' and '\"+i.unit.toString()+\"'.\");n=this._operate(e,t,this.value,i.value)}else\"*\"===t?(r.numerator=r.numerator.concat(i.unit.numerator).sort(),r.denominator=r.denominator.concat(i.unit.denominator).sort(),r.cancel()):\"/\"===t&&(r.numerator=r.numerator.concat(i.unit.denominator).sort(),r.denominator=r.denominator.concat(i.unit.numerator).sort(),r.cancel());return new ee(n,r)},compare:function(e){var t,i;if(e instanceof ee){if(this.unit.isEmpty()||e.unit.isEmpty())t=this,i=e;else if(t=this.unify(),i=e.unify(),0!==t.unit.compare(i.unit))return;return u.numericCompare(t.value,i.value)}},unify:function(){return this.convertTo({length:\"px\",duration:\"s\",angle:\"rad\"})},convertTo:function(e){var t,i,n,r,s,o=this.value,l=this.unit.clone(),u={};if(\"string\"==typeof e){for(t in a)a[t].hasOwnProperty(e)&&((u={})[t]=e);e=u}for(i in s=function(e,t){return n.hasOwnProperty(e)?(t?o/=n[e]/n[r]:o*=n[e]/n[r],r):e},e)e.hasOwnProperty(i)&&(r=e[i],n=a[i],l.map(s));return l.cancel(),new ee(o,l)}});var te=g,ie=function(e,t,i){this.op=e.trim(),this.operands=t,this.isSpaced=i};ie.prototype=Object.assign(new u,{type:\"Operation\",accept:function(e){this.operands=e.visitArray(this.operands)},eval:function(e){var t,i=this.operands[0].eval(e),n=this.operands[1].eval(e);if(e.isMathOn(this.op)){if(t=\"./\"===this.op?\"/\":this.op,i instanceof ee&&n instanceof c&&(i=i.toColor()),n instanceof ee&&i instanceof c&&(n=n.toColor()),!i.operate||!n.operate){if((i instanceof ie||n instanceof ie)&&\"/\"===i.op&&e.math===te.PARENS_DIVISION)return new ie(this.op,[i,n],this.isSpaced);throw{type:\"Operation\",message:\"Operation on an invalid type\"}}return i.operate(e,t,n)}return new ie(this.op,[i,n],this.isSpaced)},genCSS:function(e,t){this.operands[0].genCSS(e,t),this.isSpaced&&t.add(\" \"),t.add(this.op),this.isSpaced&&t.add(\" \"),this.operands[1].genCSS(e,t)}});var ne=function(e,t){if(this.value=e,this.noSpacing=t,!e)throw new Error(\"Expression requires an array parameter\")};ne.prototype=Object.assign(new u,{type:\"Expression\",accept:function(e){this.value=e.visitArray(this.value)},eval:function(e){var t,i=e.isMathOn(),n=this.parens,r=!1;return n&&e.inParenthesis(),this.value.length>1?t=new ne(this.value.map((function(t){return t.eval?t.eval(e):t})),this.noSpacing):1===this.value.length?(!this.value[0].parens||this.value[0].parensInOp||e.inCalc||(r=!0),t=this.value[0].eval(e)):t=this,n&&e.outOfParenthesis(),!this.parens||!this.parensInOp||i||r||t instanceof ee||(t=new p(t)),t},genCSS:function(e,t){for(var i=0;i<this.value.length;i++)this.value[i].genCSS(e,t),!this.noSpacing&&i+1<this.value.length&&t.add(\" \")},throwAwayComments:function(){this.value=this.value.filter((function(e){return!(e instanceof U)}))}});var re=function(){function e(e,t,i,n){this.name=e.toLowerCase(),this.index=i,this.context=t,this.currentFileInfo=n,this.func=t.frames[0].functionRegistry.get(this.name)}return e.prototype.isValid=function(){return Boolean(this.func)},e.prototype.call=function(e){var t=this;Array.isArray(e)||(e=[e]);var i=this.func.evalArgs;!1!==i&&(e=e.map((function(e){return e.eval(t.context)})));var n=function(e){return!(\"Comment\"===e.type)};return e=e.filter(n).map((function(e){if(\"Expression\"===e.type){var t=e.value.filter(n);return 1===t.length?t[0]:new ne(t)}return e})),!1===i?this.func.apply(this,function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var n=Array(e),r=0;for(t=0;t<i;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,r++)n[r]=s[o];return n}([this.context],e)):this.func.apply(this,e)},e}(),se=function(e,t,i,n){this.name=e,this.args=t,this.calc=\"calc\"===e,this._index=i,this._fileInfo=n};se.prototype=Object.assign(new u,{type:\"Call\",accept:function(e){this.args&&(this.args=e.visitArray(this.args))},eval:function(e){var t=this,i=e.mathOn;e.mathOn=!this.calc,(this.calc||e.inCalc)&&e.enterCalc();var n,r=function(){(t.calc||e.inCalc)&&e.exitCalc(),e.mathOn=i},s=new re(this.name,e,this.getIndex(),this.fileInfo());if(s.isValid())try{n=s.call(this.args),r()}catch(e){if(e.hasOwnProperty(\"line\")&&e.hasOwnProperty(\"column\"))throw e;throw{type:e.type||\"Runtime\",message:\"Error evaluating function `\"+this.name+\"`\"+(e.message?\": \"+e.message:\"\"),index:this.getIndex(),filename:this.fileInfo().filename,line:e.lineNumber,column:e.columnNumber}}if(null!=n)return n instanceof u||(n=new j(n&&!0!==n?n.toString():null)),n._index=this._index,n._fileInfo=this._fileInfo,n;var o=this.args.map((function(t){return t.eval(e)}));return r(),new se(this.name,o,this.getIndex(),this.fileInfo())},genCSS:function(e,t){t.add(this.name+\"(\",this.fileInfo(),this.getIndex());for(var i=0;i<this.args.length;i++)this.args[i].genCSS(e,t),i+1<this.args.length&&t.add(\", \");t.add(\")\")}});var oe=function(e,t,i){this.name=e,this._index=t,this._fileInfo=i};oe.prototype=Object.assign(new u,{type:\"Variable\",eval:function(e){var t,i=this.name;if(0===i.indexOf(\"@@\")&&(i=\"@\"+new oe(i.slice(1),this.getIndex(),this.fileInfo()).eval(e).value),this.evaluating)throw{type:\"Name\",message:\"Recursive variable definition for \"+i,filename:this.fileInfo().filename,index:this.getIndex()};if(this.evaluating=!0,t=this.find(e.frames,(function(t){var n=t.variable(i);if(n){if(n.important)e.importantScope[e.importantScope.length-1].important=n.important;return e.inCalc?new se(\"_SELF\",[n.value]).eval(e):n.value.eval(e)}})))return this.evaluating=!1,t;throw{type:\"Name\",message:\"variable \"+i+\" is undefined\",filename:this.fileInfo().filename,index:this.getIndex()}},find:function(e,t){for(var i=0,n=void 0;i<e.length;i++)if(n=t.call(e,e[i]))return n;return null}});var ae=function(e,t,i){this.name=e,this._index=t,this._fileInfo=i};ae.prototype=Object.assign(new u,{type:\"Property\",eval:function(e){var t,i=this.name,n=e.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;if(this.evaluating)throw{type:\"Name\",message:\"Recursive property reference for \"+i,filename:this.fileInfo().filename,index:this.getIndex()};if(this.evaluating=!0,t=this.find(e.frames,(function(t){var r,s=t.property(i);if(s){for(var o=0;o<s.length;o++)r=s[o],s[o]=new D(r.name,r.value,r.important,r.merge,r.index,r.currentFileInfo,r.inline,r.variable);if(n(s),(r=s[s.length-1]).important)e.importantScope[e.importantScope.length-1].important=r.important;return r=r.value.eval(e)}})))return this.evaluating=!1,t;throw{type:\"Name\",message:\"Property '\"+i+\"' is undefined\",filename:this.currentFileInfo.filename,index:this.index}},find:function(e,t){for(var i=0,n=void 0;i<e.length;i++)if(n=t.call(e,e[i]))return n;return null}});var le=function(e,t,i){this.key=e,this.op=t,this.value=i};le.prototype=Object.assign(new u,{type:\"Attribute\",eval:function(e){return new le(this.key.eval?this.key.eval(e):this.key,this.op,this.value&&this.value.eval?this.value.eval(e):this.value)},genCSS:function(e,t){t.add(this.toCSS(e))},toCSS:function(e){var t=this.key.toCSS?this.key.toCSS(e):this.key;return this.op&&(t+=this.op,t+=this.value.toCSS?this.value.toCSS(e):this.value),\"[\"+t+\"]\"}});var ue=function(e,t,i,n,r){this.escaped=null==i||i,this.value=t||\"\",this.quote=e.charAt(0),this._index=n,this._fileInfo=r,this.variableRegex=/@\\{([\\w-]+)\\}/g,this.propRegex=/\\$\\{([\\w-]+)\\}/g,this.allowRoot=i};ue.prototype=Object.assign(new u,{type:\"Quoted\",genCSS:function(e,t){this.escaped||t.add(this.quote,this.fileInfo(),this.getIndex()),t.add(this.value),this.escaped||t.add(this.quote)},containsVariables:function(){return this.value.match(this.variableRegex)},eval:function(e){var t=this,i=this.value;function n(e,t,i){var n=e;do{e=n.toString(),n=e.replace(t,i)}while(e!==n);return n}return i=n(i,this.variableRegex,(function(i,n){var r=new oe(\"@\"+n,t.getIndex(),t.fileInfo()).eval(e,!0);return r instanceof ue?r.value:r.toCSS()})),i=n(i,this.propRegex,(function(i,n){var r=new ae(\"$\"+n,t.getIndex(),t.fileInfo()).eval(e,!0);return r instanceof ue?r.value:r.toCSS()})),new ue(this.quote+i+this.quote,i,this.escaped,this.getIndex(),this.fileInfo())},compare:function(e){return\"Quoted\"!==e.type||this.escaped||e.escaped?e.toCSS&&this.toCSS()===e.toCSS()?0:void 0:u.numericCompare(this.value,e.value)}});var ce=function(e,t,i,n){this.value=e,this._index=t,this._fileInfo=i,this.isEvald=n};ce.prototype=Object.assign(new u,{type:\"Url\",accept:function(e){this.value=e.visit(this.value)},genCSS:function(e,t){t.add(\"url(\"),this.value.genCSS(e,t),t.add(\")\")},eval:function(e){var t,i=this.value.eval(e);if(!this.isEvald&&(\"string\"==typeof(t=this.fileInfo()&&this.fileInfo().rootpath)&&\"string\"==typeof i.value&&e.pathRequiresRewrite(i.value)?(i.quote||(t=t.replace(/[\\(\\)'\"\\s]/g,(function(e){return\"\\\\\"+e}))),i.value=e.rewritePath(i.value,t)):i.value=e.normalizePath(i.value),e.urlArgs&&!i.value.match(/^\\s*data:/))){var n=(-1===i.value.indexOf(\"?\")?\"?\":\"&\")+e.urlArgs;-1!==i.value.indexOf(\"#\")?i.value=i.value.replace(\"#\",n+\"#\"):i.value+=n}return new ce(i,this.getIndex(),this.fileInfo(),!0)}});var he=function(e,t,i,n,r){this._index=i,this._fileInfo=n;var s=new F([],null,null,this._index,this._fileInfo).createEmptySelectors();this.features=new $(t),this.rules=[new K(s,e)],this.rules[0].allowImports=!0,this.copyVisibilityInfo(r),this.allowRoot=!0,this.setParent(s,this),this.setParent(this.features,this),this.setParent(this.rules,this)};he.prototype=Object.assign(new Z,{type:\"Media\",isRulesetLike:function(){return!0},accept:function(e){this.features&&(this.features=e.visit(this.features)),this.rules&&(this.rules=e.visitArray(this.rules))},genCSS:function(e,t){t.add(\"@media \",this._fileInfo,this._index),this.features.genCSS(e,t),this.outputRuleset(e,t,this.rules)},eval:function(e){e.mediaBlocks||(e.mediaBlocks=[],e.mediaPath=[]);var t=new he(null,[],this._index,this._fileInfo,this.visibilityInfo());return this.debugInfo&&(this.rules[0].debugInfo=this.debugInfo,t.debugInfo=this.debugInfo),t.features=this.features.eval(e),e.mediaPath.push(t),e.mediaBlocks.push(t),this.rules[0].functionRegistry=e.frames[0].functionRegistry.inherit(),e.frames.unshift(this.rules[0]),t.rules=[this.rules[0].eval(e)],e.frames.shift(),e.mediaPath.pop(),0===e.mediaPath.length?t.evalTop(e):t.evalNested(e)},evalTop:function(e){var t=this;if(e.mediaBlocks.length>1){var i=new F([],null,null,this.getIndex(),this.fileInfo()).createEmptySelectors();(t=new K(i,e.mediaBlocks)).multiMedia=!0,t.copyVisibilityInfo(this.visibilityInfo()),this.setParent(t,this)}return delete e.mediaBlocks,delete e.mediaPath,t},evalNested:function(e){var t,i,n=e.mediaPath.concat([this]);for(t=0;t<n.length;t++)i=n[t].features instanceof $?n[t].features.value:n[t].features,n[t]=Array.isArray(i)?i:[i];return this.features=new $(this.permute(n).map((function(e){for(e=e.map((function(e){return e.toCSS?e:new j(e)})),t=e.length-1;t>0;t--)e.splice(t,0,new j(\"and\"));return new ne(e)}))),this.setParent(this.features,this),new K([],[])},permute:function(e){if(0===e.length)return[];if(1===e.length)return e[0];for(var t=[],i=this.permute(e.slice(1)),n=0;n<i.length;n++)for(var r=0;r<e[0].length;r++)t.push([e[0][r]].concat(i[n]));return t},bubbleSelectors:function(e){e&&(this.rules=[new K(k(e),[this.rules[0]])],this.setParent(this.rules,this))}});var fe=function(e,t,i,n,r,s){if(this.options=i,this._index=n,this._fileInfo=r,this.path=e,this.features=t,this.allowRoot=!0,void 0!==this.options.less||this.options.inline)this.css=!this.options.less||this.options.inline;else{var o=this.getPath();o&&/[#\\.\\&\\?]css([\\?;].*)?$/.test(o)&&(this.css=!0)}this.copyVisibilityInfo(s),this.setParent(this.features,this),this.setParent(this.path,this)};fe.prototype=Object.assign(new u,{type:\"Import\",accept:function(e){this.features&&(this.features=e.visit(this.features)),this.path=e.visit(this.path),this.options.isPlugin||this.options.inline||!this.root||(this.root=e.visit(this.root))},genCSS:function(e,t){this.css&&void 0===this.path._fileInfo.reference&&(t.add(\"@import \",this._fileInfo,this._index),this.path.genCSS(e,t),this.features&&(t.add(\" \"),this.features.genCSS(e,t)),t.add(\";\"))},getPath:function(){return this.path instanceof ce?this.path.value.value:this.path.value},isVariableImport:function(){var e=this.path;return e instanceof ce&&(e=e.value),!(e instanceof ue)||e.containsVariables()},evalForImport:function(e){var t=this.path;return t instanceof ce&&(t=t.value),new fe(t.eval(e),this.features,this.options,this._index,this._fileInfo,this.visibilityInfo())},evalPath:function(e){var t=this.path.eval(e),i=this._fileInfo;if(!(t instanceof ce)){var n=t.value;i&&n&&e.pathRequiresRewrite(n)?t.value=e.rewritePath(n,i.rootpath):t.value=e.normalizePath(t.value)}return t},eval:function(e){var t=this.doEval(e);return(this.options.reference||this.blocksVisibility())&&(t.length||0===t.length?t.forEach((function(e){e.addVisibilityBlock()})):t.addVisibilityBlock()),t},doEval:function(e){var t,i,n=this.features&&this.features.eval(e);if(this.options.isPlugin){if(this.root&&this.root.eval)try{this.root.eval(e)}catch(e){throw e.message=\"Plugin error during evaluation\",new O(e,this.root.imports,this.root.filename)}return(i=e.frames[0]&&e.frames[0].functionRegistry)&&this.root&&this.root.functions&&i.addMultiple(this.root.functions),[]}if(this.skip&&(\"function\"==typeof this.skip&&(this.skip=this.skip()),this.skip))return[];if(this.options.inline){var r=new j(this.root,0,{filename:this.importedFilename,reference:this.path._fileInfo&&this.path._fileInfo.reference},!0,!0);return this.features?new he([r],this.features.value):[r]}if(this.css){var s=new fe(this.evalPath(e),n,this.options,this._index);if(!s.css&&this.error)throw this.error;return s}return this.root?((t=new K(null,k(this.root.rules))).evalImports(e),this.features?new he(t.rules,this.features.value):t.rules):[]}});var pe=function(){};pe.prototype=Object.assign(new u,{evaluateJavaScript:function(e,t){var i,n=this,r={};if(!t.javascriptEnabled)throw{message:\"Inline JavaScript is not enabled. Is it set in your options?\",filename:this.fileInfo().filename,index:this.getIndex()};e=e.replace(/@\\{([\\w-]+)\\}/g,(function(e,i){return n.jsify(new oe(\"@\"+i,n.getIndex(),n.fileInfo()).eval(t))}));try{e=new Function(\"return (\"+e+\")\")}catch(t){throw{message:\"JavaScript evaluation error: \"+t.message+\" from `\"+e+\"`\",filename:this.fileInfo().filename,index:this.getIndex()}}var s=t.frames[0].variables();for(var o in s)s.hasOwnProperty(o)&&(r[o.slice(1)]={value:s[o].value,toJS:function(){return this.value.eval(t).toCSS()}});try{i=e.call(r)}catch(e){throw{message:\"JavaScript evaluation error: '\"+e.name+\": \"+e.message.replace(/[\"]/g,\"'\")+\"'\",filename:this.fileInfo().filename,index:this.getIndex()}}return i},jsify:function(e){return Array.isArray(e.value)&&e.value.length>1?\"[\"+e.value.map((function(e){return e.toCSS()})).join(\", \")+\"]\":e.toCSS()}});var ve=function(e,t,i,n){this.escaped=t,this.expression=e,this._index=i,this._fileInfo=n};ve.prototype=Object.assign(new pe,{type:\"JavaScript\",eval:function(e){var t=this.evaluateJavaScript(this.expression,e),i=typeof t;return\"number\"!==i||isNaN(t)?\"string\"===i?new ue('\"'+t+'\"',t,this.escaped,this._index):Array.isArray(t)?new j(t.join(\", \")):new j(t):new ee(t)}});var de=function(e,t){this.key=e,this.value=t};de.prototype=Object.assign(new u,{type:\"Assignment\",accept:function(e){this.value=e.visit(this.value)},eval:function(e){return this.value.eval?new de(this.key,this.value.eval(e)):this},genCSS:function(e,t){t.add(this.key+\"=\"),this.value.genCSS?this.value.genCSS(e,t):t.add(this.value)}});var me=function(e,t,i,n,r){this.op=e.trim(),this.lvalue=t,this.rvalue=i,this._index=n,this.negate=r};me.prototype=Object.assign(new u,{type:\"Condition\",accept:function(e){this.lvalue=e.visit(this.lvalue),this.rvalue=e.visit(this.rvalue)},eval:function(e){var t=function(e,t,i){switch(e){case\"and\":return t&&i;case\"or\":return t||i;default:switch(u.compare(t,i)){case-1:return\"<\"===e||\"=<\"===e||\"<=\"===e;case 0:return\"=\"===e||\">=\"===e||\"=<\"===e||\"<=\"===e;case 1:return\">\"===e||\">=\"===e;default:return!1}}}(this.op,this.lvalue.eval(e),this.rvalue.eval(e));return this.negate?!t:t}});var ge=function(e){this.value=e};ge.prototype=Object.assign(new u,{type:\"UnicodeDescriptor\"});var ye=function(e){this.value=e};ye.prototype=Object.assign(new u,{type:\"Negative\",genCSS:function(e,t){t.add(\"-\"),this.value.genCSS(e,t)},eval:function(e){return e.isMathOn()?new ie(\"*\",[new ee(-1),this.value]).eval(e):new ye(this.value.eval(e))}});var be=function(e,t,i,n,r){switch(this.selector=e,this.option=t,this.object_id=be.next_id++,this.parent_ids=[this.object_id],this._index=i,this._fileInfo=n,this.copyVisibilityInfo(r),this.allowRoot=!0,t){case\"all\":this.allowBefore=!0,this.allowAfter=!0;break;default:this.allowBefore=!1,this.allowAfter=!1}this.setParent(this.selector,this)};be.prototype=Object.assign(new u,{type:\"Extend\",accept:function(e){this.selector=e.visit(this.selector)},eval:function(e){return new be(this.selector.eval(e),this.option,this.getIndex(),this.fileInfo(),this.visibilityInfo())},clone:function(e){return new be(this.selector,this.option,this.getIndex(),this.fileInfo(),this.visibilityInfo())},findSelfSelectors:function(e){var t,i,n=[];for(t=0;t<e.length;t++)i=e[t].elements,t>0&&i.length&&\"\"===i[0].combinator.value&&(i[0].combinator.value=\" \"),n=n.concat(e[t].elements);this.selfSelectors=[new F(n)],this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo())}}),be.next_id=0;var we=function(e,t,i){this.variable=e,this._index=t,this._fileInfo=i,this.allowRoot=!0};we.prototype=Object.assign(new u,{type:\"VariableCall\",eval:function(e){var t,i=new oe(this.variable,this.getIndex(),this.fileInfo()).eval(e),n=new O({message:\"Could not evaluate variable call \"+this.variable});if(!i.ruleset){if(i.rules)t=i;else if(Array.isArray(i))t=new K(\"\",i);else{if(!Array.isArray(i.value))throw n;t=new K(\"\",i.value)}i=new X(t)}if(i.ruleset)return i.callEval(e);throw n}});var xe=function(e,t,i,n){this.value=e,this.lookups=t,this._index=i,this._fileInfo=n};xe.prototype=Object.assign(new u,{type:\"NamespaceValue\",eval:function(e){var t,i,n=this.value.eval(e);for(t=0;t<this.lookups.length;t++){if(i=this.lookups[t],Array.isArray(n)&&(n=new K([new F],n)),\"\"===i)n=n.lastDeclaration();else if(\"@\"===i.charAt(0)){if(\"@\"===i.charAt(1)&&(i=\"@\"+new oe(i.substr(1)).eval(e).value),n.variables&&(n=n.variable(i)),!n)throw{type:\"Name\",message:\"variable \"+i+\" not found\",filename:this.fileInfo().filename,index:this.getIndex()}}else{if(i=\"$@\"===i.substring(0,2)?\"$\"+new oe(i.substr(1)).eval(e).value:\"$\"===i.charAt(0)?i:\"$\"+i,n.properties&&(n=n.property(i)),!n)throw{type:\"Name\",message:'property \"'+i.substr(1)+'\" not found',filename:this.fileInfo().filename,index:this.getIndex()};n=n[n.length-1]}n.value&&(n=n.eval(e).value),n.ruleset&&(n=n.ruleset.eval(e))}return n}});var Se=function(e,t,i,n,r,s,o){this.name=e||\"anonymous mixin\",this.selectors=[new F([new m(null,e,!1,this._index,this._fileInfo)])],this.params=t,this.condition=n,this.variadic=r,this.arity=t.length,this.rules=i,this._lookups={};var a=[];this.required=t.reduce((function(e,t){return!t.name||t.name&&!t.value?e+1:(a.push(t.name),e)}),0),this.optionalParameters=a,this.frames=s,this.copyVisibilityInfo(o),this.allowRoot=!0};Se.prototype=Object.assign(new K,{type:\"MixinDefinition\",evalFirst:!0,accept:function(e){this.params&&this.params.length&&(this.params=e.visitArray(this.params)),this.rules=e.visitArray(this.rules),this.condition&&(this.condition=e.visit(this.condition))},evalParams:function(e,t,i,n){var r,s,o,a,l,u,c,h,f=new K(null,null),p=k(this.params),v=0;if(t.frames&&t.frames[0]&&t.frames[0].functionRegistry&&(f.functionRegistry=t.frames[0].functionRegistry.inherit()),t=new q.Eval(t,[f].concat(t.frames)),i)for(v=(i=k(i)).length,o=0;o<v;o++)if(u=(s=i[o])&&s.name){for(c=!1,a=0;a<p.length;a++)if(!n[a]&&u===p[a].name){n[a]=s.value.eval(e),f.prependRule(new D(u,s.value.eval(e))),c=!0;break}if(c){i.splice(o,1),o--;continue}throw{type:\"Runtime\",message:\"Named argument for \"+this.name+\" \"+i[o].name+\" not found\"}}for(h=0,o=0;o<p.length;o++)if(!n[o]){if(s=i&&i[h],u=p[o].name)if(p[o].variadic){for(r=[],a=h;a<v;a++)r.push(i[a].value.eval(e));f.prependRule(new D(u,new ne(r).eval(e)))}else{if(l=s&&s.value)l=Array.isArray(l)?new X(new K(\"\",l)):l.eval(e);else{if(!p[o].value)throw{type:\"Runtime\",message:\"wrong number of arguments for \"+this.name+\" (\"+v+\" for \"+this.arity+\")\"};l=p[o].value.eval(t),f.resetCache()}f.prependRule(new D(u,l)),n[o]=l}if(p[o].variadic&&i)for(a=h;a<v;a++)n[a]=i[a].value.eval(e);h++}return f},makeImportant:function(){var e=this.rules?this.rules.map((function(e){return e.makeImportant?e.makeImportant(!0):e})):this.rules;return new Se(this.name,this.params,e,this.condition,this.variadic,this.frames)},eval:function(e){return new Se(this.name,this.params,this.rules,this.condition,this.variadic,this.frames||k(e.frames))},evalCall:function(e,t,i){var n,r,s=[],o=this.frames?this.frames.concat(e.frames):e.frames,a=this.evalParams(e,new q.Eval(e,o),t,s);return a.prependRule(new D(\"@arguments\",new ne(s).eval(e))),n=k(this.rules),(r=new K(null,n)).originalRuleset=this,r=r.eval(new q.Eval(e,[this,a].concat(o))),i&&(r=r.makeImportant()),r},matchCondition:function(e,t){return!(this.condition&&!this.condition.eval(new q.Eval(t,[this.evalParams(t,new q.Eval(t,this.frames?this.frames.concat(t.frames):t.frames),e,[])].concat(this.frames||[]).concat(t.frames))))},matchArgs:function(e,t){var i,n=e&&e.length||0,r=this.optionalParameters,s=e?e.reduce((function(e,t){return r.indexOf(t.name)<0?e+1:e}),0):0;if(this.variadic){if(s<this.required-1)return!1}else{if(s<this.required)return!1;if(n>this.params.length)return!1}i=Math.min(s,this.arity);for(var o=0;o<i;o++)if(!this.params[o].name&&!this.params[o].variadic&&e[o].value.eval(t).toCSS()!=this.params[o].value.eval(t).toCSS())return!1;return!0}});var Ie=function(e,t,i,n,r){this.selector=new F(e),this.arguments=t||[],this._index=i,this._fileInfo=n,this.important=r,this.allowRoot=!0,this.setParent(this.selector,this)};Ie.prototype=Object.assign(new u,{type:\"MixinCall\",accept:function(e){this.selector&&(this.selector=e.visit(this.selector)),this.arguments.length&&(this.arguments=e.visitArray(this.arguments))},eval:function(e){var t,i,n,r,s,o,a,l,u,c,h,f,p,v,d,m=[],g=[],y=!1,b=[],w=[];function x(t,i){var n,r,s;for(n=0;n<2;n++){for(w[n]=!0,Q.value(n),r=0;r<i.length&&w[n];r++)(s=i[r]).matchCondition&&(w[n]=w[n]&&s.matchCondition(null,e));t.matchCondition&&(w[n]=w[n]&&t.matchCondition(m,e))}return w[0]||w[1]?w[0]!=w[1]?w[1]?1:2:0:-1}for(this.selector=this.selector.eval(e),o=0;o<this.arguments.length;o++)if(s=(r=this.arguments[o]).value.eval(e),r.expand&&Array.isArray(s.value))for(s=s.value,a=0;a<s.length;a++)m.push({value:s[a]});else m.push({name:r.name,value:s});for(d=function(t){return t.matchArgs(null,e)},o=0;o<e.frames.length;o++)if((t=e.frames[o].find(this.selector,null,d)).length>0){for(c=!0,a=0;a<t.length;a++){for(i=t[a].rule,n=t[a].path,u=!1,l=0;l<e.frames.length;l++)if(!(i instanceof Se)&&i===(e.frames[l].originalRuleset||e.frames[l])){u=!0;break}u||i.matchArgs(m,e)&&(-1!==(h={mixin:i,group:x(i,n)}).group&&b.push(h),y=!0)}for(Q.reset(),p=[0,0,0],a=0;a<b.length;a++)p[b[a].group]++;if(p[0]>0)f=2;else if(f=1,p[1]+p[2]>1)throw{type:\"Runtime\",message:\"Ambiguous use of `default()` found when matching for `\"+this.format(m)+\"`\",index:this.getIndex(),filename:this.fileInfo().filename};for(a=0;a<b.length;a++)if(0===(h=b[a].group)||h===f)try{(i=b[a].mixin)instanceof Se||(v=i.originalRuleset||i,(i=new Se(\"\",[],i.rules,null,!1,null,v.visibilityInfo())).originalRuleset=v);var S=i.evalCall(e,m,this.important).rules;this._setVisibilityToReplacement(S),Array.prototype.push.apply(g,S)}catch(e){throw{message:e.message,index:this.getIndex(),filename:this.fileInfo().filename,stack:e.stack}}if(y)return g}throw c?{type:\"Runtime\",message:\"No matching definition was found for `\"+this.format(m)+\"`\",index:this.getIndex(),filename:this.fileInfo().filename}:{type:\"Name\",message:this.selector.toCSS().trim()+\" is undefined\",index:this.getIndex(),filename:this.fileInfo().filename}},_setVisibilityToReplacement:function(e){var t;if(this.blocksVisibility())for(t=0;t<e.length;t++)e[t].addVisibilityBlock()},format:function(e){return this.selector.toCSS().trim()+\"(\"+(e?e.map((function(e){var t=\"\";return e.name&&(t+=e.name+\":\"),e.value.toCSS?t+=e.value.toCSS():t+=\"???\",t})).join(\", \"):\"\")+\")\"}});var Ce={Node:u,Color:c,AtRule:Z,DetachedRuleset:X,Operation:ie,Dimension:ee,Unit:Y,Keyword:L,Variable:oe,Property:ae,Ruleset:K,Element:m,Attribute:le,Combinator:d,Selector:F,Quoted:ue,Expression:ne,Declaration:D,Call:se,URL:ce,Import:fe,Comment:U,Anonymous:j,Value:$,JavaScript:ve,Assignment:de,Condition:me,Paren:p,Media:he,UnicodeDescriptor:ge,Negative:ye,Extend:be,VariableCall:we,NamespaceValue:xe,mixin:{Call:Ie,Definition:Se}},ke=function(){function e(){}return e.prototype.getPath=function(e){var t=e.lastIndexOf(\"?\");return t>0&&(e=e.slice(0,t)),(t=e.lastIndexOf(\"/\"))<0&&(t=e.lastIndexOf(\"\\\\\")),t<0?\"\":e.slice(0,t+1)},e.prototype.tryAppendExtension=function(e,t){return/(\\.[a-z]*$)|([\\?;].*)$/.test(e)?e:e+t},e.prototype.tryAppendLessExtension=function(e){return this.tryAppendExtension(e,\".less\")},e.prototype.supportsSync=function(){return!1},e.prototype.alwaysMakePathsAbsolute=function(){return!1},e.prototype.isPathAbsolute=function(e){return/^(?:[a-z-]+:|\\/|\\\\|#)/i.test(e)},e.prototype.join=function(e,t){return e?e+t:t},e.prototype.pathDiff=function(e,t){var i,n,r,s,o=this.extractUrlParts(e),a=this.extractUrlParts(t),l=\"\";if(o.hostPart!==a.hostPart)return\"\";for(n=Math.max(a.directories.length,o.directories.length),i=0;i<n&&a.directories[i]===o.directories[i];i++);for(s=a.directories.slice(i),r=o.directories.slice(i),i=0;i<s.length-1;i++)l+=\"../\";for(i=0;i<r.length-1;i++)l+=r[i]+\"/\";return l},e.prototype.extractUrlParts=function(e,t){var i,n,r=/^((?:[a-z-]+:)?\\/{2}(?:[^\\/\\?#]*\\/)|([\\/\\\\]))?((?:[^\\/\\\\\\?#]*[\\/\\\\])*)([^\\/\\\\\\?#]*)([#\\?].*)?$/i,s=e.match(r),o={},a=[],l=[];if(!s)throw new Error(\"Could not parse sheet href - '\"+e+\"'\");if(t&&(!s[1]||s[2])){if(!(n=t.match(r)))throw new Error(\"Could not parse page url - '\"+t+\"'\");s[1]=s[1]||n[1]||\"\",s[2]||(s[3]=n[3]+s[3])}if(s[3])for(a=s[3].replace(/\\\\/g,\"/\").split(\"/\"),i=0;i<a.length;i++)\"..\"===a[i]?l.pop():\".\"!==a[i]&&l.push(a[i]);return o.hostPart=s[1],o.directories=l,o.rawPath=(s[1]||\"\")+a.join(\"/\"),o.path=(s[1]||\"\")+l.join(\"/\"),o.filename=s[4],o.fileUrl=o.path+(s[4]||\"\"),o.url=o.fileUrl+(s[5]||\"\"),o},e}(),_e=function(){function e(){this.require=function(){return null}}return e.prototype.evalPlugin=function(e,t,i,n,r){var s,o,a,l,u,c;l=t.pluginManager,r&&(u=\"string\"==typeof r?r:r.filename);var h=(new this.less.FileManager).extractUrlParts(u).filename;if(u&&(o=l.get(u))){if(c=this.trySetOptions(o,u,h,n))return c;try{o.use&&o.use.call(this.context,o)}catch(e){return e.message=e.message||\"Error during @plugin call\",new O(e,i,u)}return o}a={exports:{},pluginManager:l,fileInfo:r},s=H.create();try{new Function(\"module\",\"require\",\"registerPlugin\",\"functions\",\"tree\",\"less\",\"fileInfo\",e)(a,this.require(u),(function(e){o=e}),s,this.less.tree,this.less,r)}catch(e){return new O(e,i,u)}if(o||(o=a.exports),(o=this.validatePlugin(o,u,h))instanceof O)return o;if(!o)return new O({message:\"Not a valid plugin\"},i,u);if(o.imports=i,o.filename=u,(!o.minVersion||this.compareVersion(\"3.0.0\",o.minVersion)<0)&&(c=this.trySetOptions(o,u,h,n)))return c;if(l.addPlugin(o,r.filename,s),o.functions=s.getLocalFunctions(),c=this.trySetOptions(o,u,h,n))return c;try{o.use&&o.use.call(this.context,o)}catch(e){return e.message=e.message||\"Error during @plugin call\",new O(e,i,u)}return o},e.prototype.trySetOptions=function(e,t,i,n){if(n&&!e.setOptions)return new O({message:\"Options have been provided but the plugin \"+i+\" does not support any options.\"});try{e.setOptions&&e.setOptions(n)}catch(e){return new O(e)}},e.prototype.validatePlugin=function(e,t,i){return e?(\"function\"==typeof e&&(e=new e),e.minVersion&&this.compareVersion(e.minVersion,this.less.version)<0?new O({message:\"Plugin \"+i+\" requires version \"+this.versionToString(e.minVersion)}):e):null},e.prototype.compareVersion=function(e,t){\"string\"==typeof e&&(e=e.match(/^(\\d+)\\.?(\\d+)?\\.?(\\d+)?/)).shift();for(var i=0;i<e.length;i++)if(e[i]!==t[i])return parseInt(e[i])>parseInt(t[i])?-1:1;return 0},e.prototype.versionToString=function(e){for(var t=\"\",i=0;i<e.length;i++)t+=(t?\".\":\"\")+e[i];return t},e.prototype.printUsage=function(e){for(var t=0;t<e.length;t++){var i=e[t];i.printUsage&&i.printUsage()}},e}(),Ae={visitDeeper:!0},Me=!1;function Ee(e){return e}var Pe=function(){function e(e){this._implementation=e,this._visitInCache={},this._visitOutCache={},Me||(!function e(t,i){var n,r;for(n in t)switch(typeof(r=t[n])){case\"function\":r.prototype&&r.prototype.type&&(r.prototype.typeIndex=i++);break;case\"object\":i=e(r,i)}return i}(Ce,1),Me=!0)}return e.prototype.visit=function(e){if(!e)return e;var t=e.typeIndex;if(!t)return e.value&&e.value.typeIndex&&this.visit(e.value),e;var i,n=this._implementation,r=this._visitInCache[t],s=this._visitOutCache[t],o=Ae;if(o.visitDeeper=!0,r||(r=n[i=\"visit\"+e.type]||Ee,s=n[i+\"Out\"]||Ee,this._visitInCache[t]=r,this._visitOutCache[t]=s),r!==Ee){var a=r.call(n,e,o);e&&n.isReplacing&&(e=a)}if(o.visitDeeper&&e)if(e.length)for(var l=0,u=e.length;l<u;l++)e[l].accept&&e[l].accept(this);else e.accept&&e.accept(this);return s!=Ee&&s.call(n,e),e},e.prototype.visitArray=function(e,t){if(!e)return e;var i,n=e.length;if(t||!this._implementation.isReplacing){for(i=0;i<n;i++)this.visit(e[i]);return e}var r=[];for(i=0;i<n;i++){var s=this.visit(e[i]);void 0!==s&&(s.splice?s.length&&this.flatten(s,r):r.push(s))}return r},e.prototype.flatten=function(e,t){var i,n,r,s,o,a;for(t||(t=[]),n=0,i=e.length;n<i;n++)if(void 0!==(r=e[n]))if(r.splice)for(o=0,s=r.length;o<s;o++)void 0!==(a=r[o])&&(a.splice?a.length&&this.flatten(a,t):t.push(a));else t.push(r);return t},e}(),Re=function(){function e(e){this.imports=[],this.variableImports=[],this._onSequencerEmpty=e,this._currentDepth=0}return e.prototype.addImport=function(e){var t=this,i={callback:e,args:null,isReady:!1};return this.imports.push(i),function(){i.args=Array.prototype.slice.call(arguments,0),i.isReady=!0,t.tryRun()}},e.prototype.addVariableImport=function(e){this.variableImports.push(e)},e.prototype.tryRun=function(){this._currentDepth++;try{for(;;){for(;this.imports.length>0;){var e=this.imports[0];if(!e.isReady)return;this.imports=this.imports.slice(1),e.callback.apply(null,e.args)}if(0===this.variableImports.length)break;var t=this.variableImports[0];this.variableImports=this.variableImports.slice(1),t()}}finally{this._currentDepth--}0===this._currentDepth&&this._onSequencerEmpty&&this._onSequencerEmpty()},e}(),Oe=function(e,t){this._visitor=new Pe(this),this._importer=e,this._finish=t,this.context=new q.Eval,this.importCount=0,this.onceFileDetectionMap={},this.recursionDetector={},this._sequencer=new Re(this._onSequencerEmpty.bind(this))};Oe.prototype={isReplacing:!1,run:function(e){try{this._visitor.visit(e)}catch(e){this.error=e}this.isFinished=!0,this._sequencer.tryRun()},_onSequencerEmpty:function(){this.isFinished&&this._finish(this.error)},visitImport:function(e,t){var i=e.options.inline;if(!e.css||i){var n=new q.Eval(this.context,k(this.context.frames)),r=n.frames[0];this.importCount++,e.isVariableImport()?this._sequencer.addVariableImport(this.processImportNode.bind(this,e,n,r)):this.processImportNode(e,n,r)}t.visitDeeper=!1},processImportNode:function(e,t,i){var n,r=e.options.inline;try{n=e.evalForImport(t)}catch(t){t.filename||(t.index=e.getIndex(),t.filename=e.fileInfo().filename),e.css=!0,e.error=t}if(!n||n.css&&!r)this.importCount--,this.isFinished&&this._sequencer.tryRun();else{n.options.multiple&&(t.importMultiple=!0);for(var s=void 0===n.css,o=0;o<i.rules.length;o++)if(i.rules[o]===e){i.rules[o]=n;break}var a=this.onImported.bind(this,n,t),l=this._sequencer.addImport(a);this._importer.push(n.getPath(),s,n.fileInfo(),n.options,l)}},onImported:function(e,t,i,n,r,s){i&&(i.filename||(i.index=e.getIndex(),i.filename=e.fileInfo().filename),this.error=i);var o=this,a=e.options.inline,l=e.options.isPlugin,u=e.options.optional,c=r||s in o.recursionDetector;if(t.importMultiple||(e.skip=!!c||function(){return s in o.onceFileDetectionMap||(o.onceFileDetectionMap[s]=!0,!1)}),!s&&u&&(e.skip=!0),n&&(e.root=n,e.importedFilename=s,!a&&!l&&(t.importMultiple||!c))){o.recursionDetector[s]=!0;var h=this.context;this.context=t;try{this._visitor.visit(n)}catch(i){this.error=i}this.context=h}o.importCount--,o.isFinished&&o._sequencer.tryRun()},visitDeclaration:function(e,t){\"DetachedRuleset\"===e.value.type?this.context.frames.unshift(e):t.visitDeeper=!1},visitDeclarationOut:function(e){\"DetachedRuleset\"===e.value.type&&this.context.frames.shift()},visitAtRule:function(e,t){this.context.frames.unshift(e)},visitAtRuleOut:function(e){this.context.frames.shift()},visitMixinDefinition:function(e,t){this.context.frames.unshift(e)},visitMixinDefinitionOut:function(e){this.context.frames.shift()},visitRuleset:function(e,t){this.context.frames.unshift(e)},visitRulesetOut:function(e){this.context.frames.shift()},visitMedia:function(e,t){this.context.frames.unshift(e.rules[0])},visitMediaOut:function(e){this.context.frames.shift()}};var Ve=function(){function e(e){this.visible=e}return e.prototype.run=function(e){this.visit(e)},e.prototype.visitArray=function(e){if(!e)return e;var t,i=e.length;for(t=0;t<i;t++)this.visit(e[t]);return e},e.prototype.visit=function(e){return e?e.constructor===Array?this.visitArray(e):(!e.blocksVisibility||e.blocksVisibility()||(this.visible?e.ensureVisibility():e.ensureInvisibility(),e.accept(this)),e):e},e}(),Fe=function(){function e(){this._visitor=new Pe(this),this.contexts=[],this.allExtendsStack=[[]]}return e.prototype.run=function(e){return(e=this._visitor.visit(e)).allExtends=this.allExtendsStack[0],e},e.prototype.visitDeclaration=function(e,t){t.visitDeeper=!1},e.prototype.visitMixinDefinition=function(e,t){t.visitDeeper=!1},e.prototype.visitRuleset=function(e,t){if(!e.root){var i,n,r,s,o=[],a=e.rules,l=a?a.length:0;for(i=0;i<l;i++)e.rules[i]instanceof Ce.Extend&&(o.push(a[i]),e.extendOnEveryPath=!0);var u=e.paths;for(i=0;i<u.length;i++){var c=u[i],h=c[c.length-1].extendList;for((s=h?k(h).concat(o):o)&&(s=s.map((function(e){return e.clone()}))),n=0;n<s.length;n++)this.foundExtends=!0,(r=s[n]).findSelfSelectors(c),r.ruleset=e,0===n&&(r.firstExtendOnThisSelectorPath=!0),this.allExtendsStack[this.allExtendsStack.length-1].push(r)}this.contexts.push(e.selectors)}},e.prototype.visitRulesetOut=function(e){e.root||(this.contexts.length=this.contexts.length-1)},e.prototype.visitMedia=function(e,t){e.allExtends=[],this.allExtendsStack.push(e.allExtends)},e.prototype.visitMediaOut=function(e){this.allExtendsStack.length=this.allExtendsStack.length-1},e.prototype.visitAtRule=function(e,t){e.allExtends=[],this.allExtendsStack.push(e.allExtends)},e.prototype.visitAtRuleOut=function(e){this.allExtendsStack.length=this.allExtendsStack.length-1},e}(),$e=function(){function e(){this._visitor=new Pe(this)}return e.prototype.run=function(e){var t=new Fe;if(this.extendIndices={},t.run(e),!t.foundExtends)return e;e.allExtends=e.allExtends.concat(this.doExtendChaining(e.allExtends,e.allExtends)),this.allExtendsStack=[e.allExtends];var i=this._visitor.visit(e);return this.checkExtendsForNonMatched(e.allExtends),i},e.prototype.checkExtendsForNonMatched=function(e){var t=this.extendIndices;e.filter((function(e){return!e.hasFoundMatches&&1==e.parent_ids.length})).forEach((function(e){var i=\"_unknown_\";try{i=e.selector.toCSS({})}catch(e){}t[e.index+\" \"+i]||(t[e.index+\" \"+i]=!0,r.warn(\"extend '\"+i+\"' has no matches\"))}))},e.prototype.doExtendChaining=function(e,t,i){var n,r,s,o,a,l,u,c,h=[],f=this;for(i=i||0,n=0;n<e.length;n++)for(r=0;r<t.length;r++)l=e[n],u=t[r],l.parent_ids.indexOf(u.object_id)>=0||(a=[u.selfSelectors[0]],(s=f.findMatch(l,a)).length&&(l.hasFoundMatches=!0,l.selfSelectors.forEach((function(e){var t=u.visibilityInfo();o=f.extendSelector(s,a,e,l.isVisible()),(c=new Ce.Extend(u.selector,u.option,0,u.fileInfo(),t)).selfSelectors=o,o[o.length-1].extendList=[c],h.push(c),c.ruleset=u.ruleset,c.parent_ids=c.parent_ids.concat(u.parent_ids,l.parent_ids),u.firstExtendOnThisSelectorPath&&(c.firstExtendOnThisSelectorPath=!0,u.ruleset.paths.push(o))}))));if(h.length){if(this.extendChainCount++,i>100){var p=\"{unable to calculate}\",v=\"{unable to calculate}\";try{p=h[0].selfSelectors[0].toCSS(),v=h[0].selector.toCSS()}catch(e){}throw{message:\"extend circular reference detected. One of the circular extends is currently:\"+p+\":extend(\"+v+\")\"}}return h.concat(f.doExtendChaining(h,t,i+1))}return h},e.prototype.visitDeclaration=function(e,t){t.visitDeeper=!1},e.prototype.visitMixinDefinition=function(e,t){t.visitDeeper=!1},e.prototype.visitSelector=function(e,t){t.visitDeeper=!1},e.prototype.visitRuleset=function(e,t){if(!e.root){var i,n,r,s,o=this.allExtendsStack[this.allExtendsStack.length-1],a=[],l=this;for(r=0;r<o.length;r++)for(n=0;n<e.paths.length;n++)if(s=e.paths[n],!e.extendOnEveryPath){var u=s[s.length-1].extendList;u&&u.length||(i=this.findMatch(o[r],s)).length&&(o[r].hasFoundMatches=!0,o[r].selfSelectors.forEach((function(e){var t;t=l.extendSelector(i,s,e,o[r].isVisible()),a.push(t)})))}e.paths=e.paths.concat(a)}},e.prototype.findMatch=function(e,t){var i,n,r,s,o,a,l,u=e.selector.elements,c=[],h=[];for(i=0;i<t.length;i++)for(n=t[i],r=0;r<n.elements.length;r++)for(s=n.elements[r],(e.allowBefore||0===i&&0===r)&&c.push({pathIndex:i,index:r,matched:0,initialCombinator:s.combinator}),a=0;a<c.length;a++)l=c[a],\"\"===(o=s.combinator.value)&&0===r&&(o=\" \"),!this.isElementValuesEqual(u[l.matched].value,s.value)||l.matched>0&&u[l.matched].combinator.value!==o?l=null:l.matched++,l&&(l.finished=l.matched===u.length,l.finished&&!e.allowAfter&&(r+1<n.elements.length||i+1<t.length)&&(l=null)),l?l.finished&&(l.length=u.length,l.endPathIndex=i,l.endPathElementIndex=r+1,c.length=0,h.push(l)):(c.splice(a,1),a--);return h},e.prototype.isElementValuesEqual=function(e,t){if(\"string\"==typeof e||\"string\"==typeof t)return e===t;if(e instanceof Ce.Attribute)return e.op===t.op&&e.key===t.key&&(e.value&&t.value?(e=e.value.value||e.value)===(t=t.value.value||t.value):!e.value&&!t.value);if(e=e.value,t=t.value,e instanceof Ce.Selector){if(!(t instanceof Ce.Selector)||e.elements.length!==t.elements.length)return!1;for(var i=0;i<e.elements.length;i++){if(e.elements[i].combinator.value!==t.elements[i].combinator.value&&(0!==i||(e.elements[i].combinator.value||\" \")!==(t.elements[i].combinator.value||\" \")))return!1;if(!this.isElementValuesEqual(e.elements[i].value,t.elements[i].value))return!1}return!0}return!1},e.prototype.extendSelector=function(e,t,i,n){var r,s,o,a,l,u=0,c=0,h=[];for(r=0;r<e.length;r++)s=t[(a=e[r]).pathIndex],o=new Ce.Element(a.initialCombinator,i.elements[0].value,i.elements[0].isVariable,i.elements[0].getIndex(),i.elements[0].fileInfo()),a.pathIndex>u&&c>0&&(h[h.length-1].elements=h[h.length-1].elements.concat(t[u].elements.slice(c)),c=0,u++),l=s.elements.slice(c,a.index).concat([o]).concat(i.elements.slice(1)),u===a.pathIndex&&r>0?h[h.length-1].elements=h[h.length-1].elements.concat(l):(h=h.concat(t.slice(u,a.pathIndex))).push(new Ce.Selector(l)),u=a.endPathIndex,(c=a.endPathElementIndex)>=t[u].elements.length&&(c=0,u++);return u<t.length&&c>0&&(h[h.length-1].elements=h[h.length-1].elements.concat(t[u].elements.slice(c)),u++),h=(h=h.concat(t.slice(u,t.length))).map((function(e){var t=e.createDerived(e.elements);return n?t.ensureVisibility():t.ensureInvisibility(),t}))},e.prototype.visitMedia=function(e,t){var i=e.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);i=i.concat(this.doExtendChaining(i,e.allExtends)),this.allExtendsStack.push(i)},e.prototype.visitMediaOut=function(e){var t=this.allExtendsStack.length-1;this.allExtendsStack.length=t},e.prototype.visitAtRule=function(e,t){var i=e.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);i=i.concat(this.doExtendChaining(i,e.allExtends)),this.allExtendsStack.push(i)},e.prototype.visitAtRuleOut=function(e){var t=this.allExtendsStack.length-1;this.allExtendsStack.length=t},e}(),Le=function(){function e(){this.contexts=[[]],this._visitor=new Pe(this)}return e.prototype.run=function(e){return this._visitor.visit(e)},e.prototype.visitDeclaration=function(e,t){t.visitDeeper=!1},e.prototype.visitMixinDefinition=function(e,t){t.visitDeeper=!1},e.prototype.visitRuleset=function(e,t){var i,n=this.contexts[this.contexts.length-1],r=[];this.contexts.push(r),e.root||((i=e.selectors)&&(i=i.filter((function(e){return e.getIsOutput()})),e.selectors=i.length?i:i=null,i&&e.joinSelectors(r,n,i)),i||(e.rules=null),e.paths=r)},e.prototype.visitRulesetOut=function(e){this.contexts.length=this.contexts.length-1},e.prototype.visitMedia=function(e,t){var i=this.contexts[this.contexts.length-1];e.rules[0].root=0===i.length||i[0].multiMedia},e.prototype.visitAtRule=function(e,t){var i=this.contexts[this.contexts.length-1];e.rules&&e.rules.length&&(e.rules[0].root=e.isRooted||0===i.length||null)},e}(),je=function(){function e(e){this._visitor=new Pe(this),this._context=e}return e.prototype.containsSilentNonBlockedChild=function(e){var t;if(!e)return!1;for(var i=0;i<e.length;i++)if((t=e[i]).isSilent&&t.isSilent(this._context)&&!t.blocksVisibility())return!0;return!1},e.prototype.keepOnlyVisibleChilds=function(e){e&&e.rules&&(e.rules=e.rules.filter((function(e){return e.isVisible()})))},e.prototype.isEmpty=function(e){return!e||!e.rules||0===e.rules.length},e.prototype.hasVisibleSelector=function(e){return!(!e||!e.paths)&&e.paths.length>0},e.prototype.resolveVisibility=function(e,t){if(!e.blocksVisibility()){if(this.isEmpty(e)&&!this.containsSilentNonBlockedChild(t))return;return e}var i=e.rules[0];if(this.keepOnlyVisibleChilds(i),!this.isEmpty(i))return e.ensureVisibility(),e.removeVisibilityBlock(),e},e.prototype.isVisibleRuleset=function(e){return!!e.firstRoot||!this.isEmpty(e)&&!(!e.root&&!this.hasVisibleSelector(e))},e}(),Ne=function(e){this._visitor=new Pe(this),this._context=e,this.utils=new je(e)};Ne.prototype={isReplacing:!0,run:function(e){return this._visitor.visit(e)},visitDeclaration:function(e,t){if(!e.blocksVisibility()&&!e.variable)return e},visitMixinDefinition:function(e,t){e.frames=[]},visitExtend:function(e,t){},visitComment:function(e,t){if(!e.blocksVisibility()&&!e.isSilent(this._context))return e},visitMedia:function(e,t){var i=e.rules[0].rules;return e.accept(this._visitor),t.visitDeeper=!1,this.utils.resolveVisibility(e,i)},visitImport:function(e,t){if(!e.blocksVisibility())return e},visitAtRule:function(e,t){return e.rules&&e.rules.length?this.visitAtRuleWithBody(e,t):this.visitAtRuleWithoutBody(e,t)},visitAnonymous:function(e,t){if(!e.blocksVisibility())return e.accept(this._visitor),e},visitAtRuleWithBody:function(e,t){var i=function(e){var t=e.rules;return function(e){var t=e.rules;return 1===t.length&&(!t[0].paths||0===t[0].paths.length)}(e)?t[0].rules:t}(e);return e.accept(this._visitor),t.visitDeeper=!1,this.utils.isEmpty(e)||this._mergeRules(e.rules[0].rules),this.utils.resolveVisibility(e,i)},visitAtRuleWithoutBody:function(e,t){if(!e.blocksVisibility()){if(\"@charset\"===e.name){if(this.charset){if(e.debugInfo){var i=new Ce.Comment(\"/* \"+e.toCSS(this._context).replace(/\\n/g,\"\")+\" */\\n\");return i.debugInfo=e.debugInfo,this._visitor.visit(i)}return}this.charset=!0}return e}},checkValidNodes:function(e,t){if(e)for(var i=0;i<e.length;i++){var n=e[i];if(t&&n instanceof Ce.Declaration&&!n.variable)throw{message:\"Properties must be inside selector blocks. They cannot be in the root\",index:n.getIndex(),filename:n.fileInfo()&&n.fileInfo().filename};if(n instanceof Ce.Call)throw{message:\"Function '\"+n.name+\"' did not return a root node\",index:n.getIndex(),filename:n.fileInfo()&&n.fileInfo().filename};if(n.type&&!n.allowRoot)throw{message:n.type+\" node returned by a function is not valid here\",index:n.getIndex(),filename:n.fileInfo()&&n.fileInfo().filename}}},visitRuleset:function(e,t){var i,n=[];if(this.checkValidNodes(e.rules,e.firstRoot),e.root)e.accept(this._visitor),t.visitDeeper=!1;else{this._compileRulesetPaths(e);for(var r=e.rules,s=r?r.length:0,o=0;o<s;)(i=r[o])&&i.rules?(n.push(this._visitor.visit(i)),r.splice(o,1),s--):o++;s>0?e.accept(this._visitor):e.rules=null,t.visitDeeper=!1}return e.rules&&(this._mergeRules(e.rules),this._removeDuplicateRules(e.rules)),this.utils.isVisibleRuleset(e)&&(e.ensureVisibility(),n.splice(0,0,e)),1===n.length?n[0]:n},_compileRulesetPaths:function(e){e.paths&&(e.paths=e.paths.filter((function(e){var t;for(\" \"===e[0].elements[0].combinator.value&&(e[0].elements[0].combinator=new Ce.Combinator(\"\")),t=0;t<e.length;t++)if(e[t].isVisible()&&e[t].getIsOutput())return!0;return!1})))},_removeDuplicateRules:function(e){if(e){var t,i,n,r={};for(n=e.length-1;n>=0;n--)if((i=e[n])instanceof Ce.Declaration)if(r[i.name]){(t=r[i.name])instanceof Ce.Declaration&&(t=r[i.name]=[r[i.name].toCSS(this._context)]);var s=i.toCSS(this._context);-1!==t.indexOf(s)?e.splice(n,1):t.push(s)}else r[i.name]=i}},_mergeRules:function(e){if(e){for(var t={},i=[],n=0;n<e.length;n++){var r=e[n];if(r.merge){var s=r.name;t[s]?e.splice(n--,1):i.push(t[s]=[]),t[s].push(r)}}i.forEach((function(e){if(e.length>0){var t=e[0],i=[],n=[new Ce.Expression(i)];e.forEach((function(e){\"+\"===e.merge&&i.length>0&&n.push(new Ce.Expression(i=[])),i.push(e.value),t.important=t.important||e.important})),t.value=new Ce.Value(n)}}))}}};var De={Visitor:Pe,ImportVisitor:Oe,MarkVisibleSelectorsVisitor:Ve,ExtendVisitor:$e,JoinSelectorVisitor:Le,ToCSSVisitor:Ne};var Be=function(){var e,t,i,n,r,s,o,a=[],l={};function u(i){for(var n,a,c,h=l.i,f=t,p=l.i-o,v=l.i+s.length-p,d=l.i+=i,m=e;l.i<v;l.i++){if(n=m.charCodeAt(l.i),l.autoCommentAbsorb&&47===n){if(\"/\"===(a=m.charAt(l.i+1))){c={index:l.i,isLineComment:!0};var g=m.indexOf(\"\\n\",l.i+2);g<0&&(g=v),l.i=g,c.text=m.substr(c.index,l.i-c.index),l.commentStore.push(c);continue}if(\"*\"===a){var y=m.indexOf(\"*/\",l.i+2);if(y>=0){c={index:l.i,text:m.substr(l.i,y+2-l.i),isLineComment:!1},l.i+=c.text.length-1,l.commentStore.push(c);continue}}break}if(32!==n&&10!==n&&9!==n&&13!==n)break}if(s=s.slice(i+l.i-d+p),o=l.i,!s.length){if(t<r.length-1)return s=r[++t],u(0),!0;l.finished=!0}return h!==l.i||f!==t}return l.save=function(){o=l.i,a.push({current:s,i:l.i,j:t})},l.restore=function(e){(l.i>i||l.i===i&&e&&!n)&&(i=l.i,n=e);var r=a.pop();s=r.current,o=l.i=r.i,t=r.j},l.forget=function(){a.pop()},l.isWhitespace=function(t){var i=l.i+(t||0),n=e.charCodeAt(i);return 32===n||13===n||9===n||10===n},l.$re=function(e){l.i>o&&(s=s.slice(l.i-o),o=l.i);var t=e.exec(s);return t?(u(t[0].length),\"string\"==typeof t?t:1===t.length?t[0]:t):null},l.$char=function(t){return e.charAt(l.i)!==t?null:(u(1),t)},l.$str=function(t){for(var i=t.length,n=0;n<i;n++)if(e.charAt(l.i+n)!==t.charAt(n))return null;return u(i),t},l.$quoted=function(t){var i=t||l.i,n=e.charAt(i);if(\"'\"===n||'\"'===n){for(var r=e.length,s=i,o=1;o+s<r;o++){switch(e.charAt(o+s)){case\"\\\\\":o++;continue;case\"\\r\":case\"\\n\":break;case n:var a=e.substr(s,o+1);return t||0===t?[n,a]:(u(o+1),a)}}return null}},l.$parseUntil=function(t){var i,n=\"\",r=null,s=!1,o=0,a=[],c=[],h=e.length,f=l.i,p=l.i,v=l.i,d=!0;i=\"string\"==typeof t?function(e){return e===t}:function(e){return t.test(e)};do{var m=e.charAt(v);if(0===o&&i(m))(r=e.substr(p,v-p))?c.push(r):c.push(\" \"),r=c,u(v-f),d=!1;else{if(s){\"*\"===m&&\"/\"===e.charAt(v+1)&&(v++,o--,s=!1),v++;continue}switch(m){case\"\\\\\":v++,m=e.charAt(v),c.push(e.substr(p,v-p+1)),p=v+1;break;case\"/\":\"*\"===e.charAt(v+1)&&(v++,s=!0,o++);break;case\"'\":case'\"':(n=l.$quoted(v))?(c.push(e.substr(p,v-p),n),p=(v+=n[1].length-1)+1):(u(v-f),r=m,d=!1);break;case\"{\":a.push(\"}\"),o++;break;case\"(\":a.push(\")\"),o++;break;case\"[\":a.push(\"]\"),o++;break;case\"}\":case\")\":case\"]\":var g=a.pop();m===g?o--:(u(v-f),r=g,d=!1)}++v>h&&(d=!1)}}while(d);return r||null},l.autoCommentAbsorb=!0,l.commentStore=[],l.finished=!1,l.peek=function(t){if(\"string\"==typeof t){for(var i=0;i<t.length;i++)if(e.charAt(l.i+i)!==t.charAt(i))return!1;return!0}return t.test(s)},l.peekChar=function(t){return e.charAt(l.i)===t},l.currentChar=function(){return e.charAt(l.i)},l.prevChar=function(){return e.charAt(l.i-1)},l.getInput=function(){return e},l.peekNotNumeric=function(){var t=e.charCodeAt(l.i);return t>57||t<43||47===t||44===t},l.start=function(n,a,c){e=n,l.i=t=o=i=0,r=a?function(e,t){var i,n,r,s,o,a,l,u,c,h=e.length,f=0,p=0,v=[],d=0;function m(t){var i=o-d;i<512&&!t||!i||(v.push(e.slice(d,o+1)),d=o+1)}for(o=0;o<h;o++)if(!((l=e.charCodeAt(o))>=97&&l<=122||l<34))switch(l){case 40:p++,n=o;continue;case 41:if(--p<0)return t(\"missing opening `(`\",o);continue;case 59:p||m();continue;case 123:f++,i=o;continue;case 125:if(--f<0)return t(\"missing opening `{`\",o);f||p||m();continue;case 92:if(o<h-1){o++;continue}return t(\"unescaped `\\\\`\",o);case 34:case 39:case 96:for(c=0,a=o,o+=1;o<h;o++)if(!((u=e.charCodeAt(o))>96)){if(u==l){c=1;break}if(92==u){if(o==h-1)return t(\"unescaped `\\\\`\",o);o++}}if(c)continue;return t(\"unmatched `\"+String.fromCharCode(l)+\"`\",a);case 47:if(p||o==h-1)continue;if(47==(u=e.charCodeAt(o+1)))for(o+=2;o<h&&(!((u=e.charCodeAt(o))<=13)||10!=u&&13!=u);o++);else if(42==u){for(r=a=o,o+=2;o<h-1&&(125==(u=e.charCodeAt(o))&&(s=o),42!=u||47!=e.charCodeAt(o+1));o++);if(o==h-1)return t(\"missing closing `*/`\",a);o++}continue;case 42:if(o<h-1&&47==e.charCodeAt(o+1))return t(\"unmatched `/*`\",o);continue}return 0!==f?t(r>i&&s>r?\"missing closing `}` or `*/`\":\"missing closing `}`\",i):0!==p?t(\"missing closing `)`\",n):(m(!0),v)}(n,c):[n],s=r[0],u(0)},l.end=function(){var t,r=l.i>=e.length;return l.i<i&&(t=n,l.i=i),{isFinished:r,furthest:l.i,furthestPossibleErrorMessage:t,furthestReachedEnd:l.i>=e.length-1,furthestChar:e[l.i]}},l},Ue=function e(t,i,n){var r,s=Be();function o(e,t){throw new O({index:s.i,filename:n.filename,type:t||\"Syntax\",message:e},i)}function a(e,t){var i=e instanceof Function?e.call(r):s.$re(e);if(i)return i;o(t||(\"string\"==typeof e?\"expected '\"+e+\"' got '\"+s.currentChar()+\"'\":\"unexpected token\"))}function l(e,t){if(s.$char(e))return e;o(t||\"expected '\"+e+\"' got '\"+s.currentChar()+\"'\")}function u(e){var t=n.filename;return{lineNumber:C(e,s.getInput()).line+1,fileName:t}}return{parserInput:s,imports:i,fileInfo:n,parseNode:function(e,t,n,o,a){var l,u=[],c=s;try{c.start(e,!1,(function(e,t){a({message:e,index:t+n})}));for(var h=0,f=void 0,p=void 0;f=t[h];h++)if(p=c.i,l=r[f]()){try{l._index=p+n,l._fileInfo=o}catch(e){}u.push(l)}else u.push(null);c.end().isFinished?a(null,u):a(!0,null)}catch(e){throw new O({index:e.index+n,message:e.message},i,o.filename)}},parse:function(r,o,a){var l,u,c,h,f=null,p=\"\";if(u=a&&a.globalVars?e.serializeVars(a.globalVars)+\"\\n\":\"\",c=a&&a.modifyVars?\"\\n\"+e.serializeVars(a.modifyVars):\"\",t.pluginManager)for(var v=t.pluginManager.getPreProcessors(),d=0;d<v.length;d++)r=v[d].process(r,{context:t,imports:i,fileInfo:n});(u||a&&a.banner)&&(p=(a&&a.banner?a.banner:\"\")+u,(h=i.contentsIgnoredChars)[n.filename]=h[n.filename]||0,h[n.filename]+=p.length),r=p+(r=r.replace(/\\r\\n?/g,\"\\n\")).replace(/^\\uFEFF/,\"\")+c,i.contents[n.filename]=r;try{s.start(r,t.chunkInput,(function(e,t){throw new O({index:t,type:\"Parse\",message:e,filename:n.filename},i)})),Ce.Node.prototype.parse=this,l=new Ce.Ruleset(null,this.parsers.primary()),Ce.Node.prototype.rootNode=l,l.root=!0,l.firstRoot=!0,l.functionRegistry=H.inherit()}catch(e){return o(new O(e,i,n.filename))}var m=s.end();if(!m.isFinished){var g=m.furthestPossibleErrorMessage;g||(g=\"Unrecognised input\",\"}\"===m.furthestChar?g+=\". Possibly missing opening '{'\":\")\"===m.furthestChar?g+=\". Possibly missing opening '('\":m.furthestReachedEnd&&(g+=\". Possibly missing something\")),f=new O({type:\"Parse\",message:g,index:m.furthest,filename:n.filename},i)}var y=function(e){return(e=f||e||i.error)?(e instanceof O||(e=new O(e,i,n.filename)),o(e)):o(null,l)};if(!1===t.processImports)return y();new De.ImportVisitor(i,y).run(l)},parsers:r={primary:function(){for(var e,t=this.mixin,i=[];;){for(;e=this.comment();)i.push(e);if(s.finished)break;if(s.peek(\"}\"))break;if(e=this.extendRule())i=i.concat(e);else if(e=t.definition()||this.declaration()||t.call(!1,!1)||this.ruleset()||this.variableCall()||this.entities.call()||this.atrule())i.push(e);else{for(var n=!1;s.$char(\";\");)n=!0;if(!n)break}}return i},comment:function(){if(s.commentStore.length){var e=s.commentStore.shift();return new Ce.Comment(e.text,e.isLineComment,e.index,n)}},entities:{mixinLookup:function(){return r.mixin.call(!0,!0)},quoted:function(e){var t,i=s.i,r=!1;if(s.save(),s.$char(\"~\"))r=!0;else if(e)return void s.restore();if(t=s.$quoted())return s.forget(),new Ce.Quoted(t.charAt(0),t.substr(1,t.length-2),r,i,n);s.restore()},keyword:function(){var e=s.$char(\"%\")||s.$re(/^\\[?(?:[\\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\\]?/);if(e)return Ce.Color.fromKeyword(e)||new Ce.Keyword(e)},call:function(){var e,t,i,r=s.i;if(!s.peek(/^url\\(/i))if(s.save(),e=s.$re(/^([\\w-]+|%|~|progid:[\\w\\.]+)\\(/)){if(e=e[1],(i=this.customFuncCall(e))&&(t=i.parse())&&i.stop)return s.forget(),t;if(t=this.arguments(t),s.$char(\")\"))return s.forget(),new Ce.Call(e,t,r,n);s.restore(\"Could not parse call arguments or missing ')'\")}else s.forget()},customFuncCall:function(e){return{alpha:t(r.ieAlpha,!0),boolean:t(i),if:t(i)}[e.toLowerCase()];function t(e,t){return{parse:e,stop:t}}function i(){return[a(r.condition,\"expected condition\")]}},arguments:function(e){var t,i,n=e||[],o=[];for(s.save();;){if(e)e=!1;else{if(!(i=r.detachedRuleset()||this.assignment()||r.expression()))break;i.value&&1==i.value.length&&(i=i.value[0]),n.push(i)}s.$char(\",\")||(s.$char(\";\")||t)&&(t=!0,i=n.length<1?n[0]:new Ce.Value(n),o.push(i),n=[])}return s.forget(),t?o:n},literal:function(){return this.dimension()||this.color()||this.quoted()||this.unicodeDescriptor()},assignment:function(){var e,t;if(s.save(),e=s.$re(/^\\w+(?=\\s?=)/i))if(s.$char(\"=\")){if(t=r.entity())return s.forget(),new Ce.Assignment(e,t);s.restore()}else s.restore();else s.restore()},url:function(){var e,t=s.i;if(s.autoCommentAbsorb=!1,s.$str(\"url(\"))return e=this.quoted()||this.variable()||this.property()||s.$re(/^(?:(?:\\\\[\\(\\)'\"])|[^\\(\\)'\"])+/)||\"\",s.autoCommentAbsorb=!0,l(\")\"),new Ce.URL(null!=e.value||e instanceof Ce.Variable||e instanceof Ce.Property?e:new Ce.Anonymous(e,t),t,n);s.autoCommentAbsorb=!0},variable:function(){var e,t,i=s.i;if(s.save(),\"@\"===s.currentChar()&&(t=s.$re(/^@@?[\\w-]+/))){if(\"(\"===(e=s.currentChar())||\"[\"===e&&!s.prevChar().match(/^\\s/)){var o=r.variableCall(t);if(o)return s.forget(),o}return s.forget(),new Ce.Variable(t,i,n)}s.restore()},variableCurly:function(){var e,t=s.i;if(\"@\"===s.currentChar()&&(e=s.$re(/^@\\{([\\w-]+)\\}/)))return new Ce.Variable(\"@\"+e[1],t,n)},property:function(){var e,t=s.i;if(\"$\"===s.currentChar()&&(e=s.$re(/^\\$[\\w-]+/)))return new Ce.Property(e,t,n)},propertyCurly:function(){var e,t=s.i;if(\"$\"===s.currentChar()&&(e=s.$re(/^\\$\\{([\\w-]+)\\}/)))return new Ce.Property(\"$\"+e[1],t,n)},color:function(){var e;if(s.save(),\"#\"===s.currentChar()&&(e=s.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\\w.#\\[])?/))&&!e[2])return s.forget(),new Ce.Color(e[1],void 0,e[0]);s.restore()},colorKeyword:function(){s.save();var e=s.autoCommentAbsorb;s.autoCommentAbsorb=!1;var t=s.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);if(s.autoCommentAbsorb=e,t){s.restore();var i=Ce.Color.fromKeyword(t);return i?(s.$str(t),i):void 0}s.forget()},dimension:function(){if(!s.peekNotNumeric()){var e=s.$re(/^([+-]?\\d*\\.?\\d+)(%|[a-z_]+)?/i);return e?new Ce.Dimension(e[1],e[2]):void 0}},unicodeDescriptor:function(){var e;if(e=s.$re(/^U\\+[0-9a-fA-F?]+(\\-[0-9a-fA-F?]+)?/))return new Ce.UnicodeDescriptor(e[0])},javascript:function(){var e,t=s.i;s.save();var i=s.$char(\"~\");if(s.$char(\"`\")){if(e=s.$re(/^[^`]*`/))return s.forget(),new Ce.JavaScript(e.substr(0,e.length-1),Boolean(i),t,n);s.restore(\"invalid javascript definition\")}else s.restore()}},variable:function(){var e;if(\"@\"===s.currentChar()&&(e=s.$re(/^(@[\\w-]+)\\s*:/)))return e[1]},variableCall:function(e){var t,i=s.i,o=!!e,a=e;if(s.save(),a||\"@\"===s.currentChar()&&(a=s.$re(/^(@[\\w-]+)(\\(\\s*\\))?/))){if(!(t=this.mixin.ruleLookups())&&(o&&\"()\"!==s.$str(\"()\")||\"()\"!==a[2]))return void s.restore(\"Missing '[...]' lookup in variable call\");o||(a=a[1]);var l=new Ce.VariableCall(a,i,n);return!o&&r.end()?(s.forget(),l):(s.forget(),new Ce.NamespaceValue(l,t,i,n))}s.restore()},extend:function(e){var t,i,r,l,u,c=s.i;if(s.$str(e?\"&:extend(\":\":extend(\")){do{for(r=null,t=null;!(r=s.$re(/^(all)(?=\\s*(\\)|,))/))&&(i=this.element());)t?t.push(i):t=[i];r=r&&r[1],t||o(\"Missing target selector for :extend().\"),u=new Ce.Extend(new Ce.Selector(t),r,c,n),l?l.push(u):l=[u]}while(s.$char(\",\"));return a(/^\\)/),e&&a(/^;/),l}},extendRule:function(){return this.extend(!0)},mixin:{call:function(e,t){var i,o,a,u,c=s.currentChar(),h=!1,f=s.i;if(\".\"===c||\"#\"===c){if(s.save(),o=this.elements()){if(s.$char(\"(\")&&(a=this.args(!0).args,l(\")\"),u=!0),!1!==t&&(i=this.ruleLookups()),!0===t&&!i)return void s.restore();if(e&&!i&&!u)return void s.restore();if(!e&&r.important()&&(h=!0),e||r.end()){s.forget();var p=new Ce.mixin.Call(o,a,f,n,!i&&h);return i?new Ce.NamespaceValue(p,i):p}}s.restore()}},elements:function(){for(var e,t,i,r,o,a=/^[#.](?:[\\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;o=s.i,t=s.$re(a);)r=new Ce.Element(i,t,!1,o,n),e?e.push(r):e=[r],i=s.$char(\">\");return e},args:function(e){var t,i,n,a,l,u,c,h=r.entities,f={args:null,variadic:!1},p=[],v=[],d=[],m=!0;for(s.save();;){if(e)u=r.detachedRuleset()||r.expression();else{if(s.commentStore.length=0,s.$str(\"...\")){f.variadic=!0,s.$char(\";\")&&!t&&(t=!0),(t?v:d).push({variadic:!0});break}u=h.variable()||h.property()||h.literal()||h.keyword()||this.call(!0)}if(!u||!m)break;a=null,u.throwAwayComments&&u.throwAwayComments(),l=u;var g=null;if(e?u.value&&1==u.value.length&&(g=u.value[0]):g=u,g&&(g instanceof Ce.Variable||g instanceof Ce.Property))if(s.$char(\":\")){if(p.length>0&&(t&&o(\"Cannot mix ; and , as delimiter types\"),i=!0),!(l=r.detachedRuleset()||r.expression())){if(!e)return s.restore(),f.args=[],f;o(\"could not understand value for named argument\")}a=n=g.name}else if(s.$str(\"...\")){if(!e){f.variadic=!0,s.$char(\";\")&&!t&&(t=!0),(t?v:d).push({name:u.name,variadic:!0});break}c=!0}else e||(n=a=g.name,l=null);l&&p.push(l),d.push({name:a,value:l,expand:c}),s.$char(\",\")?m=!0:((m=\";\"===s.$char(\";\"))||t)&&(i&&o(\"Cannot mix ; and , as delimiter types\"),t=!0,p.length>1&&(l=new Ce.Value(p)),v.push({name:n,value:l,expand:c}),n=null,p=[],i=!1)}return s.forget(),f.args=t?v:d,f},definition:function(){var e,t,i,n,o=[],l=!1;if(!(\".\"!==s.currentChar()&&\"#\"!==s.currentChar()||s.peek(/^[^{]*\\}/)))if(s.save(),t=s.$re(/^([#.](?:[\\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\\s*\\(/)){e=t[1];var u=this.args(!1);if(o=u.args,l=u.variadic,!s.$char(\")\"))return void s.restore(\"Missing closing ')'\");if(s.commentStore.length=0,s.$str(\"when\")&&(n=a(r.conditions,\"expected condition\")),i=r.block())return s.forget(),new Ce.mixin.Definition(e,o,i,n,l);s.restore()}else s.restore()},ruleLookups:function(){var e,t=[];if(\"[\"===s.currentChar()){for(;;){if(s.save(),!(e=this.lookupValue())&&\"\"!==e){s.restore();break}t.push(e),s.forget()}return t.length>0?t:void 0}},lookupValue:function(){if(s.save(),s.$char(\"[\")){var e=s.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);if(s.$char(\"]\"))return e||\"\"===e?(s.forget(),e):void s.restore();s.restore()}else s.restore()}},entity:function(){var e=this.entities;return this.comment()||e.literal()||e.variable()||e.url()||e.property()||e.call()||e.keyword()||this.mixin.call(!0)||e.javascript()},end:function(){return s.$char(\";\")||s.peek(\"}\")},ieAlpha:function(){var e;if(s.$re(/^opacity=/i))return(e=s.$re(/^\\d+/))||(e=\"@{\"+(e=a(r.entities.variable,\"Could not parse alpha\")).name.slice(1)+\"}\"),l(\")\"),new Ce.Quoted(\"\",\"alpha(opacity=\"+e+\")\")},element:function(){var e,t,i,r=s.i;if(t=this.combinator(),(e=s.$re(/^(?:\\d+\\.\\d+|\\d+)%/)||s.$re(/^(?:[.#]?|:*)(?:[\\w-]|[^\\x00-\\x9f]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)||s.$char(\"*\")||s.$char(\"&\")||this.attribute()||s.$re(/^\\([^&()@]+\\)/)||s.$re(/^[\\.#:](?=@)/)||this.entities.variableCurly())||(s.save(),s.$char(\"(\")?(i=this.selector(!1))&&s.$char(\")\")?(e=new Ce.Paren(i),s.forget()):s.restore(\"Missing closing ')'\"):s.forget()),e)return new Ce.Element(t,e,e instanceof Ce.Variable,r,n)},combinator:function(){var e=s.currentChar();if(\"/\"===e){s.save();var t=s.$re(/^\\/[a-z]+\\//i);if(t)return s.forget(),new Ce.Combinator(t);s.restore()}if(\">\"===e||\"+\"===e||\"~\"===e||\"|\"===e||\"^\"===e){for(s.i++,\"^\"===e&&\"^\"===s.currentChar()&&(e=\"^^\",s.i++);s.isWhitespace();)s.i++;return new Ce.Combinator(e)}return s.isWhitespace(-1)?new Ce.Combinator(\" \"):new Ce.Combinator(null)},selector:function(e){var t,i,r,l,u,c,h,f=s.i;for(e=!1!==e;(e&&(i=this.extend())||e&&(c=s.$str(\"when\"))||(l=this.element()))&&(c?h=a(this.conditions,\"expected condition\"):h?o(\"CSS guard can only be used at the end of selector\"):i?u=u?u.concat(i):i:(u&&o(\"Extend can only be used at the end of selector\"),r=s.currentChar(),t?t.push(l):t=[l],l=null),\"{\"!==r&&\"}\"!==r&&\";\"!==r&&\",\"!==r&&\")\"!==r););if(t)return new Ce.Selector(t,u,h,f,n);u&&o(\"Extend must be used to extend a selector, it cannot be used on its own\")},selectors:function(){for(var e,t;(e=this.selector())&&(t?t.push(e):t=[e],s.commentStore.length=0,e.condition&&t.length>1&&o(\"Guards are only currently allowed on a single selector.\"),s.$char(\",\"));)e.condition&&o(\"Guards are only currently allowed on a single selector.\"),s.commentStore.length=0;return t},attribute:function(){if(s.$char(\"[\")){var e,t,i,n=this.entities;return(e=n.variableCurly())||(e=a(/^(?:[_A-Za-z0-9-\\*]*\\|)?(?:[_A-Za-z0-9-]|\\\\.)+/)),(i=s.$re(/^[|~*$^]?=/))&&(t=n.quoted()||s.$re(/^[0-9]+%/)||s.$re(/^[\\w-]+/)||n.variableCurly()),l(\"]\"),new Ce.Attribute(e,i,t)}},block:function(){var e;if(s.$char(\"{\")&&(e=this.primary())&&s.$char(\"}\"))return e},blockRuleset:function(){var e=this.block();return e&&(e=new Ce.Ruleset(null,e)),e},detachedRuleset:function(){var e,t,i;if(s.save(),!s.$re(/^[.#]\\(/)||(t=(e=this.mixin.args(!1)).args,i=e.variadic,s.$char(\")\"))){var n=this.blockRuleset();if(n)return s.forget(),t?new Ce.mixin.Definition(null,t,n,null,i):new Ce.DetachedRuleset(n);s.restore()}else s.restore()},ruleset:function(){var e,i,n;if(s.save(),t.dumpLineNumbers&&(n=u(s.i)),(e=this.selectors())&&(i=this.block())){s.forget();var r=new Ce.Ruleset(e,i,t.strictImports);return t.dumpLineNumbers&&(r.debugInfo=n),r}s.restore()},declaration:function(){var e,t,i,r,o,a,l=s.i,u=s.currentChar();if(\".\"!==u&&\"#\"!==u&&\"&\"!==u&&\":\"!==u)if(s.save(),e=this.variable()||this.ruleProperty()){if((a=\"string\"==typeof e)&&(t=this.detachedRuleset())&&(i=!0),s.commentStore.length=0,!t){if(o=!a&&e.length>1&&e.pop().value,t=e[0].value&&\"--\"===e[0].value.slice(0,2)?this.permissiveValue():this.anonymousValue())return s.forget(),new Ce.Declaration(e,t,!1,o,l,n);t||(t=this.value()),t?r=this.important():a&&(t=this.permissiveValue())}if(t&&(this.end()||i))return s.forget(),new Ce.Declaration(e,t,r,o,l,n);s.restore()}else s.restore()},anonymousValue:function(){var e=s.i,t=s.$re(/^([^.#@\\$+\\/'\"*`(;{}-]*);/);if(t)return new Ce.Anonymous(t[1],e)},permissiveValue:function(e){var t,i,r,a,l=e||\";\",u=s.i,c=[];function h(){var e=s.currentChar();return\"string\"==typeof l?e===l:l.test(e)}if(!h()){a=[];do{((i=this.comment())||(i=this.entity()))&&a.push(i)}while(i);if(r=h(),a.length>0){if(a=new Ce.Expression(a),r)return a;c.push(a),\" \"===s.prevChar()&&c.push(new Ce.Anonymous(\" \",u))}if(s.save(),a=s.$parseUntil(l)){if(\"string\"==typeof a&&o(\"Expected '\"+a+\"'\",\"Parse\"),1===a.length&&\" \"===a[0])return s.forget(),new Ce.Anonymous(\"\",u);var f=void 0;for(t=0;t<a.length;t++)if(f=a[t],Array.isArray(f))c.push(new Ce.Quoted(f[0],f[1],!0,u,n));else{t===a.length-1&&(f=f.trim());var p=new Ce.Quoted(\"'\",f,!0,u,n);p.variableRegex=/@([\\w-]+)/g,p.propRegex=/\\$([\\w-]+)/g,c.push(p)}return s.forget(),new Ce.Expression(c,!0)}s.restore()}},import:function(){var e,t,i=s.i,r=s.$re(/^@import?\\s+/);if(r){var a=(r?this.importOptions():null)||{};if(e=this.entities.quoted()||this.entities.url())return t=this.mediaFeatures(),s.$char(\";\")||(s.i=i,o(\"missing semi-colon or unrecognised media features on import\")),t=t&&new Ce.Value(t),new Ce.Import(e,t,a,i,n);s.i=i,o(\"malformed import statement\")}},importOptions:function(){var e,t,i,n={};if(!s.$char(\"(\"))return null;do{if(e=this.importOption()){switch(i=!0,t=e){case\"css\":t=\"less\",i=!1;break;case\"once\":t=\"multiple\",i=!1}if(n[t]=i,!s.$char(\",\"))break}}while(e);return l(\")\"),n},importOption:function(){var e=s.$re(/^(less|css|multiple|once|inline|reference|optional)/);if(e)return e[1]},mediaFeature:function(){var e,t,i=this.entities,r=[];s.save();do{(e=i.keyword()||i.variable()||i.mixinLookup())?r.push(e):s.$char(\"(\")&&(t=this.property(),e=this.value(),s.$char(\")\")?t&&e?r.push(new Ce.Paren(new Ce.Declaration(t,e,null,null,s.i,n,!0))):e?r.push(new Ce.Paren(e)):o(\"badly formed media feature definition\"):o(\"Missing closing ')'\",\"Parse\"))}while(e);if(s.forget(),r.length>0)return new Ce.Expression(r)},mediaFeatures:function(){var e,t=this.entities,i=[];do{if(e=this.mediaFeature()){if(i.push(e),!s.$char(\",\"))break}else if((e=t.variable()||t.mixinLookup())&&(i.push(e),!s.$char(\",\")))break}while(e);return i.length>0?i:null},media:function(){var e,i,r,a,l=s.i;if(t.dumpLineNumbers&&(a=u(l)),s.save(),s.$str(\"@media\"))return e=this.mediaFeatures(),(i=this.block())||o(\"media definitions require block statements after any features\"),s.forget(),r=new Ce.Media(i,e,l,n),t.dumpLineNumbers&&(r.debugInfo=a),r;s.restore()},plugin:function(){var e,t,i,r=s.i;if(s.$re(/^@plugin?\\s+/)){if(i=(t=this.pluginArgs())?{pluginArgs:t,isPlugin:!0}:{isPlugin:!0},e=this.entities.quoted()||this.entities.url())return s.$char(\";\")||(s.i=r,o(\"missing semi-colon on @plugin\")),new Ce.Import(e,null,i,r,n);s.i=r,o(\"malformed @plugin statement\")}},pluginArgs:function(){if(s.save(),!s.$char(\"(\"))return s.restore(),null;var e=s.$re(/^\\s*([^\\);]+)\\)\\s*/);return e[1]?(s.forget(),e[1].trim()):(s.restore(),null)},atrule:function(){var e,i,r,a,l,c,h,f=s.i,p=!0,v=!0;if(\"@\"===s.currentChar()){if(i=this.import()||this.plugin()||this.media())return i;if(s.save(),e=s.$re(/^@[a-z-]+/)){switch(a=e,\"-\"==e.charAt(1)&&e.indexOf(\"-\",2)>0&&(a=\"@\"+e.slice(e.indexOf(\"-\",2)+1)),a){case\"@charset\":l=!0,p=!1;break;case\"@namespace\":c=!0,p=!1;break;case\"@keyframes\":case\"@counter-style\":l=!0;break;case\"@document\":case\"@supports\":h=!0,v=!1;break;default:h=!0}if(s.commentStore.length=0,l?(i=this.entity())||o(\"expected \"+e+\" identifier\"):c?(i=this.expression())||o(\"expected \"+e+\" expression\"):h&&(i=this.permissiveValue(/^[{;]/),p=\"{\"===s.currentChar(),i?i.value||(i=null):p||\";\"===s.currentChar()||o(e+\" rule is missing block or ending semi-colon\")),p&&(r=this.blockRuleset()),r||!p&&i&&s.$char(\";\"))return s.forget(),new Ce.AtRule(e,i,r,f,n,t.dumpLineNumbers?u(f):null,v);s.restore(\"at-rule options not recognised\")}}},value:function(){var e,t=[],i=s.i;do{if((e=this.expression())&&(t.push(e),!s.$char(\",\")))break}while(e);if(t.length>0)return new Ce.Value(t,i)},important:function(){if(\"!\"===s.currentChar())return s.$re(/^! *important/)},sub:function(){var e,t;if(s.save(),s.$char(\"(\"))return(e=this.addition())&&s.$char(\")\")?(s.forget(),(t=new Ce.Expression([e])).parens=!0,t):void s.restore(\"Expected ')'\");s.restore()},multiplication:function(){var e,t,i,n,r;if(e=this.operand()){for(r=s.isWhitespace(-1);!s.peek(/^\\/[*\\/]/);){if(s.save(),!(i=s.$char(\"/\")||s.$char(\"*\")||s.$str(\"./\"))){s.forget();break}if(!(t=this.operand())){s.restore();break}s.forget(),e.parensInOp=!0,t.parensInOp=!0,n=new Ce.Operation(i,[n||e,t],r),r=s.isWhitespace(-1)}return n||e}},addition:function(){var e,t,i,n,r;if(e=this.multiplication()){for(r=s.isWhitespace(-1);(i=s.$re(/^[-+]\\s+/)||!r&&(s.$char(\"+\")||s.$char(\"-\")))&&(t=this.multiplication());)e.parensInOp=!0,t.parensInOp=!0,n=new Ce.Operation(i,[n||e,t],r),r=s.isWhitespace(-1);return n||e}},conditions:function(){var e,t,i,n=s.i;if(e=this.condition(!0)){for(;s.peek(/^,\\s*(not\\s*)?\\(/)&&s.$char(\",\")&&(t=this.condition(!0));)i=new Ce.Condition(\"or\",i||e,t,n);return i||e}},condition:function(e){var t,i,n;if(t=this.conditionAnd(e)){if(i=s.$str(\"or\")){if(!(n=this.condition(e)))return;t=new Ce.Condition(i,t,n)}return t}},conditionAnd:function(e){var t,i,n,r,o=this;if(t=(r=o.negatedCondition(e)||o.parenthesisCondition(e))||e?r:o.atomicCondition(e)){if(i=s.$str(\"and\")){if(!(n=this.conditionAnd(e)))return;t=new Ce.Condition(i,t,n)}return t}},negatedCondition:function(e){if(s.$str(\"not\")){var t=this.parenthesisCondition(e);return t&&(t.negate=!t.negate),t}},parenthesisCondition:function(e){var t;if(s.save(),s.$str(\"(\")){if(t=function(t){var i;if(s.save(),i=t.condition(e)){if(s.$char(\")\"))return s.forget(),i;s.restore()}else s.restore()}(this))return s.forget(),t;if(t=this.atomicCondition(e)){if(s.$char(\")\"))return s.forget(),t;s.restore(\"expected ')' got '\"+s.currentChar()+\"'\")}else s.restore()}else s.restore()},atomicCondition:function(e){var t,i,n,r,a=this.entities,l=s.i;function u(){return this.addition()||a.keyword()||a.quoted()||a.mixinLookup()}if(t=(u=u.bind(this))())return s.$char(\">\")?r=s.$char(\"=\")?\">=\":\">\":s.$char(\"<\")?r=s.$char(\"=\")?\"<=\":\"<\":s.$char(\"=\")&&(r=s.$char(\">\")?\"=>\":s.$char(\"<\")?\"=<\":\"=\"),r?(i=u())?n=new Ce.Condition(r,t,i,l,!1):o(\"expected expression\"):n=new Ce.Condition(\"=\",t,new Ce.Keyword(\"true\"),l,!1),n},operand:function(){var e,t=this.entities;s.peek(/^-[@\\$\\(]/)&&(e=s.$char(\"-\"));var i=this.sub()||t.dimension()||t.color()||t.variable()||t.property()||t.call()||t.quoted(!0)||t.colorKeyword()||t.mixinLookup();return e&&(i.parensInOp=!0,i=new Ce.Negative(i)),i},expression:function(){var e,t,i=[],n=s.i;do{(e=this.comment())?i.push(e):((e=this.addition()||this.entity())instanceof Ce.Comment&&(e=null),e&&(i.push(e),s.peek(/^\\/[\\/*]/)||(t=s.$char(\"/\"))&&i.push(new Ce.Anonymous(t,n))))}while(e);if(i.length>0)return new Ce.Expression(i)},property:function(){var e=s.$re(/^(\\*?-?[_a-zA-Z0-9-]+)\\s*:/);if(e)return e[1]},ruleProperty:function(){var e,t,i=[],r=[];s.save();var o=s.$re(/^([_a-zA-Z0-9-]+)\\s*:/);if(o)return i=[new Ce.Keyword(o[1])],s.forget(),i;function a(e){var t=s.i,n=s.$re(e);if(n)return r.push(t),i.push(n[1])}for(a(/^(\\*?)/);a(/^((?:[\\w-]+)|(?:[@\\$]\\{[\\w-]+\\}))/););if(i.length>1&&a(/^((?:\\+_|\\+)?)\\s*:/)){for(s.forget(),\"\"===i[0]&&(i.shift(),r.shift()),t=0;t<i.length;t++)e=i[t],i[t]=\"@\"!==e.charAt(0)&&\"$\"!==e.charAt(0)?new Ce.Keyword(e):\"@\"===e.charAt(0)?new Ce.Variable(\"@\"+e.slice(2,-1),r[t],n):new Ce.Property(\"$\"+e.slice(2,-1),r[t],n);return i}s.restore()}}}};function qe(e,t,i,n){return t.eval(e)?i.eval(e):n?n.eval(e):new j}function Te(e,t){try{return t.eval(e),L.True}catch(e){return L.False}}Ue.serializeVars=function(e){var t=\"\";for(var i in e)if(Object.hasOwnProperty.call(e,i)){var n=e[i];t+=(\"@\"===i[0]?\"\":\"@\")+i+\": \"+n+(\";\"===String(n).slice(-1)?\"\":\";\")}return t},qe.evalArgs=!1,Te.evalArgs=!1;var ze,Ge={isdefined:Te,boolean:function(e){return e?L.True:L.False},if:qe};function We(e){return Math.min(1,Math.max(0,e))}function Je(e,t){var i=ze.hsla(t.h,t.s,t.l,t.a);if(i)return e.value&&/^(rgb|hsl)/.test(e.value)?i.value=e.value:i.value=\"rgb\",i}function He(e){if(e.toHSL)return e.toHSL();throw new Error(\"Argument cannot be evaluated to a color\")}function Qe(e){if(e.toHSV)return e.toHSV();throw new Error(\"Argument cannot be evaluated to a color\")}function Ke(e){if(e instanceof ee)return parseFloat(e.unit.is(\"%\")?e.value/100:e.value);if(\"number\"==typeof e)return e;throw{type:\"Argument\",message:\"color functions take numbers as parameters\"}}var Ze=ze={rgb:function(e,t,i){var n=1;if(e instanceof ne){var r=e.value;if(e=r[0],t=r[1],(i=r[2])instanceof ie){var s=i;i=s.operands[0],n=s.operands[1]}}var o=ze.rgba(e,t,i,n);if(o)return o.value=\"rgb\",o},rgba:function(e,t,i,n){try{if(e instanceof c)return n=t?Ke(t):e.alpha,new c(e.rgb,n,\"rgba\");var r=[e,t,i].map((function(e){return i=255,(t=e)instanceof ee&&t.unit.is(\"%\")?parseFloat(t.value*i/100):Ke(t);var t,i}));return n=Ke(n),new c(r,n,\"rgba\")}catch(e){}},hsl:function(e,t,i){var n=1;if(e instanceof ne){var r=e.value;if(e=r[0],t=r[1],(i=r[2])instanceof ie){var s=i;i=s.operands[0],n=s.operands[1]}}var o=ze.hsla(e,t,i,n);if(o)return o.value=\"hsl\",o},hsla:function(e,t,i,n){try{if(e instanceof c)return n=t?Ke(t):e.alpha,new c(e.rgb,n,\"hsla\");var r,s;function o(e){return 6*(e=e<0?e+1:e>1?e-1:e)<1?r+(s-r)*e*6:2*e<1?s:3*e<2?r+(s-r)*(2/3-e)*6:r}e=Ke(e)%360/360,t=We(Ke(t)),i=We(Ke(i)),n=We(Ke(n)),r=2*i-(s=i<=.5?i*(t+1):i+t-i*t);var a=[255*o(e+1/3),255*o(e),255*o(e-1/3)];return n=Ke(n),new c(a,n,\"hsla\")}catch(e){}},hsv:function(e,t,i){return ze.hsva(e,t,i,1)},hsva:function(e,t,i,n){var r,s;e=Ke(e)%360/360*360,t=Ke(t),i=Ke(i),n=Ke(n);var o=[i,i*(1-t),i*(1-(s=e/60-(r=Math.floor(e/60%6)))*t),i*(1-(1-s)*t)],a=[[0,3,1],[2,0,1],[1,0,3],[1,2,0],[3,1,0],[0,1,2]];return ze.rgba(255*o[a[r][0]],255*o[a[r][1]],255*o[a[r][2]],n)},hue:function(e){return new ee(He(e).h)},saturation:function(e){return new ee(100*He(e).s,\"%\")},lightness:function(e){return new ee(100*He(e).l,\"%\")},hsvhue:function(e){return new ee(Qe(e).h)},hsvsaturation:function(e){return new ee(100*Qe(e).s,\"%\")},hsvvalue:function(e){return new ee(100*Qe(e).v,\"%\")},red:function(e){return new ee(e.rgb[0])},green:function(e){return new ee(e.rgb[1])},blue:function(e){return new ee(e.rgb[2])},alpha:function(e){return new ee(He(e).a)},luma:function(e){return new ee(e.luma()*e.alpha*100,\"%\")},luminance:function(e){var t=.2126*e.rgb[0]/255+.7152*e.rgb[1]/255+.0722*e.rgb[2]/255;return new ee(t*e.alpha*100,\"%\")},saturate:function(e,t,i){if(!e.rgb)return null;var n=He(e);return void 0!==i&&\"relative\"===i.value?n.s+=n.s*t.value/100:n.s+=t.value/100,n.s=We(n.s),Je(e,n)},desaturate:function(e,t,i){var n=He(e);return void 0!==i&&\"relative\"===i.value?n.s-=n.s*t.value/100:n.s-=t.value/100,n.s=We(n.s),Je(e,n)},lighten:function(e,t,i){var n=He(e);return void 0!==i&&\"relative\"===i.value?n.l+=n.l*t.value/100:n.l+=t.value/100,n.l=We(n.l),Je(e,n)},darken:function(e,t,i){var n=He(e);return void 0!==i&&\"relative\"===i.value?n.l-=n.l*t.value/100:n.l-=t.value/100,n.l=We(n.l),Je(e,n)},fadein:function(e,t,i){var n=He(e);return void 0!==i&&\"relative\"===i.value?n.a+=n.a*t.value/100:n.a+=t.value/100,n.a=We(n.a),Je(e,n)},fadeout:function(e,t,i){var n=He(e);return void 0!==i&&\"relative\"===i.value?n.a-=n.a*t.value/100:n.a-=t.value/100,n.a=We(n.a),Je(e,n)},fade:function(e,t){var i=He(e);return i.a=t.value/100,i.a=We(i.a),Je(e,i)},spin:function(e,t){var i=He(e),n=(i.h+t.value)%360;return i.h=n<0?360+n:n,Je(e,i)},mix:function(e,t,i){i||(i=new ee(50));var n=i.value/100,r=2*n-1,s=He(e).a-He(t).a,o=((r*s==-1?r:(r+s)/(1+r*s))+1)/2,a=1-o,l=[e.rgb[0]*o+t.rgb[0]*a,e.rgb[1]*o+t.rgb[1]*a,e.rgb[2]*o+t.rgb[2]*a],u=e.alpha*n+t.alpha*(1-n);return new c(l,u)},greyscale:function(e){return ze.desaturate(e,new ee(100))},contrast:function(e,t,i,n){if(!e.rgb)return null;if(void 0===i&&(i=ze.rgba(255,255,255,1)),void 0===t&&(t=ze.rgba(0,0,0,1)),t.luma()>i.luma()){var r=i;i=t,t=r}return n=void 0===n?.43:Ke(n),e.luma()<n?i:t},argb:function(e){return new j(e.toARGB())},color:function(e){if(e instanceof ue&&/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(e.value)){var t=e.value.slice(1);return new c(t,void 0,\"#\"+t)}if(e instanceof c||(e=c.fromKeyword(e.value)))return e.value=void 0,e;throw{type:\"Argument\",message:\"argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF\"}},tint:function(e,t){return ze.mix(ze.rgb(255,255,255),e,t)},shade:function(e,t){return ze.mix(ze.rgb(0,0,0),e,t)}};function Xe(e,t,i){var n,r,s,o,a=t.alpha,l=i.alpha,u=[];s=l+a*(1-l);for(var h=0;h<3;h++)o=e(n=t.rgb[h]/255,r=i.rgb[h]/255),s&&(o=(l*r+a*(n-l*(n+r-o)))/s),u[h]=255*o;return new c(u,s)}var Ye={multiply:function(e,t){return e*t},screen:function(e,t){return e+t-e*t},overlay:function(e,t){return(e*=2)<=1?Ye.multiply(e,t):Ye.screen(e-1,t)},softlight:function(e,t){var i=1,n=e;return t>.5&&(n=1,i=e>.25?Math.sqrt(e):((16*e-12)*e+4)*e),e-(1-2*t)*n*(i-e)},hardlight:function(e,t){return Ye.overlay(t,e)},difference:function(e,t){return Math.abs(e-t)},exclusion:function(e,t){return e+t-2*e*t},average:function(e,t){return(e+t)/2},negation:function(e,t){return 1-Math.abs(e+t-1)}};for(var et in Ye)Ye.hasOwnProperty(et)&&(Xe[et]=Xe.bind(null,Ye[et]));var tt=function(e){return Array.isArray(e.value)?e.value:Array(e)},it={_SELF:function(e){return e},\"~\":function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 1===e.length?e[0]:new $(e)},extract:function(e,t){return t=t.value-1,tt(e)[t]},length:function(e){return new ee(tt(e).length)},range:function(e,t,i){var n,r,s=1,o=[];t?(r=t,n=e.value,i&&(s=i.value)):(n=1,r=e);for(var a=n;a<=r.value;a+=s)o.push(new ee(a,r.unit));return new ne(o)},each:function(e,t){var i,n,r=this,s=[],o=function(e){return e instanceof u?e.eval(r.context):e};n=!e.value||e instanceof ue?e.ruleset?o(e.ruleset).rules:e.rules?e.rules.map(o):Array.isArray(e)?e.map(o):[o(e)]:Array.isArray(e.value)?e.value.map(o):[o(e.value)];var a=\"@value\",l=\"@key\",c=\"@index\";t.params?(a=t.params[0]&&t.params[0].name,l=t.params[1]&&t.params[1].name,c=t.params[2]&&t.params[2].name,t=t.rules):t=t.ruleset;for(var h=0;h<n.length;h++){var f=void 0,p=void 0,v=n[h];v instanceof D?(f=\"string\"==typeof v.name?v.name:v.name[0].value,p=v.value):(f=new ee(h+1),p=v),v instanceof U||(i=t.rules.slice(0),a&&i.push(new D(a,p,!1,!1,this.index,this.currentFileInfo)),c&&i.push(new D(c,new ee(h+1),!1,!1,this.index,this.currentFileInfo)),l&&i.push(new D(l,f,!1,!1,this.index,this.currentFileInfo)),s.push(new K([new F([new m(\"\",\"&\")])],i,t.strictImports,t.visibilityInfo())))}return new K([new F([new m(\"\",\"&\")])],s,t.strictImports,t.visibilityInfo()).eval(this.context)}},nt=function(e,t,i){if(!(i instanceof ee))throw{type:\"Argument\",message:\"argument must be a number\"};return null==t?t=i.unit:i=i.unify(),new ee(e(parseFloat(i.value)),t)},rt={ceil:null,floor:null,sqrt:null,abs:null,tan:\"\",sin:\"\",cos:\"\",atan:\"rad\",asin:\"rad\",acos:\"rad\"};for(var st in rt)rt.hasOwnProperty(st)&&(rt[st]=nt.bind(null,Math[st],rt[st]));rt.round=function(e,t){var i=void 0===t?0:t.value;return nt((function(e){return e.toFixed(i)}),null,e)};var ot=function(e,t){switch((t=Array.prototype.slice.call(t)).length){case 0:throw{type:\"Argument\",message:\"one or more arguments required\"}}var i,n,r,s,o,a,l,u,c=[],h={};for(i=0;i<t.length;i++)if((r=t[i])instanceof ee)if(l=\"\"!==(a=\"\"===(s=\"\"===r.unit.toString()&&void 0!==u?new ee(r.value,u).unify():r.unify()).unit.toString()&&void 0!==l?l:s.unit.toString())&&void 0===l||\"\"!==a&&\"\"===c[0].unify().unit.toString()?a:l,u=\"\"!==a&&void 0===u?r.unit.toString():u,void 0!==(n=void 0!==h[\"\"]&&\"\"!==a&&a===l?h[\"\"]:h[a]))o=\"\"===c[n].unit.toString()&&void 0!==u?new ee(c[n].value,u).unify():c[n].unify(),(e&&s.value<o.value||!e&&s.value>o.value)&&(c[n]=r);else{if(void 0!==l&&a!==l)throw{type:\"Argument\",message:\"incompatible types\"};h[a]=c.length,c.push(r)}else Array.isArray(t[i].value)&&Array.prototype.push.apply(t,Array.prototype.slice.call(t[i].value));return 1==c.length?c[0]:(t=c.map((function(e){return e.toCSS(this.context)})).join(this.context.compress?\",\":\", \"),new j((e?\"min\":\"max\")+\"(\"+t+\")\"))},at={min:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];try{return ot(!0,e)}catch(e){}},max:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];try{return ot(!1,e)}catch(e){}},convert:function(e,t){return e.convertTo(t.value)},pi:function(){return new ee(Math.PI)},mod:function(e,t){return new ee(e.value%t.value,e.unit)},pow:function(e,t){if(\"number\"==typeof e&&\"number\"==typeof t)e=new ee(e),t=new ee(t);else if(!(e instanceof ee&&t instanceof ee))throw{type:\"Argument\",message:\"arguments must be numbers\"};return new ee(Math.pow(e.value,t.value),e.unit)},percentage:function(e){return nt((function(e){return 100*e}),\"%\",e)}},lt={e:function(e){return new ue('\"',e instanceof ve?e.evaluated:e.value,!0)},escape:function(e){return new j(encodeURI(e.value).replace(/=/g,\"%3D\").replace(/:/g,\"%3A\").replace(/#/g,\"%23\").replace(/;/g,\"%3B\").replace(/\\(/g,\"%28\").replace(/\\)/g,\"%29\"))},replace:function(e,t,i,n){var r=e.value;return i=\"Quoted\"===i.type?i.value:i.toCSS(),r=r.replace(new RegExp(t.value,n?n.value:\"\"),i),new ue(e.quote||\"\",r,e.escaped)},\"%\":function(e){for(var t=Array.prototype.slice.call(arguments,1),i=e.value,n=function(e){i=i.replace(/%[sda]/i,(function(i){var n=\"Quoted\"===t[e].type&&i.match(/s/i)?t[e].value:t[e].toCSS();return i.match(/[A-Z]$/)?encodeURIComponent(n):n}))},r=0;r<t.length;r++)n(r);return i=i.replace(/%%/g,\"%\"),new ue(e.quote||\"\",i,e.escaped)}},ut=function(e,t){return e instanceof t?L.True:L.False},ct=function(e,t){if(void 0===t)throw{type:\"Argument\",message:\"missing the required second argument to isunit.\"};if(\"string\"!=typeof(t=\"string\"==typeof t.value?t.value:t))throw{type:\"Argument\",message:\"Second argument to isunit should be a unit or a string.\"};return e instanceof ee&&e.unit.is(t)?L.True:L.False},ht={isruleset:function(e){return ut(e,X)},iscolor:function(e){return ut(e,c)},isnumber:function(e){return ut(e,ee)},isstring:function(e){return ut(e,ue)},iskeyword:function(e){return ut(e,L)},isurl:function(e){return ut(e,ce)},ispixel:function(e){return ct(e,\"px\")},ispercentage:function(e){return ct(e,\"%\")},isem:function(e){return ct(e,\"em\")},isunit:ct,unit:function(e,t){if(!(e instanceof ee))throw{type:\"Argument\",message:\"the first argument to unit must be a number\"+(e instanceof ie?\". Have you forgotten parenthesis?\":\"\")};return t=t?t instanceof L?t.value:t.toCSS():\"\",new ee(e.value,t)},\"get-unit\":function(e){return new j(e.unit)}},ft=function(e){var t={functionRegistry:H,functionCaller:re};return H.addMultiple(Ge),H.add(\"default\",Q.eval.bind(Q)),H.addMultiple(Ze),H.addMultiple(Xe),H.addMultiple(function(e){var t=function(e,t){return new ce(t,e.index,e.currentFileInfo).eval(e.context)};return{\"data-uri\":function(i,n){n||(n=i,i=null);var s=i&&i.value,o=n.value,a=this.currentFileInfo,l=a.rewriteUrls?a.currentDirectory:a.entryPath,u=o.indexOf(\"#\"),c=\"\";-1!==u&&(c=o.slice(u),o=o.slice(0,u));var h=_(this.context);h.rawBuffer=!0;var f=e.getFileManager(o,l,h,e,!0);if(!f)return t(this,n);var p=!1;if(i)p=/;base64$/.test(s);else{if(\"image/svg+xml\"===(s=e.mimeLookup(o)))p=!1;else{var v=e.charsetLookup(s);p=[\"US-ASCII\",\"UTF-8\"].indexOf(v)<0}p&&(s+=\";base64\")}var d=f.loadFileSync(o,l,h,e);if(!d.contents)return r.warn(\"Skipped data-uri embedding of \"+o+\" because file not found\"),t(this,n||i);var m=d.contents;if(p&&!e.encodeBase64)return t(this,n);var g=\"data:\"+s+\",\"+(m=p?e.encodeBase64(m):encodeURIComponent(m))+c;return new ce(new ue('\"'+g+'\"',g,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)}}}(e)),H.addMultiple(it),H.addMultiple(rt),H.addMultiple(at),H.addMultiple(lt),H.addMultiple({\"svg-gradient\":function(e){var t,i,n,r,s,o,a,l,u=\"linear\",h='x=\"0\" y=\"0\" width=\"1\" height=\"1\"',f={compress:!1},p=e.toCSS(f);function v(){throw{type:\"Argument\",message:\"svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] or direction, color list\"}}switch(2==arguments.length?(arguments[1].value.length<2&&v(),t=arguments[1].value):arguments.length<3?v():t=Array.prototype.slice.call(arguments,1),p){case\"to bottom\":i='x1=\"0%\" y1=\"0%\" x2=\"0%\" y2=\"100%\"';break;case\"to right\":i='x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"0%\"';break;case\"to bottom right\":i='x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\"';break;case\"to top right\":i='x1=\"0%\" y1=\"100%\" x2=\"100%\" y2=\"0%\"';break;case\"ellipse\":case\"ellipse at center\":u=\"radial\",i='cx=\"50%\" cy=\"50%\" r=\"75%\"',h='x=\"-50\" y=\"-50\" width=\"101\" height=\"101\"';break;default:throw{type:\"Argument\",message:\"svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'\"}}for(n='<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><'+u+'Gradient id=\"g\" '+i+\">\",r=0;r<t.length;r+=1)t[r]instanceof ne?(s=t[r].value[0],o=t[r].value[1]):(s=t[r],o=void 0),s instanceof c&&((0===r||r+1===t.length)&&void 0===o||o instanceof ee)||v(),a=o?o.toCSS(f):0===r?\"0%\":\"100%\",l=s.alpha,n+='<stop offset=\"'+a+'\" stop-color=\"'+s.toRGB()+'\"'+(l<1?' stop-opacity=\"'+l+'\"':\"\")+\"/>\";return n+=\"</\"+u+\"Gradient><rect \"+h+' fill=\"url(#g)\" /></svg>',n=encodeURIComponent(n),new ce(new ue(\"'\"+(n=\"data:image/svg+xml,\"+n)+\"'\",n,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)}}),H.addMultiple(ht),t};function pt(e,t){var i,n=(t=t||{}).variables,r=new q.Eval(t);\"object\"!=typeof n||Array.isArray(n)||(n=Object.keys(n).map((function(e){var t=n[e];return t instanceof Ce.Value||(t instanceof Ce.Expression||(t=new Ce.Expression([t])),t=new Ce.Value([t])),new Ce.Declaration(\"@\"+e,t,!1,null,0)})),r.frames=[new Ce.Ruleset(null,n)]);var s,o,a=[new De.JoinSelectorVisitor,new De.MarkVisibleSelectorsVisitor(!0),new De.ExtendVisitor,new De.ToCSSVisitor({compress:Boolean(t.compress)})],l=[];if(t.pluginManager){o=t.pluginManager.visitor();for(var u=0;u<2;u++)for(o.first();s=o.get();)s.isPreEvalVisitor?0!==u&&-1!==l.indexOf(s)||(l.push(s),s.run(e)):0!==u&&-1!==a.indexOf(s)||(s.isPreVisitor?a.unshift(s):a.push(s))}i=e.eval(r);for(u=0;u<a.length;u++)a[u].run(i);if(t.pluginManager)for(o.first();s=o.get();)-1===a.indexOf(s)&&-1===l.indexOf(s)&&s.run(i);return i}var vt,dt=function(){function e(e){this.less=e,this.visitors=[],this.preProcessors=[],this.postProcessors=[],this.installedPlugins=[],this.fileManagers=[],this.iterator=-1,this.pluginCache={},this.Loader=new e.PluginLoader(e)}return e.prototype.addPlugins=function(e){if(e)for(var t=0;t<e.length;t++)this.addPlugin(e[t])},e.prototype.addPlugin=function(e,t,i){this.installedPlugins.push(e),t&&(this.pluginCache[t]=e),e.install&&e.install(this.less,this,i||this.less.functions.functionRegistry)},e.prototype.get=function(e){return this.pluginCache[e]},e.prototype.addVisitor=function(e){this.visitors.push(e)},e.prototype.addPreProcessor=function(e,t){var i;for(i=0;i<this.preProcessors.length&&!(this.preProcessors[i].priority>=t);i++);this.preProcessors.splice(i,0,{preProcessor:e,priority:t})},e.prototype.addPostProcessor=function(e,t){var i;for(i=0;i<this.postProcessors.length&&!(this.postProcessors[i].priority>=t);i++);this.postProcessors.splice(i,0,{postProcessor:e,priority:t})},e.prototype.addFileManager=function(e){this.fileManagers.push(e)},e.prototype.getPreProcessors=function(){for(var e=[],t=0;t<this.preProcessors.length;t++)e.push(this.preProcessors[t].preProcessor);return e},e.prototype.getPostProcessors=function(){for(var e=[],t=0;t<this.postProcessors.length;t++)e.push(this.postProcessors[t].postProcessor);return e},e.prototype.getVisitors=function(){return this.visitors},e.prototype.visitor=function(){var e=this;return{first:function(){return e.iterator=-1,e.visitors[e.iterator]},get:function(){return e.iterator+=1,e.visitors[e.iterator]}}},e.prototype.getFileManagers=function(){return this.fileManagers},e}(),mt=function(e,t){return!t&&vt||(vt=new dt(e)),vt};var gt,yt,bt=function(e){var t=e.match(/^v(\\d{1,2})\\.(\\d{1,2})\\.(\\d{1,2})(?:-([0-9A-Za-z-.]+))?(?:\\+([0-9A-Za-z-.]+))?$/);if(!t)throw new Error(\"Unable to parse: \"+e);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),pre:t[4]||\"\",build:t[5]||\"\"}};function wt(e,t){var i,n,o,a;o=function(e){return function(){function t(e,t){this.root=e,this.imports=t}return t.prototype.toCSS=function(t){var i,n,s={};try{i=pt(this.root,t)}catch(e){throw new O(e,this.imports)}try{var o=Boolean(t.compress);o&&r.warn(\"The compress option has been deprecated. We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.\");var a={compress:o,dumpLineNumbers:t.dumpLineNumbers,strictUnits:Boolean(t.strictUnits),numPrecision:8};t.sourceMap?(n=new e(t.sourceMap),s.css=n.toCSS(i,a,this.imports)):s.css=i.toCSS(a)}catch(e){throw new O(e,this.imports)}if(t.pluginManager)for(var l=t.pluginManager.getPostProcessors(),u=0;u<l.length;u++)s.css=l[u].process(s.css,{sourceMap:n,options:t,imports:this.imports});for(var c in t.sourceMap&&(s.map=n.getExternalSourceMap()),s.imports=[],this.imports.files)this.imports.files.hasOwnProperty(c)&&c!==this.imports.rootFilename&&s.imports.push(c);return s},t}()}(n=function(e,t){return function(){function i(e){this.options=e}return i.prototype.toCSS=function(t,i,n){var r=new e({contentsIgnoredCharsMap:n.contentsIgnoredChars,rootNode:t,contentsMap:n.contents,sourceMapFilename:this.options.sourceMapFilename,sourceMapURL:this.options.sourceMapURL,outputFilename:this.options.sourceMapOutputFilename,sourceMapBasepath:this.options.sourceMapBasepath,sourceMapRootpath:this.options.sourceMapRootpath,outputSourceFiles:this.options.outputSourceFiles,sourceMapGenerator:this.options.sourceMapGenerator,sourceMapFileInline:this.options.sourceMapFileInline,disableSourcemapAnnotation:this.options.disableSourcemapAnnotation}),s=r.toCSS(i);return this.sourceMap=r.sourceMap,this.sourceMapURL=r.sourceMapURL,this.options.sourceMapInputFilename&&(this.sourceMapInputFilename=r.normalizeFilename(this.options.sourceMapInputFilename)),void 0!==this.options.sourceMapBasepath&&void 0!==this.sourceMapURL&&(this.sourceMapURL=r.removeBasepath(this.sourceMapURL)),s+this.getCSSAppendage()},i.prototype.getCSSAppendage=function(){var e=this.sourceMapURL;if(this.options.sourceMapFileInline){if(void 0===this.sourceMap)return\"\";e=\"data:application/json;base64,\"+t.encodeBase64(this.sourceMap)}return this.options.disableSourcemapAnnotation?\"\":e?\"/*# sourceMappingURL=\"+e+\" */\":\"\"},i.prototype.getExternalSourceMap=function(){return this.sourceMap},i.prototype.setExternalSourceMap=function(e){this.sourceMap=e},i.prototype.isInline=function(){return this.options.sourceMapFileInline},i.prototype.getSourceMapURL=function(){return this.sourceMapURL},i.prototype.getOutputFilename=function(){return this.options.sourceMapOutputFilename},i.prototype.getInputFilename=function(){return this.sourceMapInputFilename},i}()}(i=function(e){return function(){function t(t){this._css=[],this._rootNode=t.rootNode,this._contentsMap=t.contentsMap,this._contentsIgnoredCharsMap=t.contentsIgnoredCharsMap,t.sourceMapFilename&&(this._sourceMapFilename=t.sourceMapFilename.replace(/\\\\/g,\"/\")),this._outputFilename=t.outputFilename,this.sourceMapURL=t.sourceMapURL,t.sourceMapBasepath&&(this._sourceMapBasepath=t.sourceMapBasepath.replace(/\\\\/g,\"/\")),t.sourceMapRootpath?(this._sourceMapRootpath=t.sourceMapRootpath.replace(/\\\\/g,\"/\"),\"/\"!==this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1)&&(this._sourceMapRootpath+=\"/\")):this._sourceMapRootpath=\"\",this._outputSourceFiles=t.outputSourceFiles,this._sourceMapGeneratorConstructor=e.getSourceMapGenerator(),this._lineNumber=0,this._column=0}return t.prototype.removeBasepath=function(e){return this._sourceMapBasepath&&0===e.indexOf(this._sourceMapBasepath)&&(\"\\\\\"!==(e=e.substring(this._sourceMapBasepath.length)).charAt(0)&&\"/\"!==e.charAt(0)||(e=e.substring(1))),e},t.prototype.normalizeFilename=function(e){return e=e.replace(/\\\\/g,\"/\"),e=this.removeBasepath(e),(this._sourceMapRootpath||\"\")+e},t.prototype.add=function(e,t,i,n){if(e){var r,s,o,a,l;if(t&&t.filename){var u=this._contentsMap[t.filename];if(this._contentsIgnoredCharsMap[t.filename]&&((i-=this._contentsIgnoredCharsMap[t.filename])<0&&(i=0),u=u.slice(this._contentsIgnoredCharsMap[t.filename])),void 0===u)return void this._css.push(e);a=(s=(u=u.substring(0,i)).split(\"\\n\"))[s.length-1]}if(o=(r=e.split(\"\\n\"))[r.length-1],t&&t.filename)if(n)for(l=0;l<r.length;l++)this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+l+1,column:0===l?this._column:0},original:{line:s.length+l,column:0===l?a.length:0},source:this.normalizeFilename(t.filename)});else this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+1,column:this._column},original:{line:s.length,column:a.length},source:this.normalizeFilename(t.filename)});1===r.length?this._column+=o.length:(this._lineNumber+=r.length-1,this._column=o.length),this._css.push(e)}},t.prototype.isEmpty=function(){return 0===this._css.length},t.prototype.toCSS=function(e){if(this._sourceMapGenerator=new this._sourceMapGeneratorConstructor({file:this._outputFilename,sourceRoot:null}),this._outputSourceFiles)for(var t in this._contentsMap)if(this._contentsMap.hasOwnProperty(t)){var i=this._contentsMap[t];this._contentsIgnoredCharsMap[t]&&(i=i.slice(this._contentsIgnoredCharsMap[t])),this._sourceMapGenerator.setSourceContent(this.normalizeFilename(t),i)}if(this._rootNode.genCSS(e,this),this._css.length>0){var n=void 0,r=JSON.stringify(this._sourceMapGenerator.toJSON());this.sourceMapURL?n=this.sourceMapURL:this._sourceMapFilename&&(n=this._sourceMapFilename),this.sourceMapURL=n,this.sourceMap=r}return this._css.join(\"\")},t}()}(e=new s(e,t)),e)),a=function(e){return function(){function t(e,t,i){this.less=e,this.rootFilename=i.filename,this.paths=t.paths||[],this.contents={},this.contentsIgnoredChars={},this.mime=t.mime,this.error=null,this.context=t,this.queue=[],this.files={}}return t.prototype.push=function(t,i,n,s,o){var a=this,l=this.context.pluginManager.Loader;this.queue.push(t);var u=function(e,i,n){a.queue.splice(a.queue.indexOf(t),1);var l=n===a.rootFilename;s.optional&&e?(o(null,{rules:[]},!1,null),r.info(\"The file \"+n+\" was skipped because it was not found and the import was marked optional.\")):(a.files[n]||s.inline||(a.files[n]={root:i,options:s}),e&&!a.error&&(a.error=e),o(e,i,l,n))},c={rewriteUrls:this.context.rewriteUrls,entryPath:n.entryPath,rootpath:n.rootpath,rootFilename:n.rootFilename},h=e.getFileManager(t,n.currentDirectory,this.context,e);if(h){var f,p,v=function(e){var t,i=e.filename,r=e.contents.replace(/^\\uFEFF/,\"\");c.currentDirectory=h.getPath(i),c.rewriteUrls&&(c.rootpath=h.join(a.context.rootpath||\"\",h.pathDiff(c.currentDirectory,c.entryPath)),!h.isPathAbsolute(c.rootpath)&&h.alwaysMakePathsAbsolute()&&(c.rootpath=h.join(c.entryPath,c.rootpath))),c.filename=i;var o=new q.Parse(a.context);o.processImports=!1,a.contents[i]=r,(n.reference||s.reference)&&(c.reference=!0),s.isPlugin?(t=l.evalPlugin(r,o,a,s.pluginArgs,c))instanceof O?u(t,null,i):u(null,t,i):s.inline?u(null,r,i):!a.files[i]||a.files[i].options.multiple||s.multiple?new Ue(o,a,c).parse(r,(function(e,t){u(e,t,i)})):u(null,a.files[i].root,i)},d=_(this.context);i&&(d.ext=s.isPlugin?\".js\":\".less\"),s.isPlugin?(d.mime=\"application/javascript\",d.syncImport?f=l.loadPluginSync(t,n.currentDirectory,d,e,h):p=l.loadPlugin(t,n.currentDirectory,d,e,h)):d.syncImport?f=h.loadFileSync(t,n.currentDirectory,d,e):p=h.loadFile(t,n.currentDirectory,d,e,(function(e,t){e?u(e):v(t)})),f?f.filename?v(f):u(f):p&&p.then(v,u)}else u({message:\"Could not find a file-manager for \"+t})},t}()}(e);var u,c=function(e,t,i){var n=function(e,i,r){if(\"function\"==typeof i?(r=i,i=M(this.options,{})):i=M(this.options,i||{}),!r){var s=this;return new Promise((function(t,r){n.call(s,e,i,(function(e,i){e?r(e):t(i)}))}))}this.parse(e,i,(function(e,i,n,s){if(e)return r(e);var o;try{o=new t(i,n).toCSS(s)}catch(e){return r(e)}r(null,o)}))};return n}(0,o),h=function(e,t,i){var n=function(e,t,r){if(\"function\"==typeof t?(r=t,t=M(this.options,{})):t=M(this.options,t||{}),!r){var s=this;return new Promise((function(i,r){n.call(s,e,t,(function(e,t){e?r(e):i(t)}))}))}var o,a=void 0,l=new mt(this,!t.reUsePluginManager);if(t.pluginManager=l,o=new q.Parse(t),t.rootFileInfo)a=t.rootFileInfo;else{var u=t.filename||\"input\",c=u.replace(/[^\\/\\\\]*$/,\"\");(a={filename:u,rewriteUrls:o.rewriteUrls,rootpath:o.rootpath||\"\",currentDirectory:c,entryPath:c,rootFilename:u}).rootpath&&\"/\"!==a.rootpath.slice(-1)&&(a.rootpath+=\"/\")}var h=new i(this,o,a);this.importManager=h,t.plugins&&t.plugins.forEach((function(e){var t,i;if(e.fileContent){if(i=e.fileContent.replace(/^\\uFEFF/,\"\"),(t=l.Loader.evalPlugin(i,o,h,e.options,e.filename))instanceof O)return r(t)}else l.addPlugin(e)})),new Ue(o,h,a).parse(e,(function(e,i){if(e)return r(e);r(null,i,h,t)}),t)};return n}(0,0,a),f=bt(\"v4.1.1\"),p={version:[f.major,f.minor,f.patch],data:l,tree:Ce,Environment:s,AbstractFileManager:ke,AbstractPluginLoader:_e,environment:e,visitors:De,Parser:Ue,functions:ft(e),contexts:q,SourceMapOutput:i,SourceMapBuilder:n,ParseTree:o,ImportManager:a,render:c,parse:h,LessError:O,transformTree:pt,utils:P,PluginManager:mt,logger:r},v=function(e){return function(){var t=Object.create(e.prototype);return e.apply(t,Array.prototype.slice.call(arguments,0)),t}},d=Object.create(p);for(var m in p.tree)if(\"function\"==typeof(u=p.tree[m]))d[m.toLowerCase()]=v(u);else for(var g in d[m]=Object.create(null),u)d[m][g.toLowerCase()]=v(u[g]);return p.parse=p.parse.bind(d),p.render=p.render.bind(d),d}var xt={},St=function(){};St.prototype=Object.assign(new ke,{alwaysMakePathsAbsolute:function(){return!0},join:function(e,t){return e?this.extractUrlParts(t,e).path:t},doXHR:function(e,t,i,n){var r=new XMLHttpRequest,s=!gt.isFileProtocol||gt.fileAsync;function o(t,i,n){t.status>=200&&t.status<300?i(t.responseText,t.getResponseHeader(\"Last-Modified\")):\"function\"==typeof n&&n(t.status,e)}\"function\"==typeof r.overrideMimeType&&r.overrideMimeType(\"text/css\"),yt.debug(\"XHR: Getting '\"+e+\"'\"),r.open(\"GET\",e,s),r.setRequestHeader(\"Accept\",t||\"text/x-less, text/css; q=0.9, */*; q=0.5\"),r.send(null),gt.isFileProtocol&&!gt.fileAsync?0===r.status||r.status>=200&&r.status<300?i(r.responseText):n(r.status,e):s?r.onreadystatechange=function(){4==r.readyState&&o(r,i,n)}:o(r,i,n)},supports:function(){return!0},clearFileCache:function(){xt={}},loadFile:function(e,t,i,n){t&&!this.isPathAbsolute(e)&&(e=t+e),e=i.ext?this.tryAppendExtension(e,i.ext):e,i=i||{};var r=this.extractUrlParts(e,window.location.href).url,s=this;return new Promise((function(e,t){if(i.useFileCache&&xt[r])try{var n=xt[r];return e({contents:n,filename:r,webInfo:{lastModified:new Date}})}catch(e){return t({filename:r,message:\"Error loading file \"+r+\" error was \"+e.message})}s.doXHR(r,i.mime,(function(t,i){xt[r]=t,e({contents:t,filename:r,webInfo:{lastModified:i}})}),(function(e,i){t({type:\"File\",message:\"'\"+i+\"' wasn't found (\"+e+\")\",href:r})}))}))}});var It=function(e,t){return gt=e,yt=t,St},Ct=function(e){this.less=e};Ct.prototype=Object.assign(new _e,{loadPlugin:function(e,t,i,n,r){return new Promise((function(s,o){r.loadFile(e,t,i,n).then(s).catch(o)}))}});var kt=function(t,n,r){return{add:function(s,o){r.errorReporting&&\"html\"!==r.errorReporting?\"console\"===r.errorReporting?function(e,t){var i=e.filename||t,s=[],o=(e.type||\"Syntax\")+\"Error: \"+(e.message||\"There is an error in your .less file\")+\" in \"+i,a=function(e,t,i){void 0!==e.extract[t]&&s.push(\"{line} {content}\".replace(/\\{line\\}/,(parseInt(e.line,10)||0)+(t-1)).replace(/\\{class\\}/,i).replace(/\\{content\\}/,e.extract[t]))};e.line&&(a(e,0,\"\"),a(e,1,\"line\"),a(e,2,\"\"),o+=\" on line \"+e.line+\", column \"+(e.column+1)+\":\\n\"+s.join(\"\\n\")),e.stack&&(e.extract||r.logLevel>=4)&&(o+=\"\\nStack Trace\\n\"+e.stack),n.logger.error(o)}(s,o):\"function\"==typeof r.errorReporting&&r.errorReporting(\"add\",s,o):function(n,s){var o,a,l=\"less-error-message:\"+e(s||\"\"),u=t.document.createElement(\"div\"),c=[],h=n.filename||s,f=h.match(/([^\\/]+(\\?.*)?)$/)[1];u.id=l,u.className=\"less-error-message\",a=\"<h3>\"+(n.type||\"Syntax\")+\"Error: \"+(n.message||\"There is an error in your .less file\")+'</h3><p>in <a href=\"'+h+'\">'+f+\"</a> \";var p=function(e,t,i){void 0!==e.extract[t]&&c.push('<li><label>{line}</label><pre class=\"{class}\">{content}</pre></li>'.replace(/\\{line\\}/,(parseInt(e.line,10)||0)+(t-1)).replace(/\\{class\\}/,i).replace(/\\{content\\}/,e.extract[t]))};n.line&&(p(n,0,\"\"),p(n,1,\"line\"),p(n,2,\"\"),a+=\"on line \"+n.line+\", column \"+(n.column+1)+\":</p><ul>\"+c.join(\"\")+\"</ul>\"),n.stack&&(n.extract||r.logLevel>=4)&&(a+=\"<br/>Stack Trace</br />\"+n.stack.split(\"\\n\").slice(1).join(\"<br/>\")),u.innerHTML=a,i(t.document,[\".less-error-message ul, .less-error-message li {\",\"list-style-type: none;\",\"margin-right: 15px;\",\"padding: 4px 0;\",\"margin: 0;\",\"}\",\".less-error-message label {\",\"font-size: 12px;\",\"margin-right: 15px;\",\"padding: 4px 0;\",\"color: #cc7777;\",\"}\",\".less-error-message pre {\",\"color: #dd6666;\",\"padding: 4px 0;\",\"margin: 0;\",\"display: inline-block;\",\"}\",\".less-error-message pre.line {\",\"color: #ff0000;\",\"}\",\".less-error-message h3 {\",\"font-size: 20px;\",\"font-weight: bold;\",\"padding: 15px 0 5px 0;\",\"margin: 0;\",\"}\",\".less-error-message a {\",\"color: #10a\",\"}\",\".less-error-message .error {\",\"color: red;\",\"font-weight: bold;\",\"padding-bottom: 2px;\",\"border-bottom: 1px dashed red;\",\"}\"].join(\"\\n\"),{title:\"error-message\"}),u.style.cssText=[\"font-family: Arial, sans-serif\",\"border: 1px solid #e00\",\"background-color: #eee\",\"border-radius: 5px\",\"-webkit-border-radius: 5px\",\"-moz-border-radius: 5px\",\"color: #e00\",\"padding: 15px\",\"margin-bottom: 15px\"].join(\";\"),\"development\"===r.env&&(o=setInterval((function(){var e=t.document,i=e.body;i&&(e.getElementById(l)?i.replaceChild(u,e.getElementById(l)):i.insertBefore(u,i.firstChild),clearInterval(o))}),10))}(s,o)},remove:function(i){r.errorReporting&&\"html\"!==r.errorReporting?\"console\"===r.errorReporting||\"function\"==typeof r.errorReporting&&r.errorReporting(\"remove\",i):function(i){var n=t.document.getElementById(\"less-error-message:\"+e(i));n&&n.parentNode.removeChild(n)}(i)}}},_t={javascriptEnabled:!1,depends:!1,compress:!1,lint:!1,paths:[],color:!0,strictImports:!1,insecure:!1,rootpath:\"\",rewriteUrls:!1,math:1,strictUnits:!1,globalVars:null,modifyVars:null,urlArgs:\"\"};if(window.less)for(var At in window.less)window.less.hasOwnProperty(At)&&(_t[At]=window.less[At]);!function(e,i){t(i,n(e)),void 0===i.isFileProtocol&&(i.isFileProtocol=/^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(e.location.protocol)),i.async=i.async||!1,i.fileAsync=i.fileAsync||!1,i.poll=i.poll||(i.isFileProtocol?1e3:1500),i.env=i.env||(\"127.0.0.1\"==e.location.hostname||\"0.0.0.0\"==e.location.hostname||\"localhost\"==e.location.hostname||e.location.port&&e.location.port.length>0||i.isFileProtocol?\"development\":\"production\");var r=/!dumpLineNumbers:(comments|mediaquery|all)/.exec(e.location.hash);r&&(i.dumpLineNumbers=r[1]),void 0===i.useFileCache&&(i.useFileCache=!0),void 0===i.onReady&&(i.onReady=!0),i.relativeUrls&&(i.rewriteUrls=\"all\")}(window,_t),_t.plugins=_t.plugins||[],window.LESS_PLUGINS&&(_t.plugins=_t.plugins.concat(window.LESS_PLUGINS));var Mt,Et,Pt,Rt=function(e,n){var r=e.document,s=wt();s.options=n;var o=s.environment,a=It(n,s.logger),l=new a;o.addFileManager(l),s.FileManager=a,s.PluginLoader=Ct,function(e,t){t.logLevel=void 0!==t.logLevel?t.logLevel:\"development\"===t.env?3:1,t.loggers||(t.loggers=[{debug:function(e){t.logLevel>=4&&console.log(e)},info:function(e){t.logLevel>=3&&console.log(e)},warn:function(e){t.logLevel>=2&&console.warn(e)},error:function(e){t.logLevel>=1&&console.error(e)}}]);for(var i=0;i<t.loggers.length;i++)e.logger.addListener(t.loggers[i])}(s,n);var u=kt(e,s,n),c=s.cache=n.cache||function(e,t,i){var n=null;if(\"development\"!==t.env)try{n=void 0===e.localStorage?null:e.localStorage}catch(e){}return{setCSS:function(e,t,r,s){if(n){i.info(\"saving \"+e+\" to cache.\");try{n.setItem(e,s),n.setItem(e+\":timestamp\",t),r&&n.setItem(e+\":vars\",JSON.stringify(r))}catch(t){i.error('failed to save \"'+e+'\" to local storage for caching.')}}},getCSS:function(e,t,i){var r=n&&n.getItem(e),s=n&&n.getItem(e+\":timestamp\"),o=n&&n.getItem(e+\":vars\");if(i=i||{},o=o||\"{}\",s&&t.lastModified&&new Date(t.lastModified).valueOf()===new Date(s).valueOf()&&JSON.stringify(i)===o)return r}}}(e,n,s.logger);!function(){function e(){throw{type:\"Runtime\",message:\"Image size functions are not supported in browser version of less\"}}var t={\"image-size\":function(t){return e(),-1},\"image-width\":function(t){return e(),-1},\"image-height\":function(t){return e(),-1}};H.addMultiple(t)}(s.environment),n.functions&&s.functions.functionRegistry.addMultiple(n.functions);var h=/^text\\/(x-)?less$/;function f(e){var t={};for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}function p(e,t){var i=Array.prototype.slice.call(arguments,2);return function(){var n=i.concat(Array.prototype.slice.call(arguments,0));return e.apply(t,n)}}function v(e){for(var t,i=r.getElementsByTagName(\"style\"),o=0;o<i.length;o++)if((t=i[o]).type.match(h)){var a=f(n);a.modifyVars=e;var l=t.innerHTML||\"\";a.filename=r.location.href.replace(/#.*$/,\"\"),s.render(l,a,p((function(e,t,i){t?u.add(t,\"inline\"):(e.type=\"text/css\",e.styleSheet?e.styleSheet.cssText=i.css:e.innerHTML=i.css)}),null,t))}}function d(e,i,r,a,h){var p=f(n);t(p,e),p.mime=e.type,h&&(p.modifyVars=h),l.loadFile(e.href,null,p,o).then((function(t){!function(t){var n=t.contents,o=t.filename,h=t.webInfo,f={currentDirectory:l.getPath(o),filename:o,rootFilename:o,rewriteUrls:p.rewriteUrls};if(f.entryPath=f.currentDirectory,f.rootpath=p.rootpath||f.currentDirectory,h){h.remaining=a;var v=c.getCSS(o,h,p.modifyVars);if(!r&&v)return h.local=!0,void i(null,v,n,e,h,o)}u.remove(o),p.rootFileInfo=f,s.render(n,p,(function(t,r){t?(t.href=o,i(t)):(c.setCSS(e.href,h.lastModified,p.modifyVars,r.css),i(null,r.css,n,e,h,o))}))}(t)})).catch((function(e){console.log(e),i(e)}))}function m(e,t,i){for(var n=0;n<s.sheets.length;n++)d(s.sheets[n],e,t,s.sheets.length-(n+1),i)}return s.watch=function(){return s.watchMode||(s.env=\"development\",\"development\"===s.env&&(s.watchTimer=setInterval((function(){s.watchMode&&(l.clearFileCache(),m((function(t,n,r,s,o){t?u.add(t,t.href||s.href):n&&i(e.document,n,s)})))}),n.poll))),this.watchMode=!0,!0},s.unwatch=function(){return clearInterval(s.watchTimer),this.watchMode=!1,!1},s.registerStylesheetsImmediately=function(){var e=r.getElementsByTagName(\"link\");s.sheets=[];for(var t=0;t<e.length;t++)(\"stylesheet/less\"===e[t].rel||e[t].rel.match(/stylesheet/)&&e[t].type.match(h))&&s.sheets.push(e[t])},s.registerStylesheets=function(){return new Promise((function(e,t){s.registerStylesheetsImmediately(),e()}))},s.modifyVars=function(e){return s.refresh(!0,e,!1)},s.refresh=function(t,n,r){return(t||r)&&!1!==r&&l.clearFileCache(),new Promise((function(r,o){var a,l,c,h;a=l=new Date,0===(h=s.sheets.length)?(l=new Date,c=l-a,s.logger.info(\"Less has finished and no sheets were loaded.\"),r({startTime:a,endTime:l,totalMilliseconds:c,sheets:s.sheets.length})):m((function(t,n,f,p,v){if(t)return u.add(t,t.href||p.href),void o(t);v.local?s.logger.info(\"Loading \"+p.href+\" from cache.\"):s.logger.info(\"Rendered \"+p.href+\" successfully.\"),i(e.document,n,p),s.logger.info(\"CSS for \"+p.href+\" generated in \"+(new Date-l)+\"ms\"),0===--h&&(c=new Date-a,s.logger.info(\"Less has finished. CSS generated in \"+c+\"ms\"),r({startTime:a,endTime:l,totalMilliseconds:c,sheets:s.sheets.length})),l=new Date}),t,n),v(n)}))},s.refreshStyles=v,s}(window,_t);function Ot(e){e.filename&&console.warn(e),_t.async||Et.removeChild(Pt)}return window.less=Rt,_t.onReady&&(/!watch/.test(window.location.hash)&&Rt.watch(),_t.async||(Mt=\"body { display: none !important }\",Et=document.head||document.getElementsByTagName(\"head\")[0],(Pt=document.createElement(\"style\")).type=\"text/css\",Pt.styleSheet?Pt.styleSheet.cssText=Mt:Pt.appendChild(document.createTextNode(Mt)),Et.appendChild(Pt)),Rt.registerStylesheetsImmediately(),Rt.pageLoadFinished=Rt.refresh(\"development\"===Rt.env).then(Ot,Ot)),Rt}));\n//# sourceMappingURL=less.min.js.map\n"
  },
  {
    "path": "src/renderer/lib/marked.js",
    "content": "/**\n * marked - a markdown parser\n * Copyright (c) 2011-2021, Christopher Jeffrey. (MIT Licensed)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\n(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n        typeof define === 'function' && define.amd ? define(['exports'], factory) :\n            (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {}));\n})(this, (function (exports) { 'use strict';\n\n    function _defineProperties(target, props) {\n        for (var i = 0; i < props.length; i++) {\n            var descriptor = props[i];\n            descriptor.enumerable = descriptor.enumerable || false;\n            descriptor.configurable = true;\n            if (\"value\" in descriptor) descriptor.writable = true;\n            Object.defineProperty(target, descriptor.key, descriptor);\n        }\n    }\n\n    function _createClass(Constructor, protoProps, staticProps) {\n        if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n        if (staticProps) _defineProperties(Constructor, staticProps);\n        return Constructor;\n    }\n\n    function _unsupportedIterableToArray(o, minLen) {\n        if (!o) return;\n        if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n        var n = Object.prototype.toString.call(o).slice(8, -1);\n        if (n === \"Object\" && o.constructor) n = o.constructor.name;\n        if (n === \"Map\" || n === \"Set\") return Array.from(o);\n        if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n    }\n\n    function _arrayLikeToArray(arr, len) {\n        if (len == null || len > arr.length) len = arr.length;\n\n        for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n        return arr2;\n    }\n\n    function _createForOfIteratorHelperLoose(o, allowArrayLike) {\n        var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n        if (it) return (it = it.call(o)).next.bind(it);\n\n        if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n            if (it) o = it;\n            var i = 0;\n            return function () {\n                if (i >= o.length) return {\n                    done: true\n                };\n                return {\n                    done: false,\n                    value: o[i++]\n                };\n            };\n        }\n\n        throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n    }\n\n    function getDefaults() {\n        return {\n            baseUrl: null,\n            breaks: false,\n            extensions: null,\n            gfm: true,\n            headerIds: true,\n            headerPrefix: '',\n            highlight: null,\n            langPrefix: 'language-',\n            mangle: true,\n            pedantic: false,\n            renderer: null,\n            sanitize: false,\n            sanitizer: null,\n            silent: false,\n            smartLists: false,\n            smartypants: false,\n            tokenizer: null,\n            walkTokens: null,\n            xhtml: false\n        };\n    }\n    exports.defaults = getDefaults();\n    function changeDefaults(newDefaults) {\n        exports.defaults = newDefaults;\n    }\n\n    /**\n     * Helpers\n     */\n    var escapeTest = /[&<>\"']/;\n    var escapeReplace = /[&<>\"']/g;\n    var escapeTestNoEncode = /[<>\"']|&(?!#?\\w+;)/;\n    var escapeReplaceNoEncode = /[<>\"']|&(?!#?\\w+;)/g;\n    var escapeReplacements = {\n        '&': '&amp;',\n        '<': '&lt;',\n        '>': '&gt;',\n        '\"': '&quot;',\n        \"'\": '&#39;'\n    };\n\n    var getEscapeReplacement = function getEscapeReplacement(ch) {\n        return escapeReplacements[ch];\n    };\n\n    function escape(html, encode) {\n        if (encode) {\n            if (escapeTest.test(html)) {\n                return html.replace(escapeReplace, getEscapeReplacement);\n            }\n        } else {\n            if (escapeTestNoEncode.test(html)) {\n                return html.replace(escapeReplaceNoEncode, getEscapeReplacement);\n            }\n        }\n\n        return html;\n    }\n    var unescapeTest = /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig;\n    function unescape(html) {\n        // explicitly match decimal, hex, and named HTML entities\n        return html.replace(unescapeTest, function (_, n) {\n            n = n.toLowerCase();\n            if (n === 'colon') return ':';\n\n            if (n.charAt(0) === '#') {\n                return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));\n            }\n\n            return '';\n        });\n    }\n    var caret = /(^|[^\\[])\\^/g;\n    function edit(regex, opt) {\n        regex = regex.source || regex;\n        opt = opt || '';\n        var obj = {\n            replace: function replace(name, val) {\n                val = val.source || val;\n                val = val.replace(caret, '$1');\n                regex = regex.replace(name, val);\n                return obj;\n            },\n            getRegex: function getRegex() {\n                return new RegExp(regex, opt);\n            }\n        };\n        return obj;\n    }\n    var nonWordAndColonTest = /[^\\w:]/g;\n    var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;\n    function cleanUrl(sanitize, base, href) {\n        if (sanitize) {\n            var prot;\n\n            try {\n                prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase();\n            } catch (e) {\n                return null;\n            }\n\n            if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {\n                return null;\n            }\n        }\n\n        if (base && !originIndependentUrl.test(href)) {\n            href = resolveUrl(base, href);\n        }\n\n        try {\n            href = encodeURI(href).replace(/%25/g, '%');\n        } catch (e) {\n            return null;\n        }\n\n        return href;\n    }\n    var baseUrls = {};\n    var justDomain = /^[^:]+:\\/*[^/]*$/;\n    var protocol = /^([^:]+:)[\\s\\S]*$/;\n    var domain = /^([^:]+:\\/*[^/]*)[\\s\\S]*$/;\n    function resolveUrl(base, href) {\n        if (!baseUrls[' ' + base]) {\n            // we can ignore everything in base after the last slash of its path component,\n            // but we might need to add _that_\n            // https://tools.ietf.org/html/rfc3986#section-3\n            if (justDomain.test(base)) {\n                baseUrls[' ' + base] = base + '/';\n            } else {\n                baseUrls[' ' + base] = rtrim(base, '/', true);\n            }\n        }\n\n        base = baseUrls[' ' + base];\n        var relativeBase = base.indexOf(':') === -1;\n\n        if (href.substring(0, 2) === '//') {\n            if (relativeBase) {\n                return href;\n            }\n\n            return base.replace(protocol, '$1') + href;\n        } else if (href.charAt(0) === '/') {\n            if (relativeBase) {\n                return href;\n            }\n\n            return base.replace(domain, '$1') + href;\n        } else {\n            return base + href;\n        }\n    }\n    var noopTest = {\n        exec: function noopTest() {}\n    };\n    function merge(obj) {\n        var i = 1,\n            target,\n            key;\n\n        for (; i < arguments.length; i++) {\n            target = arguments[i];\n\n            for (key in target) {\n                if (Object.prototype.hasOwnProperty.call(target, key)) {\n                    obj[key] = target[key];\n                }\n            }\n        }\n\n        return obj;\n    }\n    function splitCells(tableRow, count) {\n        // ensure that every cell-delimiting pipe has a space\n        // before it to distinguish it from an escaped pipe\n        var row = tableRow.replace(/\\|/g, function (match, offset, str) {\n                var escaped = false,\n                    curr = offset;\n\n                while (--curr >= 0 && str[curr] === '\\\\') {\n                    escaped = !escaped;\n                }\n\n                if (escaped) {\n                    // odd number of slashes means | is escaped\n                    // so we leave it alone\n                    return '|';\n                } else {\n                    // add space before unescaped |\n                    return ' |';\n                }\n            }),\n            cells = row.split(/ \\|/);\n        var i = 0; // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n\n        if (!cells[0].trim()) {\n            cells.shift();\n        }\n\n        if (!cells[cells.length - 1].trim()) {\n            cells.pop();\n        }\n\n        if (cells.length > count) {\n            cells.splice(count);\n        } else {\n            while (cells.length < count) {\n                cells.push('');\n            }\n        }\n\n        for (; i < cells.length; i++) {\n            // leading or trailing whitespace is ignored per the gfm spec\n            cells[i] = cells[i].trim().replace(/\\\\\\|/g, '|');\n        }\n\n        return cells;\n    } // Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n    // /c*$/ is vulnerable to REDOS.\n    // invert: Remove suffix of non-c chars instead. Default falsey.\n\n    function rtrim(str, c, invert) {\n        var l = str.length;\n\n        if (l === 0) {\n            return '';\n        } // Length of suffix matching the invert condition.\n\n\n        var suffLen = 0; // Step left until we fail to match the invert condition.\n\n        while (suffLen < l) {\n            var currChar = str.charAt(l - suffLen - 1);\n\n            if (currChar === c && !invert) {\n                suffLen++;\n            } else if (currChar !== c && invert) {\n                suffLen++;\n            } else {\n                break;\n            }\n        }\n\n        return str.substr(0, l - suffLen);\n    }\n    function findClosingBracket(str, b) {\n        if (str.indexOf(b[1]) === -1) {\n            return -1;\n        }\n\n        var l = str.length;\n        var level = 0,\n            i = 0;\n\n        for (; i < l; i++) {\n            if (str[i] === '\\\\') {\n                i++;\n            } else if (str[i] === b[0]) {\n                level++;\n            } else if (str[i] === b[1]) {\n                level--;\n\n                if (level < 0) {\n                    return i;\n                }\n            }\n        }\n\n        return -1;\n    }\n    function checkSanitizeDeprecation(opt) {\n        if (opt && opt.sanitize && !opt.silent) {\n            console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');\n        }\n    } // copied from https://stackoverflow.com/a/5450113/806777\n\n    function repeatString(pattern, count) {\n        if (count < 1) {\n            return '';\n        }\n\n        var result = '';\n\n        while (count > 1) {\n            if (count & 1) {\n                result += pattern;\n            }\n\n            count >>= 1;\n            pattern += pattern;\n        }\n\n        return result + pattern;\n    }\n\n    function outputLink(cap, link, raw, lexer) {\n        var href = link.href;\n        var title = link.title ? escape(link.title) : null;\n        var text = cap[1].replace(/\\\\([\\[\\]])/g, '$1');\n\n        if (cap[0].charAt(0) !== '!') {\n            lexer.state.inLink = true;\n            var token = {\n                type: 'link',\n                raw: raw,\n                href: href,\n                title: title,\n                text: text,\n                tokens: lexer.inlineTokens(text, [])\n            };\n            lexer.state.inLink = false;\n            return token;\n        } else {\n            return {\n                type: 'image',\n                raw: raw,\n                href: href,\n                title: title,\n                text: escape(text)\n            };\n        }\n    }\n\n    function indentCodeCompensation(raw, text) {\n        var matchIndentToCode = raw.match(/^(\\s+)(?:```)/);\n\n        if (matchIndentToCode === null) {\n            return text;\n        }\n\n        var indentToCode = matchIndentToCode[1];\n        return text.split('\\n').map(function (node) {\n            var matchIndentInNode = node.match(/^\\s+/);\n\n            if (matchIndentInNode === null) {\n                return node;\n            }\n\n            var indentInNode = matchIndentInNode[0];\n\n            if (indentInNode.length >= indentToCode.length) {\n                return node.slice(indentToCode.length);\n            }\n\n            return node;\n        }).join('\\n');\n    }\n    /**\n     * Tokenizer\n     */\n\n\n    var Tokenizer = /*#__PURE__*/function () {\n        function Tokenizer(options) {\n            this.options = options || exports.defaults;\n        }\n\n        var _proto = Tokenizer.prototype;\n\n        _proto.space = function space(src) {\n            var cap = this.rules.block.newline.exec(src);\n\n            if (cap) {\n                if (cap[0].length > 1) {\n                    return {\n                        type: 'space',\n                        raw: cap[0]\n                    };\n                }\n\n                return {\n                    raw: '\\n'\n                };\n            }\n        };\n\n        _proto.code = function code(src) {\n            var cap = this.rules.block.code.exec(src);\n\n            if (cap) {\n                var text = cap[0].replace(/^ {1,4}/gm, '');\n                return {\n                    type: 'code',\n                    raw: cap[0],\n                    codeBlockStyle: 'indented',\n                    text: !this.options.pedantic ? rtrim(text, '\\n') : text\n                };\n            }\n        };\n\n        _proto.fences = function fences(src) {\n            var cap = this.rules.block.fences.exec(src);\n\n            if (cap) {\n                var raw = cap[0];\n                var text = indentCodeCompensation(raw, cap[3] || '');\n                return {\n                    type: 'code',\n                    raw: raw,\n                    lang: cap[2] ? cap[2].trim() : cap[2],\n                    text: text\n                };\n            }\n        };\n\n        _proto.heading = function heading(src) {\n            var cap = this.rules.block.heading.exec(src);\n\n            if (cap) {\n                var text = cap[2].trim(); // remove trailing #s\n\n                if (/#$/.test(text)) {\n                    var trimmed = rtrim(text, '#');\n\n                    if (this.options.pedantic) {\n                        text = trimmed.trim();\n                    } else if (!trimmed || / $/.test(trimmed)) {\n                        // CommonMark requires space before trailing #s\n                        text = trimmed.trim();\n                    }\n                }\n\n                var token = {\n                    type: 'heading',\n                    raw: cap[0],\n                    depth: cap[1].length,\n                    text: text,\n                    tokens: []\n                };\n                this.lexer.inline(token.text, token.tokens);\n                return token;\n            }\n        };\n\n        _proto.hr = function hr(src) {\n            var cap = this.rules.block.hr.exec(src);\n\n            if (cap) {\n                return {\n                    type: 'hr',\n                    raw: cap[0]\n                };\n            }\n        };\n\n        _proto.blockquote = function blockquote(src) {\n            var cap = this.rules.block.blockquote.exec(src);\n\n            if (cap) {\n                var text = cap[0].replace(/^ *> ?/gm, '');\n                return {\n                    type: 'blockquote',\n                    raw: cap[0],\n                    tokens: this.lexer.blockTokens(text, []),\n                    text: text\n                };\n            }\n        };\n\n        _proto.list = function list(src) {\n            var cap = this.rules.block.list.exec(src);\n\n            if (cap) {\n                var raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, lines, itemContents;\n                var bull = cap[1].trim();\n                var isordered = bull.length > 1;\n                var list = {\n                    type: 'list',\n                    raw: '',\n                    ordered: isordered,\n                    start: isordered ? +bull.slice(0, -1) : '',\n                    loose: false,\n                    items: []\n                };\n                bull = isordered ? \"\\\\d{1,9}\\\\\" + bull.slice(-1) : \"\\\\\" + bull;\n\n                if (this.options.pedantic) {\n                    bull = isordered ? bull : '[*+-]';\n                } // Get next list item\n\n\n                var itemRegex = new RegExp(\"^( {0,3}\" + bull + \")((?: [^\\\\n]*| *)(?:\\\\n[^\\\\n]*)*(?:\\\\n|$))\"); // Get each top-level item\n\n                while (src) {\n                    if (this.rules.block.hr.test(src)) {\n                        // End list if we encounter an HR (possibly move into itemRegex?)\n                        break;\n                    }\n\n                    if (!(cap = itemRegex.exec(src))) {\n                        break;\n                    }\n\n                    lines = cap[2].split('\\n');\n\n                    if (this.options.pedantic) {\n                        indent = 2;\n                        itemContents = lines[0].trimLeft();\n                    } else {\n                        indent = cap[2].search(/[^ ]/); // Find first non-space char\n\n                        indent = cap[1].length + (indent > 4 ? 1 : indent); // intented code blocks after 4 spaces; indent is always 1\n\n                        itemContents = lines[0].slice(indent - cap[1].length);\n                    }\n\n                    blankLine = false;\n                    raw = cap[0];\n\n                    if (!lines[0] && /^ *$/.test(lines[1])) {\n                        // items begin with at most one blank line\n                        raw = cap[1] + lines.slice(0, 2).join('\\n') + '\\n';\n                        list.loose = true;\n                        lines = [];\n                    }\n\n                    var nextBulletRegex = new RegExp(\"^ {0,\" + Math.min(3, indent - 1) + \"}(?:[*+-]|\\\\d{1,9}[.)])\");\n\n                    for (i = 1; i < lines.length; i++) {\n                        line = lines[i];\n\n                        if (this.options.pedantic) {\n                            // Re-align to follow commonmark nesting rules\n                            line = line.replace(/^ {1,4}(?=( {4})*[^ ])/g, '  ');\n                        } // End list item if found start of new bullet\n\n\n                        if (nextBulletRegex.test(line)) {\n                            raw = cap[1] + lines.slice(0, i).join('\\n') + '\\n';\n                            break;\n                        } // Until we encounter a blank line, item contents do not need indentation\n\n\n                        if (!blankLine) {\n                            if (!line.trim()) {\n                                // Check if current line is empty\n                                blankLine = true;\n                            } // Dedent if possible\n\n\n                            if (line.search(/[^ ]/) >= indent) {\n                                itemContents += '\\n' + line.slice(indent);\n                            } else {\n                                itemContents += '\\n' + line;\n                            }\n\n                            continue;\n                        } // Dedent this line\n\n\n                        if (line.search(/[^ ]/) >= indent || !line.trim()) {\n                            itemContents += '\\n' + line.slice(indent);\n                            continue;\n                        } else {\n                            // Line was not properly indented; end of this item\n                            raw = cap[1] + lines.slice(0, i).join('\\n') + '\\n';\n                            break;\n                        }\n                    }\n\n                    if (!list.loose) {\n                        // If the previous item ended with a blank line, the list is loose\n                        if (endsWithBlankLine) {\n                            list.loose = true;\n                        } else if (/\\n *\\n *$/.test(raw)) {\n                            endsWithBlankLine = true;\n                        }\n                    } // Check for task list items\n\n\n                    if (this.options.gfm) {\n                        istask = /^\\[[ xX]\\] /.exec(itemContents);\n\n                        if (istask) {\n                            ischecked = istask[0] !== '[ ] ';\n                            itemContents = itemContents.replace(/^\\[[ xX]\\] +/, '');\n                        }\n                    }\n\n                    list.items.push({\n                        type: 'list_item',\n                        raw: raw,\n                        task: !!istask,\n                        checked: ischecked,\n                        loose: false,\n                        text: itemContents\n                    });\n                    list.raw += raw;\n                    src = src.slice(raw.length);\n                } // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n\n\n                list.items[list.items.length - 1].raw = raw.trimRight();\n                list.items[list.items.length - 1].text = itemContents.trimRight();\n                list.raw = list.raw.trimRight();\n                var l = list.items.length; // Item child tokens handled here at end because we needed to have the final item to trim it first\n\n                for (i = 0; i < l; i++) {\n                    this.lexer.state.top = false;\n                    list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n\n                    if (list.items[i].tokens.some(function (t) {\n                        return t.type === 'space';\n                    })) {\n                        list.loose = true;\n                        list.items[i].loose = true;\n                    }\n                }\n\n                return list;\n            }\n        };\n\n        _proto.html = function html(src) {\n            var cap = this.rules.block.html.exec(src);\n\n            if (cap) {\n                var token = {\n                    type: 'html',\n                    raw: cap[0],\n                    pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),\n                    text: cap[0]\n                };\n\n                if (this.options.sanitize) {\n                    token.type = 'paragraph';\n                    token.text = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]);\n                    token.tokens = [];\n                    this.lexer.inline(token.text, token.tokens);\n                }\n\n                return token;\n            }\n        };\n\n        _proto.def = function def(src) {\n            var cap = this.rules.block.def.exec(src);\n\n            if (cap) {\n                if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);\n                var tag = cap[1].toLowerCase().replace(/\\s+/g, ' ');\n                return {\n                    type: 'def',\n                    tag: tag,\n                    raw: cap[0],\n                    href: cap[2],\n                    title: cap[3]\n                };\n            }\n        };\n\n        _proto.table = function table(src) {\n            var cap = this.rules.block.table.exec(src);\n\n            if (cap) {\n                var item = {\n                    type: 'table',\n                    header: splitCells(cap[1]).map(function (c) {\n                        return {\n                            text: c\n                        };\n                    }),\n                    align: cap[2].replace(/^ *|\\| *$/g, '').split(/ *\\| */),\n                    rows: cap[3] ? cap[3].replace(/\\n$/, '').split('\\n') : []\n                };\n\n                if (item.header.length === item.align.length) {\n                    item.raw = cap[0];\n                    var l = item.align.length;\n                    var i, j, k, row;\n\n                    for (i = 0; i < l; i++) {\n                        if (/^ *-+: *$/.test(item.align[i])) {\n                            item.align[i] = 'right';\n                        } else if (/^ *:-+: *$/.test(item.align[i])) {\n                            item.align[i] = 'center';\n                        } else if (/^ *:-+ *$/.test(item.align[i])) {\n                            item.align[i] = 'left';\n                        } else {\n                            item.align[i] = null;\n                        }\n                    }\n\n                    l = item.rows.length;\n\n                    for (i = 0; i < l; i++) {\n                        item.rows[i] = splitCells(item.rows[i], item.header.length).map(function (c) {\n                            return {\n                                text: c\n                            };\n                        });\n                    } // parse child tokens inside headers and cells\n                    // header child tokens\n\n\n                    l = item.header.length;\n\n                    for (j = 0; j < l; j++) {\n                        item.header[j].tokens = [];\n                        this.lexer.inlineTokens(item.header[j].text, item.header[j].tokens);\n                    } // cell child tokens\n\n\n                    l = item.rows.length;\n\n                    for (j = 0; j < l; j++) {\n                        row = item.rows[j];\n\n                        for (k = 0; k < row.length; k++) {\n                            row[k].tokens = [];\n                            this.lexer.inlineTokens(row[k].text, row[k].tokens);\n                        }\n                    }\n\n                    return item;\n                }\n            }\n        };\n\n        _proto.lheading = function lheading(src) {\n            var cap = this.rules.block.lheading.exec(src);\n\n            if (cap) {\n                var token = {\n                    type: 'heading',\n                    raw: cap[0],\n                    depth: cap[2].charAt(0) === '=' ? 1 : 2,\n                    text: cap[1],\n                    tokens: []\n                };\n                this.lexer.inline(token.text, token.tokens);\n                return token;\n            }\n        };\n\n        _proto.paragraph = function paragraph(src) {\n            var cap = this.rules.block.paragraph.exec(src);\n\n            if (cap) {\n                var token = {\n                    type: 'paragraph',\n                    raw: cap[0],\n                    text: cap[1].charAt(cap[1].length - 1) === '\\n' ? cap[1].slice(0, -1) : cap[1],\n                    tokens: []\n                };\n                this.lexer.inline(token.text, token.tokens);\n                return token;\n            }\n        };\n\n        _proto.text = function text(src) {\n            var cap = this.rules.block.text.exec(src);\n\n            if (cap) {\n                var token = {\n                    type: 'text',\n                    raw: cap[0],\n                    text: cap[0],\n                    tokens: []\n                };\n                this.lexer.inline(token.text, token.tokens);\n                return token;\n            }\n        };\n\n        _proto.escape = function escape$1(src) {\n            var cap = this.rules.inline.escape.exec(src);\n\n            if (cap) {\n                return {\n                    type: 'escape',\n                    raw: cap[0],\n                    text: escape(cap[1])\n                };\n            }\n        };\n\n        _proto.tag = function tag(src) {\n            var cap = this.rules.inline.tag.exec(src);\n\n            if (cap) {\n                if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {\n                    this.lexer.state.inLink = true;\n                } else if (this.lexer.state.inLink && /^<\\/a>/i.test(cap[0])) {\n                    this.lexer.state.inLink = false;\n                }\n\n                if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n                    this.lexer.state.inRawBlock = true;\n                } else if (this.lexer.state.inRawBlock && /^<\\/(pre|code|kbd|script)(\\s|>)/i.test(cap[0])) {\n                    this.lexer.state.inRawBlock = false;\n                }\n\n                return {\n                    type: this.options.sanitize ? 'text' : 'html',\n                    raw: cap[0],\n                    inLink: this.lexer.state.inLink,\n                    inRawBlock: this.lexer.state.inRawBlock,\n                    text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]\n                };\n            }\n        };\n\n        _proto.link = function link(src) {\n            var cap = this.rules.inline.link.exec(src);\n\n            if (cap) {\n                var trimmedUrl = cap[2].trim();\n\n                if (!this.options.pedantic && /^</.test(trimmedUrl)) {\n                    // commonmark requires matching angle brackets\n                    if (!/>$/.test(trimmedUrl)) {\n                        return;\n                    } // ending angle bracket cannot be escaped\n\n\n                    var rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n\n                    if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n                        return;\n                    }\n                } else {\n                    // find closing parenthesis\n                    var lastParenIndex = findClosingBracket(cap[2], '()');\n\n                    if (lastParenIndex > -1) {\n                        var start = cap[0].indexOf('!') === 0 ? 5 : 4;\n                        var linkLen = start + cap[1].length + lastParenIndex;\n                        cap[2] = cap[2].substring(0, lastParenIndex);\n                        cap[0] = cap[0].substring(0, linkLen).trim();\n                        cap[3] = '';\n                    }\n                }\n\n                var href = cap[2];\n                var title = '';\n\n                if (this.options.pedantic) {\n                    // split pedantic href and title\n                    var link = /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/.exec(href);\n\n                    if (link) {\n                        href = link[1];\n                        title = link[3];\n                    }\n                } else {\n                    title = cap[3] ? cap[3].slice(1, -1) : '';\n                }\n\n                href = href.trim();\n\n                if (/^</.test(href)) {\n                    if (this.options.pedantic && !/>$/.test(trimmedUrl)) {\n                        // pedantic allows starting angle bracket without ending angle bracket\n                        href = href.slice(1);\n                    } else {\n                        href = href.slice(1, -1);\n                    }\n                }\n\n                return outputLink(cap, {\n                    href: href ? href.replace(this.rules.inline._escapes, '$1') : href,\n                    title: title ? title.replace(this.rules.inline._escapes, '$1') : title\n                }, cap[0], this.lexer);\n            }\n        };\n\n        _proto.reflink = function reflink(src, links) {\n            var cap;\n\n            if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {\n                var link = (cap[2] || cap[1]).replace(/\\s+/g, ' ');\n                link = links[link.toLowerCase()];\n\n                if (!link || !link.href) {\n                    var text = cap[0].charAt(0);\n                    return {\n                        type: 'text',\n                        raw: text,\n                        text: text\n                    };\n                }\n\n                return outputLink(cap, link, cap[0], this.lexer);\n            }\n        };\n\n        _proto.emStrong = function emStrong(src, maskedSrc, prevChar) {\n            if (prevChar === void 0) {\n                prevChar = '';\n            }\n\n            var match = this.rules.inline.emStrong.lDelim.exec(src);\n            if (!match) return; // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n\n            if (match[3] && prevChar.match(/(?:[0-9A-Za-z\\xAA\\xB2\\xB3\\xB5\\xB9\\xBA\\xBC-\\xBE\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u0660-\\u0669\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07C0-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088E\\u08A0-\\u08C9\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0966-\\u096F\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09E6-\\u09F1\\u09F4-\\u09F9\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A6F\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AE6-\\u0AEF\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B66-\\u0B6F\\u0B71-\\u0B77\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0BE6-\\u0BF2\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C5D\\u0C60\\u0C61\\u0C66-\\u0C6F\\u0C78-\\u0C7E\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDD\\u0CDE\\u0CE0\\u0CE1\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D04-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D58-\\u0D61\\u0D66-\\u0D78\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DE6-\\u0DEF\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F20-\\u0F33\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F-\\u1049\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u1090-\\u1099\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1369-\\u137C\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u1711\\u171F-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u17E0-\\u17E9\\u17F0-\\u17F9\\u1810-\\u1819\\u1820-\\u1878\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19DA\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4C\\u1B50-\\u1B59\\u1B83-\\u1BA0\\u1BAE-\\u1BE5\\u1C00-\\u1C23\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2070\\u2071\\u2074-\\u2079\\u207F-\\u2089\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2150-\\u2189\\u2460-\\u249B\\u24EA-\\u24FF\\u2776-\\u2793\\u2C00-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2CFD\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u3192-\\u3195\\u31A0-\\u31BF\\u31F0-\\u31FF\\u3220-\\u3229\\u3248-\\u324F\\u3251-\\u325F\\u3280-\\u3289\\u32B1-\\u32BF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7CA\\uA7D0\\uA7D1\\uA7D3\\uA7D5-\\uA7D9\\uA7F2-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA830-\\uA835\\uA840-\\uA873\\uA882-\\uA8B3\\uA8D0-\\uA8D9\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA900-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF-\\uA9D9\\uA9E0-\\uA9E4\\uA9E6-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABE2\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDD07-\\uDD33\\uDD40-\\uDD78\\uDD8A\\uDD8B\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDEE1-\\uDEFB\\uDF00-\\uDF23\\uDF2D-\\uDF4A\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF\\uDFD1-\\uDFD5]|\\uD801[\\uDC00-\\uDC9D\\uDCA0-\\uDCA9\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDD70-\\uDD7A\\uDD7C-\\uDD8A\\uDD8C-\\uDD92\\uDD94\\uDD95\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67\\uDF80-\\uDF85\\uDF87-\\uDFB0\\uDFB2-\\uDFBA]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC58-\\uDC76\\uDC79-\\uDC9E\\uDCA7-\\uDCAF\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDCFB-\\uDD1B\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBC-\\uDDCF\\uDDD2-\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE40-\\uDE48\\uDE60-\\uDE7E\\uDE80-\\uDE9F\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDEEB-\\uDEEF\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF58-\\uDF72\\uDF78-\\uDF91\\uDFA9-\\uDFAF]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDCFA-\\uDD23\\uDD30-\\uDD39\\uDE60-\\uDE7E\\uDE80-\\uDEA9\\uDEB0\\uDEB1\\uDF00-\\uDF27\\uDF30-\\uDF45\\uDF51-\\uDF54\\uDF70-\\uDF81\\uDFB0-\\uDFCB\\uDFE0-\\uDFF6]|\\uD804[\\uDC03-\\uDC37\\uDC52-\\uDC6F\\uDC71\\uDC72\\uDC75\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDCF0-\\uDCF9\\uDD03-\\uDD26\\uDD36-\\uDD3F\\uDD44\\uDD47\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDD0-\\uDDDA\\uDDDC\\uDDE1-\\uDDF4\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDEF0-\\uDEF9\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC50-\\uDC59\\uDC5F-\\uDC61\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEAA\\uDEB8\\uDEC0-\\uDEC9\\uDF00-\\uDF1A\\uDF30-\\uDF3B\\uDF40-\\uDF46]|\\uD806[\\uDC00-\\uDC2B\\uDCA0-\\uDCF2\\uDCFF-\\uDD06\\uDD09\\uDD0C-\\uDD13\\uDD15\\uDD16\\uDD18-\\uDD2F\\uDD3F\\uDD41\\uDD50-\\uDD59\\uDDA0-\\uDDA7\\uDDAA-\\uDDD0\\uDDE1\\uDDE3\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE89\\uDE9D\\uDEB0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC50-\\uDC6C\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46\\uDD50-\\uDD59\\uDD60-\\uDD65\\uDD67\\uDD68\\uDD6A-\\uDD89\\uDD98\\uDDA0-\\uDDA9\\uDEE0-\\uDEF2\\uDFB0\\uDFC0-\\uDFD4]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|\\uD80B[\\uDF90-\\uDFF0]|[\\uD80C\\uD81C-\\uD820\\uD822\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDE70-\\uDEBE\\uDEC0-\\uDEC9\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF5B-\\uDF61\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDE40-\\uDE96\\uDF00-\\uDF4A\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1\\uDFE3]|\\uD821[\\uDC00-\\uDFF7]|\\uD823[\\uDC00-\\uDCD5\\uDD00-\\uDD08]|\\uD82B[\\uDFF0-\\uDFF3\\uDFF5-\\uDFFB\\uDFFD\\uDFFE]|\\uD82C[\\uDC00-\\uDD22\\uDD50-\\uDD52\\uDD64-\\uDD67\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD834[\\uDEE0-\\uDEF3\\uDF60-\\uDF78]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB\\uDFCE-\\uDFFF]|\\uD837[\\uDF00-\\uDF1E]|\\uD838[\\uDD00-\\uDD2C\\uDD37-\\uDD3D\\uDD40-\\uDD49\\uDD4E\\uDE90-\\uDEAD\\uDEC0-\\uDEEB\\uDEF0-\\uDEF9]|\\uD839[\\uDFE0-\\uDFE6\\uDFE8-\\uDFEB\\uDFED\\uDFEE\\uDFF0-\\uDFFE]|\\uD83A[\\uDC00-\\uDCC4\\uDCC7-\\uDCCF\\uDD00-\\uDD43\\uDD4B\\uDD50-\\uDD59]|\\uD83B[\\uDC71-\\uDCAB\\uDCAD-\\uDCAF\\uDCB1-\\uDCB4\\uDD01-\\uDD2D\\uDD2F-\\uDD3D\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD83C[\\uDD00-\\uDD0C]|\\uD83E[\\uDFF0-\\uDFF9]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF38\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A])/)) return;\n            var nextChar = match[1] || match[2] || '';\n\n            if (!nextChar || nextChar && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar))) {\n                var lLength = match[0].length - 1;\n                var rDelim,\n                    rLength,\n                    delimTotal = lLength,\n                    midDelimTotal = 0;\n                var endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;\n                endReg.lastIndex = 0; // Clip maskedSrc to same section of string as src (move to lexer?)\n\n                maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n                while ((match = endReg.exec(maskedSrc)) != null) {\n                    rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n                    if (!rDelim) continue; // skip single * in __abc*abc__\n\n                    rLength = rDelim.length;\n\n                    if (match[3] || match[4]) {\n                        // found another Left Delim\n                        delimTotal += rLength;\n                        continue;\n                    } else if (match[5] || match[6]) {\n                        // either Left or Right Delim\n                        if (lLength % 3 && !((lLength + rLength) % 3)) {\n                            midDelimTotal += rLength;\n                            continue; // CommonMark Emphasis Rules 9-10\n                        }\n                    }\n\n                    delimTotal -= rLength;\n                    if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n                    // Remove extra characters. *a*** -> *a*\n\n                    rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); // Create `em` if smallest delimiter has odd char count. *a***\n\n                    if (Math.min(lLength, rLength) % 2) {\n                        var _text = src.slice(1, lLength + match.index + rLength);\n\n                        return {\n                            type: 'em',\n                            raw: src.slice(0, lLength + match.index + rLength + 1),\n                            text: _text,\n                            tokens: this.lexer.inlineTokens(_text, [])\n                        };\n                    } // Create 'strong' if smallest delimiter has even char count. **a***\n\n\n                    var text = src.slice(2, lLength + match.index + rLength - 1);\n                    return {\n                        type: 'strong',\n                        raw: src.slice(0, lLength + match.index + rLength + 1),\n                        text: text,\n                        tokens: this.lexer.inlineTokens(text, [])\n                    };\n                }\n            }\n        };\n\n        _proto.codespan = function codespan(src) {\n            var cap = this.rules.inline.code.exec(src);\n\n            if (cap) {\n                var text = cap[2].replace(/\\n/g, ' ');\n                var hasNonSpaceChars = /[^ ]/.test(text);\n                var hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);\n\n                if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n                    text = text.substring(1, text.length - 1);\n                }\n\n                text = escape(text, true);\n                return {\n                    type: 'codespan',\n                    raw: cap[0],\n                    text: text\n                };\n            }\n        };\n\n        _proto.br = function br(src) {\n            var cap = this.rules.inline.br.exec(src);\n\n            if (cap) {\n                return {\n                    type: 'br',\n                    raw: cap[0]\n                };\n            }\n        };\n\n        _proto.del = function del(src) {\n            var cap = this.rules.inline.del.exec(src);\n\n            if (cap) {\n                return {\n                    type: 'del',\n                    raw: cap[0],\n                    text: cap[2],\n                    tokens: this.lexer.inlineTokens(cap[2], [])\n                };\n            }\n        };\n\n        _proto.autolink = function autolink(src, mangle) {\n            var cap = this.rules.inline.autolink.exec(src);\n\n            if (cap) {\n                var text, href;\n\n                if (cap[2] === '@') {\n                    text = escape(this.options.mangle ? mangle(cap[1]) : cap[1]);\n                    href = 'mailto:' + text;\n                } else {\n                    text = escape(cap[1]);\n                    href = text;\n                }\n\n                return {\n                    type: 'link',\n                    raw: cap[0],\n                    text: text,\n                    href: href,\n                    tokens: [{\n                        type: 'text',\n                        raw: text,\n                        text: text\n                    }]\n                };\n            }\n        };\n\n        _proto.url = function url(src, mangle) {\n            var cap;\n\n            if (cap = this.rules.inline.url.exec(src)) {\n                var text, href;\n\n                if (cap[2] === '@') {\n                    text = escape(this.options.mangle ? mangle(cap[0]) : cap[0]);\n                    href = 'mailto:' + text;\n                } else {\n                    // do extended autolink path validation\n                    var prevCapZero;\n\n                    do {\n                        prevCapZero = cap[0];\n                        cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];\n                    } while (prevCapZero !== cap[0]);\n\n                    text = escape(cap[0]);\n\n                    if (cap[1] === 'www.') {\n                        href = 'http://' + text;\n                    } else {\n                        href = text;\n                    }\n                }\n\n                return {\n                    type: 'link',\n                    raw: cap[0],\n                    text: text,\n                    href: href,\n                    tokens: [{\n                        type: 'text',\n                        raw: text,\n                        text: text\n                    }]\n                };\n            }\n        };\n\n        _proto.inlineText = function inlineText(src, smartypants) {\n            var cap = this.rules.inline.text.exec(src);\n\n            if (cap) {\n                var text;\n\n                if (this.lexer.state.inRawBlock) {\n                    text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0];\n                } else {\n                    text = escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);\n                }\n\n                return {\n                    type: 'text',\n                    raw: cap[0],\n                    text: text\n                };\n            }\n        };\n\n        return Tokenizer;\n    }();\n\n    /**\n     * Block-Level Grammar\n     */\n\n    var block = {\n        newline: /^(?: *(?:\\n|$))+/,\n        code: /^( {4}[^\\n]+(?:\\n(?: *(?:\\n|$))*)?)+/,\n        fences: /^ {0,3}(`{3,}(?=[^`\\n]*\\n)|~{3,})([^\\n]*)\\n(?:|([\\s\\S]*?)\\n)(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,\n        hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)/,\n        heading: /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,\n        blockquote: /^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/,\n        list: /^( {0,3}bull)( [^\\n]+?)?(?:\\n|$)/,\n        html: '^ {0,3}(?:' // optional indentation\n            + '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)' // (1)\n            + '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n            + '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n            + '|<![A-Z][\\\\s\\\\S]*?(?:>\\\\n*|$)' // (4)\n            + '|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>\\\\n*|$)' // (5)\n            + '|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (6)\n            + '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) open tag\n            + '|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n *)+\\\\n|$)' // (7) closing tag\n            + ')',\n        def: /^ {0,3}\\[(label)\\]: *\\n? *<?([^\\s>]+)>?(?:(?: +\\n? *| *\\n *)(title))? *(?:\\n+|$)/,\n        table: noopTest,\n        lheading: /^([^\\n]+)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n        // regex template, placeholders will be replaced according to different paragraph\n        // interruption rules of commonmark and the original markdown spec:\n        _paragraph: /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html| +\\n)[^\\n]+)*)/,\n        text: /^[^\\n]+/\n    };\n    block._label = /(?!\\s*\\])(?:\\\\[\\[\\]]|[^\\[\\]])+/;\n    block._title = /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/;\n    block.def = edit(block.def).replace('label', block._label).replace('title', block._title).getRegex();\n    block.bullet = /(?:[*+-]|\\d{1,9}[.)])/;\n    block.listItemStart = edit(/^( *)(bull) */).replace('bull', block.bullet).getRegex();\n    block.list = edit(block.list).replace(/bull/g, block.bullet).replace('hr', '\\\\n+(?=\\\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$))').replace('def', '\\\\n+(?=' + block.def.source + ')').getRegex();\n    block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul';\n    block._comment = /<!--(?!-?>)[\\s\\S]*?(?:-->|$)/;\n    block.html = edit(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/).getRegex();\n    block.paragraph = edit(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs\n        .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n        .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks\n        .getRegex();\n    block.blockquote = edit(block.blockquote).replace('paragraph', block.paragraph).getRegex();\n    /**\n     * Normal Block Grammar\n     */\n\n    block.normal = merge({}, block);\n    /**\n     * GFM Block Grammar\n     */\n\n    block.gfm = merge({}, block.normal, {\n        table: '^ *([^\\\\n ].*\\\\|.*)\\\\n' // Header\n            + ' {0,3}(?:\\\\| *)?(:?-+:? *(?:\\\\| *:?-+:? *)*)(?:\\\\| *)?' // Align\n            + '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)' // Cells\n\n    });\n    block.gfm.table = edit(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n        .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks\n        .getRegex();\n    /**\n     * Pedantic grammar (original John Gruber's loose markdown specification)\n     */\n\n    block.pedantic = merge({}, block.normal, {\n        html: edit('^ *(?:comment *(?:\\\\n|\\\\s*$)' + '|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n            + '|<tag(?:\"[^\"]*\"|\\'[^\\']*\\'|\\\\s[^\\'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))').replace('comment', block._comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b').getRegex(),\n        def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n        heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n        fences: noopTest,\n        // fences not supported\n        paragraph: edit(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex()\n    });\n    /**\n     * Inline-Level Grammar\n     */\n\n    var inline = {\n        escape: /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,\n        autolink: /^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/,\n        url: noopTest,\n        tag: '^comment' + '|^</[a-zA-Z][\\\\w:-]*\\\\s*>' // self-closing tag\n            + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n            + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. <?php ?>\n            + '|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>' // declaration, e.g. <!DOCTYPE html>\n            + '|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>',\n        // CDATA section\n        link: /^!?\\[(label)\\]\\(\\s*(href)(?:\\s+(title))?\\s*\\)/,\n        reflink: /^!?\\[(label)\\]\\[(?!\\s*\\])((?:\\\\[\\[\\]]?|[^\\[\\]\\\\])+)\\]/,\n        nolink: /^!?\\[(?!\\s*\\])((?:\\[[^\\[\\]]*\\]|\\\\[\\[\\]]|[^\\[\\]])*)\\](?:\\[\\])?/,\n        reflinkSearch: 'reflink|nolink(?!\\\\()',\n        emStrong: {\n            lDelim: /^(?:\\*+(?:([punct_])|[^\\s*]))|^_+(?:([punct*])|([^\\s_]))/,\n            //        (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left.  (5) and (6) can be either Left or Right.\n            //        () Skip orphan delim inside strong    (1) #***                (2) a***#, a***                   (3) #***a, ***a                 (4) ***#              (5) #***#                 (6) a***a\n            rDelimAst: /^[^_*]*?\\_\\_[^_*]*?\\*[^_*]*?(?=\\_\\_)|[punct_](\\*+)(?=[\\s]|$)|[^punct*_\\s](\\*+)(?=[punct_\\s]|$)|[punct_\\s](\\*+)(?=[^punct*_\\s])|[\\s](\\*+)(?=[punct_])|[punct_](\\*+)(?=[punct_])|[^punct*_\\s](\\*+)(?=[^punct*_\\s])/,\n            rDelimUnd: /^[^_*]*?\\*\\*[^_*]*?\\_[^_*]*?(?=\\*\\*)|[punct*](\\_+)(?=[\\s]|$)|[^punct*_\\s](\\_+)(?=[punct*\\s]|$)|[punct*\\s](\\_+)(?=[^punct*_\\s])|[\\s](\\_+)(?=[punct*])|[punct*](\\_+)(?=[punct*])/ // ^- Not allowed for _\n\n        },\n        code: /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,\n        br: /^( {2,}|\\\\)\\n(?!\\s*$)/,\n        del: noopTest,\n        text: /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,\n        punctuation: /^([\\spunctuation])/\n    }; // list of punctuation marks from CommonMark spec\n    // without * and _ to handle the different emphasis markers * and _\n\n    inline._punctuation = '!\"#$%&\\'()+\\\\-.,/:;<=>?@\\\\[\\\\]`^{|}~';\n    inline.punctuation = edit(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, <html>\n\n    inline.blockSkip = /\\[[^\\]]*?\\]\\([^\\)]*?\\)|`[^`]*?`|<[^>]*?>/g;\n    inline.escapedEmSt = /\\\\\\*|\\\\_/g;\n    inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex();\n    inline.emStrong.lDelim = edit(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex();\n    inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, 'g').replace(/punct/g, inline._punctuation).getRegex();\n    inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, 'g').replace(/punct/g, inline._punctuation).getRegex();\n    inline._escapes = /\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/g;\n    inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;\n    inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;\n    inline.autolink = edit(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex();\n    inline._attribute = /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/;\n    inline.tag = edit(inline.tag).replace('comment', inline._comment).replace('attribute', inline._attribute).getRegex();\n    inline._label = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\n    inline._href = /<(?:\\\\.|[^\\n<>\\\\])+>|[^\\s\\x00-\\x1f]*/;\n    inline._title = /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/;\n    inline.link = edit(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex();\n    inline.reflink = edit(inline.reflink).replace('label', inline._label).getRegex();\n    inline.reflinkSearch = edit(inline.reflinkSearch, 'g').replace('reflink', inline.reflink).replace('nolink', inline.nolink).getRegex();\n    /**\n     * Normal Inline Grammar\n     */\n\n    inline.normal = merge({}, inline);\n    /**\n     * Pedantic Inline Grammar\n     */\n\n    inline.pedantic = merge({}, inline.normal, {\n        strong: {\n            start: /^__|\\*\\*/,\n            middle: /^__(?=\\S)([\\s\\S]*?\\S)__(?!_)|^\\*\\*(?=\\S)([\\s\\S]*?\\S)\\*\\*(?!\\*)/,\n            endAst: /\\*\\*(?!\\*)/g,\n            endUnd: /__(?!_)/g\n        },\n        em: {\n            start: /^_|\\*/,\n            middle: /^()\\*(?=\\S)([\\s\\S]*?\\S)\\*(?!\\*)|^_(?=\\S)([\\s\\S]*?\\S)_(?!_)/,\n            endAst: /\\*(?!\\*)/g,\n            endUnd: /_(?!_)/g\n        },\n        link: edit(/^!?\\[(label)\\]\\((.*?)\\)/).replace('label', inline._label).getRegex(),\n        reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace('label', inline._label).getRegex()\n    });\n    /**\n     * GFM Inline Grammar\n     */\n\n    inline.gfm = merge({}, inline.normal, {\n        escape: edit(inline.escape).replace('])', '~|])').getRegex(),\n        _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,\n        url: /^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/,\n        _backpedal: /(?:[^?!.,:;*_~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,\n        del: /^(~~?)(?=[^\\s~])([\\s\\S]*?[^\\s~])\\1(?=[^~]|$)/,\n        text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|https?:\\/\\/|ftp:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/\n    });\n    inline.gfm.url = edit(inline.gfm.url, 'i').replace('email', inline.gfm._extended_email).getRegex();\n    /**\n     * GFM + Line Breaks Inline Grammar\n     */\n\n    inline.breaks = merge({}, inline.gfm, {\n        br: edit(inline.br).replace('{2,}', '*').getRegex(),\n        text: edit(inline.gfm.text).replace('\\\\b_', '\\\\b_| {2,}\\\\n').replace(/\\{2,\\}/g, '*').getRegex()\n    });\n\n    /**\n     * smartypants text replacement\n     */\n\n    function smartypants(text) {\n        return text // em-dashes\n            .replace(/---/g, \"\\u2014\") // en-dashes\n            .replace(/--/g, \"\\u2013\") // opening singles\n            .replace(/(^|[-\\u2014/(\\[{\"\\s])'/g, \"$1\\u2018\") // closing singles & apostrophes\n            .replace(/'/g, \"\\u2019\") // opening doubles\n            .replace(/(^|[-\\u2014/(\\[{\\u2018\\s])\"/g, \"$1\\u201C\") // closing doubles\n            .replace(/\"/g, \"\\u201D\") // ellipses\n            .replace(/\\.{3}/g, \"\\u2026\");\n    }\n    /**\n     * mangle email addresses\n     */\n\n\n    function mangle(text) {\n        var out = '',\n            i,\n            ch;\n        var l = text.length;\n\n        for (i = 0; i < l; i++) {\n            ch = text.charCodeAt(i);\n\n            if (Math.random() > 0.5) {\n                ch = 'x' + ch.toString(16);\n            }\n\n            out += '&#' + ch + ';';\n        }\n\n        return out;\n    }\n    /**\n     * Block Lexer\n     */\n\n\n    var Lexer = /*#__PURE__*/function () {\n        function Lexer(options) {\n            this.tokens = [];\n            this.tokens.links = Object.create(null);\n            this.options = options || exports.defaults;\n            this.options.tokenizer = this.options.tokenizer || new Tokenizer();\n            this.tokenizer = this.options.tokenizer;\n            this.tokenizer.options = this.options;\n            this.tokenizer.lexer = this;\n            this.inlineQueue = [];\n            this.state = {\n                inLink: false,\n                inRawBlock: false,\n                top: true\n            };\n            var rules = {\n                block: block.normal,\n                inline: inline.normal\n            };\n\n            if (this.options.pedantic) {\n                rules.block = block.pedantic;\n                rules.inline = inline.pedantic;\n            } else if (this.options.gfm) {\n                rules.block = block.gfm;\n\n                if (this.options.breaks) {\n                    rules.inline = inline.breaks;\n                } else {\n                    rules.inline = inline.gfm;\n                }\n            }\n\n            this.tokenizer.rules = rules;\n        }\n        /**\n         * Expose Rules\n         */\n\n\n        /**\n         * Static Lex Method\n         */\n        Lexer.lex = function lex(src, options) {\n            var lexer = new Lexer(options);\n            return lexer.lex(src);\n        }\n        /**\n         * Static Lex Inline Method\n         */\n        ;\n\n        Lexer.lexInline = function lexInline(src, options) {\n            var lexer = new Lexer(options);\n            return lexer.inlineTokens(src);\n        }\n        /**\n         * Preprocessing\n         */\n        ;\n\n        var _proto = Lexer.prototype;\n\n        _proto.lex = function lex(src) {\n            src = src.replace(/\\r\\n|\\r/g, '\\n').replace(/\\t/g, '    ');\n            this.blockTokens(src, this.tokens);\n            var next;\n\n            while (next = this.inlineQueue.shift()) {\n                this.inlineTokens(next.src, next.tokens);\n            }\n\n            return this.tokens;\n        }\n        /**\n         * Lexing\n         */\n        ;\n\n        _proto.blockTokens = function blockTokens(src, tokens) {\n            var _this = this;\n\n            if (tokens === void 0) {\n                tokens = [];\n            }\n\n            if (this.options.pedantic) {\n                src = src.replace(/^ +$/gm, '');\n            }\n\n            var token, lastToken, cutSrc, lastParagraphClipped;\n\n            while (src) {\n                if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some(function (extTokenizer) {\n                    if (token = extTokenizer.call({\n                        lexer: _this\n                    }, src, tokens)) {\n                        src = src.substring(token.raw.length);\n                        tokens.push(token);\n                        return true;\n                    }\n\n                    return false;\n                })) {\n                    continue;\n                } // newline\n\n\n                if (token = this.tokenizer.space(src)) {\n                    src = src.substring(token.raw.length);\n\n                    if (token.type) {\n                        tokens.push(token);\n                    }\n\n                    continue;\n                } // code\n\n\n                if (token = this.tokenizer.code(src)) {\n                    src = src.substring(token.raw.length);\n                    lastToken = tokens[tokens.length - 1]; // An indented code block cannot interrupt a paragraph.\n\n                    if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n                        lastToken.raw += '\\n' + token.raw;\n                        lastToken.text += '\\n' + token.text;\n                        this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n                    } else {\n                        tokens.push(token);\n                    }\n\n                    continue;\n                } // fences\n\n\n                if (token = this.tokenizer.fences(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // heading\n\n\n                if (token = this.tokenizer.heading(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // hr\n\n\n                if (token = this.tokenizer.hr(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // blockquote\n\n\n                if (token = this.tokenizer.blockquote(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // list\n\n\n                if (token = this.tokenizer.list(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // html\n\n\n                if (token = this.tokenizer.html(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // def\n\n\n                if (token = this.tokenizer.def(src)) {\n                    src = src.substring(token.raw.length);\n                    lastToken = tokens[tokens.length - 1];\n\n                    if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {\n                        lastToken.raw += '\\n' + token.raw;\n                        lastToken.text += '\\n' + token.raw;\n                        this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n                    } else if (!this.tokens.links[token.tag]) {\n                        this.tokens.links[token.tag] = {\n                            href: token.href,\n                            title: token.title\n                        };\n                    }\n\n                    continue;\n                } // table (gfm)\n\n\n                if (token = this.tokenizer.table(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // lheading\n\n\n                if (token = this.tokenizer.lheading(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // top-level paragraph\n                // prevent paragraph consuming extensions by clipping 'src' to extension start\n\n\n                cutSrc = src;\n\n                if (this.options.extensions && this.options.extensions.startBlock) {\n                    (function () {\n                        var startIndex = Infinity;\n                        var tempSrc = src.slice(1);\n                        var tempStart = void 0;\n\n                        _this.options.extensions.startBlock.forEach(function (getStartIndex) {\n                            tempStart = getStartIndex.call({\n                                lexer: this\n                            }, tempSrc);\n\n                            if (typeof tempStart === 'number' && tempStart >= 0) {\n                                startIndex = Math.min(startIndex, tempStart);\n                            }\n                        });\n\n                        if (startIndex < Infinity && startIndex >= 0) {\n                            cutSrc = src.substring(0, startIndex + 1);\n                        }\n                    })();\n                }\n\n                if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n                    lastToken = tokens[tokens.length - 1];\n\n                    if (lastParagraphClipped && lastToken.type === 'paragraph') {\n                        lastToken.raw += '\\n' + token.raw;\n                        lastToken.text += '\\n' + token.text;\n                        this.inlineQueue.pop();\n                        this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n                    } else {\n                        tokens.push(token);\n                    }\n\n                    lastParagraphClipped = cutSrc.length !== src.length;\n                    src = src.substring(token.raw.length);\n                    continue;\n                } // text\n\n\n                if (token = this.tokenizer.text(src)) {\n                    src = src.substring(token.raw.length);\n                    lastToken = tokens[tokens.length - 1];\n\n                    if (lastToken && lastToken.type === 'text') {\n                        lastToken.raw += '\\n' + token.raw;\n                        lastToken.text += '\\n' + token.text;\n                        this.inlineQueue.pop();\n                        this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;\n                    } else {\n                        tokens.push(token);\n                    }\n\n                    continue;\n                }\n\n                if (src) {\n                    var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n\n                    if (this.options.silent) {\n                        console.error(errMsg);\n                        break;\n                    } else {\n                        throw new Error(errMsg);\n                    }\n                }\n            }\n\n            this.state.top = true;\n            return tokens;\n        };\n\n        _proto.inline = function inline(src, tokens) {\n            this.inlineQueue.push({\n                src: src,\n                tokens: tokens\n            });\n        }\n        /**\n         * Lexing/Compiling\n         */\n        ;\n\n        _proto.inlineTokens = function inlineTokens(src, tokens) {\n            var _this2 = this;\n\n            if (tokens === void 0) {\n                tokens = [];\n            }\n\n            var token, lastToken, cutSrc; // String with links masked to avoid interference with em and strong\n\n            var maskedSrc = src;\n            var match;\n            var keepPrevChar, prevChar; // Mask out reflinks\n\n            if (this.tokens.links) {\n                var links = Object.keys(this.tokens.links);\n\n                if (links.length > 0) {\n                    while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n                        if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n                            maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n                        }\n                    }\n                }\n            } // Mask out other blocks\n\n\n            while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n                maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n            } // Mask out escaped em & strong delimiters\n\n\n            while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {\n                maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);\n            }\n\n            while (src) {\n                if (!keepPrevChar) {\n                    prevChar = '';\n                }\n\n                keepPrevChar = false; // extensions\n\n                if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some(function (extTokenizer) {\n                    if (token = extTokenizer.call({\n                        lexer: _this2\n                    }, src, tokens)) {\n                        src = src.substring(token.raw.length);\n                        tokens.push(token);\n                        return true;\n                    }\n\n                    return false;\n                })) {\n                    continue;\n                } // escape\n\n\n                if (token = this.tokenizer.escape(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // tag\n\n\n                if (token = this.tokenizer.tag(src)) {\n                    src = src.substring(token.raw.length);\n                    lastToken = tokens[tokens.length - 1];\n\n                    if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n                        lastToken.raw += token.raw;\n                        lastToken.text += token.text;\n                    } else {\n                        tokens.push(token);\n                    }\n\n                    continue;\n                } // link\n\n\n                if (token = this.tokenizer.link(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // reflink, nolink\n\n\n                if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n                    src = src.substring(token.raw.length);\n                    lastToken = tokens[tokens.length - 1];\n\n                    if (lastToken && token.type === 'text' && lastToken.type === 'text') {\n                        lastToken.raw += token.raw;\n                        lastToken.text += token.text;\n                    } else {\n                        tokens.push(token);\n                    }\n\n                    continue;\n                } // em & strong\n\n\n                if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // code\n\n\n                if (token = this.tokenizer.codespan(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // br\n\n\n                if (token = this.tokenizer.br(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // del (gfm)\n\n\n                if (token = this.tokenizer.del(src)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // autolink\n\n\n                if (token = this.tokenizer.autolink(src, mangle)) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // url (gfm)\n\n\n                if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {\n                    src = src.substring(token.raw.length);\n                    tokens.push(token);\n                    continue;\n                } // text\n                // prevent inlineText consuming extensions by clipping 'src' to extension start\n\n\n                cutSrc = src;\n\n                if (this.options.extensions && this.options.extensions.startInline) {\n                    (function () {\n                        var startIndex = Infinity;\n                        var tempSrc = src.slice(1);\n                        var tempStart = void 0;\n\n                        _this2.options.extensions.startInline.forEach(function (getStartIndex) {\n                            tempStart = getStartIndex.call({\n                                lexer: this\n                            }, tempSrc);\n\n                            if (typeof tempStart === 'number' && tempStart >= 0) {\n                                startIndex = Math.min(startIndex, tempStart);\n                            }\n                        });\n\n                        if (startIndex < Infinity && startIndex >= 0) {\n                            cutSrc = src.substring(0, startIndex + 1);\n                        }\n                    })();\n                }\n\n                if (token = this.tokenizer.inlineText(cutSrc, smartypants)) {\n                    src = src.substring(token.raw.length);\n\n                    if (token.raw.slice(-1) !== '_') {\n                        // Track prevChar before string of ____ started\n                        prevChar = token.raw.slice(-1);\n                    }\n\n                    keepPrevChar = true;\n                    lastToken = tokens[tokens.length - 1];\n\n                    if (lastToken && lastToken.type === 'text') {\n                        lastToken.raw += token.raw;\n                        lastToken.text += token.text;\n                    } else {\n                        tokens.push(token);\n                    }\n\n                    continue;\n                }\n\n                if (src) {\n                    var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n\n                    if (this.options.silent) {\n                        console.error(errMsg);\n                        break;\n                    } else {\n                        throw new Error(errMsg);\n                    }\n                }\n            }\n\n            return tokens;\n        };\n\n        _createClass(Lexer, null, [{\n            key: \"rules\",\n            get: function get() {\n                return {\n                    block: block,\n                    inline: inline\n                };\n            }\n        }]);\n\n        return Lexer;\n    }();\n\n    /**\n     * Renderer\n     */\n\n    var Renderer = /*#__PURE__*/function () {\n        function Renderer(options) {\n            this.options = options || exports.defaults;\n        }\n\n        var _proto = Renderer.prototype;\n\n        _proto.code = function code(_code, infostring, escaped) {\n            var lang = (infostring || '').match(/\\S*/)[0];\n\n            if (this.options.highlight) {\n                var out = this.options.highlight(_code, lang);\n\n                if (out != null && out !== _code) {\n                    escaped = true;\n                    _code = out;\n                }\n            }\n\n            _code = _code.replace(/\\n$/, '') + '\\n';\n\n            if (!lang) {\n                return '<pre><code>' + (escaped ? _code : escape(_code, true)) + '</code></pre>\\n';\n            }\n\n            return '<pre><code class=\"' + this.options.langPrefix + escape(lang, true) + '\">' + (escaped ? _code : escape(_code, true)) + '</code></pre>\\n';\n        };\n\n        _proto.blockquote = function blockquote(quote) {\n            return '<blockquote>\\n' + quote + '</blockquote>\\n';\n        };\n\n        _proto.html = function html(_html) {\n            return _html;\n        };\n\n        _proto.heading = function heading(text, level, raw, slugger) {\n            if (this.options.headerIds) {\n                return '<h' + level + ' id=\"' + this.options.headerPrefix + slugger.slug(raw) + '\">' + text + '</h' + level + '>\\n';\n            } // ignore IDs\n\n\n            return '<h' + level + '>' + text + '</h' + level + '>\\n';\n        };\n\n        _proto.hr = function hr() {\n            return this.options.xhtml ? '<hr/>\\n' : '<hr>\\n';\n        };\n\n        _proto.list = function list(body, ordered, start) {\n            var type = ordered ? 'ol' : 'ul',\n                startatt = ordered && start !== 1 ? ' start=\"' + start + '\"' : '';\n            return '<' + type + startatt + '>\\n' + body + '</' + type + '>\\n';\n        };\n\n        _proto.listitem = function listitem(text) {\n            return '<li>' + text + '</li>\\n';\n        };\n\n        _proto.checkbox = function checkbox(checked) {\n            return '<input ' + (checked ? 'checked=\"\" ' : '') + 'disabled=\"\" type=\"checkbox\"' + (this.options.xhtml ? ' /' : '') + '> ';\n        };\n\n        _proto.paragraph = function paragraph(text) {\n            return '<p>' + text + '</p>\\n';\n        };\n\n        _proto.table = function table(header, body) {\n            if (body) body = '<tbody>' + body + '</tbody>';\n            return '<table>\\n' + '<thead>\\n' + header + '</thead>\\n' + body + '</table>\\n';\n        };\n\n        _proto.tablerow = function tablerow(content) {\n            return '<tr>\\n' + content + '</tr>\\n';\n        };\n\n        _proto.tablecell = function tablecell(content, flags) {\n            var type = flags.header ? 'th' : 'td';\n            var tag = flags.align ? '<' + type + ' align=\"' + flags.align + '\">' : '<' + type + '>';\n            return tag + content + '</' + type + '>\\n';\n        } // span level renderer\n        ;\n\n        _proto.strong = function strong(text) {\n            return '<strong>' + text + '</strong>';\n        };\n\n        _proto.em = function em(text) {\n            return '<em>' + text + '</em>';\n        };\n\n        _proto.codespan = function codespan(text) {\n            return '<code>' + text + '</code>';\n        };\n\n        _proto.br = function br() {\n            return this.options.xhtml ? '<br/>' : '<br>';\n        };\n\n        _proto.del = function del(text) {\n            return '<del>' + text + '</del>';\n        };\n\n        _proto.link = function link(href, title, text) {\n            href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);\n\n            if (href === null) {\n                return text;\n            }\n\n            var out = '<a href=\"' + escape(href) + '\" target=\"_blank\"';\n\n            if (title) {\n                out += ' title=\"' + title + '\"';\n            }\n\n            out += '>' + text + '</a>';\n            return out;\n        };\n\n        _proto.image = function image(href, title, text) {\n            href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);\n\n            if (href === null) {\n                return text;\n            }\n\n            var out = '<img style=\"max-width:100%\" src=\"' + href + '\" alt=\"' + text + '\"';\n\n            if (title) {\n                out += ' title=\"' + title + '\"';\n            }\n\n            out += this.options.xhtml ? '/>' : '>';\n            return out;\n        };\n\n        _proto.text = function text(_text) {\n            return _text;\n        };\n\n        return Renderer;\n    }();\n\n    /**\n     * TextRenderer\n     * returns only the textual part of the token\n     */\n    var TextRenderer = /*#__PURE__*/function () {\n        function TextRenderer() {}\n\n        var _proto = TextRenderer.prototype;\n\n        // no need for block level renderers\n        _proto.strong = function strong(text) {\n            return text;\n        };\n\n        _proto.em = function em(text) {\n            return text;\n        };\n\n        _proto.codespan = function codespan(text) {\n            return text;\n        };\n\n        _proto.del = function del(text) {\n            return text;\n        };\n\n        _proto.html = function html(text) {\n            return text;\n        };\n\n        _proto.text = function text(_text) {\n            return _text;\n        };\n\n        _proto.link = function link(href, title, text) {\n            return '' + text;\n        };\n\n        _proto.image = function image(href, title, text) {\n            return '' + text;\n        };\n\n        _proto.br = function br() {\n            return '';\n        };\n\n        return TextRenderer;\n    }();\n\n    /**\n     * Slugger generates header id\n     */\n    var Slugger = /*#__PURE__*/function () {\n        function Slugger() {\n            this.seen = {};\n        }\n\n        var _proto = Slugger.prototype;\n\n        _proto.serialize = function serialize(value) {\n            return value.toLowerCase().trim() // remove html tags\n                .replace(/<[!\\/a-z].*?>/ig, '') // remove unwanted chars\n                .replace(/[\\u2000-\\u206F\\u2E00-\\u2E7F\\\\'!\"#$%&()*+,./:;<=>?@[\\]^`{|}~]/g, '').replace(/\\s/g, '-');\n        }\n        /**\n         * Finds the next safe (unique) slug to use\n         */\n        ;\n\n        _proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) {\n            var slug = originalSlug;\n            var occurenceAccumulator = 0;\n\n            if (this.seen.hasOwnProperty(slug)) {\n                occurenceAccumulator = this.seen[originalSlug];\n\n                do {\n                    occurenceAccumulator++;\n                    slug = originalSlug + '-' + occurenceAccumulator;\n                } while (this.seen.hasOwnProperty(slug));\n            }\n\n            if (!isDryRun) {\n                this.seen[originalSlug] = occurenceAccumulator;\n                this.seen[slug] = 0;\n            }\n\n            return slug;\n        }\n        /**\n         * Convert string to unique id\n         * @param {object} options\n         * @param {boolean} options.dryrun Generates the next unique slug without updating the internal accumulator.\n         */\n        ;\n\n        _proto.slug = function slug(value, options) {\n            if (options === void 0) {\n                options = {};\n            }\n\n            var slug = this.serialize(value);\n            return this.getNextSafeSlug(slug, options.dryrun);\n        };\n\n        return Slugger;\n    }();\n\n    /**\n     * Parsing & Compiling\n     */\n\n    var Parser = /*#__PURE__*/function () {\n        function Parser(options) {\n            this.options = options || exports.defaults;\n            this.options.renderer = this.options.renderer || new Renderer();\n            this.renderer = this.options.renderer;\n            this.renderer.options = this.options;\n            this.textRenderer = new TextRenderer();\n            this.slugger = new Slugger();\n        }\n        /**\n         * Static Parse Method\n         */\n\n\n        Parser.parse = function parse(tokens, options) {\n            var parser = new Parser(options);\n            return parser.parse(tokens);\n        }\n        /**\n         * Static Parse Inline Method\n         */\n        ;\n\n        Parser.parseInline = function parseInline(tokens, options) {\n            var parser = new Parser(options);\n            return parser.parseInline(tokens);\n        }\n        /**\n         * Parse Loop\n         */\n        ;\n\n        var _proto = Parser.prototype;\n\n        _proto.parse = function parse(tokens, top) {\n            if (top === void 0) {\n                top = true;\n            }\n\n            var out = '',\n                i,\n                j,\n                k,\n                l2,\n                l3,\n                row,\n                cell,\n                header,\n                body,\n                token,\n                ordered,\n                start,\n                loose,\n                itemBody,\n                item,\n                checked,\n                task,\n                checkbox,\n                ret;\n            var l = tokens.length;\n\n            for (i = 0; i < l; i++) {\n                token = tokens[i]; // Run any renderer extensions\n\n                if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {\n                    ret = this.options.extensions.renderers[token.type].call({\n                        parser: this\n                    }, token);\n\n                    if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(token.type)) {\n                        out += ret || '';\n                        continue;\n                    }\n                }\n\n                switch (token.type) {\n                    case 'space':\n                    {\n                        continue;\n                    }\n\n                    case 'hr':\n                    {\n                        out += this.renderer.hr();\n                        continue;\n                    }\n\n                    case 'heading':\n                    {\n                        out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape(this.parseInline(token.tokens, this.textRenderer)), this.slugger);\n                        continue;\n                    }\n\n                    case 'code':\n                    {\n                        out += this.renderer.code(token.text, token.lang, token.escaped);\n                        continue;\n                    }\n\n                    case 'table':\n                    {\n                        header = ''; // header\n\n                        cell = '';\n                        l2 = token.header.length;\n\n                        for (j = 0; j < l2; j++) {\n                            cell += this.renderer.tablecell(this.parseInline(token.header[j].tokens), {\n                                header: true,\n                                align: token.align[j]\n                            });\n                        }\n\n                        header += this.renderer.tablerow(cell);\n                        body = '';\n                        l2 = token.rows.length;\n\n                        for (j = 0; j < l2; j++) {\n                            row = token.rows[j];\n                            cell = '';\n                            l3 = row.length;\n\n                            for (k = 0; k < l3; k++) {\n                                cell += this.renderer.tablecell(this.parseInline(row[k].tokens), {\n                                    header: false,\n                                    align: token.align[k]\n                                });\n                            }\n\n                            body += this.renderer.tablerow(cell);\n                        }\n\n                        out += this.renderer.table(header, body);\n                        continue;\n                    }\n\n                    case 'blockquote':\n                    {\n                        body = this.parse(token.tokens);\n                        out += this.renderer.blockquote(body);\n                        continue;\n                    }\n\n                    case 'list':\n                    {\n                        ordered = token.ordered;\n                        start = token.start;\n                        loose = token.loose;\n                        l2 = token.items.length;\n                        body = '';\n\n                        for (j = 0; j < l2; j++) {\n                            item = token.items[j];\n                            checked = item.checked;\n                            task = item.task;\n                            itemBody = '';\n\n                            if (item.task) {\n                                checkbox = this.renderer.checkbox(checked);\n\n                                if (loose) {\n                                    if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {\n                                        item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n\n                                        if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n                                            item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;\n                                        }\n                                    } else {\n                                        item.tokens.unshift({\n                                            type: 'text',\n                                            text: checkbox\n                                        });\n                                    }\n                                } else {\n                                    itemBody += checkbox;\n                                }\n                            }\n\n                            itemBody += this.parse(item.tokens, loose);\n                            body += this.renderer.listitem(itemBody, task, checked);\n                        }\n\n                        out += this.renderer.list(body, ordered, start);\n                        continue;\n                    }\n\n                    case 'html':\n                    {\n                        // TODO parse inline content if parameter markdown=1\n                        out += this.renderer.html(token.text);\n                        continue;\n                    }\n\n                    case 'paragraph':\n                    {\n                        out += this.renderer.paragraph(this.parseInline(token.tokens));\n                        continue;\n                    }\n\n                    case 'text':\n                    {\n                        body = token.tokens ? this.parseInline(token.tokens) : token.text;\n\n                        while (i + 1 < l && tokens[i + 1].type === 'text') {\n                            token = tokens[++i];\n                            body += '\\n' + (token.tokens ? this.parseInline(token.tokens) : token.text);\n                        }\n\n                        out += top ? this.renderer.paragraph(body) : body;\n                        continue;\n                    }\n\n                    default:\n                    {\n                        var errMsg = 'Token with \"' + token.type + '\" type was not found.';\n\n                        if (this.options.silent) {\n                            console.error(errMsg);\n                            return;\n                        } else {\n                            throw new Error(errMsg);\n                        }\n                    }\n                }\n            }\n\n            return out;\n        }\n        /**\n         * Parse Inline Tokens\n         */\n        ;\n\n        _proto.parseInline = function parseInline(tokens, renderer) {\n            renderer = renderer || this.renderer;\n            var out = '',\n                i,\n                token,\n                ret;\n            var l = tokens.length;\n\n            for (i = 0; i < l; i++) {\n                token = tokens[i]; // Run any renderer extensions\n\n                if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {\n                    ret = this.options.extensions.renderers[token.type].call({\n                        parser: this\n                    }, token);\n\n                    if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {\n                        out += ret || '';\n                        continue;\n                    }\n                }\n\n                switch (token.type) {\n                    case 'escape':\n                    {\n                        out += renderer.text(token.text);\n                        break;\n                    }\n\n                    case 'html':\n                    {\n                        out += renderer.html(token.text);\n                        break;\n                    }\n\n                    case 'link':\n                    {\n                        out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));\n                        break;\n                    }\n\n                    case 'image':\n                    {\n                        out += renderer.image(token.href, token.title, token.text);\n                        break;\n                    }\n\n                    case 'strong':\n                    {\n                        out += renderer.strong(this.parseInline(token.tokens, renderer));\n                        break;\n                    }\n\n                    case 'em':\n                    {\n                        out += renderer.em(this.parseInline(token.tokens, renderer));\n                        break;\n                    }\n\n                    case 'codespan':\n                    {\n                        out += renderer.codespan(token.text);\n                        break;\n                    }\n\n                    case 'br':\n                    {\n                        out += renderer.br();\n                        break;\n                    }\n\n                    case 'del':\n                    {\n                        out += renderer.del(this.parseInline(token.tokens, renderer));\n                        break;\n                    }\n\n                    case 'text':\n                    {\n                        out += renderer.text(token.text);\n                        break;\n                    }\n\n                    default:\n                    {\n                        var errMsg = 'Token with \"' + token.type + '\" type was not found.';\n\n                        if (this.options.silent) {\n                            console.error(errMsg);\n                            return;\n                        } else {\n                            throw new Error(errMsg);\n                        }\n                    }\n                }\n            }\n\n            return out;\n        };\n\n        return Parser;\n    }();\n\n    /**\n     * Marked\n     */\n\n    function marked(src, opt, callback) {\n        // throw error in case of non string input\n        if (typeof src === 'undefined' || src === null) {\n            throw new Error('marked(): input parameter is undefined or null');\n        }\n\n        if (typeof src !== 'string') {\n            throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');\n        }\n\n        if (typeof opt === 'function') {\n            callback = opt;\n            opt = null;\n        }\n\n        opt = merge({}, marked.defaults, opt || {});\n        checkSanitizeDeprecation(opt);\n\n        if (callback) {\n            var highlight = opt.highlight;\n            var tokens;\n\n            try {\n                tokens = Lexer.lex(src, opt);\n            } catch (e) {\n                return callback(e);\n            }\n\n            var done = function done(err) {\n                var out;\n\n                if (!err) {\n                    try {\n                        if (opt.walkTokens) {\n                            marked.walkTokens(tokens, opt.walkTokens);\n                        }\n\n                        out = Parser.parse(tokens, opt);\n                    } catch (e) {\n                        err = e;\n                    }\n                }\n\n                opt.highlight = highlight;\n                return err ? callback(err) : callback(null, out);\n            };\n\n            if (!highlight || highlight.length < 3) {\n                return done();\n            }\n\n            delete opt.highlight;\n            if (!tokens.length) return done();\n            var pending = 0;\n            marked.walkTokens(tokens, function (token) {\n                if (token.type === 'code') {\n                    pending++;\n                    setTimeout(function () {\n                        highlight(token.text, token.lang, function (err, code) {\n                            if (err) {\n                                return done(err);\n                            }\n\n                            if (code != null && code !== token.text) {\n                                token.text = code;\n                                token.escaped = true;\n                            }\n\n                            pending--;\n\n                            if (pending === 0) {\n                                done();\n                            }\n                        });\n                    }, 0);\n                }\n            });\n\n            if (pending === 0) {\n                done();\n            }\n\n            return;\n        }\n\n        try {\n            var _tokens = Lexer.lex(src, opt);\n\n            if (opt.walkTokens) {\n                marked.walkTokens(_tokens, opt.walkTokens);\n            }\n\n            return Parser.parse(_tokens, opt);\n        } catch (e) {\n            e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n            if (opt.silent) {\n                return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';\n            }\n\n            throw e;\n        }\n    }\n    /**\n     * Options\n     */\n\n\n    marked.options = marked.setOptions = function (opt) {\n        merge(marked.defaults, opt);\n        changeDefaults(marked.defaults);\n        return marked;\n    };\n\n    marked.getDefaults = getDefaults;\n    marked.defaults = exports.defaults;\n    /**\n     * Use Extension\n     */\n\n    marked.use = function () {\n        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n            args[_key] = arguments[_key];\n        }\n\n        var opts = merge.apply(void 0, [{}].concat(args));\n        var extensions = marked.defaults.extensions || {\n            renderers: {},\n            childTokens: {}\n        };\n        var hasExtensions;\n        args.forEach(function (pack) {\n            // ==-- Parse \"addon\" extensions --== //\n            if (pack.extensions) {\n                hasExtensions = true;\n                pack.extensions.forEach(function (ext) {\n                    if (!ext.name) {\n                        throw new Error('extension name required');\n                    }\n\n                    if (ext.renderer) {\n                        // Renderer extensions\n                        var prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null;\n\n                        if (prevRenderer) {\n                            // Replace extension with func to run new extension but fall back if false\n                            extensions.renderers[ext.name] = function () {\n                                for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n                                    args[_key2] = arguments[_key2];\n                                }\n\n                                var ret = ext.renderer.apply(this, args);\n\n                                if (ret === false) {\n                                    ret = prevRenderer.apply(this, args);\n                                }\n\n                                return ret;\n                            };\n                        } else {\n                            extensions.renderers[ext.name] = ext.renderer;\n                        }\n                    }\n\n                    if (ext.tokenizer) {\n                        // Tokenizer Extensions\n                        if (!ext.level || ext.level !== 'block' && ext.level !== 'inline') {\n                            throw new Error(\"extension level must be 'block' or 'inline'\");\n                        }\n\n                        if (extensions[ext.level]) {\n                            extensions[ext.level].unshift(ext.tokenizer);\n                        } else {\n                            extensions[ext.level] = [ext.tokenizer];\n                        }\n\n                        if (ext.start) {\n                            // Function to check for start of token\n                            if (ext.level === 'block') {\n                                if (extensions.startBlock) {\n                                    extensions.startBlock.push(ext.start);\n                                } else {\n                                    extensions.startBlock = [ext.start];\n                                }\n                            } else if (ext.level === 'inline') {\n                                if (extensions.startInline) {\n                                    extensions.startInline.push(ext.start);\n                                } else {\n                                    extensions.startInline = [ext.start];\n                                }\n                            }\n                        }\n                    }\n\n                    if (ext.childTokens) {\n                        // Child tokens to be visited by walkTokens\n                        extensions.childTokens[ext.name] = ext.childTokens;\n                    }\n                });\n            } // ==-- Parse \"overwrite\" extensions --== //\n\n\n            if (pack.renderer) {\n                (function () {\n                    var renderer = marked.defaults.renderer || new Renderer();\n\n                    var _loop = function _loop(prop) {\n                        var prevRenderer = renderer[prop]; // Replace renderer with func to run extension, but fall back if false\n\n                        renderer[prop] = function () {\n                            for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n                                args[_key3] = arguments[_key3];\n                            }\n\n                            var ret = pack.renderer[prop].apply(renderer, args);\n\n                            if (ret === false) {\n                                ret = prevRenderer.apply(renderer, args);\n                            }\n\n                            return ret;\n                        };\n                    };\n\n                    for (var prop in pack.renderer) {\n                        _loop(prop);\n                    }\n\n                    opts.renderer = renderer;\n                })();\n            }\n\n            if (pack.tokenizer) {\n                (function () {\n                    var tokenizer = marked.defaults.tokenizer || new Tokenizer();\n\n                    var _loop2 = function _loop2(prop) {\n                        var prevTokenizer = tokenizer[prop]; // Replace tokenizer with func to run extension, but fall back if false\n\n                        tokenizer[prop] = function () {\n                            for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n                                args[_key4] = arguments[_key4];\n                            }\n\n                            var ret = pack.tokenizer[prop].apply(tokenizer, args);\n\n                            if (ret === false) {\n                                ret = prevTokenizer.apply(tokenizer, args);\n                            }\n\n                            return ret;\n                        };\n                    };\n\n                    for (var prop in pack.tokenizer) {\n                        _loop2(prop);\n                    }\n\n                    opts.tokenizer = tokenizer;\n                })();\n            } // ==-- Parse WalkTokens extensions --== //\n\n\n            if (pack.walkTokens) {\n                var _walkTokens = marked.defaults.walkTokens;\n\n                opts.walkTokens = function (token) {\n                    pack.walkTokens.call(this, token);\n\n                    if (_walkTokens) {\n                        _walkTokens.call(this, token);\n                    }\n                };\n            }\n\n            if (hasExtensions) {\n                opts.extensions = extensions;\n            }\n\n            marked.setOptions(opts);\n        });\n    };\n    /**\n     * Run callback for every token\n     */\n\n\n    marked.walkTokens = function (tokens, callback) {\n        var _loop3 = function _loop3() {\n            var token = _step.value;\n            callback.call(marked, token);\n\n            switch (token.type) {\n                case 'table':\n                {\n                    for (var _iterator2 = _createForOfIteratorHelperLoose(token.header), _step2; !(_step2 = _iterator2()).done;) {\n                        var cell = _step2.value;\n                        marked.walkTokens(cell.tokens, callback);\n                    }\n\n                    for (var _iterator3 = _createForOfIteratorHelperLoose(token.rows), _step3; !(_step3 = _iterator3()).done;) {\n                        var row = _step3.value;\n\n                        for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) {\n                            var _cell = _step4.value;\n                            marked.walkTokens(_cell.tokens, callback);\n                        }\n                    }\n\n                    break;\n                }\n\n                case 'list':\n                {\n                    marked.walkTokens(token.items, callback);\n                    break;\n                }\n\n                default:\n                {\n                    if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) {\n                        // Walk any extensions\n                        marked.defaults.extensions.childTokens[token.type].forEach(function (childTokens) {\n                            marked.walkTokens(token[childTokens], callback);\n                        });\n                    } else if (token.tokens) {\n                        marked.walkTokens(token.tokens, callback);\n                    }\n                }\n            }\n        };\n\n        for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) {\n            _loop3();\n        }\n    };\n    /**\n     * Parse Inline\n     */\n\n\n    marked.parseInline = function (src, opt) {\n        // throw error in case of non string input\n        if (typeof src === 'undefined' || src === null) {\n            throw new Error('marked.parseInline(): input parameter is undefined or null');\n        }\n\n        if (typeof src !== 'string') {\n            throw new Error('marked.parseInline(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');\n        }\n\n        opt = merge({}, marked.defaults, opt || {});\n        checkSanitizeDeprecation(opt);\n\n        try {\n            var tokens = Lexer.lexInline(src, opt);\n\n            if (opt.walkTokens) {\n                marked.walkTokens(tokens, opt.walkTokens);\n            }\n\n            return Parser.parseInline(tokens, opt);\n        } catch (e) {\n            e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n            if (opt.silent) {\n                return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';\n            }\n\n            throw e;\n        }\n    };\n    /**\n     * Expose\n     */\n\n\n    marked.Parser = Parser;\n    marked.parser = Parser.parse;\n    marked.Renderer = Renderer;\n    marked.TextRenderer = TextRenderer;\n    marked.Lexer = Lexer;\n    marked.lexer = Lexer.lex;\n    marked.Tokenizer = Tokenizer;\n    marked.Slugger = Slugger;\n    marked.parse = marked;\n    var options = marked.options;\n    var setOptions = marked.setOptions;\n    var use = marked.use;\n    var walkTokens = marked.walkTokens;\n    var parseInline = marked.parseInline;\n    var parse = marked;\n    var parser = Parser.parse;\n    var lexer = Lexer.lex;\n\n    exports.Lexer = Lexer;\n    exports.Parser = Parser;\n    exports.Renderer = Renderer;\n    exports.Slugger = Slugger;\n    exports.TextRenderer = TextRenderer;\n    exports.Tokenizer = Tokenizer;\n    exports[\"default\"] = marked;\n    exports.getDefaults = getDefaults;\n    exports.lexer = lexer;\n    exports.options = options;\n    exports.parse = parse;\n    exports.parseInline = parseInline;\n    exports.parser = parser;\n    exports.setOptions = setOptions;\n    exports.use = use;\n    exports.walkTokens = walkTokens;\n\n    Object.defineProperty(exports, '__esModule', { value: true });\n\n}));"
  },
  {
    "path": "src/renderer/lib/smoothscroll.js",
    "content": "/* smoothscroll v0.4.4 - 2019 - Dustan Kasten, Jeremias Menichelli - MIT License */\n(function () {\n    'use strict';\n  \n    // polyfill\n    function polyfill() {\n      // aliases\n      var w = window;\n      var d = document;\n  \n      // return if scroll behavior is supported and polyfill is not forced\n      if (\n        'scrollBehavior' in d.documentElement.style &&\n        w.__forceSmoothScrollPolyfill__ !== true\n      ) {\n        return;\n      }\n  \n      // globals\n      var Element = w.HTMLElement || w.Element;\n      var SCROLL_TIME = 468;\n  \n      // object gathering original scroll methods\n      var original = {\n        scroll: w.scroll || w.scrollTo,\n        scrollBy: w.scrollBy,\n        elementScroll: Element.prototype.scroll || scrollElement,\n        scrollIntoView: Element.prototype.scrollIntoView\n      };\n  \n      // define timing method\n      var now =\n        w.performance && w.performance.now\n          ? w.performance.now.bind(w.performance)\n          : Date.now;\n  \n      /**\n       * indicates if a the current browser is made by Microsoft\n       * @method isMicrosoftBrowser\n       * @param {String} userAgent\n       * @returns {Boolean}\n       */\n      function isMicrosoftBrowser(userAgent) {\n        var userAgentPatterns = ['MSIE ', 'Trident/', 'Edge/'];\n  \n        return new RegExp(userAgentPatterns.join('|')).test(userAgent);\n      }\n  \n      /*\n       * IE has rounding bug rounding down clientHeight and clientWidth and\n       * rounding up scrollHeight and scrollWidth causing false positives\n       * on hasScrollableSpace\n       */\n      var ROUNDING_TOLERANCE = isMicrosoftBrowser(w.navigator.userAgent) ? 1 : 0;\n  \n      /**\n       * changes scroll position inside an element\n       * @method scrollElement\n       * @param {Number} x\n       * @param {Number} y\n       * @returns {undefined}\n       */\n      function scrollElement(x, y) {\n        this.scrollLeft = x;\n        this.scrollTop = y;\n      }\n  \n      /**\n       * returns result of applying ease math function to a number\n       * @method ease\n       * @param {Number} k\n       * @returns {Number}\n       */\n      function ease(k) {\n        return 0.5 * (1 - Math.cos(Math.PI * k));\n      }\n  \n      /**\n       * indicates if a smooth behavior should be applied\n       * @method shouldBailOut\n       * @param {Number|Object} firstArg\n       * @returns {Boolean}\n       */\n      function shouldBailOut(firstArg) {\n        if (\n          firstArg === null ||\n          typeof firstArg !== 'object' ||\n          firstArg.behavior === undefined ||\n          firstArg.behavior === 'auto' ||\n          firstArg.behavior === 'instant'\n        ) {\n          // first argument is not an object/null\n          // or behavior is auto, instant or undefined\n          return true;\n        }\n  \n        if (typeof firstArg === 'object' && firstArg.behavior === 'smooth') {\n          // first argument is an object and behavior is smooth\n          return false;\n        }\n  \n        // throw error when behavior is not supported\n        throw new TypeError(\n          'behavior member of ScrollOptions ' +\n            firstArg.behavior +\n            ' is not a valid value for enumeration ScrollBehavior.'\n        );\n      }\n  \n      /**\n       * indicates if an element has scrollable space in the provided axis\n       * @method hasScrollableSpace\n       * @param {Node} el\n       * @param {String} axis\n       * @returns {Boolean}\n       */\n      function hasScrollableSpace(el, axis) {\n        if (axis === 'Y') {\n          return el.clientHeight + ROUNDING_TOLERANCE < el.scrollHeight;\n        }\n  \n        if (axis === 'X') {\n          return el.clientWidth + ROUNDING_TOLERANCE < el.scrollWidth;\n        }\n      }\n  \n      /**\n       * indicates if an element has a scrollable overflow property in the axis\n       * @method canOverflow\n       * @param {Node} el\n       * @param {String} axis\n       * @returns {Boolean}\n       */\n      function canOverflow(el, axis) {\n        var overflowValue = w.getComputedStyle(el, null)['overflow' + axis];\n  \n        return overflowValue === 'auto' || overflowValue === 'scroll';\n      }\n  \n      /**\n       * indicates if an element can be scrolled in either axis\n       * @method isScrollable\n       * @param {Node} el\n       * @param {String} axis\n       * @returns {Boolean}\n       */\n      function isScrollable(el) {\n        var isScrollableY = hasScrollableSpace(el, 'Y') && canOverflow(el, 'Y');\n        var isScrollableX = hasScrollableSpace(el, 'X') && canOverflow(el, 'X');\n  \n        return isScrollableY || isScrollableX;\n      }\n  \n      /**\n       * finds scrollable parent of an element\n       * @method findScrollableParent\n       * @param {Node} el\n       * @returns {Node} el\n       */\n      function findScrollableParent(el) {\n        while (el !== d.body && isScrollable(el) === false) {\n          el = el.parentNode || el.host;\n        }\n  \n        return el;\n      }\n  \n      /**\n       * self invoked function that, given a context, steps through scrolling\n       * @method step\n       * @param {Object} context\n       * @returns {undefined}\n       */\n      function step(context) {\n        var time = now();\n        var value;\n        var currentX;\n        var currentY;\n        var elapsed = (time - context.startTime) / SCROLL_TIME;\n  \n        // avoid elapsed times higher than one\n        elapsed = elapsed > 1 ? 1 : elapsed;\n  \n        // apply easing to elapsed time\n        value = ease(elapsed);\n  \n        currentX = context.startX + (context.x - context.startX) * value;\n        currentY = context.startY + (context.y - context.startY) * value;\n  \n        context.method.call(context.scrollable, currentX, currentY);\n  \n        // scroll more if we have not reached our destination\n        if (currentX !== context.x || currentY !== context.y) {\n          w.requestAnimationFrame(step.bind(w, context));\n        }\n      }\n  \n      /**\n       * scrolls window or element with a smooth behavior\n       * @method smoothScroll\n       * @param {Object|Node} el\n       * @param {Number} x\n       * @param {Number} y\n       * @returns {undefined}\n       */\n      function smoothScroll(el, x, y) {\n        var scrollable;\n        var startX;\n        var startY;\n        var method;\n        var startTime = now();\n  \n        // define scroll context\n        if (el === d.body) {\n          scrollable = w;\n          startX = w.scrollX || w.pageXOffset;\n          startY = w.scrollY || w.pageYOffset;\n          method = original.scroll;\n        } else {\n          scrollable = el;\n          startX = el.scrollLeft;\n          startY = el.scrollTop;\n          method = scrollElement;\n        }\n  \n        // scroll looping over a frame\n        step({\n          scrollable: scrollable,\n          method: method,\n          startTime: startTime,\n          startX: startX,\n          startY: startY,\n          x: x,\n          y: y\n        });\n      }\n  \n      // ORIGINAL METHODS OVERRIDES\n      // w.scroll and w.scrollTo\n      w.scroll = w.scrollTo = function() {\n        // avoid action when no arguments are passed\n        if (arguments[0] === undefined) {\n          return;\n        }\n  \n        // avoid smooth behavior if not required\n        if (shouldBailOut(arguments[0]) === true) {\n          original.scroll.call(\n            w,\n            arguments[0].left !== undefined\n              ? arguments[0].left\n              : typeof arguments[0] !== 'object'\n                ? arguments[0]\n                : w.scrollX || w.pageXOffset,\n            // use top prop, second argument if present or fallback to scrollY\n            arguments[0].top !== undefined\n              ? arguments[0].top\n              : arguments[1] !== undefined\n                ? arguments[1]\n                : w.scrollY || w.pageYOffset\n          );\n  \n          return;\n        }\n  \n        // LET THE SMOOTHNESS BEGIN!\n        smoothScroll.call(\n          w,\n          d.body,\n          arguments[0].left !== undefined\n            ? ~~arguments[0].left\n            : w.scrollX || w.pageXOffset,\n          arguments[0].top !== undefined\n            ? ~~arguments[0].top\n            : w.scrollY || w.pageYOffset\n        );\n      };\n  \n      // w.scrollBy\n      w.scrollBy = function() {\n        // avoid action when no arguments are passed\n        if (arguments[0] === undefined) {\n          return;\n        }\n  \n        // avoid smooth behavior if not required\n        if (shouldBailOut(arguments[0])) {\n          original.scrollBy.call(\n            w,\n            arguments[0].left !== undefined\n              ? arguments[0].left\n              : typeof arguments[0] !== 'object' ? arguments[0] : 0,\n            arguments[0].top !== undefined\n              ? arguments[0].top\n              : arguments[1] !== undefined ? arguments[1] : 0\n          );\n  \n          return;\n        }\n  \n        // LET THE SMOOTHNESS BEGIN!\n        smoothScroll.call(\n          w,\n          d.body,\n          ~~arguments[0].left + (w.scrollX || w.pageXOffset),\n          ~~arguments[0].top + (w.scrollY || w.pageYOffset)\n        );\n      };\n  \n      // Element.prototype.scroll and Element.prototype.scrollTo\n      Element.prototype.scroll = Element.prototype.scrollTo = function() {\n        // avoid action when no arguments are passed\n        if (arguments[0] === undefined) {\n          return;\n        }\n  \n        // avoid smooth behavior if not required\n        if (shouldBailOut(arguments[0]) === true) {\n          // if one number is passed, throw error to match Firefox implementation\n          if (typeof arguments[0] === 'number' && arguments[1] === undefined) {\n            throw new SyntaxError('Value could not be converted');\n          }\n  \n          original.elementScroll.call(\n            this,\n            // use left prop, first number argument or fallback to scrollLeft\n            arguments[0].left !== undefined\n              ? ~~arguments[0].left\n              : typeof arguments[0] !== 'object' ? ~~arguments[0] : this.scrollLeft,\n            // use top prop, second argument or fallback to scrollTop\n            arguments[0].top !== undefined\n              ? ~~arguments[0].top\n              : arguments[1] !== undefined ? ~~arguments[1] : this.scrollTop\n          );\n  \n          return;\n        }\n  \n        var left = arguments[0].left;\n        var top = arguments[0].top;\n  \n        // LET THE SMOOTHNESS BEGIN!\n        smoothScroll.call(\n          this,\n          this,\n          typeof left === 'undefined' ? this.scrollLeft : ~~left,\n          typeof top === 'undefined' ? this.scrollTop : ~~top\n        );\n      };\n  \n      // Element.prototype.scrollBy\n      Element.prototype.scrollBy = function() {\n        // avoid action when no arguments are passed\n        if (arguments[0] === undefined) {\n          return;\n        }\n  \n        // avoid smooth behavior if not required\n        if (shouldBailOut(arguments[0]) === true) {\n          original.elementScroll.call(\n            this,\n            arguments[0].left !== undefined\n              ? ~~arguments[0].left + this.scrollLeft\n              : ~~arguments[0] + this.scrollLeft,\n            arguments[0].top !== undefined\n              ? ~~arguments[0].top + this.scrollTop\n              : ~~arguments[1] + this.scrollTop\n          );\n  \n          return;\n        }\n  \n        this.scroll({\n          left: ~~arguments[0].left + this.scrollLeft,\n          top: ~~arguments[0].top + this.scrollTop,\n          behavior: arguments[0].behavior\n        });\n      };\n  \n      // Element.prototype.scrollIntoView\n      Element.prototype.scrollIntoView = function() {\n        // avoid smooth behavior if not required\n        if (shouldBailOut(arguments[0]) === true) {\n          original.scrollIntoView.call(\n            this,\n            arguments[0] === undefined ? true : arguments[0]\n          );\n  \n          return;\n        }\n  \n        // LET THE SMOOTHNESS BEGIN!\n        var scrollableParent = findScrollableParent(this);\n        var parentRects = scrollableParent.getBoundingClientRect();\n        var clientRects = this.getBoundingClientRect();\n  \n        if (scrollableParent !== d.body) {\n          // reveal element inside parent\n          smoothScroll.call(\n            this,\n            scrollableParent,\n            scrollableParent.scrollLeft + clientRects.left - parentRects.left,\n            scrollableParent.scrollTop + clientRects.top - parentRects.top\n          );\n  \n          // reveal parent in viewport unless is fixed\n          if (w.getComputedStyle(scrollableParent).position !== 'fixed') {\n            w.scrollBy({\n              left: parentRects.left,\n              top: parentRects.top,\n              behavior: 'smooth'\n            });\n          }\n        } else {\n          // reveal element in viewport\n          w.scrollBy({\n            left: clientRects.left,\n            top: clientRects.top,\n            behavior: 'smooth'\n          });\n        }\n      };\n    }\n  \n    if (typeof exports === 'object' && typeof module !== 'undefined') {\n      // commonjs\n      module.exports = { polyfill: polyfill };\n    } else {\n      // global\n      polyfill();\n    }\n  \n  }());\n  "
  },
  {
    "path": "src/renderer/lib/vue-horizontal.js",
    "content": "var VueHorizontal=function(t,e){\"use strict\";function n(t){return t&&\"object\"==typeof t&&\"default\"in t?t:{default:t}}var i=n(e).default.extend({name:\"VueHorizontal\",data:function(){return{left:0,width:0,scrollWidth:0,hasPrev:!1,hasNext:!1,debounceId:void 0}},props:{button:{type:Boolean,default:function(){return!0}},buttonBetween:{type:Boolean,default:function(){return!0}},scroll:{type:Boolean,default:function(){return!1}},responsive:{type:Boolean,default:function(){return!1}},displacement:{type:Number,default:function(){return 1}},snap:{type:String,default:function(){return\"start\"}}},mounted:function(){this.onScrollDebounce()},beforeDestroy:function(){clearTimeout(this.debounceId)},methods:{children:function(){return this.$refs.container.children},findPrevSlot:function(t){for(var e=this.children(),n=0;n<e.length;n++){var i=e[n].getBoundingClientRect();if(i.left<=t&&t<=i.right)return e[n];if(t<=i.left)return e[n]}},findNextSlot:function(t){for(var e=this.children(),n=0;n<e.length;n++){var i=e[n].getBoundingClientRect();if(!(i.right<=t)){if(i.left<=t)return e[n];if(t<=i.left)return e[n]}}},prev:function(){this.$emit(\"prev\");var t=this.$refs.container,e=t.getBoundingClientRect().left,n=e+t.clientWidth*-this.displacement-2.5,i=this.findPrevSlot(n);if(i){var o=i.getBoundingClientRect().left-e;this.scrollToLeft(t.scrollLeft+o)}else{var l=t.clientWidth*this.displacement;this.scrollToLeft(t.scrollLeft-l)}},next:function(){this.$emit(\"next\");var t=this.$refs.container,e=t.getBoundingClientRect().left,n=e+t.clientWidth*this.displacement+2.5,i=this.findNextSlot(n);if(i){var o=i.getBoundingClientRect().left-e;if(o>2.5)return void this.scrollToLeft(t.scrollLeft+o)}var l=t.clientWidth*this.displacement;this.scrollToLeft(t.scrollLeft+l)},scrollToIndex:function(t){var e=this.children();if(e[t]){var n=this.$refs.container,i=e[t].getBoundingClientRect().left-n.getBoundingClientRect().left;this.scrollToLeft(n.scrollLeft+i)}},scrollToLeft:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"smooth\",n=this.$refs.container;n.scrollTo({left:t,behavior:e})},onScroll:function(){var t=this.$refs.container;t&&(this.$emit(\"scroll\",{left:t.scrollLeft}),clearTimeout(this.debounceId),this.debounceId=setTimeout(this.onScrollDebounce,100))},onScrollDebounce:function(){var t=this;this.refresh((function(e){t.$emit(\"scroll-debounce\",e)}))},refresh:function(t){var e=this;this.$nextTick((function(){var n=e.calculate();e.left=n.left,e.width=n.width,e.scrollWidth=n.scrollWidth,e.hasNext=n.hasNext,e.hasPrev=n.hasPrev,null==t||t(n)}))},calculate:function(){var t=this.$refs.container,e=this.children()[0];return{left:t.scrollLeft,width:t.clientWidth,scrollWidth:t.scrollWidth,hasNext:t.scrollWidth>t.scrollLeft+t.clientWidth+2.5,hasPrev:function(){var n,i;if(0===t.scrollLeft)return!1;var o=t.getBoundingClientRect().left,l=null!==(n=null==e||null===(i=e.getBoundingClientRect())||void 0===i?void 0:i.left)&&void 0!==n?n:0;return Math.abs(o-l)>=2.5}()}}}});function o(t,e,n,i,o,l,r,a,s,c){\"boolean\"!=typeof r&&(s=a,a=r,r=!1);const d=\"function\"==typeof n?n.options:n;let h;if(t&&t.render&&(d.render=t.render,d.staticRenderFns=t.staticRenderFns,d._compiled=!0,o&&(d.functional=!0)),i&&(d._scopeId=i),l?(h=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||\"undefined\"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),e&&e.call(this,s(t)),t&&t._registeredComponents&&t._registeredComponents.add(l)},d._ssrRegister=h):e&&(h=r?function(t){e.call(this,c(t,this.$root.$options.shadowRoot))}:function(t){e.call(this,a(t))}),h)if(d.functional){const t=d.render;d.render=function(e,n){return h.call(n),t(e,n)}}else{const t=d.beforeCreate;d.beforeCreate=t?[].concat(t,h):[h]}return n}const l=\"undefined\"!=typeof navigator&&/msie [6-9]\\\\b/.test(navigator.userAgent.toLowerCase());function r(t){return(t,e)=>function(t,e){const n=l?e.media||\"default\":t,i=s[n]||(s[n]={ids:new Set,styles:[]});if(!i.ids.has(t)){i.ids.add(t);let n=e.source;if(e.map&&(n+=\"\\n/*# sourceURL=\"+e.map.sources[0]+\" */\",n+=\"\\n/*# sourceMappingURL=data:application/json;base64,\"+btoa(unescape(encodeURIComponent(JSON.stringify(e.map))))+\" */\"),i.element||(i.element=document.createElement(\"style\"),i.element.type=\"text/css\",e.media&&i.element.setAttribute(\"media\",e.media),void 0===a&&(a=document.head||document.getElementsByTagName(\"head\")[0]),a.appendChild(i.element)),\"styleSheet\"in i.element)i.styles.push(n),i.element.styleSheet.cssText=i.styles.filter(Boolean).join(\"\\n\");else{const t=i.ids.size-1,e=document.createTextNode(n),o=i.element.childNodes;o[t]&&i.element.removeChild(o[t]),o.length?i.element.insertBefore(e,o[t]):i.element.appendChild(e)}}}(t,e)}let a;const s={};var c=o({render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n(\"div\",{staticClass:\"vue-horizontal\",staticStyle:{position:\"relative\",display:\"flex\"}},[t.button&&t.hasPrev?n(\"div\",{staticClass:\"v-hl-btn v-hl-btn-prev\",class:{\"v-hl-btn-between\":t.buttonBetween},attrs:{role:\"button\"},on:{click:function(e){return e.stopPropagation(),t.prev(e)}}},[t._t(\"btn-prev\",[n(\"svg\",{staticClass:\"v-hl-svg\",attrs:{viewBox:\"0 0 24 24\",\"aria-label\":\"horizontal scroll area navigate to previous button\"}},[n(\"path\",{attrs:{d:\"m9.8 12 5 5a1 1 0 1 1-1.4 1.4l-5.7-5.7a1 1 0 0 1 0-1.4l5.7-5.7a1 1 0 0 1 1.4 1.4l-5 5z\"}})])])],2):t._e(),t._v(\" \"),t.button&&t.hasNext?n(\"div\",{staticClass:\"v-hl-btn v-hl-btn-next\",class:{\"v-hl-btn-between\":t.buttonBetween},attrs:{role:\"button\"},on:{click:function(e){return e.stopPropagation(),t.next(e)}}},[t._t(\"btn-next\",[n(\"svg\",{staticClass:\"v-hl-svg\",attrs:{viewBox:\"0 0 24 24\",\"aria-label\":\"horizontal scroll area navigate to next button\"}},[n(\"path\",{attrs:{d:\"m14.3 12.1-5-5a1 1 0 0 1 1.4-1.4l5.7 5.7a1 1 0 0 1 0 1.4l-5.7 5.7a1 1 0 0 1-1.4-1.4l5-5z\"}})])])],2):t._e(),t._v(\" \"),n(\"div\",{ref:\"container\",staticClass:\"v-hl-container\",class:{\"v-hl-responsive\":t.responsive,\"v-hl-scroll\":t.scroll,\"v-hl-snap-start\":\"start\"===t.snap,\"v-hl-snap-center\":\"center\"===t.snap,\"v-hl-snap-end\":\"end\"===t.snap},on:{\"&scroll\":function(e){return t.onScroll(e)}}},[t._t(\"default\")],2)])},staticRenderFns:[]},(function(t){t&&t(\"data-v-45080727_0\",{source:\".v-hl-btn[data-v-45080727]{position:absolute;align-self:center;z-index:1;top:0;bottom:0;display:flex;align-items:center;cursor:pointer}.v-hl-btn-prev[data-v-45080727]{left:0}.v-hl-btn-prev.v-hl-btn-between[data-v-45080727]{transform:translateX(-50%)}.v-hl-btn-next[data-v-45080727]{right:0}.v-hl-btn-next.v-hl-btn-between[data-v-45080727]{transform:translateX(50%)}.v-hl-svg[data-v-45080727]{width:40px;height:40px;margin:6px;padding:6px;border-radius:20px;box-sizing:border-box;background:#fff;color:#000;fill:currentColor;box-shadow:0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24)}.v-hl-container[data-v-45080727]{display:flex;width:100%;margin:0;padding:0;border:none;box-sizing:content-box;overflow-x:scroll;overflow-y:hidden;scroll-snap-type:x mandatory;-webkit-overflow-scrolling:touch}.v-hl-container>*[data-v-45080727]{flex-shrink:0;box-sizing:border-box;min-height:1px}.v-hl-snap-start>*[data-v-45080727]{scroll-snap-align:start}.v-hl-snap-center>*[data-v-45080727]{scroll-snap-align:center}.v-hl-snap-end>*[data-v-45080727]{scroll-snap-align:end}.v-hl-container[data-v-45080727]:not(.v-hl-scroll){scrollbar-width:none;-ms-overflow-style:none;padding-bottom:30px;margin-bottom:-30px;clip-path:inset(0 0 30px 0)}.v-hl-container[data-v-45080727]:not(.v-hl-scroll)::-webkit-scrollbar{width:0!important;height:0!important}.v-hl-responsive>*[data-v-45080727]{width:100%;margin-right:24px}.v-hl-responsive[data-v-45080727]>:last-child{margin-right:0}@media (min-width:640px){.v-hl-responsive>*[data-v-45080727]{width:calc((100% - 24px)/ 2)}}@media (min-width:768px){.v-hl-responsive>*[data-v-45080727]{width:calc((100% - 48px)/ 3)}}@media (min-width:1024px){.v-hl-responsive>*[data-v-45080727]{width:calc((100% - 72px)/ 4)}}@media (min-width:1280px){.v-hl-responsive>*[data-v-45080727]{width:calc((100% - 96px)/ 5)}}\",map:void 0,media:void 0})}),i,\"data-v-45080727\",!1,void 0,!1,r,void 0,void 0),d=function(t){d.installed||(d.installed=!0,t.component(\"VueHorizontal\",c))},h={install:d},u=null;return\"undefined\"!=typeof window?u=window.Vue:\"undefined\"!=typeof global&&(u=global.Vue),u&&u.use(h),c.install=d,t.default=c,Object.defineProperty(t,\"__esModule\",{value:!0}),t}({},Vue);"
  },
  {
    "path": "src/renderer/lib/vue.dev.js",
    "content": "/*!\n * Vue.js v2.6.14\n * (c) 2014-2021 Evan You\n * Released under the MIT License.\n */\n(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n        typeof define === 'function' && define.amd ? define(factory) :\n            (global = global || self, global.Vue = factory());\n}(this, function () { 'use strict';\n\n    /*  */\n\n    var emptyObject = Object.freeze({});\n\n    // These helpers produce better VM code in JS engines due to their\n    // explicitness and function inlining.\n    function isUndef (v) {\n        return v === undefined || v === null\n    }\n\n    function isDef (v) {\n        return v !== undefined && v !== null\n    }\n\n    function isTrue (v) {\n        return v === true\n    }\n\n    function isFalse (v) {\n        return v === false\n    }\n\n    /**\n     * Check if value is primitive.\n     */\n    function isPrimitive (value) {\n        return (\n            typeof value === 'string' ||\n            typeof value === 'number' ||\n            // $flow-disable-line\n            typeof value === 'symbol' ||\n            typeof value === 'boolean'\n        )\n    }\n\n    /**\n     * Quick object check - this is primarily used to tell\n     * Objects from primitive values when we know the value\n     * is a JSON-compliant type.\n     */\n    function isObject (obj) {\n        return obj !== null && typeof obj === 'object'\n    }\n\n    /**\n     * Get the raw type string of a value, e.g., [object Object].\n     */\n    var _toString = Object.prototype.toString;\n\n    function toRawType (value) {\n        return _toString.call(value).slice(8, -1)\n    }\n\n    /**\n     * Strict object type check. Only returns true\n     * for plain JavaScript objects.\n     */\n    function isPlainObject (obj) {\n        return _toString.call(obj) === '[object Object]'\n    }\n\n    function isRegExp (v) {\n        return _toString.call(v) === '[object RegExp]'\n    }\n\n    /**\n     * Check if val is a valid array index.\n     */\n    function isValidArrayIndex (val) {\n        var n = parseFloat(String(val));\n        return n >= 0 && Math.floor(n) === n && isFinite(val)\n    }\n\n    function isPromise (val) {\n        return (\n            isDef(val) &&\n            typeof val.then === 'function' &&\n            typeof val.catch === 'function'\n        )\n    }\n\n    /**\n     * Convert a value to a string that is actually rendered.\n     */\n    function toString (val) {\n        return val == null\n            ? ''\n            : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)\n                ? JSON.stringify(val, null, 2)\n                : String(val)\n    }\n\n    /**\n     * Convert an input value to a number for persistence.\n     * If the conversion fails, return original string.\n     */\n    function toNumber (val) {\n        var n = parseFloat(val);\n        return isNaN(n) ? val : n\n    }\n\n    /**\n     * Make a map and return a function for checking if a key\n     * is in that map.\n     */\n    function makeMap (\n        str,\n        expectsLowerCase\n    ) {\n        var map = Object.create(null);\n        var list = str.split(',');\n        for (var i = 0; i < list.length; i++) {\n            map[list[i]] = true;\n        }\n        return expectsLowerCase\n            ? function (val) { return map[val.toLowerCase()]; }\n            : function (val) { return map[val]; }\n    }\n\n    /**\n     * Check if a tag is a built-in tag.\n     */\n    var isBuiltInTag = makeMap('slot,component', true);\n\n    /**\n     * Check if an attribute is a reserved attribute.\n     */\n    var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');\n\n    /**\n     * Remove an item from an array.\n     */\n    function remove (arr, item) {\n        if (arr.length) {\n            var index = arr.indexOf(item);\n            if (index > -1) {\n                return arr.splice(index, 1)\n            }\n        }\n    }\n\n    /**\n     * Check whether an object has the property.\n     */\n    var hasOwnProperty = Object.prototype.hasOwnProperty;\n    function hasOwn (obj, key) {\n        return hasOwnProperty.call(obj, key)\n    }\n\n    /**\n     * Create a cached version of a pure function.\n     */\n    function cached (fn) {\n        var cache = Object.create(null);\n        return (function cachedFn (str) {\n            var hit = cache[str];\n            return hit || (cache[str] = fn(str))\n        })\n    }\n\n    /**\n     * Camelize a hyphen-delimited string.\n     */\n    var camelizeRE = /-(\\w)/g;\n    var camelize = cached(function (str) {\n        return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })\n    });\n\n    /**\n     * Capitalize a string.\n     */\n    var capitalize = cached(function (str) {\n        return str.charAt(0).toUpperCase() + str.slice(1)\n    });\n\n    /**\n     * Hyphenate a camelCase string.\n     */\n    var hyphenateRE = /\\B([A-Z])/g;\n    var hyphenate = cached(function (str) {\n        return str.replace(hyphenateRE, '-$1').toLowerCase()\n    });\n\n    /**\n     * Simple bind polyfill for environments that do not support it,\n     * e.g., PhantomJS 1.x. Technically, we don't need this anymore\n     * since native bind is now performant enough in most browsers.\n     * But removing it would mean breaking code that was able to run in\n     * PhantomJS 1.x, so this must be kept for backward compatibility.\n     */\n\n    /* istanbul ignore next */\n    function polyfillBind (fn, ctx) {\n        function boundFn (a) {\n            var l = arguments.length;\n            return l\n                ? l > 1\n                    ? fn.apply(ctx, arguments)\n                    : fn.call(ctx, a)\n                : fn.call(ctx)\n        }\n\n        boundFn._length = fn.length;\n        return boundFn\n    }\n\n    function nativeBind (fn, ctx) {\n        return fn.bind(ctx)\n    }\n\n    var bind = Function.prototype.bind\n        ? nativeBind\n        : polyfillBind;\n\n    /**\n     * Convert an Array-like object to a real Array.\n     */\n    function toArray (list, start) {\n        start = start || 0;\n        var i = list.length - start;\n        var ret = new Array(i);\n        while (i--) {\n            ret[i] = list[i + start];\n        }\n        return ret\n    }\n\n    /**\n     * Mix properties into target object.\n     */\n    function extend (to, _from) {\n        for (var key in _from) {\n            to[key] = _from[key];\n        }\n        return to\n    }\n\n    /**\n     * Merge an Array of Objects into a single Object.\n     */\n    function toObject (arr) {\n        var res = {};\n        for (var i = 0; i < arr.length; i++) {\n            if (arr[i]) {\n                extend(res, arr[i]);\n            }\n        }\n        return res\n    }\n\n    /* eslint-disable no-unused-vars */\n\n    /**\n     * Perform no operation.\n     * Stubbing args to make Flow happy without leaving useless transpiled code\n     * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).\n     */\n    function noop (a, b, c) {}\n\n    /**\n     * Always return false.\n     */\n    var no = function (a, b, c) { return false; };\n\n    /* eslint-enable no-unused-vars */\n\n    /**\n     * Return the same value.\n     */\n    var identity = function (_) { return _; };\n\n    /**\n     * Generate a string containing static keys from compiler modules.\n     */\n    function genStaticKeys (modules) {\n        return modules.reduce(function (keys, m) {\n            return keys.concat(m.staticKeys || [])\n        }, []).join(',')\n    }\n\n    /**\n     * Check if two values are loosely equal - that is,\n     * if they are plain objects, do they have the same shape?\n     */\n    function looseEqual (a, b) {\n        if (a === b) { return true }\n        var isObjectA = isObject(a);\n        var isObjectB = isObject(b);\n        if (isObjectA && isObjectB) {\n            try {\n                var isArrayA = Array.isArray(a);\n                var isArrayB = Array.isArray(b);\n                if (isArrayA && isArrayB) {\n                    return a.length === b.length && a.every(function (e, i) {\n                        return looseEqual(e, b[i])\n                    })\n                } else if (a instanceof Date && b instanceof Date) {\n                    return a.getTime() === b.getTime()\n                } else if (!isArrayA && !isArrayB) {\n                    var keysA = Object.keys(a);\n                    var keysB = Object.keys(b);\n                    return keysA.length === keysB.length && keysA.every(function (key) {\n                        return looseEqual(a[key], b[key])\n                    })\n                } else {\n                    /* istanbul ignore next */\n                    return false\n                }\n            } catch (e) {\n                /* istanbul ignore next */\n                return false\n            }\n        } else if (!isObjectA && !isObjectB) {\n            return String(a) === String(b)\n        } else {\n            return false\n        }\n    }\n\n    /**\n     * Return the first index at which a loosely equal value can be\n     * found in the array (if value is a plain object, the array must\n     * contain an object of the same shape), or -1 if it is not present.\n     */\n    function looseIndexOf (arr, val) {\n        for (var i = 0; i < arr.length; i++) {\n            if (looseEqual(arr[i], val)) { return i }\n        }\n        return -1\n    }\n\n    /**\n     * Ensure a function is called only once.\n     */\n    function once (fn) {\n        var called = false;\n        return function () {\n            if (!called) {\n                called = true;\n                fn.apply(this, arguments);\n            }\n        }\n    }\n\n    var SSR_ATTR = 'data-server-rendered';\n\n    var ASSET_TYPES = [\n        'component',\n        'directive',\n        'filter'\n    ];\n\n    var LIFECYCLE_HOOKS = [\n        'beforeCreate',\n        'created',\n        'beforeMount',\n        'mounted',\n        'beforeUpdate',\n        'updated',\n        'beforeDestroy',\n        'destroyed',\n        'activated',\n        'deactivated',\n        'errorCaptured',\n        'serverPrefetch'\n    ];\n\n    /*  */\n\n\n\n    var config = ({\n        /**\n         * Option merge strategies (used in core/util/options)\n         */\n        // $flow-disable-line\n        optionMergeStrategies: Object.create(null),\n\n        /**\n         * Whether to suppress warnings.\n         */\n        silent: false,\n\n        /**\n         * Show production mode tip message on boot?\n         */\n        productionTip: \"development\" !== 'production',\n\n        /**\n         * Whether to enable devtools\n         */\n        devtools: \"development\" !== 'production',\n\n        /**\n         * Whether to record perf\n         */\n        performance: false,\n\n        /**\n         * Error handler for watcher errors\n         */\n        errorHandler: null,\n\n        /**\n         * Warn handler for watcher warns\n         */\n        warnHandler: null,\n\n        /**\n         * Ignore certain custom elements\n         */\n        ignoredElements: [],\n\n        /**\n         * Custom user key aliases for v-on\n         */\n        // $flow-disable-line\n        keyCodes: Object.create(null),\n\n        /**\n         * Check if a tag is reserved so that it cannot be registered as a\n         * component. This is platform-dependent and may be overwritten.\n         */\n        isReservedTag: no,\n\n        /**\n         * Check if an attribute is reserved so that it cannot be used as a component\n         * prop. This is platform-dependent and may be overwritten.\n         */\n        isReservedAttr: no,\n\n        /**\n         * Check if a tag is an unknown element.\n         * Platform-dependent.\n         */\n        isUnknownElement: no,\n\n        /**\n         * Get the namespace of an element\n         */\n        getTagNamespace: noop,\n\n        /**\n         * Parse the real tag name for the specific platform.\n         */\n        parsePlatformTagName: identity,\n\n        /**\n         * Check if an attribute must be bound using property, e.g. value\n         * Platform-dependent.\n         */\n        mustUseProp: no,\n\n        /**\n         * Perform updates asynchronously. Intended to be used by Vue Test Utils\n         * This will significantly reduce performance if set to false.\n         */\n        async: true,\n\n        /**\n         * Exposed for legacy reasons\n         */\n        _lifecycleHooks: LIFECYCLE_HOOKS\n    });\n\n    /*  */\n\n    /**\n     * unicode letters used for parsing html tags, component names and property paths.\n     * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname\n     * skipping \\u10000-\\uEFFFF due to it freezing up PhantomJS\n     */\n    var unicodeRegExp = /a-zA-Z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD/;\n\n    /**\n     * Check if a string starts with $ or _\n     */\n    function isReserved (str) {\n        var c = (str + '').charCodeAt(0);\n        return c === 0x24 || c === 0x5F\n    }\n\n    /**\n     * Define a property.\n     */\n    function def (obj, key, val, enumerable) {\n        Object.defineProperty(obj, key, {\n            value: val,\n            enumerable: !!enumerable,\n            writable: true,\n            configurable: true\n        });\n    }\n\n    /**\n     * Parse simple path.\n     */\n    var bailRE = new RegExp((\"[^\" + (unicodeRegExp.source) + \".$_\\\\d]\"));\n    function parsePath (path) {\n        if (bailRE.test(path)) {\n            return\n        }\n        var segments = path.split('.');\n        return function (obj) {\n            for (var i = 0; i < segments.length; i++) {\n                if (!obj) { return }\n                obj = obj[segments[i]];\n            }\n            return obj\n        }\n    }\n\n    /*  */\n\n    // can we use __proto__?\n    var hasProto = '__proto__' in {};\n\n    // Browser environment sniffing\n    var inBrowser = typeof window !== 'undefined';\n    var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;\n    var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();\n    var UA = inBrowser && window.navigator.userAgent.toLowerCase();\n    var isIE = UA && /msie|trident/.test(UA);\n    var isIE9 = UA && UA.indexOf('msie 9.0') > 0;\n    var isEdge = UA && UA.indexOf('edge/') > 0;\n    var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');\n    var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');\n    var isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge;\n    var isPhantomJS = UA && /phantomjs/.test(UA);\n    var isFF = UA && UA.match(/firefox\\/(\\d+)/);\n\n    // Firefox has a \"watch\" function on Object.prototype...\n    var nativeWatch = ({}).watch;\n\n    var supportsPassive = false;\n    if (inBrowser) {\n        try {\n            var opts = {};\n            Object.defineProperty(opts, 'passive', ({\n                get: function get () {\n                    /* istanbul ignore next */\n                    supportsPassive = true;\n                }\n            })); // https://github.com/facebook/flow/issues/285\n            window.addEventListener('test-passive', null, opts);\n        } catch (e) {}\n    }\n\n    // this needs to be lazy-evaled because vue may be required before\n    // vue-server-renderer can set VUE_ENV\n    var _isServer;\n    var isServerRendering = function () {\n        if (_isServer === undefined) {\n            /* istanbul ignore if */\n            if (!inBrowser && !inWeex && typeof global !== 'undefined') {\n                // detect presence of vue-server-renderer and avoid\n                // Webpack shimming the process\n                _isServer = global['process'] && global['process'].env.VUE_ENV === 'server';\n            } else {\n                _isServer = false;\n            }\n        }\n        return _isServer\n    };\n\n    // detect devtools\n    var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;\n\n    /* istanbul ignore next */\n    function isNative (Ctor) {\n        return typeof Ctor === 'function' && /native code/.test(Ctor.toString())\n    }\n\n    var hasSymbol =\n        typeof Symbol !== 'undefined' && isNative(Symbol) &&\n        typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);\n\n    var _Set;\n    /* istanbul ignore if */ // $flow-disable-line\n    if (typeof Set !== 'undefined' && isNative(Set)) {\n        // use native Set when available.\n        _Set = Set;\n    } else {\n        // a non-standard Set polyfill that only works with primitive keys.\n        _Set = /*@__PURE__*/(function () {\n            function Set () {\n                this.set = Object.create(null);\n            }\n            Set.prototype.has = function has (key) {\n                return this.set[key] === true\n            };\n            Set.prototype.add = function add (key) {\n                this.set[key] = true;\n            };\n            Set.prototype.clear = function clear () {\n                this.set = Object.create(null);\n            };\n\n            return Set;\n        }());\n    }\n\n    /*  */\n\n    var warn = noop;\n    var tip = noop;\n    var generateComponentTrace = (noop); // work around flow check\n    var formatComponentName = (noop);\n\n    {\n        var hasConsole = typeof console !== 'undefined';\n        var classifyRE = /(?:^|[-_])(\\w)/g;\n        var classify = function (str) { return str\n            .replace(classifyRE, function (c) { return c.toUpperCase(); })\n            .replace(/[-_]/g, ''); };\n\n        warn = function (msg, vm) {\n            var trace = vm ? generateComponentTrace(vm) : '';\n\n            if (config.warnHandler) {\n                config.warnHandler.call(null, msg, vm, trace);\n            } else if (hasConsole && (!config.silent)) {\n                console.error((\"[Vue warn]: \" + msg + trace));\n            }\n        };\n\n        tip = function (msg, vm) {\n            if (hasConsole && (!config.silent)) {\n                console.warn(\"[Vue tip]: \" + msg + (\n                    vm ? generateComponentTrace(vm) : ''\n                ));\n            }\n        };\n\n        formatComponentName = function (vm, includeFile) {\n            if (vm.$root === vm) {\n                return '<Root>'\n            }\n            var options = typeof vm === 'function' && vm.cid != null\n                ? vm.options\n                : vm._isVue\n                    ? vm.$options || vm.constructor.options\n                    : vm;\n            var name = options.name || options._componentTag;\n            var file = options.__file;\n            if (!name && file) {\n                var match = file.match(/([^/\\\\]+)\\.vue$/);\n                name = match && match[1];\n            }\n\n            return (\n                (name ? (\"<\" + (classify(name)) + \">\") : \"<Anonymous>\") +\n                (file && includeFile !== false ? (\" at \" + file) : '')\n            )\n        };\n\n        var repeat = function (str, n) {\n            var res = '';\n            while (n) {\n                if (n % 2 === 1) { res += str; }\n                if (n > 1) { str += str; }\n                n >>= 1;\n            }\n            return res\n        };\n\n        generateComponentTrace = function (vm) {\n            if (vm._isVue && vm.$parent) {\n                var tree = [];\n                var currentRecursiveSequence = 0;\n                while (vm) {\n                    if (tree.length > 0) {\n                        var last = tree[tree.length - 1];\n                        if (last.constructor === vm.constructor) {\n                            currentRecursiveSequence++;\n                            vm = vm.$parent;\n                            continue\n                        } else if (currentRecursiveSequence > 0) {\n                            tree[tree.length - 1] = [last, currentRecursiveSequence];\n                            currentRecursiveSequence = 0;\n                        }\n                    }\n                    tree.push(vm);\n                    vm = vm.$parent;\n                }\n                return '\\n\\nfound in\\n\\n' + tree\n                    .map(function (vm, i) { return (\"\" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)\n                        ? ((formatComponentName(vm[0])) + \"... (\" + (vm[1]) + \" recursive calls)\")\n                        : formatComponentName(vm))); })\n                    .join('\\n')\n            } else {\n                return (\"\\n\\n(found in \" + (formatComponentName(vm)) + \")\")\n            }\n        };\n    }\n\n    /*  */\n\n    var uid = 0;\n\n    /**\n     * A dep is an observable that can have multiple\n     * directives subscribing to it.\n     */\n    var Dep = function Dep () {\n        this.id = uid++;\n        this.subs = [];\n    };\n\n    Dep.prototype.addSub = function addSub (sub) {\n        this.subs.push(sub);\n    };\n\n    Dep.prototype.removeSub = function removeSub (sub) {\n        remove(this.subs, sub);\n    };\n\n    Dep.prototype.depend = function depend () {\n        if (Dep.target) {\n            Dep.target.addDep(this);\n        }\n    };\n\n    Dep.prototype.notify = function notify () {\n        // stabilize the subscriber list first\n        var subs = this.subs.slice();\n        if (!config.async) {\n            // subs aren't sorted in scheduler if not running async\n            // we need to sort them now to make sure they fire in correct\n            // order\n            subs.sort(function (a, b) { return a.id - b.id; });\n        }\n        for (var i = 0, l = subs.length; i < l; i++) {\n            subs[i].update();\n        }\n    };\n\n    // The current target watcher being evaluated.\n    // This is globally unique because only one watcher\n    // can be evaluated at a time.\n    Dep.target = null;\n    var targetStack = [];\n\n    function pushTarget (target) {\n        targetStack.push(target);\n        Dep.target = target;\n    }\n\n    function popTarget () {\n        targetStack.pop();\n        Dep.target = targetStack[targetStack.length - 1];\n    }\n\n    /*  */\n\n    var VNode = function VNode (\n        tag,\n        data,\n        children,\n        text,\n        elm,\n        context,\n        componentOptions,\n        asyncFactory\n    ) {\n        this.tag = tag;\n        this.data = data;\n        this.children = children;\n        this.text = text;\n        this.elm = elm;\n        this.ns = undefined;\n        this.context = context;\n        this.fnContext = undefined;\n        this.fnOptions = undefined;\n        this.fnScopeId = undefined;\n        this.key = data && data.key;\n        this.componentOptions = componentOptions;\n        this.componentInstance = undefined;\n        this.parent = undefined;\n        this.raw = false;\n        this.isStatic = false;\n        this.isRootInsert = true;\n        this.isComment = false;\n        this.isCloned = false;\n        this.isOnce = false;\n        this.asyncFactory = asyncFactory;\n        this.asyncMeta = undefined;\n        this.isAsyncPlaceholder = false;\n    };\n\n    var prototypeAccessors = { child: { configurable: true } };\n\n    // DEPRECATED: alias for componentInstance for backwards compat.\n    /* istanbul ignore next */\n    prototypeAccessors.child.get = function () {\n        return this.componentInstance\n    };\n\n    Object.defineProperties( VNode.prototype, prototypeAccessors );\n\n    var createEmptyVNode = function (text) {\n        if ( text === void 0 ) text = '';\n\n        var node = new VNode();\n        node.text = text;\n        node.isComment = true;\n        return node\n    };\n\n    function createTextVNode (val) {\n        return new VNode(undefined, undefined, undefined, String(val))\n    }\n\n    // optimized shallow clone\n    // used for static nodes and slot nodes because they may be reused across\n    // multiple renders, cloning them avoids errors when DOM manipulations rely\n    // on their elm reference.\n    function cloneVNode (vnode) {\n        var cloned = new VNode(\n            vnode.tag,\n            vnode.data,\n            // #7975\n            // clone children array to avoid mutating original in case of cloning\n            // a child.\n            vnode.children && vnode.children.slice(),\n            vnode.text,\n            vnode.elm,\n            vnode.context,\n            vnode.componentOptions,\n            vnode.asyncFactory\n        );\n        cloned.ns = vnode.ns;\n        cloned.isStatic = vnode.isStatic;\n        cloned.key = vnode.key;\n        cloned.isComment = vnode.isComment;\n        cloned.fnContext = vnode.fnContext;\n        cloned.fnOptions = vnode.fnOptions;\n        cloned.fnScopeId = vnode.fnScopeId;\n        cloned.asyncMeta = vnode.asyncMeta;\n        cloned.isCloned = true;\n        return cloned\n    }\n\n    /*\n   * not type checking this file because flow doesn't play well with\n   * dynamically accessing methods on Array prototype\n   */\n\n    var arrayProto = Array.prototype;\n    var arrayMethods = Object.create(arrayProto);\n\n    var methodsToPatch = [\n        'push',\n        'pop',\n        'shift',\n        'unshift',\n        'splice',\n        'sort',\n        'reverse'\n    ];\n\n    /**\n     * Intercept mutating methods and emit events\n     */\n    methodsToPatch.forEach(function (method) {\n        // cache original method\n        var original = arrayProto[method];\n        def(arrayMethods, method, function mutator () {\n            var args = [], len = arguments.length;\n            while ( len-- ) args[ len ] = arguments[ len ];\n\n            var result = original.apply(this, args);\n            var ob = this.__ob__;\n            var inserted;\n            switch (method) {\n                case 'push':\n                case 'unshift':\n                    inserted = args;\n                    break\n                case 'splice':\n                    inserted = args.slice(2);\n                    break\n            }\n            if (inserted) { ob.observeArray(inserted); }\n            // notify change\n            ob.dep.notify();\n            return result\n        });\n    });\n\n    /*  */\n\n    var arrayKeys = Object.getOwnPropertyNames(arrayMethods);\n\n    /**\n     * In some cases we may want to disable observation inside a component's\n     * update computation.\n     */\n    var shouldObserve = true;\n\n    function toggleObserving (value) {\n        shouldObserve = value;\n    }\n\n    /**\n     * Observer class that is attached to each observed\n     * object. Once attached, the observer converts the target\n     * object's property keys into getter/setters that\n     * collect dependencies and dispatch updates.\n     */\n    var Observer = function Observer (value) {\n        this.value = value;\n        this.dep = new Dep();\n        this.vmCount = 0;\n        def(value, '__ob__', this);\n        if (Array.isArray(value)) {\n            if (hasProto) {\n                protoAugment(value, arrayMethods);\n            } else {\n                copyAugment(value, arrayMethods, arrayKeys);\n            }\n            this.observeArray(value);\n        } else {\n            this.walk(value);\n        }\n    };\n\n    /**\n     * Walk through all properties and convert them into\n     * getter/setters. This method should only be called when\n     * value type is Object.\n     */\n    Observer.prototype.walk = function walk (obj) {\n        var keys = Object.keys(obj);\n        for (var i = 0; i < keys.length; i++) {\n            defineReactive$$1(obj, keys[i]);\n        }\n    };\n\n    /**\n     * Observe a list of Array items.\n     */\n    Observer.prototype.observeArray = function observeArray (items) {\n        for (var i = 0, l = items.length; i < l; i++) {\n            observe(items[i]);\n        }\n    };\n\n    // helpers\n\n    /**\n     * Augment a target Object or Array by intercepting\n     * the prototype chain using __proto__\n     */\n    function protoAugment (target, src) {\n        /* eslint-disable no-proto */\n        target.__proto__ = src;\n        /* eslint-enable no-proto */\n    }\n\n    /**\n     * Augment a target Object or Array by defining\n     * hidden properties.\n     */\n    /* istanbul ignore next */\n    function copyAugment (target, src, keys) {\n        for (var i = 0, l = keys.length; i < l; i++) {\n            var key = keys[i];\n            def(target, key, src[key]);\n        }\n    }\n\n    /**\n     * Attempt to create an observer instance for a value,\n     * returns the new observer if successfully observed,\n     * or the existing observer if the value already has one.\n     */\n    function observe (value, asRootData) {\n        if (!isObject(value) || value instanceof VNode) {\n            return\n        }\n        var ob;\n        if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {\n            ob = value.__ob__;\n        } else if (\n            shouldObserve &&\n            !isServerRendering() &&\n            (Array.isArray(value) || isPlainObject(value)) &&\n            Object.isExtensible(value) &&\n            !value._isVue\n        ) {\n            ob = new Observer(value);\n        }\n        if (asRootData && ob) {\n            ob.vmCount++;\n        }\n        return ob\n    }\n\n    /**\n     * Define a reactive property on an Object.\n     */\n    function defineReactive$$1 (\n        obj,\n        key,\n        val,\n        customSetter,\n        shallow\n    ) {\n        var dep = new Dep();\n\n        var property = Object.getOwnPropertyDescriptor(obj, key);\n        if (property && property.configurable === false) {\n            return\n        }\n\n        // cater for pre-defined getter/setters\n        var getter = property && property.get;\n        var setter = property && property.set;\n        if ((!getter || setter) && arguments.length === 2) {\n            val = obj[key];\n        }\n\n        var childOb = !shallow && observe(val);\n        Object.defineProperty(obj, key, {\n            enumerable: true,\n            configurable: true,\n            get: function reactiveGetter () {\n                var value = getter ? getter.call(obj) : val;\n                if (Dep.target) {\n                    dep.depend();\n                    if (childOb) {\n                        childOb.dep.depend();\n                        if (Array.isArray(value)) {\n                            dependArray(value);\n                        }\n                    }\n                }\n                return value\n            },\n            set: function reactiveSetter (newVal) {\n                var value = getter ? getter.call(obj) : val;\n                /* eslint-disable no-self-compare */\n                if (newVal === value || (newVal !== newVal && value !== value)) {\n                    return\n                }\n                /* eslint-enable no-self-compare */\n                if (customSetter) {\n                    customSetter();\n                }\n                // #7981: for accessor properties without setter\n                if (getter && !setter) { return }\n                if (setter) {\n                    setter.call(obj, newVal);\n                } else {\n                    val = newVal;\n                }\n                childOb = !shallow && observe(newVal);\n                dep.notify();\n            }\n        });\n    }\n\n    /**\n     * Set a property on an object. Adds the new property and\n     * triggers change notification if the property doesn't\n     * already exist.\n     */\n    function set (target, key, val) {\n        if (isUndef(target) || isPrimitive(target)\n        ) {\n            warn((\"Cannot set reactive property on undefined, null, or primitive value: \" + ((target))));\n        }\n        if (Array.isArray(target) && isValidArrayIndex(key)) {\n            target.length = Math.max(target.length, key);\n            target.splice(key, 1, val);\n            return val\n        }\n        if (key in target && !(key in Object.prototype)) {\n            target[key] = val;\n            return val\n        }\n        var ob = (target).__ob__;\n        if (target._isVue || (ob && ob.vmCount)) {\n            warn(\n                'Avoid adding reactive properties to a Vue instance or its root $data ' +\n                'at runtime - declare it upfront in the data option.'\n            );\n            return val\n        }\n        if (!ob) {\n            target[key] = val;\n            return val\n        }\n        defineReactive$$1(ob.value, key, val);\n        ob.dep.notify();\n        return val\n    }\n\n    /**\n     * Delete a property and trigger change if necessary.\n     */\n    function del (target, key) {\n        if (isUndef(target) || isPrimitive(target)\n        ) {\n            warn((\"Cannot delete reactive property on undefined, null, or primitive value: \" + ((target))));\n        }\n        if (Array.isArray(target) && isValidArrayIndex(key)) {\n            target.splice(key, 1);\n            return\n        }\n        var ob = (target).__ob__;\n        if (target._isVue || (ob && ob.vmCount)) {\n            warn(\n                'Avoid deleting properties on a Vue instance or its root $data ' +\n                '- just set it to null.'\n            );\n            return\n        }\n        if (!hasOwn(target, key)) {\n            return\n        }\n        delete target[key];\n        if (!ob) {\n            return\n        }\n        ob.dep.notify();\n    }\n\n    /**\n     * Collect dependencies on array elements when the array is touched, since\n     * we cannot intercept array element access like property getters.\n     */\n    function dependArray (value) {\n        for (var e = (void 0), i = 0, l = value.length; i < l; i++) {\n            e = value[i];\n            e && e.__ob__ && e.__ob__.dep.depend();\n            if (Array.isArray(e)) {\n                dependArray(e);\n            }\n        }\n    }\n\n    /*  */\n\n    /**\n     * Option overwriting strategies are functions that handle\n     * how to merge a parent option value and a child option\n     * value into the final value.\n     */\n    var strats = config.optionMergeStrategies;\n\n    /**\n     * Options with restrictions\n     */\n    {\n        strats.el = strats.propsData = function (parent, child, vm, key) {\n            if (!vm) {\n                warn(\n                    \"option \\\"\" + key + \"\\\" can only be used during instance \" +\n                    'creation with the `new` keyword.'\n                );\n            }\n            return defaultStrat(parent, child)\n        };\n    }\n\n    /**\n     * Helper that recursively merges two data objects together.\n     */\n    function mergeData (to, from) {\n        if (!from) { return to }\n        var key, toVal, fromVal;\n\n        var keys = hasSymbol\n            ? Reflect.ownKeys(from)\n            : Object.keys(from);\n\n        for (var i = 0; i < keys.length; i++) {\n            key = keys[i];\n            // in case the object is already observed...\n            if (key === '__ob__') { continue }\n            toVal = to[key];\n            fromVal = from[key];\n            if (!hasOwn(to, key)) {\n                set(to, key, fromVal);\n            } else if (\n                toVal !== fromVal &&\n                isPlainObject(toVal) &&\n                isPlainObject(fromVal)\n            ) {\n                mergeData(toVal, fromVal);\n            }\n        }\n        return to\n    }\n\n    /**\n     * Data\n     */\n    function mergeDataOrFn (\n        parentVal,\n        childVal,\n        vm\n    ) {\n        if (!vm) {\n            // in a Vue.extend merge, both should be functions\n            if (!childVal) {\n                return parentVal\n            }\n            if (!parentVal) {\n                return childVal\n            }\n            // when parentVal & childVal are both present,\n            // we need to return a function that returns the\n            // merged result of both functions... no need to\n            // check if parentVal is a function here because\n            // it has to be a function to pass previous merges.\n            return function mergedDataFn () {\n                return mergeData(\n                    typeof childVal === 'function' ? childVal.call(this, this) : childVal,\n                    typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal\n                )\n            }\n        } else {\n            return function mergedInstanceDataFn () {\n                // instance merge\n                var instanceData = typeof childVal === 'function'\n                    ? childVal.call(vm, vm)\n                    : childVal;\n                var defaultData = typeof parentVal === 'function'\n                    ? parentVal.call(vm, vm)\n                    : parentVal;\n                if (instanceData) {\n                    return mergeData(instanceData, defaultData)\n                } else {\n                    return defaultData\n                }\n            }\n        }\n    }\n\n    strats.data = function (\n        parentVal,\n        childVal,\n        vm\n    ) {\n        if (!vm) {\n            if (childVal && typeof childVal !== 'function') {\n                warn(\n                    'The \"data\" option should be a function ' +\n                    'that returns a per-instance value in component ' +\n                    'definitions.',\n                    vm\n                );\n\n                return parentVal\n            }\n            return mergeDataOrFn(parentVal, childVal)\n        }\n\n        return mergeDataOrFn(parentVal, childVal, vm)\n    };\n\n    /**\n     * Hooks and props are merged as arrays.\n     */\n    function mergeHook (\n        parentVal,\n        childVal\n    ) {\n        var res = childVal\n            ? parentVal\n                ? parentVal.concat(childVal)\n                : Array.isArray(childVal)\n                    ? childVal\n                    : [childVal]\n            : parentVal;\n        return res\n            ? dedupeHooks(res)\n            : res\n    }\n\n    function dedupeHooks (hooks) {\n        var res = [];\n        for (var i = 0; i < hooks.length; i++) {\n            if (res.indexOf(hooks[i]) === -1) {\n                res.push(hooks[i]);\n            }\n        }\n        return res\n    }\n\n    LIFECYCLE_HOOKS.forEach(function (hook) {\n        strats[hook] = mergeHook;\n    });\n\n    /**\n     * Assets\n     *\n     * When a vm is present (instance creation), we need to do\n     * a three-way merge between constructor options, instance\n     * options and parent options.\n     */\n    function mergeAssets (\n        parentVal,\n        childVal,\n        vm,\n        key\n    ) {\n        var res = Object.create(parentVal || null);\n        if (childVal) {\n            assertObjectType(key, childVal, vm);\n            return extend(res, childVal)\n        } else {\n            return res\n        }\n    }\n\n    ASSET_TYPES.forEach(function (type) {\n        strats[type + 's'] = mergeAssets;\n    });\n\n    /**\n     * Watchers.\n     *\n     * Watchers hashes should not overwrite one\n     * another, so we merge them as arrays.\n     */\n    strats.watch = function (\n        parentVal,\n        childVal,\n        vm,\n        key\n    ) {\n        // work around Firefox's Object.prototype.watch...\n        if (parentVal === nativeWatch) { parentVal = undefined; }\n        if (childVal === nativeWatch) { childVal = undefined; }\n        /* istanbul ignore if */\n        if (!childVal) { return Object.create(parentVal || null) }\n        {\n            assertObjectType(key, childVal, vm);\n        }\n        if (!parentVal) { return childVal }\n        var ret = {};\n        extend(ret, parentVal);\n        for (var key$1 in childVal) {\n            var parent = ret[key$1];\n            var child = childVal[key$1];\n            if (parent && !Array.isArray(parent)) {\n                parent = [parent];\n            }\n            ret[key$1] = parent\n                ? parent.concat(child)\n                : Array.isArray(child) ? child : [child];\n        }\n        return ret\n    };\n\n    /**\n     * Other object hashes.\n     */\n    strats.props =\n        strats.methods =\n            strats.inject =\n                strats.computed = function (\n                    parentVal,\n                    childVal,\n                    vm,\n                    key\n                ) {\n                    if (childVal && \"development\" !== 'production') {\n                        assertObjectType(key, childVal, vm);\n                    }\n                    if (!parentVal) { return childVal }\n                    var ret = Object.create(null);\n                    extend(ret, parentVal);\n                    if (childVal) { extend(ret, childVal); }\n                    return ret\n                };\n    strats.provide = mergeDataOrFn;\n\n    /**\n     * Default strategy.\n     */\n    var defaultStrat = function (parentVal, childVal) {\n        return childVal === undefined\n            ? parentVal\n            : childVal\n    };\n\n    /**\n     * Validate component names\n     */\n    function checkComponents (options) {\n        for (var key in options.components) {\n            validateComponentName(key);\n        }\n    }\n\n    function validateComponentName (name) {\n        if (!new RegExp((\"^[a-zA-Z][\\\\-\\\\.0-9_\" + (unicodeRegExp.source) + \"]*$\")).test(name)) {\n            warn(\n                'Invalid component name: \"' + name + '\". Component names ' +\n                'should conform to valid custom element name in html5 specification.'\n            );\n        }\n        if (isBuiltInTag(name) || config.isReservedTag(name)) {\n            warn(\n                'Do not use built-in or reserved HTML elements as component ' +\n                'id: ' + name\n            );\n        }\n    }\n\n    /**\n     * Ensure all props option syntax are normalized into the\n     * Object-based format.\n     */\n    function normalizeProps (options, vm) {\n        var props = options.props;\n        if (!props) { return }\n        var res = {};\n        var i, val, name;\n        if (Array.isArray(props)) {\n            i = props.length;\n            while (i--) {\n                val = props[i];\n                if (typeof val === 'string') {\n                    name = camelize(val);\n                    res[name] = { type: null };\n                } else {\n                    warn('props must be strings when using array syntax.');\n                }\n            }\n        } else if (isPlainObject(props)) {\n            for (var key in props) {\n                val = props[key];\n                name = camelize(key);\n                res[name] = isPlainObject(val)\n                    ? val\n                    : { type: val };\n            }\n        } else {\n            warn(\n                \"Invalid value for option \\\"props\\\": expected an Array or an Object, \" +\n                \"but got \" + (toRawType(props)) + \".\",\n                vm\n            );\n        }\n        options.props = res;\n    }\n\n    /**\n     * Normalize all injections into Object-based format\n     */\n    function normalizeInject (options, vm) {\n        var inject = options.inject;\n        if (!inject) { return }\n        var normalized = options.inject = {};\n        if (Array.isArray(inject)) {\n            for (var i = 0; i < inject.length; i++) {\n                normalized[inject[i]] = { from: inject[i] };\n            }\n        } else if (isPlainObject(inject)) {\n            for (var key in inject) {\n                var val = inject[key];\n                normalized[key] = isPlainObject(val)\n                    ? extend({ from: key }, val)\n                    : { from: val };\n            }\n        } else {\n            warn(\n                \"Invalid value for option \\\"inject\\\": expected an Array or an Object, \" +\n                \"but got \" + (toRawType(inject)) + \".\",\n                vm\n            );\n        }\n    }\n\n    /**\n     * Normalize raw function directives into object format.\n     */\n    function normalizeDirectives (options) {\n        var dirs = options.directives;\n        if (dirs) {\n            for (var key in dirs) {\n                var def$$1 = dirs[key];\n                if (typeof def$$1 === 'function') {\n                    dirs[key] = { bind: def$$1, update: def$$1 };\n                }\n            }\n        }\n    }\n\n    function assertObjectType (name, value, vm) {\n        if (!isPlainObject(value)) {\n            warn(\n                \"Invalid value for option \\\"\" + name + \"\\\": expected an Object, \" +\n                \"but got \" + (toRawType(value)) + \".\",\n                vm\n            );\n        }\n    }\n\n    /**\n     * Merge two option objects into a new one.\n     * Core utility used in both instantiation and inheritance.\n     */\n    function mergeOptions (\n        parent,\n        child,\n        vm\n    ) {\n        {\n            checkComponents(child);\n        }\n\n        if (typeof child === 'function') {\n            child = child.options;\n        }\n\n        normalizeProps(child, vm);\n        normalizeInject(child, vm);\n        normalizeDirectives(child);\n\n        // Apply extends and mixins on the child options,\n        // but only if it is a raw options object that isn't\n        // the result of another mergeOptions call.\n        // Only merged options has the _base property.\n        if (!child._base) {\n            if (child.extends) {\n                parent = mergeOptions(parent, child.extends, vm);\n            }\n            if (child.mixins) {\n                for (var i = 0, l = child.mixins.length; i < l; i++) {\n                    parent = mergeOptions(parent, child.mixins[i], vm);\n                }\n            }\n        }\n\n        var options = {};\n        var key;\n        for (key in parent) {\n            mergeField(key);\n        }\n        for (key in child) {\n            if (!hasOwn(parent, key)) {\n                mergeField(key);\n            }\n        }\n        function mergeField (key) {\n            var strat = strats[key] || defaultStrat;\n            options[key] = strat(parent[key], child[key], vm, key);\n        }\n        return options\n    }\n\n    /**\n     * Resolve an asset.\n     * This function is used because child instances need access\n     * to assets defined in its ancestor chain.\n     */\n    function resolveAsset (\n        options,\n        type,\n        id,\n        warnMissing\n    ) {\n        /* istanbul ignore if */\n        if (typeof id !== 'string') {\n            return\n        }\n        var assets = options[type];\n        // check local registration variations first\n        if (hasOwn(assets, id)) { return assets[id] }\n        var camelizedId = camelize(id);\n        if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }\n        var PascalCaseId = capitalize(camelizedId);\n        if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }\n        // fallback to prototype chain\n        var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];\n        if (warnMissing && !res) {\n            warn(\n                'Failed to resolve ' + type.slice(0, -1) + ': ' + id,\n                options\n            );\n        }\n        return res\n    }\n\n    /*  */\n\n\n\n    function validateProp (\n        key,\n        propOptions,\n        propsData,\n        vm\n    ) {\n        var prop = propOptions[key];\n        var absent = !hasOwn(propsData, key);\n        var value = propsData[key];\n        // boolean casting\n        var booleanIndex = getTypeIndex(Boolean, prop.type);\n        if (booleanIndex > -1) {\n            if (absent && !hasOwn(prop, 'default')) {\n                value = false;\n            } else if (value === '' || value === hyphenate(key)) {\n                // only cast empty string / same name to boolean if\n                // boolean has higher priority\n                var stringIndex = getTypeIndex(String, prop.type);\n                if (stringIndex < 0 || booleanIndex < stringIndex) {\n                    value = true;\n                }\n            }\n        }\n        // check default value\n        if (value === undefined) {\n            value = getPropDefaultValue(vm, prop, key);\n            // since the default value is a fresh copy,\n            // make sure to observe it.\n            var prevShouldObserve = shouldObserve;\n            toggleObserving(true);\n            observe(value);\n            toggleObserving(prevShouldObserve);\n        }\n        {\n            assertProp(prop, key, value, vm, absent);\n        }\n        return value\n    }\n\n    /**\n     * Get the default value of a prop.\n     */\n    function getPropDefaultValue (vm, prop, key) {\n        // no default, return undefined\n        if (!hasOwn(prop, 'default')) {\n            return undefined\n        }\n        var def = prop.default;\n        // warn against non-factory defaults for Object & Array\n        if (isObject(def)) {\n            warn(\n                'Invalid default value for prop \"' + key + '\": ' +\n                'Props with type Object/Array must use a factory function ' +\n                'to return the default value.',\n                vm\n            );\n        }\n        // the raw prop value was also undefined from previous render,\n        // return previous default value to avoid unnecessary watcher trigger\n        if (vm && vm.$options.propsData &&\n            vm.$options.propsData[key] === undefined &&\n            vm._props[key] !== undefined\n        ) {\n            return vm._props[key]\n        }\n        // call factory function for non-Function types\n        // a value is Function if its prototype is function even across different execution context\n        return typeof def === 'function' && getType(prop.type) !== 'Function'\n            ? def.call(vm)\n            : def\n    }\n\n    /**\n     * Assert whether a prop is valid.\n     */\n    function assertProp (\n        prop,\n        name,\n        value,\n        vm,\n        absent\n    ) {\n        if (prop.required && absent) {\n            warn(\n                'Missing required prop: \"' + name + '\"',\n                vm\n            );\n            return\n        }\n        if (value == null && !prop.required) {\n            return\n        }\n        var type = prop.type;\n        var valid = !type || type === true;\n        var expectedTypes = [];\n        if (type) {\n            if (!Array.isArray(type)) {\n                type = [type];\n            }\n            for (var i = 0; i < type.length && !valid; i++) {\n                var assertedType = assertType(value, type[i], vm);\n                expectedTypes.push(assertedType.expectedType || '');\n                valid = assertedType.valid;\n            }\n        }\n\n        var haveExpectedTypes = expectedTypes.some(function (t) { return t; });\n        if (!valid && haveExpectedTypes) {\n            warn(\n                getInvalidTypeMessage(name, value, expectedTypes),\n                vm\n            );\n            return\n        }\n        var validator = prop.validator;\n        if (validator) {\n            if (!validator(value)) {\n                warn(\n                    'Invalid prop: custom validator check failed for prop \"' + name + '\".',\n                    vm\n                );\n            }\n        }\n    }\n\n    var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol|BigInt)$/;\n\n    function assertType (value, type, vm) {\n        var valid;\n        var expectedType = getType(type);\n        if (simpleCheckRE.test(expectedType)) {\n            var t = typeof value;\n            valid = t === expectedType.toLowerCase();\n            // for primitive wrapper objects\n            if (!valid && t === 'object') {\n                valid = value instanceof type;\n            }\n        } else if (expectedType === 'Object') {\n            valid = isPlainObject(value);\n        } else if (expectedType === 'Array') {\n            valid = Array.isArray(value);\n        } else {\n            try {\n                valid = value instanceof type;\n            } catch (e) {\n                warn('Invalid prop type: \"' + String(type) + '\" is not a constructor', vm);\n                valid = false;\n            }\n        }\n        return {\n            valid: valid,\n            expectedType: expectedType\n        }\n    }\n\n    var functionTypeCheckRE = /^\\s*function (\\w+)/;\n\n    /**\n     * Use function string name to check built-in types,\n     * because a simple equality check will fail when running\n     * across different vms / iframes.\n     */\n    function getType (fn) {\n        var match = fn && fn.toString().match(functionTypeCheckRE);\n        return match ? match[1] : ''\n    }\n\n    function isSameType (a, b) {\n        return getType(a) === getType(b)\n    }\n\n    function getTypeIndex (type, expectedTypes) {\n        if (!Array.isArray(expectedTypes)) {\n            return isSameType(expectedTypes, type) ? 0 : -1\n        }\n        for (var i = 0, len = expectedTypes.length; i < len; i++) {\n            if (isSameType(expectedTypes[i], type)) {\n                return i\n            }\n        }\n        return -1\n    }\n\n    function getInvalidTypeMessage (name, value, expectedTypes) {\n        var message = \"Invalid prop: type check failed for prop \\\"\" + name + \"\\\".\" +\n            \" Expected \" + (expectedTypes.map(capitalize).join(', '));\n        var expectedType = expectedTypes[0];\n        var receivedType = toRawType(value);\n        // check if we need to specify expected value\n        if (\n            expectedTypes.length === 1 &&\n            isExplicable(expectedType) &&\n            isExplicable(typeof value) &&\n            !isBoolean(expectedType, receivedType)\n        ) {\n            message += \" with value \" + (styleValue(value, expectedType));\n        }\n        message += \", got \" + receivedType + \" \";\n        // check if we need to specify received value\n        if (isExplicable(receivedType)) {\n            message += \"with value \" + (styleValue(value, receivedType)) + \".\";\n        }\n        return message\n    }\n\n    function styleValue (value, type) {\n        if (type === 'String') {\n            return (\"\\\"\" + value + \"\\\"\")\n        } else if (type === 'Number') {\n            return (\"\" + (Number(value)))\n        } else {\n            return (\"\" + value)\n        }\n    }\n\n    var EXPLICABLE_TYPES = ['string', 'number', 'boolean'];\n    function isExplicable (value) {\n        return EXPLICABLE_TYPES.some(function (elem) { return value.toLowerCase() === elem; })\n    }\n\n    function isBoolean () {\n        var args = [], len = arguments.length;\n        while ( len-- ) args[ len ] = arguments[ len ];\n\n        return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; })\n    }\n\n    /*  */\n\n    function handleError (err, vm, info) {\n        // Deactivate deps tracking while processing error handler to avoid possible infinite rendering.\n        // See: https://github.com/vuejs/vuex/issues/1505\n        pushTarget();\n        try {\n            if (vm) {\n                var cur = vm;\n                while ((cur = cur.$parent)) {\n                    var hooks = cur.$options.errorCaptured;\n                    if (hooks) {\n                        for (var i = 0; i < hooks.length; i++) {\n                            try {\n                                var capture = hooks[i].call(cur, err, vm, info) === false;\n                                if (capture) { return }\n                            } catch (e) {\n                                globalHandleError(e, cur, 'errorCaptured hook');\n                            }\n                        }\n                    }\n                }\n            }\n            globalHandleError(err, vm, info);\n        } finally {\n            popTarget();\n        }\n    }\n\n    function invokeWithErrorHandling (\n        handler,\n        context,\n        args,\n        vm,\n        info\n    ) {\n        var res;\n        try {\n            res = args ? handler.apply(context, args) : handler.call(context);\n            if (res && !res._isVue && isPromise(res) && !res._handled) {\n                res.catch(function (e) { return handleError(e, vm, info + \" (Promise/async)\"); });\n                // issue #9511\n                // avoid catch triggering multiple times when nested calls\n                res._handled = true;\n            }\n        } catch (e) {\n            handleError(e, vm, info);\n        }\n        return res\n    }\n\n    function globalHandleError (err, vm, info) {\n        if (config.errorHandler) {\n            try {\n                return config.errorHandler.call(null, err, vm, info)\n            } catch (e) {\n                // if the user intentionally throws the original error in the handler,\n                // do not log it twice\n                if (e !== err) {\n                    logError(e, null, 'config.errorHandler');\n                }\n            }\n        }\n        logError(err, vm, info);\n    }\n\n    function logError (err, vm, info) {\n        {\n            warn((\"Error in \" + info + \": \\\"\" + (err.toString()) + \"\\\"\"), vm);\n        }\n        /* istanbul ignore else */\n        if ((inBrowser || inWeex) && typeof console !== 'undefined') {\n            console.error(err);\n        } else {\n            throw err\n        }\n    }\n\n    /*  */\n\n    var isUsingMicroTask = false;\n\n    var callbacks = [];\n    var pending = false;\n\n    function flushCallbacks () {\n        pending = false;\n        var copies = callbacks.slice(0);\n        callbacks.length = 0;\n        for (var i = 0; i < copies.length; i++) {\n            copies[i]();\n        }\n    }\n\n    // Here we have async deferring wrappers using microtasks.\n    // In 2.5 we used (macro) tasks (in combination with microtasks).\n    // However, it has subtle problems when state is changed right before repaint\n    // (e.g. #6813, out-in transitions).\n    // Also, using (macro) tasks in event handler would cause some weird behaviors\n    // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).\n    // So we now use microtasks everywhere, again.\n    // A major drawback of this tradeoff is that there are some scenarios\n    // where microtasks have too high a priority and fire in between supposedly\n    // sequential events (e.g. #4521, #6690, which have workarounds)\n    // or even between bubbling of the same event (#6566).\n    var timerFunc;\n\n    // The nextTick behavior leverages the microtask queue, which can be accessed\n    // via either native Promise.then or MutationObserver.\n    // MutationObserver has wider support, however it is seriously bugged in\n    // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It\n    // completely stops working after triggering a few times... so, if native\n    // Promise is available, we will use it:\n    /* istanbul ignore next, $flow-disable-line */\n    if (typeof Promise !== 'undefined' && isNative(Promise)) {\n        var p = Promise.resolve();\n        timerFunc = function () {\n            p.then(flushCallbacks);\n            // In problematic UIWebViews, Promise.then doesn't completely break, but\n            // it can get stuck in a weird state where callbacks are pushed into the\n            // microtask queue but the queue isn't being flushed, until the browser\n            // needs to do some other work, e.g. handle a timer. Therefore we can\n            // \"force\" the microtask queue to be flushed by adding an empty timer.\n            if (isIOS) { setTimeout(noop); }\n        };\n        isUsingMicroTask = true;\n    } else if (!isIE && typeof MutationObserver !== 'undefined' && (\n        isNative(MutationObserver) ||\n        // PhantomJS and iOS 7.x\n        MutationObserver.toString() === '[object MutationObserverConstructor]'\n    )) {\n        // Use MutationObserver where native Promise is not available,\n        // e.g. PhantomJS, iOS7, Android 4.4\n        // (#6466 MutationObserver is unreliable in IE11)\n        var counter = 1;\n        var observer = new MutationObserver(flushCallbacks);\n        var textNode = document.createTextNode(String(counter));\n        observer.observe(textNode, {\n            characterData: true\n        });\n        timerFunc = function () {\n            counter = (counter + 1) % 2;\n            textNode.data = String(counter);\n        };\n        isUsingMicroTask = true;\n    } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {\n        // Fallback to setImmediate.\n        // Technically it leverages the (macro) task queue,\n        // but it is still a better choice than setTimeout.\n        timerFunc = function () {\n            setImmediate(flushCallbacks);\n        };\n    } else {\n        // Fallback to setTimeout.\n        timerFunc = function () {\n            setTimeout(flushCallbacks, 0);\n        };\n    }\n\n    function nextTick (cb, ctx) {\n        var _resolve;\n        callbacks.push(function () {\n            if (cb) {\n                try {\n                    cb.call(ctx);\n                } catch (e) {\n                    handleError(e, ctx, 'nextTick');\n                }\n            } else if (_resolve) {\n                _resolve(ctx);\n            }\n        });\n        if (!pending) {\n            pending = true;\n            timerFunc();\n        }\n        // $flow-disable-line\n        if (!cb && typeof Promise !== 'undefined') {\n            return new Promise(function (resolve) {\n                _resolve = resolve;\n            })\n        }\n    }\n\n    /*  */\n\n    var mark;\n    var measure;\n\n    {\n        var perf = inBrowser && window.performance;\n        /* istanbul ignore if */\n        if (\n            perf &&\n            perf.mark &&\n            perf.measure &&\n            perf.clearMarks &&\n            perf.clearMeasures\n        ) {\n            mark = function (tag) { return perf.mark(tag); };\n            measure = function (name, startTag, endTag) {\n                perf.measure(name, startTag, endTag);\n                perf.clearMarks(startTag);\n                perf.clearMarks(endTag);\n                // perf.clearMeasures(name)\n            };\n        }\n    }\n\n    /* not type checking this file because flow doesn't play well with Proxy */\n\n    var initProxy;\n\n    {\n        var allowedGlobals = makeMap(\n            'Infinity,undefined,NaN,isFinite,isNaN,' +\n            'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n            'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' +\n            'require' // for Webpack/Browserify\n        );\n\n        var warnNonPresent = function (target, key) {\n            warn(\n                \"Property or method \\\"\" + key + \"\\\" is not defined on the instance but \" +\n                'referenced during render. Make sure that this property is reactive, ' +\n                'either in the data option, or for class-based components, by ' +\n                'initializing the property. ' +\n                'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',\n                target\n            );\n        };\n\n        var warnReservedPrefix = function (target, key) {\n            warn(\n                \"Property \\\"\" + key + \"\\\" must be accessed with \\\"$data.\" + key + \"\\\" because \" +\n                'properties starting with \"$\" or \"_\" are not proxied in the Vue instance to ' +\n                'prevent conflicts with Vue internals. ' +\n                'See: https://vuejs.org/v2/api/#data',\n                target\n            );\n        };\n\n        var hasProxy =\n            typeof Proxy !== 'undefined' && isNative(Proxy);\n\n        if (hasProxy) {\n            var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');\n            config.keyCodes = new Proxy(config.keyCodes, {\n                set: function set (target, key, value) {\n                    if (isBuiltInModifier(key)) {\n                        warn((\"Avoid overwriting built-in modifier in config.keyCodes: .\" + key));\n                        return false\n                    } else {\n                        target[key] = value;\n                        return true\n                    }\n                }\n            });\n        }\n\n        var hasHandler = {\n            has: function has (target, key) {\n                var has = key in target;\n                var isAllowed = allowedGlobals(key) ||\n                    (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data));\n                if (!has && !isAllowed) {\n                    if (key in target.$data) { warnReservedPrefix(target, key); }\n                    else { warnNonPresent(target, key); }\n                }\n                return has || !isAllowed\n            }\n        };\n\n        var getHandler = {\n            get: function get (target, key) {\n                if (typeof key === 'string' && !(key in target)) {\n                    if (key in target.$data) { warnReservedPrefix(target, key); }\n                    else { warnNonPresent(target, key); }\n                }\n                return target[key]\n            }\n        };\n\n        initProxy = function initProxy (vm) {\n            if (hasProxy) {\n                // determine which proxy handler to use\n                var options = vm.$options;\n                var handlers = options.render && options.render._withStripped\n                    ? getHandler\n                    : hasHandler;\n                vm._renderProxy = new Proxy(vm, handlers);\n            } else {\n                vm._renderProxy = vm;\n            }\n        };\n    }\n\n    /*  */\n\n    var seenObjects = new _Set();\n\n    /**\n     * Recursively traverse an object to evoke all converted\n     * getters, so that every nested property inside the object\n     * is collected as a \"deep\" dependency.\n     */\n    function traverse (val) {\n        _traverse(val, seenObjects);\n        seenObjects.clear();\n    }\n\n    function _traverse (val, seen) {\n        var i, keys;\n        var isA = Array.isArray(val);\n        if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {\n            return\n        }\n        if (val.__ob__) {\n            var depId = val.__ob__.dep.id;\n            if (seen.has(depId)) {\n                return\n            }\n            seen.add(depId);\n        }\n        if (isA) {\n            i = val.length;\n            while (i--) { _traverse(val[i], seen); }\n        } else {\n            keys = Object.keys(val);\n            i = keys.length;\n            while (i--) { _traverse(val[keys[i]], seen); }\n        }\n    }\n\n    /*  */\n\n    var normalizeEvent = cached(function (name) {\n        var passive = name.charAt(0) === '&';\n        name = passive ? name.slice(1) : name;\n        var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first\n        name = once$$1 ? name.slice(1) : name;\n        var capture = name.charAt(0) === '!';\n        name = capture ? name.slice(1) : name;\n        return {\n            name: name,\n            once: once$$1,\n            capture: capture,\n            passive: passive\n        }\n    });\n\n    function createFnInvoker (fns, vm) {\n        function invoker () {\n            var arguments$1 = arguments;\n\n            var fns = invoker.fns;\n            if (Array.isArray(fns)) {\n                var cloned = fns.slice();\n                for (var i = 0; i < cloned.length; i++) {\n                    invokeWithErrorHandling(cloned[i], null, arguments$1, vm, \"v-on handler\");\n                }\n            } else {\n                // return handler return value for single handlers\n                return invokeWithErrorHandling(fns, null, arguments, vm, \"v-on handler\")\n            }\n        }\n        invoker.fns = fns;\n        return invoker\n    }\n\n    function updateListeners (\n        on,\n        oldOn,\n        add,\n        remove$$1,\n        createOnceHandler,\n        vm\n    ) {\n        var name, def$$1, cur, old, event;\n        for (name in on) {\n            def$$1 = cur = on[name];\n            old = oldOn[name];\n            event = normalizeEvent(name);\n            if (isUndef(cur)) {\n                warn(\n                    \"Invalid handler for event \\\"\" + (event.name) + \"\\\": got \" + String(cur),\n                    vm\n                );\n            } else if (isUndef(old)) {\n                if (isUndef(cur.fns)) {\n                    cur = on[name] = createFnInvoker(cur, vm);\n                }\n                if (isTrue(event.once)) {\n                    cur = on[name] = createOnceHandler(event.name, cur, event.capture);\n                }\n                add(event.name, cur, event.capture, event.passive, event.params);\n            } else if (cur !== old) {\n                old.fns = cur;\n                on[name] = old;\n            }\n        }\n        for (name in oldOn) {\n            if (isUndef(on[name])) {\n                event = normalizeEvent(name);\n                remove$$1(event.name, oldOn[name], event.capture);\n            }\n        }\n    }\n\n    /*  */\n\n    function mergeVNodeHook (def, hookKey, hook) {\n        if (def instanceof VNode) {\n            def = def.data.hook || (def.data.hook = {});\n        }\n        var invoker;\n        var oldHook = def[hookKey];\n\n        function wrappedHook () {\n            hook.apply(this, arguments);\n            // important: remove merged hook to ensure it's called only once\n            // and prevent memory leak\n            remove(invoker.fns, wrappedHook);\n        }\n\n        if (isUndef(oldHook)) {\n            // no existing hook\n            invoker = createFnInvoker([wrappedHook]);\n        } else {\n            /* istanbul ignore if */\n            if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {\n                // already a merged invoker\n                invoker = oldHook;\n                invoker.fns.push(wrappedHook);\n            } else {\n                // existing plain hook\n                invoker = createFnInvoker([oldHook, wrappedHook]);\n            }\n        }\n\n        invoker.merged = true;\n        def[hookKey] = invoker;\n    }\n\n    /*  */\n\n    function extractPropsFromVNodeData (\n        data,\n        Ctor,\n        tag\n    ) {\n        // we are only extracting raw values here.\n        // validation and default values are handled in the child\n        // component itself.\n        var propOptions = Ctor.options.props;\n        if (isUndef(propOptions)) {\n            return\n        }\n        var res = {};\n        var attrs = data.attrs;\n        var props = data.props;\n        if (isDef(attrs) || isDef(props)) {\n            for (var key in propOptions) {\n                var altKey = hyphenate(key);\n                {\n                    var keyInLowerCase = key.toLowerCase();\n                    if (\n                        key !== keyInLowerCase &&\n                        attrs && hasOwn(attrs, keyInLowerCase)\n                    ) {\n                        tip(\n                            \"Prop \\\"\" + keyInLowerCase + \"\\\" is passed to component \" +\n                            (formatComponentName(tag || Ctor)) + \", but the declared prop name is\" +\n                            \" \\\"\" + key + \"\\\". \" +\n                            \"Note that HTML attributes are case-insensitive and camelCased \" +\n                            \"props need to use their kebab-case equivalents when using in-DOM \" +\n                            \"templates. You should probably use \\\"\" + altKey + \"\\\" instead of \\\"\" + key + \"\\\".\"\n                        );\n                    }\n                }\n                checkProp(res, props, key, altKey, true) ||\n                checkProp(res, attrs, key, altKey, false);\n            }\n        }\n        return res\n    }\n\n    function checkProp (\n        res,\n        hash,\n        key,\n        altKey,\n        preserve\n    ) {\n        if (isDef(hash)) {\n            if (hasOwn(hash, key)) {\n                res[key] = hash[key];\n                if (!preserve) {\n                    delete hash[key];\n                }\n                return true\n            } else if (hasOwn(hash, altKey)) {\n                res[key] = hash[altKey];\n                if (!preserve) {\n                    delete hash[altKey];\n                }\n                return true\n            }\n        }\n        return false\n    }\n\n    /*  */\n\n    // The template compiler attempts to minimize the need for normalization by\n    // statically analyzing the template at compile time.\n    //\n    // For plain HTML markup, normalization can be completely skipped because the\n    // generated render function is guaranteed to return Array<VNode>. There are\n    // two cases where extra normalization is needed:\n\n    // 1. When the children contains components - because a functional component\n    // may return an Array instead of a single root. In this case, just a simple\n    // normalization is needed - if any child is an Array, we flatten the whole\n    // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep\n    // because functional components already normalize their own children.\n    function simpleNormalizeChildren (children) {\n        for (var i = 0; i < children.length; i++) {\n            if (Array.isArray(children[i])) {\n                return Array.prototype.concat.apply([], children)\n            }\n        }\n        return children\n    }\n\n    // 2. When the children contains constructs that always generated nested Arrays,\n    // e.g. <template>, <slot>, v-for, or when the children is provided by user\n    // with hand-written render functions / JSX. In such cases a full normalization\n    // is needed to cater to all possible types of children values.\n    function normalizeChildren (children) {\n        return isPrimitive(children)\n            ? [createTextVNode(children)]\n            : Array.isArray(children)\n                ? normalizeArrayChildren(children)\n                : undefined\n    }\n\n    function isTextNode (node) {\n        return isDef(node) && isDef(node.text) && isFalse(node.isComment)\n    }\n\n    function normalizeArrayChildren (children, nestedIndex) {\n        var res = [];\n        var i, c, lastIndex, last;\n        for (i = 0; i < children.length; i++) {\n            c = children[i];\n            if (isUndef(c) || typeof c === 'boolean') { continue }\n            lastIndex = res.length - 1;\n            last = res[lastIndex];\n            //  nested\n            if (Array.isArray(c)) {\n                if (c.length > 0) {\n                    c = normalizeArrayChildren(c, ((nestedIndex || '') + \"_\" + i));\n                    // merge adjacent text nodes\n                    if (isTextNode(c[0]) && isTextNode(last)) {\n                        res[lastIndex] = createTextVNode(last.text + (c[0]).text);\n                        c.shift();\n                    }\n                    res.push.apply(res, c);\n                }\n            } else if (isPrimitive(c)) {\n                if (isTextNode(last)) {\n                    // merge adjacent text nodes\n                    // this is necessary for SSR hydration because text nodes are\n                    // essentially merged when rendered to HTML strings\n                    res[lastIndex] = createTextVNode(last.text + c);\n                } else if (c !== '') {\n                    // convert primitive to vnode\n                    res.push(createTextVNode(c));\n                }\n            } else {\n                if (isTextNode(c) && isTextNode(last)) {\n                    // merge adjacent text nodes\n                    res[lastIndex] = createTextVNode(last.text + c.text);\n                } else {\n                    // default key for nested array children (likely generated by v-for)\n                    if (isTrue(children._isVList) &&\n                        isDef(c.tag) &&\n                        isUndef(c.key) &&\n                        isDef(nestedIndex)) {\n                        c.key = \"__vlist\" + nestedIndex + \"_\" + i + \"__\";\n                    }\n                    res.push(c);\n                }\n            }\n        }\n        return res\n    }\n\n    /*  */\n\n    function initProvide (vm) {\n        var provide = vm.$options.provide;\n        if (provide) {\n            vm._provided = typeof provide === 'function'\n                ? provide.call(vm)\n                : provide;\n        }\n    }\n\n    function initInjections (vm) {\n        var result = resolveInject(vm.$options.inject, vm);\n        if (result) {\n            toggleObserving(false);\n            Object.keys(result).forEach(function (key) {\n                /* istanbul ignore else */\n                {\n                    defineReactive$$1(vm, key, result[key], function () {\n                        warn(\n                            \"Avoid mutating an injected value directly since the changes will be \" +\n                            \"overwritten whenever the provided component re-renders. \" +\n                            \"injection being mutated: \\\"\" + key + \"\\\"\",\n                            vm\n                        );\n                    });\n                }\n            });\n            toggleObserving(true);\n        }\n    }\n\n    function resolveInject (inject, vm) {\n        if (inject) {\n            // inject is :any because flow is not smart enough to figure out cached\n            var result = Object.create(null);\n            var keys = hasSymbol\n                ? Reflect.ownKeys(inject)\n                : Object.keys(inject);\n\n            for (var i = 0; i < keys.length; i++) {\n                var key = keys[i];\n                // #6574 in case the inject object is observed...\n                if (key === '__ob__') { continue }\n                var provideKey = inject[key].from;\n                var source = vm;\n                while (source) {\n                    if (source._provided && hasOwn(source._provided, provideKey)) {\n                        result[key] = source._provided[provideKey];\n                        break\n                    }\n                    source = source.$parent;\n                }\n                if (!source) {\n                    if ('default' in inject[key]) {\n                        var provideDefault = inject[key].default;\n                        result[key] = typeof provideDefault === 'function'\n                            ? provideDefault.call(vm)\n                            : provideDefault;\n                    } else {\n                        warn((\"Injection \\\"\" + key + \"\\\" not found\"), vm);\n                    }\n                }\n            }\n            return result\n        }\n    }\n\n    /*  */\n\n\n\n    /**\n     * Runtime helper for resolving raw children VNodes into a slot object.\n     */\n    function resolveSlots (\n        children,\n        context\n    ) {\n        if (!children || !children.length) {\n            return {}\n        }\n        var slots = {};\n        for (var i = 0, l = children.length; i < l; i++) {\n            var child = children[i];\n            var data = child.data;\n            // remove slot attribute if the node is resolved as a Vue slot node\n            if (data && data.attrs && data.attrs.slot) {\n                delete data.attrs.slot;\n            }\n            // named slots should only be respected if the vnode was rendered in the\n            // same context.\n            if ((child.context === context || child.fnContext === context) &&\n                data && data.slot != null\n            ) {\n                var name = data.slot;\n                var slot = (slots[name] || (slots[name] = []));\n                if (child.tag === 'template') {\n                    slot.push.apply(slot, child.children || []);\n                } else {\n                    slot.push(child);\n                }\n            } else {\n                (slots.default || (slots.default = [])).push(child);\n            }\n        }\n        // ignore slots that contains only whitespace\n        for (var name$1 in slots) {\n            if (slots[name$1].every(isWhitespace)) {\n                delete slots[name$1];\n            }\n        }\n        return slots\n    }\n\n    function isWhitespace (node) {\n        return (node.isComment && !node.asyncFactory) || node.text === ' '\n    }\n\n    /*  */\n\n    function isAsyncPlaceholder (node) {\n        return node.isComment && node.asyncFactory\n    }\n\n    /*  */\n\n    function normalizeScopedSlots (\n        slots,\n        normalSlots,\n        prevSlots\n    ) {\n        var res;\n        var hasNormalSlots = Object.keys(normalSlots).length > 0;\n        var isStable = slots ? !!slots.$stable : !hasNormalSlots;\n        var key = slots && slots.$key;\n        if (!slots) {\n            res = {};\n        } else if (slots._normalized) {\n            // fast path 1: child component re-render only, parent did not change\n            return slots._normalized\n        } else if (\n            isStable &&\n            prevSlots &&\n            prevSlots !== emptyObject &&\n            key === prevSlots.$key &&\n            !hasNormalSlots &&\n            !prevSlots.$hasNormal\n        ) {\n            // fast path 2: stable scoped slots w/ no normal slots to proxy,\n            // only need to normalize once\n            return prevSlots\n        } else {\n            res = {};\n            for (var key$1 in slots) {\n                if (slots[key$1] && key$1[0] !== '$') {\n                    res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]);\n                }\n            }\n        }\n        // expose normal slots on scopedSlots\n        for (var key$2 in normalSlots) {\n            if (!(key$2 in res)) {\n                res[key$2] = proxyNormalSlot(normalSlots, key$2);\n            }\n        }\n        // avoriaz seems to mock a non-extensible $scopedSlots object\n        // and when that is passed down this would cause an error\n        if (slots && Object.isExtensible(slots)) {\n            (slots)._normalized = res;\n        }\n        def(res, '$stable', isStable);\n        def(res, '$key', key);\n        def(res, '$hasNormal', hasNormalSlots);\n        return res\n    }\n\n    function normalizeScopedSlot(normalSlots, key, fn) {\n        var normalized = function () {\n            var res = arguments.length ? fn.apply(null, arguments) : fn({});\n            res = res && typeof res === 'object' && !Array.isArray(res)\n                ? [res] // single vnode\n                : normalizeChildren(res);\n            var vnode = res && res[0];\n            return res && (\n                !vnode ||\n                (res.length === 1 && vnode.isComment && !isAsyncPlaceholder(vnode)) // #9658, #10391\n            ) ? undefined\n                : res\n        };\n        // this is a slot using the new v-slot syntax without scope. although it is\n        // compiled as a scoped slot, render fn users would expect it to be present\n        // on this.$slots because the usage is semantically a normal slot.\n        if (fn.proxy) {\n            Object.defineProperty(normalSlots, key, {\n                get: normalized,\n                enumerable: true,\n                configurable: true\n            });\n        }\n        return normalized\n    }\n\n    function proxyNormalSlot(slots, key) {\n        return function () { return slots[key]; }\n    }\n\n    /*  */\n\n    /**\n     * Runtime helper for rendering v-for lists.\n     */\n    function renderList (\n        val,\n        render\n    ) {\n        var ret, i, l, keys, key;\n        if (Array.isArray(val) || typeof val === 'string') {\n            ret = new Array(val.length);\n            for (i = 0, l = val.length; i < l; i++) {\n                ret[i] = render(val[i], i);\n            }\n        } else if (typeof val === 'number') {\n            ret = new Array(val);\n            for (i = 0; i < val; i++) {\n                ret[i] = render(i + 1, i);\n            }\n        } else if (isObject(val)) {\n            if (hasSymbol && val[Symbol.iterator]) {\n                ret = [];\n                var iterator = val[Symbol.iterator]();\n                var result = iterator.next();\n                while (!result.done) {\n                    ret.push(render(result.value, ret.length));\n                    result = iterator.next();\n                }\n            } else {\n                keys = Object.keys(val);\n                ret = new Array(keys.length);\n                for (i = 0, l = keys.length; i < l; i++) {\n                    key = keys[i];\n                    ret[i] = render(val[key], key, i);\n                }\n            }\n        }\n        if (!isDef(ret)) {\n            ret = [];\n        }\n        (ret)._isVList = true;\n        return ret\n    }\n\n    /*  */\n\n    /**\n     * Runtime helper for rendering <slot>\n     */\n    function renderSlot (\n        name,\n        fallbackRender,\n        props,\n        bindObject\n    ) {\n        var scopedSlotFn = this.$scopedSlots[name];\n        var nodes;\n        if (scopedSlotFn) {\n            // scoped slot\n            props = props || {};\n            if (bindObject) {\n                if (!isObject(bindObject)) {\n                    warn('slot v-bind without argument expects an Object', this);\n                }\n                props = extend(extend({}, bindObject), props);\n            }\n            nodes =\n                scopedSlotFn(props) ||\n                (typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender);\n        } else {\n            nodes =\n                this.$slots[name] ||\n                (typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender);\n        }\n\n        var target = props && props.slot;\n        if (target) {\n            return this.$createElement('template', { slot: target }, nodes)\n        } else {\n            return nodes\n        }\n    }\n\n    /*  */\n\n    /**\n     * Runtime helper for resolving filters\n     */\n    function resolveFilter (id) {\n        return resolveAsset(this.$options, 'filters', id, true) || identity\n    }\n\n    /*  */\n\n    function isKeyNotMatch (expect, actual) {\n        if (Array.isArray(expect)) {\n            return expect.indexOf(actual) === -1\n        } else {\n            return expect !== actual\n        }\n    }\n\n    /**\n     * Runtime helper for checking keyCodes from config.\n     * exposed as Vue.prototype._k\n     * passing in eventKeyName as last argument separately for backwards compat\n     */\n    function checkKeyCodes (\n        eventKeyCode,\n        key,\n        builtInKeyCode,\n        eventKeyName,\n        builtInKeyName\n    ) {\n        var mappedKeyCode = config.keyCodes[key] || builtInKeyCode;\n        if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {\n            return isKeyNotMatch(builtInKeyName, eventKeyName)\n        } else if (mappedKeyCode) {\n            return isKeyNotMatch(mappedKeyCode, eventKeyCode)\n        } else if (eventKeyName) {\n            return hyphenate(eventKeyName) !== key\n        }\n        return eventKeyCode === undefined\n    }\n\n    /*  */\n\n    /**\n     * Runtime helper for merging v-bind=\"object\" into a VNode's data.\n     */\n    function bindObjectProps (\n        data,\n        tag,\n        value,\n        asProp,\n        isSync\n    ) {\n        if (value) {\n            if (!isObject(value)) {\n                warn(\n                    'v-bind without argument expects an Object or Array value',\n                    this\n                );\n            } else {\n                if (Array.isArray(value)) {\n                    value = toObject(value);\n                }\n                var hash;\n                var loop = function ( key ) {\n                    if (\n                        key === 'class' ||\n                        key === 'style' ||\n                        isReservedAttribute(key)\n                    ) {\n                        hash = data;\n                    } else {\n                        var type = data.attrs && data.attrs.type;\n                        hash = asProp || config.mustUseProp(tag, type, key)\n                            ? data.domProps || (data.domProps = {})\n                            : data.attrs || (data.attrs = {});\n                    }\n                    var camelizedKey = camelize(key);\n                    var hyphenatedKey = hyphenate(key);\n                    if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) {\n                        hash[key] = value[key];\n\n                        if (isSync) {\n                            var on = data.on || (data.on = {});\n                            on[(\"update:\" + key)] = function ($event) {\n                                value[key] = $event;\n                            };\n                        }\n                    }\n                };\n\n                for (var key in value) loop( key );\n            }\n        }\n        return data\n    }\n\n    /*  */\n\n    /**\n     * Runtime helper for rendering static trees.\n     */\n    function renderStatic (\n        index,\n        isInFor\n    ) {\n        var cached = this._staticTrees || (this._staticTrees = []);\n        var tree = cached[index];\n        // if has already-rendered static tree and not inside v-for,\n        // we can reuse the same tree.\n        if (tree && !isInFor) {\n            return tree\n        }\n        // otherwise, render a fresh tree.\n        tree = cached[index] = this.$options.staticRenderFns[index].call(\n            this._renderProxy,\n            null,\n            this // for render fns generated for functional component templates\n        );\n        markStatic(tree, (\"__static__\" + index), false);\n        return tree\n    }\n\n    /**\n     * Runtime helper for v-once.\n     * Effectively it means marking the node as static with a unique key.\n     */\n    function markOnce (\n        tree,\n        index,\n        key\n    ) {\n        markStatic(tree, (\"__once__\" + index + (key ? (\"_\" + key) : \"\")), true);\n        return tree\n    }\n\n    function markStatic (\n        tree,\n        key,\n        isOnce\n    ) {\n        if (Array.isArray(tree)) {\n            for (var i = 0; i < tree.length; i++) {\n                if (tree[i] && typeof tree[i] !== 'string') {\n                    markStaticNode(tree[i], (key + \"_\" + i), isOnce);\n                }\n            }\n        } else {\n            markStaticNode(tree, key, isOnce);\n        }\n    }\n\n    function markStaticNode (node, key, isOnce) {\n        node.isStatic = true;\n        node.key = key;\n        node.isOnce = isOnce;\n    }\n\n    /*  */\n\n    function bindObjectListeners (data, value) {\n        if (value) {\n            if (!isPlainObject(value)) {\n                warn(\n                    'v-on without argument expects an Object value',\n                    this\n                );\n            } else {\n                var on = data.on = data.on ? extend({}, data.on) : {};\n                for (var key in value) {\n                    var existing = on[key];\n                    var ours = value[key];\n                    on[key] = existing ? [].concat(existing, ours) : ours;\n                }\n            }\n        }\n        return data\n    }\n\n    /*  */\n\n    function resolveScopedSlots (\n        fns, // see flow/vnode\n        res,\n        // the following are added in 2.6\n        hasDynamicKeys,\n        contentHashKey\n    ) {\n        res = res || { $stable: !hasDynamicKeys };\n        for (var i = 0; i < fns.length; i++) {\n            var slot = fns[i];\n            if (Array.isArray(slot)) {\n                resolveScopedSlots(slot, res, hasDynamicKeys);\n            } else if (slot) {\n                // marker for reverse proxying v-slot without scope on this.$slots\n                if (slot.proxy) {\n                    slot.fn.proxy = true;\n                }\n                res[slot.key] = slot.fn;\n            }\n        }\n        if (contentHashKey) {\n            (res).$key = contentHashKey;\n        }\n        return res\n    }\n\n    /*  */\n\n    function bindDynamicKeys (baseObj, values) {\n        for (var i = 0; i < values.length; i += 2) {\n            var key = values[i];\n            if (typeof key === 'string' && key) {\n                baseObj[values[i]] = values[i + 1];\n            } else if (key !== '' && key !== null) {\n                // null is a special value for explicitly removing a binding\n                warn(\n                    (\"Invalid value for dynamic directive argument (expected string or null): \" + key),\n                    this\n                );\n            }\n        }\n        return baseObj\n    }\n\n    // helper to dynamically append modifier runtime markers to event names.\n    // ensure only append when value is already string, otherwise it will be cast\n    // to string and cause the type check to miss.\n    function prependModifier (value, symbol) {\n        return typeof value === 'string' ? symbol + value : value\n    }\n\n    /*  */\n\n    function installRenderHelpers (target) {\n        target._o = markOnce;\n        target._n = toNumber;\n        target._s = toString;\n        target._l = renderList;\n        target._t = renderSlot;\n        target._q = looseEqual;\n        target._i = looseIndexOf;\n        target._m = renderStatic;\n        target._f = resolveFilter;\n        target._k = checkKeyCodes;\n        target._b = bindObjectProps;\n        target._v = createTextVNode;\n        target._e = createEmptyVNode;\n        target._u = resolveScopedSlots;\n        target._g = bindObjectListeners;\n        target._d = bindDynamicKeys;\n        target._p = prependModifier;\n    }\n\n    /*  */\n\n    function FunctionalRenderContext (\n        data,\n        props,\n        children,\n        parent,\n        Ctor\n    ) {\n        var this$1 = this;\n\n        var options = Ctor.options;\n        // ensure the createElement function in functional components\n        // gets a unique context - this is necessary for correct named slot check\n        var contextVm;\n        if (hasOwn(parent, '_uid')) {\n            contextVm = Object.create(parent);\n            // $flow-disable-line\n            contextVm._original = parent;\n        } else {\n            // the context vm passed in is a functional context as well.\n            // in this case we want to make sure we are able to get a hold to the\n            // real context instance.\n            contextVm = parent;\n            // $flow-disable-line\n            parent = parent._original;\n        }\n        var isCompiled = isTrue(options._compiled);\n        var needNormalization = !isCompiled;\n\n        this.data = data;\n        this.props = props;\n        this.children = children;\n        this.parent = parent;\n        this.listeners = data.on || emptyObject;\n        this.injections = resolveInject(options.inject, parent);\n        this.slots = function () {\n            if (!this$1.$slots) {\n                normalizeScopedSlots(\n                    data.scopedSlots,\n                    this$1.$slots = resolveSlots(children, parent)\n                );\n            }\n            return this$1.$slots\n        };\n\n        Object.defineProperty(this, 'scopedSlots', ({\n            enumerable: true,\n            get: function get () {\n                return normalizeScopedSlots(data.scopedSlots, this.slots())\n            }\n        }));\n\n        // support for compiled functional template\n        if (isCompiled) {\n            // exposing $options for renderStatic()\n            this.$options = options;\n            // pre-resolve slots for renderSlot()\n            this.$slots = this.slots();\n            this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots);\n        }\n\n        if (options._scopeId) {\n            this._c = function (a, b, c, d) {\n                var vnode = createElement(contextVm, a, b, c, d, needNormalization);\n                if (vnode && !Array.isArray(vnode)) {\n                    vnode.fnScopeId = options._scopeId;\n                    vnode.fnContext = parent;\n                }\n                return vnode\n            };\n        } else {\n            this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); };\n        }\n    }\n\n    installRenderHelpers(FunctionalRenderContext.prototype);\n\n    function createFunctionalComponent (\n        Ctor,\n        propsData,\n        data,\n        contextVm,\n        children\n    ) {\n        var options = Ctor.options;\n        var props = {};\n        var propOptions = options.props;\n        if (isDef(propOptions)) {\n            for (var key in propOptions) {\n                props[key] = validateProp(key, propOptions, propsData || emptyObject);\n            }\n        } else {\n            if (isDef(data.attrs)) { mergeProps(props, data.attrs); }\n            if (isDef(data.props)) { mergeProps(props, data.props); }\n        }\n\n        var renderContext = new FunctionalRenderContext(\n            data,\n            props,\n            children,\n            contextVm,\n            Ctor\n        );\n\n        var vnode = options.render.call(null, renderContext._c, renderContext);\n\n        if (vnode instanceof VNode) {\n            return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext)\n        } else if (Array.isArray(vnode)) {\n            var vnodes = normalizeChildren(vnode) || [];\n            var res = new Array(vnodes.length);\n            for (var i = 0; i < vnodes.length; i++) {\n                res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);\n            }\n            return res\n        }\n    }\n\n    function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) {\n        // #7817 clone node before setting fnContext, otherwise if the node is reused\n        // (e.g. it was from a cached normal slot) the fnContext causes named slots\n        // that should not be matched to match.\n        var clone = cloneVNode(vnode);\n        clone.fnContext = contextVm;\n        clone.fnOptions = options;\n        {\n            (clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext;\n        }\n        if (data.slot) {\n            (clone.data || (clone.data = {})).slot = data.slot;\n        }\n        return clone\n    }\n\n    function mergeProps (to, from) {\n        for (var key in from) {\n            to[camelize(key)] = from[key];\n        }\n    }\n\n    /*  */\n\n    /*  */\n\n    /*  */\n\n    /*  */\n\n    // inline hooks to be invoked on component VNodes during patch\n    var componentVNodeHooks = {\n        init: function init (vnode, hydrating) {\n            if (\n                vnode.componentInstance &&\n                !vnode.componentInstance._isDestroyed &&\n                vnode.data.keepAlive\n            ) {\n                // kept-alive components, treat as a patch\n                var mountedNode = vnode; // work around flow\n                componentVNodeHooks.prepatch(mountedNode, mountedNode);\n            } else {\n                var child = vnode.componentInstance = createComponentInstanceForVnode(\n                    vnode,\n                    activeInstance\n                );\n                child.$mount(hydrating ? vnode.elm : undefined, hydrating);\n            }\n        },\n\n        prepatch: function prepatch (oldVnode, vnode) {\n            var options = vnode.componentOptions;\n            var child = vnode.componentInstance = oldVnode.componentInstance;\n            updateChildComponent(\n                child,\n                options.propsData, // updated props\n                options.listeners, // updated listeners\n                vnode, // new parent vnode\n                options.children // new children\n            );\n        },\n\n        insert: function insert (vnode) {\n            var context = vnode.context;\n            var componentInstance = vnode.componentInstance;\n            if (!componentInstance._isMounted) {\n                componentInstance._isMounted = true;\n                callHook(componentInstance, 'mounted');\n            }\n            if (vnode.data.keepAlive) {\n                if (context._isMounted) {\n                    // vue-router#1212\n                    // During updates, a kept-alive component's child components may\n                    // change, so directly walking the tree here may call activated hooks\n                    // on incorrect children. Instead we push them into a queue which will\n                    // be processed after the whole patch process ended.\n                    queueActivatedComponent(componentInstance);\n                } else {\n                    activateChildComponent(componentInstance, true /* direct */);\n                }\n            }\n        },\n\n        destroy: function destroy (vnode) {\n            var componentInstance = vnode.componentInstance;\n            if (!componentInstance._isDestroyed) {\n                if (!vnode.data.keepAlive) {\n                    componentInstance.$destroy();\n                } else {\n                    deactivateChildComponent(componentInstance, true /* direct */);\n                }\n            }\n        }\n    };\n\n    var hooksToMerge = Object.keys(componentVNodeHooks);\n\n    function createComponent (\n        Ctor,\n        data,\n        context,\n        children,\n        tag\n    ) {\n        if (isUndef(Ctor)) {\n            return\n        }\n\n        var baseCtor = context.$options._base;\n\n        // plain options object: turn it into a constructor\n        if (isObject(Ctor)) {\n            Ctor = baseCtor.extend(Ctor);\n        }\n\n        // if at this stage it's not a constructor or an async component factory,\n        // reject.\n        if (typeof Ctor !== 'function') {\n            {\n                warn((\"Invalid Component definition: \" + (String(Ctor))), context);\n            }\n            return\n        }\n\n        // async component\n        var asyncFactory;\n        if (isUndef(Ctor.cid)) {\n            asyncFactory = Ctor;\n            Ctor = resolveAsyncComponent(asyncFactory, baseCtor);\n            if (Ctor === undefined) {\n                // return a placeholder node for async component, which is rendered\n                // as a comment node but preserves all the raw information for the node.\n                // the information will be used for async server-rendering and hydration.\n                return createAsyncPlaceholder(\n                    asyncFactory,\n                    data,\n                    context,\n                    children,\n                    tag\n                )\n            }\n        }\n\n        data = data || {};\n\n        // resolve constructor options in case global mixins are applied after\n        // component constructor creation\n        resolveConstructorOptions(Ctor);\n\n        // transform component v-model data into props & events\n        if (isDef(data.model)) {\n            transformModel(Ctor.options, data);\n        }\n\n        // extract props\n        var propsData = extractPropsFromVNodeData(data, Ctor, tag);\n\n        // functional component\n        if (isTrue(Ctor.options.functional)) {\n            return createFunctionalComponent(Ctor, propsData, data, context, children)\n        }\n\n        // extract listeners, since these needs to be treated as\n        // child component listeners instead of DOM listeners\n        var listeners = data.on;\n        // replace with listeners with .native modifier\n        // so it gets processed during parent component patch.\n        data.on = data.nativeOn;\n\n        if (isTrue(Ctor.options.abstract)) {\n            // abstract components do not keep anything\n            // other than props & listeners & slot\n\n            // work around flow\n            var slot = data.slot;\n            data = {};\n            if (slot) {\n                data.slot = slot;\n            }\n        }\n\n        // install component management hooks onto the placeholder node\n        installComponentHooks(data);\n\n        // return a placeholder vnode\n        var name = Ctor.options.name || tag;\n        var vnode = new VNode(\n            (\"vue-component-\" + (Ctor.cid) + (name ? (\"-\" + name) : '')),\n            data, undefined, undefined, undefined, context,\n            { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },\n            asyncFactory\n        );\n\n        return vnode\n    }\n\n    function createComponentInstanceForVnode (\n        // we know it's MountedComponentVNode but flow doesn't\n        vnode,\n        // activeInstance in lifecycle state\n        parent\n    ) {\n        var options = {\n            _isComponent: true,\n            _parentVnode: vnode,\n            parent: parent\n        };\n        // check inline-template render functions\n        var inlineTemplate = vnode.data.inlineTemplate;\n        if (isDef(inlineTemplate)) {\n            options.render = inlineTemplate.render;\n            options.staticRenderFns = inlineTemplate.staticRenderFns;\n        }\n        return new vnode.componentOptions.Ctor(options)\n    }\n\n    function installComponentHooks (data) {\n        var hooks = data.hook || (data.hook = {});\n        for (var i = 0; i < hooksToMerge.length; i++) {\n            var key = hooksToMerge[i];\n            var existing = hooks[key];\n            var toMerge = componentVNodeHooks[key];\n            if (existing !== toMerge && !(existing && existing._merged)) {\n                hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge;\n            }\n        }\n    }\n\n    function mergeHook$1 (f1, f2) {\n        var merged = function (a, b) {\n            // flow complains about extra args which is why we use any\n            f1(a, b);\n            f2(a, b);\n        };\n        merged._merged = true;\n        return merged\n    }\n\n    // transform component v-model info (value and callback) into\n    // prop and event handler respectively.\n    function transformModel (options, data) {\n        var prop = (options.model && options.model.prop) || 'value';\n        var event = (options.model && options.model.event) || 'input'\n        ;(data.attrs || (data.attrs = {}))[prop] = data.model.value;\n        var on = data.on || (data.on = {});\n        var existing = on[event];\n        var callback = data.model.callback;\n        if (isDef(existing)) {\n            if (\n                Array.isArray(existing)\n                    ? existing.indexOf(callback) === -1\n                    : existing !== callback\n            ) {\n                on[event] = [callback].concat(existing);\n            }\n        } else {\n            on[event] = callback;\n        }\n    }\n\n    /*  */\n\n    var SIMPLE_NORMALIZE = 1;\n    var ALWAYS_NORMALIZE = 2;\n\n    // wrapper function for providing a more flexible interface\n    // without getting yelled at by flow\n    function createElement (\n        context,\n        tag,\n        data,\n        children,\n        normalizationType,\n        alwaysNormalize\n    ) {\n        if (Array.isArray(data) || isPrimitive(data)) {\n            normalizationType = children;\n            children = data;\n            data = undefined;\n        }\n        if (isTrue(alwaysNormalize)) {\n            normalizationType = ALWAYS_NORMALIZE;\n        }\n        return _createElement(context, tag, data, children, normalizationType)\n    }\n\n    function _createElement (\n        context,\n        tag,\n        data,\n        children,\n        normalizationType\n    ) {\n        if (isDef(data) && isDef((data).__ob__)) {\n            warn(\n                \"Avoid using observed data object as vnode data: \" + (JSON.stringify(data)) + \"\\n\" +\n                'Always create fresh vnode data objects in each render!',\n                context\n            );\n            return createEmptyVNode()\n        }\n        // object syntax in v-bind\n        if (isDef(data) && isDef(data.is)) {\n            tag = data.is;\n        }\n        if (!tag) {\n            // in case of component :is set to falsy value\n            return createEmptyVNode()\n        }\n        // warn against non-primitive key\n        if (isDef(data) && isDef(data.key) && !isPrimitive(data.key)\n        ) {\n            {\n                warn(\n                    'Avoid using non-primitive value as key, ' +\n                    'use string/number value instead.',\n                    context\n                );\n            }\n        }\n        // support single function children as default scoped slot\n        if (Array.isArray(children) &&\n            typeof children[0] === 'function'\n        ) {\n            data = data || {};\n            data.scopedSlots = { default: children[0] };\n            children.length = 0;\n        }\n        if (normalizationType === ALWAYS_NORMALIZE) {\n            children = normalizeChildren(children);\n        } else if (normalizationType === SIMPLE_NORMALIZE) {\n            children = simpleNormalizeChildren(children);\n        }\n        var vnode, ns;\n        if (typeof tag === 'string') {\n            var Ctor;\n            ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);\n            if (config.isReservedTag(tag)) {\n                // platform built-in elements\n                if (isDef(data) && isDef(data.nativeOn) && data.tag !== 'component') {\n                    warn(\n                        (\"The .native modifier for v-on is only valid on components but it was used on <\" + tag + \">.\"),\n                        context\n                    );\n                }\n                vnode = new VNode(\n                    config.parsePlatformTagName(tag), data, children,\n                    undefined, undefined, context\n                );\n            } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {\n                // component\n                vnode = createComponent(Ctor, data, context, children, tag);\n            } else {\n                // unknown or unlisted namespaced elements\n                // check at runtime because it may get assigned a namespace when its\n                // parent normalizes children\n                vnode = new VNode(\n                    tag, data, children,\n                    undefined, undefined, context\n                );\n            }\n        } else {\n            // direct component options / constructor\n            vnode = createComponent(tag, data, context, children);\n        }\n        if (Array.isArray(vnode)) {\n            return vnode\n        } else if (isDef(vnode)) {\n            if (isDef(ns)) { applyNS(vnode, ns); }\n            if (isDef(data)) { registerDeepBindings(data); }\n            return vnode\n        } else {\n            return createEmptyVNode()\n        }\n    }\n\n    function applyNS (vnode, ns, force) {\n        vnode.ns = ns;\n        if (vnode.tag === 'foreignObject') {\n            // use default namespace inside foreignObject\n            ns = undefined;\n            force = true;\n        }\n        if (isDef(vnode.children)) {\n            for (var i = 0, l = vnode.children.length; i < l; i++) {\n                var child = vnode.children[i];\n                if (isDef(child.tag) && (\n                    isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {\n                    applyNS(child, ns, force);\n                }\n            }\n        }\n    }\n\n    // ref #5318\n    // necessary to ensure parent re-render when deep bindings like :style and\n    // :class are used on slot nodes\n    function registerDeepBindings (data) {\n        if (isObject(data.style)) {\n            traverse(data.style);\n        }\n        if (isObject(data.class)) {\n            traverse(data.class);\n        }\n    }\n\n    /*  */\n\n    function initRender (vm) {\n        vm._vnode = null; // the root of the child tree\n        vm._staticTrees = null; // v-once cached trees\n        var options = vm.$options;\n        var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree\n        var renderContext = parentVnode && parentVnode.context;\n        vm.$slots = resolveSlots(options._renderChildren, renderContext);\n        vm.$scopedSlots = emptyObject;\n        // bind the createElement fn to this instance\n        // so that we get proper render context inside it.\n        // args order: tag, data, children, normalizationType, alwaysNormalize\n        // internal version is used by render functions compiled from templates\n        vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };\n        // normalization is always applied for the public version, used in\n        // user-written render functions.\n        vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };\n\n        // $attrs & $listeners are exposed for easier HOC creation.\n        // they need to be reactive so that HOCs using them are always updated\n        var parentData = parentVnode && parentVnode.data;\n\n        /* istanbul ignore else */\n        {\n            defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () {\n                !isUpdatingChildComponent && warn(\"$attrs is readonly.\", vm);\n            }, true);\n            defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () {\n                !isUpdatingChildComponent && warn(\"$listeners is readonly.\", vm);\n            }, true);\n        }\n    }\n\n    var currentRenderingInstance = null;\n\n    function renderMixin (Vue) {\n        // install runtime convenience helpers\n        installRenderHelpers(Vue.prototype);\n\n        Vue.prototype.$nextTick = function (fn) {\n            return nextTick(fn, this)\n        };\n\n        Vue.prototype._render = function () {\n            var vm = this;\n            var ref = vm.$options;\n            var render = ref.render;\n            var _parentVnode = ref._parentVnode;\n\n            if (_parentVnode) {\n                vm.$scopedSlots = normalizeScopedSlots(\n                    _parentVnode.data.scopedSlots,\n                    vm.$slots,\n                    vm.$scopedSlots\n                );\n            }\n\n            // set parent vnode. this allows render functions to have access\n            // to the data on the placeholder node.\n            vm.$vnode = _parentVnode;\n            // render self\n            var vnode;\n            try {\n                // There's no need to maintain a stack because all render fns are called\n                // separately from one another. Nested component's render fns are called\n                // when parent component is patched.\n                currentRenderingInstance = vm;\n                vnode = render.call(vm._renderProxy, vm.$createElement);\n            } catch (e) {\n                handleError(e, vm, \"render\");\n                // return error render result,\n                // or previous vnode to prevent render error causing blank component\n                /* istanbul ignore else */\n                if (vm.$options.renderError) {\n                    try {\n                        vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e);\n                    } catch (e) {\n                        handleError(e, vm, \"renderError\");\n                        vnode = vm._vnode;\n                    }\n                } else {\n                    vnode = vm._vnode;\n                }\n            } finally {\n                currentRenderingInstance = null;\n            }\n            // if the returned array contains only a single node, allow it\n            if (Array.isArray(vnode) && vnode.length === 1) {\n                vnode = vnode[0];\n            }\n            // return empty vnode in case the render function errored out\n            if (!(vnode instanceof VNode)) {\n                if (Array.isArray(vnode)) {\n                    warn(\n                        'Multiple root nodes returned from render function. Render function ' +\n                        'should return a single root node.',\n                        vm\n                    );\n                }\n                vnode = createEmptyVNode();\n            }\n            // set parent\n            vnode.parent = _parentVnode;\n            return vnode\n        };\n    }\n\n    /*  */\n\n    function ensureCtor (comp, base) {\n        if (\n            comp.__esModule ||\n            (hasSymbol && comp[Symbol.toStringTag] === 'Module')\n        ) {\n            comp = comp.default;\n        }\n        return isObject(comp)\n            ? base.extend(comp)\n            : comp\n    }\n\n    function createAsyncPlaceholder (\n        factory,\n        data,\n        context,\n        children,\n        tag\n    ) {\n        var node = createEmptyVNode();\n        node.asyncFactory = factory;\n        node.asyncMeta = { data: data, context: context, children: children, tag: tag };\n        return node\n    }\n\n    function resolveAsyncComponent (\n        factory,\n        baseCtor\n    ) {\n        if (isTrue(factory.error) && isDef(factory.errorComp)) {\n            return factory.errorComp\n        }\n\n        if (isDef(factory.resolved)) {\n            return factory.resolved\n        }\n\n        var owner = currentRenderingInstance;\n        if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) {\n            // already pending\n            factory.owners.push(owner);\n        }\n\n        if (isTrue(factory.loading) && isDef(factory.loadingComp)) {\n            return factory.loadingComp\n        }\n\n        if (owner && !isDef(factory.owners)) {\n            var owners = factory.owners = [owner];\n            var sync = true;\n            var timerLoading = null;\n            var timerTimeout = null\n\n            ;(owner).$on('hook:destroyed', function () { return remove(owners, owner); });\n\n            var forceRender = function (renderCompleted) {\n                for (var i = 0, l = owners.length; i < l; i++) {\n                    (owners[i]).$forceUpdate();\n                }\n\n                if (renderCompleted) {\n                    owners.length = 0;\n                    if (timerLoading !== null) {\n                        clearTimeout(timerLoading);\n                        timerLoading = null;\n                    }\n                    if (timerTimeout !== null) {\n                        clearTimeout(timerTimeout);\n                        timerTimeout = null;\n                    }\n                }\n            };\n\n            var resolve = once(function (res) {\n                // cache resolved\n                factory.resolved = ensureCtor(res, baseCtor);\n                // invoke callbacks only if this is not a synchronous resolve\n                // (async resolves are shimmed as synchronous during SSR)\n                if (!sync) {\n                    forceRender(true);\n                } else {\n                    owners.length = 0;\n                }\n            });\n\n            var reject = once(function (reason) {\n                warn(\n                    \"Failed to resolve async component: \" + (String(factory)) +\n                    (reason ? (\"\\nReason: \" + reason) : '')\n                );\n                if (isDef(factory.errorComp)) {\n                    factory.error = true;\n                    forceRender(true);\n                }\n            });\n\n            var res = factory(resolve, reject);\n\n            if (isObject(res)) {\n                if (isPromise(res)) {\n                    // () => Promise\n                    if (isUndef(factory.resolved)) {\n                        res.then(resolve, reject);\n                    }\n                } else if (isPromise(res.component)) {\n                    res.component.then(resolve, reject);\n\n                    if (isDef(res.error)) {\n                        factory.errorComp = ensureCtor(res.error, baseCtor);\n                    }\n\n                    if (isDef(res.loading)) {\n                        factory.loadingComp = ensureCtor(res.loading, baseCtor);\n                        if (res.delay === 0) {\n                            factory.loading = true;\n                        } else {\n                            timerLoading = setTimeout(function () {\n                                timerLoading = null;\n                                if (isUndef(factory.resolved) && isUndef(factory.error)) {\n                                    factory.loading = true;\n                                    forceRender(false);\n                                }\n                            }, res.delay || 200);\n                        }\n                    }\n\n                    if (isDef(res.timeout)) {\n                        timerTimeout = setTimeout(function () {\n                            timerTimeout = null;\n                            if (isUndef(factory.resolved)) {\n                                reject(\n                                    \"timeout (\" + (res.timeout) + \"ms)\"\n                                );\n                            }\n                        }, res.timeout);\n                    }\n                }\n            }\n\n            sync = false;\n            // return in case resolved synchronously\n            return factory.loading\n                ? factory.loadingComp\n                : factory.resolved\n        }\n    }\n\n    /*  */\n\n    function getFirstComponentChild (children) {\n        if (Array.isArray(children)) {\n            for (var i = 0; i < children.length; i++) {\n                var c = children[i];\n                if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {\n                    return c\n                }\n            }\n        }\n    }\n\n    /*  */\n\n    /*  */\n\n    function initEvents (vm) {\n        vm._events = Object.create(null);\n        vm._hasHookEvent = false;\n        // init parent attached events\n        var listeners = vm.$options._parentListeners;\n        if (listeners) {\n            updateComponentListeners(vm, listeners);\n        }\n    }\n\n    var target;\n\n    function add (event, fn) {\n        target.$on(event, fn);\n    }\n\n    function remove$1 (event, fn) {\n        target.$off(event, fn);\n    }\n\n    function createOnceHandler (event, fn) {\n        var _target = target;\n        return function onceHandler () {\n            var res = fn.apply(null, arguments);\n            if (res !== null) {\n                _target.$off(event, onceHandler);\n            }\n        }\n    }\n\n    function updateComponentListeners (\n        vm,\n        listeners,\n        oldListeners\n    ) {\n        target = vm;\n        updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm);\n        target = undefined;\n    }\n\n    function eventsMixin (Vue) {\n        var hookRE = /^hook:/;\n        Vue.prototype.$on = function (event, fn) {\n            var vm = this;\n            if (Array.isArray(event)) {\n                for (var i = 0, l = event.length; i < l; i++) {\n                    vm.$on(event[i], fn);\n                }\n            } else {\n                (vm._events[event] || (vm._events[event] = [])).push(fn);\n                // optimize hook:event cost by using a boolean flag marked at registration\n                // instead of a hash lookup\n                if (hookRE.test(event)) {\n                    vm._hasHookEvent = true;\n                }\n            }\n            return vm\n        };\n\n        Vue.prototype.$once = function (event, fn) {\n            var vm = this;\n            function on () {\n                vm.$off(event, on);\n                fn.apply(vm, arguments);\n            }\n            on.fn = fn;\n            vm.$on(event, on);\n            return vm\n        };\n\n        Vue.prototype.$off = function (event, fn) {\n            var vm = this;\n            // all\n            if (!arguments.length) {\n                vm._events = Object.create(null);\n                return vm\n            }\n            // array of events\n            if (Array.isArray(event)) {\n                for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {\n                    vm.$off(event[i$1], fn);\n                }\n                return vm\n            }\n            // specific event\n            var cbs = vm._events[event];\n            if (!cbs) {\n                return vm\n            }\n            if (!fn) {\n                vm._events[event] = null;\n                return vm\n            }\n            // specific handler\n            var cb;\n            var i = cbs.length;\n            while (i--) {\n                cb = cbs[i];\n                if (cb === fn || cb.fn === fn) {\n                    cbs.splice(i, 1);\n                    break\n                }\n            }\n            return vm\n        };\n\n        Vue.prototype.$emit = function (event) {\n            var vm = this;\n            {\n                var lowerCaseEvent = event.toLowerCase();\n                if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {\n                    tip(\n                        \"Event \\\"\" + lowerCaseEvent + \"\\\" is emitted in component \" +\n                        (formatComponentName(vm)) + \" but the handler is registered for \\\"\" + event + \"\\\". \" +\n                        \"Note that HTML attributes are case-insensitive and you cannot use \" +\n                        \"v-on to listen to camelCase events when using in-DOM templates. \" +\n                        \"You should probably use \\\"\" + (hyphenate(event)) + \"\\\" instead of \\\"\" + event + \"\\\".\"\n                    );\n                }\n            }\n            var cbs = vm._events[event];\n            if (cbs) {\n                cbs = cbs.length > 1 ? toArray(cbs) : cbs;\n                var args = toArray(arguments, 1);\n                var info = \"event handler for \\\"\" + event + \"\\\"\";\n                for (var i = 0, l = cbs.length; i < l; i++) {\n                    invokeWithErrorHandling(cbs[i], vm, args, vm, info);\n                }\n            }\n            return vm\n        };\n    }\n\n    /*  */\n\n    var activeInstance = null;\n    var isUpdatingChildComponent = false;\n\n    function setActiveInstance(vm) {\n        var prevActiveInstance = activeInstance;\n        activeInstance = vm;\n        return function () {\n            activeInstance = prevActiveInstance;\n        }\n    }\n\n    function initLifecycle (vm) {\n        var options = vm.$options;\n\n        // locate first non-abstract parent\n        var parent = options.parent;\n        if (parent && !options.abstract) {\n            while (parent.$options.abstract && parent.$parent) {\n                parent = parent.$parent;\n            }\n            parent.$children.push(vm);\n        }\n\n        vm.$parent = parent;\n        vm.$root = parent ? parent.$root : vm;\n\n        vm.$children = [];\n        vm.$refs = {};\n\n        vm._watcher = null;\n        vm._inactive = null;\n        vm._directInactive = false;\n        vm._isMounted = false;\n        vm._isDestroyed = false;\n        vm._isBeingDestroyed = false;\n    }\n\n    function lifecycleMixin (Vue) {\n        Vue.prototype._update = function (vnode, hydrating) {\n            var vm = this;\n            var prevEl = vm.$el;\n            var prevVnode = vm._vnode;\n            var restoreActiveInstance = setActiveInstance(vm);\n            vm._vnode = vnode;\n            // Vue.prototype.__patch__ is injected in entry points\n            // based on the rendering backend used.\n            if (!prevVnode) {\n                // initial render\n                vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */);\n            } else {\n                // updates\n                vm.$el = vm.__patch__(prevVnode, vnode);\n            }\n            restoreActiveInstance();\n            // update __vue__ reference\n            if (prevEl) {\n                prevEl.__vue__ = null;\n            }\n            if (vm.$el) {\n                vm.$el.__vue__ = vm;\n            }\n            // if parent is an HOC, update its $el as well\n            if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {\n                vm.$parent.$el = vm.$el;\n            }\n            // updated hook is called by the scheduler to ensure that children are\n            // updated in a parent's updated hook.\n        };\n\n        Vue.prototype.$forceUpdate = function () {\n            var vm = this;\n            if (vm._watcher) {\n                vm._watcher.update();\n            }\n        };\n\n        Vue.prototype.$destroy = function () {\n            var vm = this;\n            if (vm._isBeingDestroyed) {\n                return\n            }\n            callHook(vm, 'beforeDestroy');\n            vm._isBeingDestroyed = true;\n            // remove self from parent\n            var parent = vm.$parent;\n            if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {\n                remove(parent.$children, vm);\n            }\n            // teardown watchers\n            if (vm._watcher) {\n                vm._watcher.teardown();\n            }\n            var i = vm._watchers.length;\n            while (i--) {\n                vm._watchers[i].teardown();\n            }\n            // remove reference from data ob\n            // frozen object may not have observer.\n            if (vm._data.__ob__) {\n                vm._data.__ob__.vmCount--;\n            }\n            // call the last hook...\n            vm._isDestroyed = true;\n            // invoke destroy hooks on current rendered tree\n            vm.__patch__(vm._vnode, null);\n            // fire destroyed hook\n            callHook(vm, 'destroyed');\n            // turn off all instance listeners.\n            vm.$off();\n            // remove __vue__ reference\n            if (vm.$el) {\n                vm.$el.__vue__ = null;\n            }\n            // release circular reference (#6759)\n            if (vm.$vnode) {\n                vm.$vnode.parent = null;\n            }\n        };\n    }\n\n    function mountComponent (\n        vm,\n        el,\n        hydrating\n    ) {\n        vm.$el = el;\n        if (!vm.$options.render) {\n            vm.$options.render = createEmptyVNode;\n            {\n                /* istanbul ignore if */\n                if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||\n                    vm.$options.el || el) {\n                    warn(\n                        'You are using the runtime-only build of Vue where the template ' +\n                        'compiler is not available. Either pre-compile the templates into ' +\n                        'render functions, or use the compiler-included build.',\n                        vm\n                    );\n                } else {\n                    warn(\n                        'Failed to mount component: template or render function not defined.',\n                        vm\n                    );\n                }\n            }\n        }\n        callHook(vm, 'beforeMount');\n\n        var updateComponent;\n        /* istanbul ignore if */\n        if (config.performance && mark) {\n            updateComponent = function () {\n                var name = vm._name;\n                var id = vm._uid;\n                var startTag = \"vue-perf-start:\" + id;\n                var endTag = \"vue-perf-end:\" + id;\n\n                mark(startTag);\n                var vnode = vm._render();\n                mark(endTag);\n                measure((\"vue \" + name + \" render\"), startTag, endTag);\n\n                mark(startTag);\n                vm._update(vnode, hydrating);\n                mark(endTag);\n                measure((\"vue \" + name + \" patch\"), startTag, endTag);\n            };\n        } else {\n            updateComponent = function () {\n                vm._update(vm._render(), hydrating);\n            };\n        }\n\n        // we set this to vm._watcher inside the watcher's constructor\n        // since the watcher's initial patch may call $forceUpdate (e.g. inside child\n        // component's mounted hook), which relies on vm._watcher being already defined\n        new Watcher(vm, updateComponent, noop, {\n            before: function before () {\n                if (vm._isMounted && !vm._isDestroyed) {\n                    callHook(vm, 'beforeUpdate');\n                }\n            }\n        }, true /* isRenderWatcher */);\n        hydrating = false;\n\n        // manually mounted instance, call mounted on self\n        // mounted is called for render-created child components in its inserted hook\n        if (vm.$vnode == null) {\n            vm._isMounted = true;\n            callHook(vm, 'mounted');\n        }\n        return vm\n    }\n\n    function updateChildComponent (\n        vm,\n        propsData,\n        listeners,\n        parentVnode,\n        renderChildren\n    ) {\n        {\n            isUpdatingChildComponent = true;\n        }\n\n        // determine whether component has slot children\n        // we need to do this before overwriting $options._renderChildren.\n\n        // check if there are dynamic scopedSlots (hand-written or compiled but with\n        // dynamic slot names). Static scoped slots compiled from template has the\n        // \"$stable\" marker.\n        var newScopedSlots = parentVnode.data.scopedSlots;\n        var oldScopedSlots = vm.$scopedSlots;\n        var hasDynamicScopedSlot = !!(\n            (newScopedSlots && !newScopedSlots.$stable) ||\n            (oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) ||\n            (newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key) ||\n            (!newScopedSlots && vm.$scopedSlots.$key)\n        );\n\n        // Any static slot children from the parent may have changed during parent's\n        // update. Dynamic scoped slots may also have changed. In such cases, a forced\n        // update is necessary to ensure correctness.\n        var needsForceUpdate = !!(\n            renderChildren ||               // has new static slots\n            vm.$options._renderChildren ||  // has old static slots\n            hasDynamicScopedSlot\n        );\n\n        vm.$options._parentVnode = parentVnode;\n        vm.$vnode = parentVnode; // update vm's placeholder node without re-render\n\n        if (vm._vnode) { // update child tree's parent\n            vm._vnode.parent = parentVnode;\n        }\n        vm.$options._renderChildren = renderChildren;\n\n        // update $attrs and $listeners hash\n        // these are also reactive so they may trigger child update if the child\n        // used them during render\n        vm.$attrs = parentVnode.data.attrs || emptyObject;\n        vm.$listeners = listeners || emptyObject;\n\n        // update props\n        if (propsData && vm.$options.props) {\n            toggleObserving(false);\n            var props = vm._props;\n            var propKeys = vm.$options._propKeys || [];\n            for (var i = 0; i < propKeys.length; i++) {\n                var key = propKeys[i];\n                var propOptions = vm.$options.props; // wtf flow?\n                props[key] = validateProp(key, propOptions, propsData, vm);\n            }\n            toggleObserving(true);\n            // keep a copy of raw propsData\n            vm.$options.propsData = propsData;\n        }\n\n        // update listeners\n        listeners = listeners || emptyObject;\n        var oldListeners = vm.$options._parentListeners;\n        vm.$options._parentListeners = listeners;\n        updateComponentListeners(vm, listeners, oldListeners);\n\n        // resolve slots + force update if has children\n        if (needsForceUpdate) {\n            vm.$slots = resolveSlots(renderChildren, parentVnode.context);\n            vm.$forceUpdate();\n        }\n\n        {\n            isUpdatingChildComponent = false;\n        }\n    }\n\n    function isInInactiveTree (vm) {\n        while (vm && (vm = vm.$parent)) {\n            if (vm._inactive) { return true }\n        }\n        return false\n    }\n\n    function activateChildComponent (vm, direct) {\n        if (direct) {\n            vm._directInactive = false;\n            if (isInInactiveTree(vm)) {\n                return\n            }\n        } else if (vm._directInactive) {\n            return\n        }\n        if (vm._inactive || vm._inactive === null) {\n            vm._inactive = false;\n            for (var i = 0; i < vm.$children.length; i++) {\n                activateChildComponent(vm.$children[i]);\n            }\n            callHook(vm, 'activated');\n        }\n    }\n\n    function deactivateChildComponent (vm, direct) {\n        if (direct) {\n            vm._directInactive = true;\n            if (isInInactiveTree(vm)) {\n                return\n            }\n        }\n        if (!vm._inactive) {\n            vm._inactive = true;\n            for (var i = 0; i < vm.$children.length; i++) {\n                deactivateChildComponent(vm.$children[i]);\n            }\n            callHook(vm, 'deactivated');\n        }\n    }\n\n    function callHook (vm, hook) {\n        // #7573 disable dep collection when invoking lifecycle hooks\n        pushTarget();\n        var handlers = vm.$options[hook];\n        var info = hook + \" hook\";\n        if (handlers) {\n            for (var i = 0, j = handlers.length; i < j; i++) {\n                invokeWithErrorHandling(handlers[i], vm, null, vm, info);\n            }\n        }\n        if (vm._hasHookEvent) {\n            vm.$emit('hook:' + hook);\n        }\n        popTarget();\n    }\n\n    /*  */\n\n    var MAX_UPDATE_COUNT = 100;\n\n    var queue = [];\n    var activatedChildren = [];\n    var has = {};\n    var circular = {};\n    var waiting = false;\n    var flushing = false;\n    var index = 0;\n\n    /**\n     * Reset the scheduler's state.\n     */\n    function resetSchedulerState () {\n        index = queue.length = activatedChildren.length = 0;\n        has = {};\n        {\n            circular = {};\n        }\n        waiting = flushing = false;\n    }\n\n    // Async edge case #6566 requires saving the timestamp when event listeners are\n    // attached. However, calling performance.now() has a perf overhead especially\n    // if the page has thousands of event listeners. Instead, we take a timestamp\n    // every time the scheduler flushes and use that for all event listeners\n    // attached during that flush.\n    var currentFlushTimestamp = 0;\n\n    // Async edge case fix requires storing an event listener's attach timestamp.\n    var getNow = Date.now;\n\n    // Determine what event timestamp the browser is using. Annoyingly, the\n    // timestamp can either be hi-res (relative to page load) or low-res\n    // (relative to UNIX epoch), so in order to compare time we have to use the\n    // same timestamp type when saving the flush timestamp.\n    // All IE versions use low-res event timestamps, and have problematic clock\n    // implementations (#9632)\n    if (inBrowser && !isIE) {\n        var performance = window.performance;\n        if (\n            performance &&\n            typeof performance.now === 'function' &&\n            getNow() > document.createEvent('Event').timeStamp\n        ) {\n            // if the event timestamp, although evaluated AFTER the Date.now(), is\n            // smaller than it, it means the event is using a hi-res timestamp,\n            // and we need to use the hi-res version for event listener timestamps as\n            // well.\n            getNow = function () { return performance.now(); };\n        }\n    }\n\n    /**\n     * Flush both queues and run the watchers.\n     */\n    function flushSchedulerQueue () {\n        currentFlushTimestamp = getNow();\n        flushing = true;\n        var watcher, id;\n\n        // Sort queue before flush.\n        // This ensures that:\n        // 1. Components are updated from parent to child. (because parent is always\n        //    created before the child)\n        // 2. A component's user watchers are run before its render watcher (because\n        //    user watchers are created before the render watcher)\n        // 3. If a component is destroyed during a parent component's watcher run,\n        //    its watchers can be skipped.\n        queue.sort(function (a, b) { return a.id - b.id; });\n\n        // do not cache length because more watchers might be pushed\n        // as we run existing watchers\n        for (index = 0; index < queue.length; index++) {\n            watcher = queue[index];\n            if (watcher.before) {\n                watcher.before();\n            }\n            id = watcher.id;\n            has[id] = null;\n            watcher.run();\n            // in dev build, check and stop circular updates.\n            if (has[id] != null) {\n                circular[id] = (circular[id] || 0) + 1;\n                if (circular[id] > MAX_UPDATE_COUNT) {\n                    warn(\n                        'You may have an infinite update loop ' + (\n                            watcher.user\n                                ? (\"in watcher with expression \\\"\" + (watcher.expression) + \"\\\"\")\n                                : \"in a component render function.\"\n                        ),\n                        watcher.vm\n                    );\n                    break\n                }\n            }\n        }\n\n        // keep copies of post queues before resetting state\n        var activatedQueue = activatedChildren.slice();\n        var updatedQueue = queue.slice();\n\n        resetSchedulerState();\n\n        // call component updated and activated hooks\n        callActivatedHooks(activatedQueue);\n        callUpdatedHooks(updatedQueue);\n\n        // devtool hook\n        /* istanbul ignore if */\n        if (devtools && config.devtools) {\n            devtools.emit('flush');\n        }\n    }\n\n    function callUpdatedHooks (queue) {\n        var i = queue.length;\n        while (i--) {\n            var watcher = queue[i];\n            var vm = watcher.vm;\n            if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {\n                callHook(vm, 'updated');\n            }\n        }\n    }\n\n    /**\n     * Queue a kept-alive component that was activated during patch.\n     * The queue will be processed after the entire tree has been patched.\n     */\n    function queueActivatedComponent (vm) {\n        // setting _inactive to false here so that a render function can\n        // rely on checking whether it's in an inactive tree (e.g. router-view)\n        vm._inactive = false;\n        activatedChildren.push(vm);\n    }\n\n    function callActivatedHooks (queue) {\n        for (var i = 0; i < queue.length; i++) {\n            queue[i]._inactive = true;\n            activateChildComponent(queue[i], true /* true */);\n        }\n    }\n\n    /**\n     * Push a watcher into the watcher queue.\n     * Jobs with duplicate IDs will be skipped unless it's\n     * pushed when the queue is being flushed.\n     */\n    function queueWatcher (watcher) {\n        var id = watcher.id;\n        if (has[id] == null) {\n            has[id] = true;\n            if (!flushing) {\n                queue.push(watcher);\n            } else {\n                // if already flushing, splice the watcher based on its id\n                // if already past its id, it will be run next immediately.\n                var i = queue.length - 1;\n                while (i > index && queue[i].id > watcher.id) {\n                    i--;\n                }\n                queue.splice(i + 1, 0, watcher);\n            }\n            // queue the flush\n            if (!waiting) {\n                waiting = true;\n\n                if (!config.async) {\n                    flushSchedulerQueue();\n                    return\n                }\n                nextTick(flushSchedulerQueue);\n            }\n        }\n    }\n\n    /*  */\n\n\n\n    var uid$2 = 0;\n\n    /**\n     * A watcher parses an expression, collects dependencies,\n     * and fires callback when the expression value changes.\n     * This is used for both the $watch() api and directives.\n     */\n    var Watcher = function Watcher (\n        vm,\n        expOrFn,\n        cb,\n        options,\n        isRenderWatcher\n    ) {\n        this.vm = vm;\n        if (isRenderWatcher) {\n            vm._watcher = this;\n        }\n        vm._watchers.push(this);\n        // options\n        if (options) {\n            this.deep = !!options.deep;\n            this.user = !!options.user;\n            this.lazy = !!options.lazy;\n            this.sync = !!options.sync;\n            this.before = options.before;\n        } else {\n            this.deep = this.user = this.lazy = this.sync = false;\n        }\n        this.cb = cb;\n        this.id = ++uid$2; // uid for batching\n        this.active = true;\n        this.dirty = this.lazy; // for lazy watchers\n        this.deps = [];\n        this.newDeps = [];\n        this.depIds = new _Set();\n        this.newDepIds = new _Set();\n        this.expression = expOrFn.toString();\n        // parse expression for getter\n        if (typeof expOrFn === 'function') {\n            this.getter = expOrFn;\n        } else {\n            this.getter = parsePath(expOrFn);\n            if (!this.getter) {\n                this.getter = noop;\n                warn(\n                    \"Failed watching path: \\\"\" + expOrFn + \"\\\" \" +\n                    'Watcher only accepts simple dot-delimited paths. ' +\n                    'For full control, use a function instead.',\n                    vm\n                );\n            }\n        }\n        this.value = this.lazy\n            ? undefined\n            : this.get();\n    };\n\n    /**\n     * Evaluate the getter, and re-collect dependencies.\n     */\n    Watcher.prototype.get = function get () {\n        pushTarget(this);\n        var value;\n        var vm = this.vm;\n        try {\n            value = this.getter.call(vm, vm);\n        } catch (e) {\n            if (this.user) {\n                handleError(e, vm, (\"getter for watcher \\\"\" + (this.expression) + \"\\\"\"));\n            } else {\n                throw e\n            }\n        } finally {\n            // \"touch\" every property so they are all tracked as\n            // dependencies for deep watching\n            if (this.deep) {\n                traverse(value);\n            }\n            popTarget();\n            this.cleanupDeps();\n        }\n        return value\n    };\n\n    /**\n     * Add a dependency to this directive.\n     */\n    Watcher.prototype.addDep = function addDep (dep) {\n        var id = dep.id;\n        if (!this.newDepIds.has(id)) {\n            this.newDepIds.add(id);\n            this.newDeps.push(dep);\n            if (!this.depIds.has(id)) {\n                dep.addSub(this);\n            }\n        }\n    };\n\n    /**\n     * Clean up for dependency collection.\n     */\n    Watcher.prototype.cleanupDeps = function cleanupDeps () {\n        var i = this.deps.length;\n        while (i--) {\n            var dep = this.deps[i];\n            if (!this.newDepIds.has(dep.id)) {\n                dep.removeSub(this);\n            }\n        }\n        var tmp = this.depIds;\n        this.depIds = this.newDepIds;\n        this.newDepIds = tmp;\n        this.newDepIds.clear();\n        tmp = this.deps;\n        this.deps = this.newDeps;\n        this.newDeps = tmp;\n        this.newDeps.length = 0;\n    };\n\n    /**\n     * Subscriber interface.\n     * Will be called when a dependency changes.\n     */\n    Watcher.prototype.update = function update () {\n        /* istanbul ignore else */\n        if (this.lazy) {\n            this.dirty = true;\n        } else if (this.sync) {\n            this.run();\n        } else {\n            queueWatcher(this);\n        }\n    };\n\n    /**\n     * Scheduler job interface.\n     * Will be called by the scheduler.\n     */\n    Watcher.prototype.run = function run () {\n        if (this.active) {\n            var value = this.get();\n            if (\n                value !== this.value ||\n                // Deep watchers and watchers on Object/Arrays should fire even\n                // when the value is the same, because the value may\n                // have mutated.\n                isObject(value) ||\n                this.deep\n            ) {\n                // set new value\n                var oldValue = this.value;\n                this.value = value;\n                if (this.user) {\n                    var info = \"callback for watcher \\\"\" + (this.expression) + \"\\\"\";\n                    invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info);\n                } else {\n                    this.cb.call(this.vm, value, oldValue);\n                }\n            }\n        }\n    };\n\n    /**\n     * Evaluate the value of the watcher.\n     * This only gets called for lazy watchers.\n     */\n    Watcher.prototype.evaluate = function evaluate () {\n        this.value = this.get();\n        this.dirty = false;\n    };\n\n    /**\n     * Depend on all deps collected by this watcher.\n     */\n    Watcher.prototype.depend = function depend () {\n        var i = this.deps.length;\n        while (i--) {\n            this.deps[i].depend();\n        }\n    };\n\n    /**\n     * Remove self from all dependencies' subscriber list.\n     */\n    Watcher.prototype.teardown = function teardown () {\n        if (this.active) {\n            // remove self from vm's watcher list\n            // this is a somewhat expensive operation so we skip it\n            // if the vm is being destroyed.\n            if (!this.vm._isBeingDestroyed) {\n                remove(this.vm._watchers, this);\n            }\n            var i = this.deps.length;\n            while (i--) {\n                this.deps[i].removeSub(this);\n            }\n            this.active = false;\n        }\n    };\n\n    /*  */\n\n    var sharedPropertyDefinition = {\n        enumerable: true,\n        configurable: true,\n        get: noop,\n        set: noop\n    };\n\n    function proxy (target, sourceKey, key) {\n        sharedPropertyDefinition.get = function proxyGetter () {\n            return this[sourceKey][key]\n        };\n        sharedPropertyDefinition.set = function proxySetter (val) {\n            this[sourceKey][key] = val;\n        };\n        Object.defineProperty(target, key, sharedPropertyDefinition);\n    }\n\n    function initState (vm) {\n        vm._watchers = [];\n        var opts = vm.$options;\n        if (opts.props) { initProps(vm, opts.props); }\n        if (opts.methods) { initMethods(vm, opts.methods); }\n        if (opts.data) {\n            initData(vm);\n        } else {\n            observe(vm._data = {}, true /* asRootData */);\n        }\n        if (opts.computed) { initComputed(vm, opts.computed); }\n        if (opts.watch && opts.watch !== nativeWatch) {\n            initWatch(vm, opts.watch);\n        }\n    }\n\n    function initProps (vm, propsOptions) {\n        var propsData = vm.$options.propsData || {};\n        var props = vm._props = {};\n        // cache prop keys so that future props updates can iterate using Array\n        // instead of dynamic object key enumeration.\n        var keys = vm.$options._propKeys = [];\n        var isRoot = !vm.$parent;\n        // root instance props should be converted\n        if (!isRoot) {\n            toggleObserving(false);\n        }\n        var loop = function ( key ) {\n            keys.push(key);\n            var value = validateProp(key, propsOptions, propsData, vm);\n            /* istanbul ignore else */\n            {\n                var hyphenatedKey = hyphenate(key);\n                if (isReservedAttribute(hyphenatedKey) ||\n                    config.isReservedAttr(hyphenatedKey)) {\n                    warn(\n                        (\"\\\"\" + hyphenatedKey + \"\\\" is a reserved attribute and cannot be used as component prop.\"),\n                        vm\n                    );\n                }\n                defineReactive$$1(props, key, value, function () {\n                    if (!isRoot && !isUpdatingChildComponent) {\n                        warn(\n                            \"Avoid mutating a prop directly since the value will be \" +\n                            \"overwritten whenever the parent component re-renders. \" +\n                            \"Instead, use a data or computed property based on the prop's \" +\n                            \"value. Prop being mutated: \\\"\" + key + \"\\\"\",\n                            vm\n                        );\n                    }\n                });\n            }\n            // static props are already proxied on the component's prototype\n            // during Vue.extend(). We only need to proxy props defined at\n            // instantiation here.\n            if (!(key in vm)) {\n                proxy(vm, \"_props\", key);\n            }\n        };\n\n        for (var key in propsOptions) loop( key );\n        toggleObserving(true);\n    }\n\n    function initData (vm) {\n        var data = vm.$options.data;\n        data = vm._data = typeof data === 'function'\n            ? getData(data, vm)\n            : data || {};\n        if (!isPlainObject(data)) {\n            data = {};\n            warn(\n                'data functions should return an object:\\n' +\n                'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',\n                vm\n            );\n        }\n        // proxy data on instance\n        var keys = Object.keys(data);\n        var props = vm.$options.props;\n        var methods = vm.$options.methods;\n        var i = keys.length;\n        while (i--) {\n            var key = keys[i];\n            {\n                if (methods && hasOwn(methods, key)) {\n                    warn(\n                        (\"Method \\\"\" + key + \"\\\" has already been defined as a data property.\"),\n                        vm\n                    );\n                }\n            }\n            if (props && hasOwn(props, key)) {\n                warn(\n                    \"The data property \\\"\" + key + \"\\\" is already declared as a prop. \" +\n                    \"Use prop default value instead.\",\n                    vm\n                );\n            } else if (!isReserved(key)) {\n                proxy(vm, \"_data\", key);\n            }\n        }\n        // observe data\n        observe(data, true /* asRootData */);\n    }\n\n    function getData (data, vm) {\n        // #7573 disable dep collection when invoking data getters\n        pushTarget();\n        try {\n            return data.call(vm, vm)\n        } catch (e) {\n            handleError(e, vm, \"data()\");\n            return {}\n        } finally {\n            popTarget();\n        }\n    }\n\n    var computedWatcherOptions = { lazy: true };\n\n    function initComputed (vm, computed) {\n        // $flow-disable-line\n        var watchers = vm._computedWatchers = Object.create(null);\n        // computed properties are just getters during SSR\n        var isSSR = isServerRendering();\n\n        for (var key in computed) {\n            var userDef = computed[key];\n            var getter = typeof userDef === 'function' ? userDef : userDef.get;\n            if (getter == null) {\n                warn(\n                    (\"Getter is missing for computed property \\\"\" + key + \"\\\".\"),\n                    vm\n                );\n            }\n\n            if (!isSSR) {\n                // create internal watcher for the computed property.\n                watchers[key] = new Watcher(\n                    vm,\n                    getter || noop,\n                    noop,\n                    computedWatcherOptions\n                );\n            }\n\n            // component-defined computed properties are already defined on the\n            // component prototype. We only need to define computed properties defined\n            // at instantiation here.\n            if (!(key in vm)) {\n                defineComputed(vm, key, userDef);\n            } else {\n                if (key in vm.$data) {\n                    warn((\"The computed property \\\"\" + key + \"\\\" is already defined in data.\"), vm);\n                } else if (vm.$options.props && key in vm.$options.props) {\n                    warn((\"The computed property \\\"\" + key + \"\\\" is already defined as a prop.\"), vm);\n                } else if (vm.$options.methods && key in vm.$options.methods) {\n                    warn((\"The computed property \\\"\" + key + \"\\\" is already defined as a method.\"), vm);\n                }\n            }\n        }\n    }\n\n    function defineComputed (\n        target,\n        key,\n        userDef\n    ) {\n        var shouldCache = !isServerRendering();\n        if (typeof userDef === 'function') {\n            sharedPropertyDefinition.get = shouldCache\n                ? createComputedGetter(key)\n                : createGetterInvoker(userDef);\n            sharedPropertyDefinition.set = noop;\n        } else {\n            sharedPropertyDefinition.get = userDef.get\n                ? shouldCache && userDef.cache !== false\n                    ? createComputedGetter(key)\n                    : createGetterInvoker(userDef.get)\n                : noop;\n            sharedPropertyDefinition.set = userDef.set || noop;\n        }\n        if (sharedPropertyDefinition.set === noop) {\n            sharedPropertyDefinition.set = function () {\n                warn(\n                    (\"Computed property \\\"\" + key + \"\\\" was assigned to but it has no setter.\"),\n                    this\n                );\n            };\n        }\n        Object.defineProperty(target, key, sharedPropertyDefinition);\n    }\n\n    function createComputedGetter (key) {\n        return function computedGetter () {\n            var watcher = this._computedWatchers && this._computedWatchers[key];\n            if (watcher) {\n                if (watcher.dirty) {\n                    watcher.evaluate();\n                }\n                if (Dep.target) {\n                    watcher.depend();\n                }\n                return watcher.value\n            }\n        }\n    }\n\n    function createGetterInvoker(fn) {\n        return function computedGetter () {\n            return fn.call(this, this)\n        }\n    }\n\n    function initMethods (vm, methods) {\n        var props = vm.$options.props;\n        for (var key in methods) {\n            {\n                if (typeof methods[key] !== 'function') {\n                    warn(\n                        \"Method \\\"\" + key + \"\\\" has type \\\"\" + (typeof methods[key]) + \"\\\" in the component definition. \" +\n                        \"Did you reference the function correctly?\",\n                        vm\n                    );\n                }\n                if (props && hasOwn(props, key)) {\n                    warn(\n                        (\"Method \\\"\" + key + \"\\\" has already been defined as a prop.\"),\n                        vm\n                    );\n                }\n                if ((key in vm) && isReserved(key)) {\n                    warn(\n                        \"Method \\\"\" + key + \"\\\" conflicts with an existing Vue instance method. \" +\n                        \"Avoid defining component methods that start with _ or $.\"\n                    );\n                }\n            }\n            vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);\n        }\n    }\n\n    function initWatch (vm, watch) {\n        for (var key in watch) {\n            var handler = watch[key];\n            if (Array.isArray(handler)) {\n                for (var i = 0; i < handler.length; i++) {\n                    createWatcher(vm, key, handler[i]);\n                }\n            } else {\n                createWatcher(vm, key, handler);\n            }\n        }\n    }\n\n    function createWatcher (\n        vm,\n        expOrFn,\n        handler,\n        options\n    ) {\n        if (isPlainObject(handler)) {\n            options = handler;\n            handler = handler.handler;\n        }\n        if (typeof handler === 'string') {\n            handler = vm[handler];\n        }\n        return vm.$watch(expOrFn, handler, options)\n    }\n\n    function stateMixin (Vue) {\n        // flow somehow has problems with directly declared definition object\n        // when using Object.defineProperty, so we have to procedurally build up\n        // the object here.\n        var dataDef = {};\n        dataDef.get = function () { return this._data };\n        var propsDef = {};\n        propsDef.get = function () { return this._props };\n        {\n            dataDef.set = function () {\n                warn(\n                    'Avoid replacing instance root $data. ' +\n                    'Use nested data properties instead.',\n                    this\n                );\n            };\n            propsDef.set = function () {\n                warn(\"$props is readonly.\", this);\n            };\n        }\n        Object.defineProperty(Vue.prototype, '$data', dataDef);\n        Object.defineProperty(Vue.prototype, '$props', propsDef);\n\n        Vue.prototype.$set = set;\n        Vue.prototype.$delete = del;\n\n        Vue.prototype.$watch = function (\n            expOrFn,\n            cb,\n            options\n        ) {\n            var vm = this;\n            if (isPlainObject(cb)) {\n                return createWatcher(vm, expOrFn, cb, options)\n            }\n            options = options || {};\n            options.user = true;\n            var watcher = new Watcher(vm, expOrFn, cb, options);\n            if (options.immediate) {\n                var info = \"callback for immediate watcher \\\"\" + (watcher.expression) + \"\\\"\";\n                pushTarget();\n                invokeWithErrorHandling(cb, vm, [watcher.value], vm, info);\n                popTarget();\n            }\n            return function unwatchFn () {\n                watcher.teardown();\n            }\n        };\n    }\n\n    /*  */\n\n    var uid$3 = 0;\n\n    function initMixin (Vue) {\n        Vue.prototype._init = function (options) {\n            var vm = this;\n            // a uid\n            vm._uid = uid$3++;\n\n            var startTag, endTag;\n            /* istanbul ignore if */\n            if (config.performance && mark) {\n                startTag = \"vue-perf-start:\" + (vm._uid);\n                endTag = \"vue-perf-end:\" + (vm._uid);\n                mark(startTag);\n            }\n\n            // a flag to avoid this being observed\n            vm._isVue = true;\n            // merge options\n            if (options && options._isComponent) {\n                // optimize internal component instantiation\n                // since dynamic options merging is pretty slow, and none of the\n                // internal component options needs special treatment.\n                initInternalComponent(vm, options);\n            } else {\n                vm.$options = mergeOptions(\n                    resolveConstructorOptions(vm.constructor),\n                    options || {},\n                    vm\n                );\n            }\n            /* istanbul ignore else */\n            {\n                initProxy(vm);\n            }\n            // expose real self\n            vm._self = vm;\n            initLifecycle(vm);\n            initEvents(vm);\n            initRender(vm);\n            callHook(vm, 'beforeCreate');\n            initInjections(vm); // resolve injections before data/props\n            initState(vm);\n            initProvide(vm); // resolve provide after data/props\n            callHook(vm, 'created');\n\n            /* istanbul ignore if */\n            if (config.performance && mark) {\n                vm._name = formatComponentName(vm, false);\n                mark(endTag);\n                measure((\"vue \" + (vm._name) + \" init\"), startTag, endTag);\n            }\n\n            if (vm.$options.el) {\n                vm.$mount(vm.$options.el);\n            }\n        };\n    }\n\n    function initInternalComponent (vm, options) {\n        var opts = vm.$options = Object.create(vm.constructor.options);\n        // doing this because it's faster than dynamic enumeration.\n        var parentVnode = options._parentVnode;\n        opts.parent = options.parent;\n        opts._parentVnode = parentVnode;\n\n        var vnodeComponentOptions = parentVnode.componentOptions;\n        opts.propsData = vnodeComponentOptions.propsData;\n        opts._parentListeners = vnodeComponentOptions.listeners;\n        opts._renderChildren = vnodeComponentOptions.children;\n        opts._componentTag = vnodeComponentOptions.tag;\n\n        if (options.render) {\n            opts.render = options.render;\n            opts.staticRenderFns = options.staticRenderFns;\n        }\n    }\n\n    function resolveConstructorOptions (Ctor) {\n        var options = Ctor.options;\n        if (Ctor.super) {\n            var superOptions = resolveConstructorOptions(Ctor.super);\n            var cachedSuperOptions = Ctor.superOptions;\n            if (superOptions !== cachedSuperOptions) {\n                // super option changed,\n                // need to resolve new options.\n                Ctor.superOptions = superOptions;\n                // check if there are any late-modified/attached options (#4976)\n                var modifiedOptions = resolveModifiedOptions(Ctor);\n                // update base extend options\n                if (modifiedOptions) {\n                    extend(Ctor.extendOptions, modifiedOptions);\n                }\n                options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);\n                if (options.name) {\n                    options.components[options.name] = Ctor;\n                }\n            }\n        }\n        return options\n    }\n\n    function resolveModifiedOptions (Ctor) {\n        var modified;\n        var latest = Ctor.options;\n        var sealed = Ctor.sealedOptions;\n        for (var key in latest) {\n            if (latest[key] !== sealed[key]) {\n                if (!modified) { modified = {}; }\n                modified[key] = latest[key];\n            }\n        }\n        return modified\n    }\n\n    function Vue (options) {\n        if (!(this instanceof Vue)\n        ) {\n            warn('Vue is a constructor and should be called with the `new` keyword');\n        }\n        this._init(options);\n    }\n\n    initMixin(Vue);\n    stateMixin(Vue);\n    eventsMixin(Vue);\n    lifecycleMixin(Vue);\n    renderMixin(Vue);\n\n    /*  */\n\n    function initUse (Vue) {\n        Vue.use = function (plugin) {\n            var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));\n            if (installedPlugins.indexOf(plugin) > -1) {\n                return this\n            }\n\n            // additional parameters\n            var args = toArray(arguments, 1);\n            args.unshift(this);\n            if (typeof plugin.install === 'function') {\n                plugin.install.apply(plugin, args);\n            } else if (typeof plugin === 'function') {\n                plugin.apply(null, args);\n            }\n            installedPlugins.push(plugin);\n            return this\n        };\n    }\n\n    /*  */\n\n    function initMixin$1 (Vue) {\n        Vue.mixin = function (mixin) {\n            this.options = mergeOptions(this.options, mixin);\n            return this\n        };\n    }\n\n    /*  */\n\n    function initExtend (Vue) {\n        /**\n         * Each instance constructor, including Vue, has a unique\n         * cid. This enables us to create wrapped \"child\n         * constructors\" for prototypal inheritance and cache them.\n         */\n        Vue.cid = 0;\n        var cid = 1;\n\n        /**\n         * Class inheritance\n         */\n        Vue.extend = function (extendOptions) {\n            extendOptions = extendOptions || {};\n            var Super = this;\n            var SuperId = Super.cid;\n            var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});\n            if (cachedCtors[SuperId]) {\n                return cachedCtors[SuperId]\n            }\n\n            var name = extendOptions.name || Super.options.name;\n            if (name) {\n                validateComponentName(name);\n            }\n\n            var Sub = function VueComponent (options) {\n                this._init(options);\n            };\n            Sub.prototype = Object.create(Super.prototype);\n            Sub.prototype.constructor = Sub;\n            Sub.cid = cid++;\n            Sub.options = mergeOptions(\n                Super.options,\n                extendOptions\n            );\n            Sub['super'] = Super;\n\n            // For props and computed properties, we define the proxy getters on\n            // the Vue instances at extension time, on the extended prototype. This\n            // avoids Object.defineProperty calls for each instance created.\n            if (Sub.options.props) {\n                initProps$1(Sub);\n            }\n            if (Sub.options.computed) {\n                initComputed$1(Sub);\n            }\n\n            // allow further extension/mixin/plugin usage\n            Sub.extend = Super.extend;\n            Sub.mixin = Super.mixin;\n            Sub.use = Super.use;\n\n            // create asset registers, so extended classes\n            // can have their private assets too.\n            ASSET_TYPES.forEach(function (type) {\n                Sub[type] = Super[type];\n            });\n            // enable recursive self-lookup\n            if (name) {\n                Sub.options.components[name] = Sub;\n            }\n\n            // keep a reference to the super options at extension time.\n            // later at instantiation we can check if Super's options have\n            // been updated.\n            Sub.superOptions = Super.options;\n            Sub.extendOptions = extendOptions;\n            Sub.sealedOptions = extend({}, Sub.options);\n\n            // cache constructor\n            cachedCtors[SuperId] = Sub;\n            return Sub\n        };\n    }\n\n    function initProps$1 (Comp) {\n        var props = Comp.options.props;\n        for (var key in props) {\n            proxy(Comp.prototype, \"_props\", key);\n        }\n    }\n\n    function initComputed$1 (Comp) {\n        var computed = Comp.options.computed;\n        for (var key in computed) {\n            defineComputed(Comp.prototype, key, computed[key]);\n        }\n    }\n\n    /*  */\n\n    function initAssetRegisters (Vue) {\n        /**\n         * Create asset registration methods.\n         */\n        ASSET_TYPES.forEach(function (type) {\n            Vue[type] = function (\n                id,\n                definition\n            ) {\n                if (!definition) {\n                    return this.options[type + 's'][id]\n                } else {\n                    /* istanbul ignore if */\n                    if (type === 'component') {\n                        validateComponentName(id);\n                    }\n                    if (type === 'component' && isPlainObject(definition)) {\n                        definition.name = definition.name || id;\n                        definition = this.options._base.extend(definition);\n                    }\n                    if (type === 'directive' && typeof definition === 'function') {\n                        definition = { bind: definition, update: definition };\n                    }\n                    this.options[type + 's'][id] = definition;\n                    return definition\n                }\n            };\n        });\n    }\n\n    /*  */\n\n\n\n\n\n    function getComponentName (opts) {\n        return opts && (opts.Ctor.options.name || opts.tag)\n    }\n\n    function matches (pattern, name) {\n        if (Array.isArray(pattern)) {\n            return pattern.indexOf(name) > -1\n        } else if (typeof pattern === 'string') {\n            return pattern.split(',').indexOf(name) > -1\n        } else if (isRegExp(pattern)) {\n            return pattern.test(name)\n        }\n        /* istanbul ignore next */\n        return false\n    }\n\n    function pruneCache (keepAliveInstance, filter) {\n        var cache = keepAliveInstance.cache;\n        var keys = keepAliveInstance.keys;\n        var _vnode = keepAliveInstance._vnode;\n        for (var key in cache) {\n            var entry = cache[key];\n            if (entry) {\n                var name = entry.name;\n                if (name && !filter(name)) {\n                    pruneCacheEntry(cache, key, keys, _vnode);\n                }\n            }\n        }\n    }\n\n    function pruneCacheEntry (\n        cache,\n        key,\n        keys,\n        current\n    ) {\n        var entry = cache[key];\n        if (entry && (!current || entry.tag !== current.tag)) {\n            entry.componentInstance.$destroy();\n        }\n        cache[key] = null;\n        remove(keys, key);\n    }\n\n    var patternTypes = [String, RegExp, Array];\n\n    var KeepAlive = {\n        name: 'keep-alive',\n        abstract: true,\n\n        props: {\n            include: patternTypes,\n            exclude: patternTypes,\n            max: [String, Number]\n        },\n\n        methods: {\n            cacheVNode: function cacheVNode() {\n                var ref = this;\n                var cache = ref.cache;\n                var keys = ref.keys;\n                var vnodeToCache = ref.vnodeToCache;\n                var keyToCache = ref.keyToCache;\n                if (vnodeToCache) {\n                    var tag = vnodeToCache.tag;\n                    var componentInstance = vnodeToCache.componentInstance;\n                    var componentOptions = vnodeToCache.componentOptions;\n                    cache[keyToCache] = {\n                        name: getComponentName(componentOptions),\n                        tag: tag,\n                        componentInstance: componentInstance,\n                    };\n                    keys.push(keyToCache);\n                    // prune oldest entry\n                    if (this.max && keys.length > parseInt(this.max)) {\n                        pruneCacheEntry(cache, keys[0], keys, this._vnode);\n                    }\n                    this.vnodeToCache = null;\n                }\n            }\n        },\n\n        created: function created () {\n            this.cache = Object.create(null);\n            this.keys = [];\n        },\n\n        destroyed: function destroyed () {\n            for (var key in this.cache) {\n                pruneCacheEntry(this.cache, key, this.keys);\n            }\n        },\n\n        mounted: function mounted () {\n            var this$1 = this;\n\n            this.cacheVNode();\n            this.$watch('include', function (val) {\n                pruneCache(this$1, function (name) { return matches(val, name); });\n            });\n            this.$watch('exclude', function (val) {\n                pruneCache(this$1, function (name) { return !matches(val, name); });\n            });\n        },\n\n        updated: function updated () {\n            this.cacheVNode();\n        },\n\n        render: function render () {\n            var slot = this.$slots.default;\n            var vnode = getFirstComponentChild(slot);\n            var componentOptions = vnode && vnode.componentOptions;\n            if (componentOptions) {\n                // check pattern\n                var name = getComponentName(componentOptions);\n                var ref = this;\n                var include = ref.include;\n                var exclude = ref.exclude;\n                if (\n                    // not included\n                    (include && (!name || !matches(include, name))) ||\n                    // excluded\n                    (exclude && name && matches(exclude, name))\n                ) {\n                    return vnode\n                }\n\n                var ref$1 = this;\n                var cache = ref$1.cache;\n                var keys = ref$1.keys;\n                var key = vnode.key == null\n                    // same constructor may get registered as different local components\n                    // so cid alone is not enough (#3269)\n                    ? componentOptions.Ctor.cid + (componentOptions.tag ? (\"::\" + (componentOptions.tag)) : '')\n                    : vnode.key;\n                if (cache[key]) {\n                    vnode.componentInstance = cache[key].componentInstance;\n                    // make current key freshest\n                    remove(keys, key);\n                    keys.push(key);\n                } else {\n                    // delay setting the cache until update\n                    this.vnodeToCache = vnode;\n                    this.keyToCache = key;\n                }\n\n                vnode.data.keepAlive = true;\n            }\n            return vnode || (slot && slot[0])\n        }\n    };\n\n    var builtInComponents = {\n        KeepAlive: KeepAlive\n    };\n\n    /*  */\n\n    function initGlobalAPI (Vue) {\n        // config\n        var configDef = {};\n        configDef.get = function () { return config; };\n        {\n            configDef.set = function () {\n                warn(\n                    'Do not replace the Vue.config object, set individual fields instead.'\n                );\n            };\n        }\n        Object.defineProperty(Vue, 'config', configDef);\n\n        // exposed util methods.\n        // NOTE: these are not considered part of the public API - avoid relying on\n        // them unless you are aware of the risk.\n        Vue.util = {\n            warn: warn,\n            extend: extend,\n            mergeOptions: mergeOptions,\n            defineReactive: defineReactive$$1\n        };\n\n        Vue.set = set;\n        Vue.delete = del;\n        Vue.nextTick = nextTick;\n\n        // 2.6 explicit observable API\n        Vue.observable = function (obj) {\n            observe(obj);\n            return obj\n        };\n\n        Vue.options = Object.create(null);\n        ASSET_TYPES.forEach(function (type) {\n            Vue.options[type + 's'] = Object.create(null);\n        });\n\n        // this is used to identify the \"base\" constructor to extend all plain-object\n        // components with in Weex's multi-instance scenarios.\n        Vue.options._base = Vue;\n\n        extend(Vue.options.components, builtInComponents);\n\n        initUse(Vue);\n        initMixin$1(Vue);\n        initExtend(Vue);\n        initAssetRegisters(Vue);\n    }\n\n    initGlobalAPI(Vue);\n\n    Object.defineProperty(Vue.prototype, '$isServer', {\n        get: isServerRendering\n    });\n\n    Object.defineProperty(Vue.prototype, '$ssrContext', {\n        get: function get () {\n            /* istanbul ignore next */\n            return this.$vnode && this.$vnode.ssrContext\n        }\n    });\n\n    // expose FunctionalRenderContext for ssr runtime helper installation\n    Object.defineProperty(Vue, 'FunctionalRenderContext', {\n        value: FunctionalRenderContext\n    });\n\n    Vue.version = '2.6.14';\n\n    /*  */\n\n    // these are reserved for web because they are directly compiled away\n    // during template compilation\n    var isReservedAttr = makeMap('style,class');\n\n    // attributes that should be using props for binding\n    var acceptValue = makeMap('input,textarea,option,select,progress');\n    var mustUseProp = function (tag, type, attr) {\n        return (\n            (attr === 'value' && acceptValue(tag)) && type !== 'button' ||\n            (attr === 'selected' && tag === 'option') ||\n            (attr === 'checked' && tag === 'input') ||\n            (attr === 'muted' && tag === 'video')\n        )\n    };\n\n    var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');\n\n    var isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only');\n\n    var convertEnumeratedValue = function (key, value) {\n        return isFalsyAttrValue(value) || value === 'false'\n            ? 'false'\n            // allow arbitrary string value for contenteditable\n            : key === 'contenteditable' && isValidContentEditableValue(value)\n                ? value\n                : 'true'\n    };\n\n    var isBooleanAttr = makeMap(\n        'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +\n        'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +\n        'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +\n        'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +\n        'required,reversed,scoped,seamless,selected,sortable,' +\n        'truespeed,typemustmatch,visible'\n    );\n\n    var xlinkNS = 'http://www.w3.org/1999/xlink';\n\n    var isXlink = function (name) {\n        return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'\n    };\n\n    var getXlinkProp = function (name) {\n        return isXlink(name) ? name.slice(6, name.length) : ''\n    };\n\n    var isFalsyAttrValue = function (val) {\n        return val == null || val === false\n    };\n\n    /*  */\n\n    function genClassForVnode (vnode) {\n        var data = vnode.data;\n        var parentNode = vnode;\n        var childNode = vnode;\n        while (isDef(childNode.componentInstance)) {\n            childNode = childNode.componentInstance._vnode;\n            if (childNode && childNode.data) {\n                data = mergeClassData(childNode.data, data);\n            }\n        }\n        while (isDef(parentNode = parentNode.parent)) {\n            if (parentNode && parentNode.data) {\n                data = mergeClassData(data, parentNode.data);\n            }\n        }\n        return renderClass(data.staticClass, data.class)\n    }\n\n    function mergeClassData (child, parent) {\n        return {\n            staticClass: concat(child.staticClass, parent.staticClass),\n            class: isDef(child.class)\n                ? [child.class, parent.class]\n                : parent.class\n        }\n    }\n\n    function renderClass (\n        staticClass,\n        dynamicClass\n    ) {\n        if (isDef(staticClass) || isDef(dynamicClass)) {\n            return concat(staticClass, stringifyClass(dynamicClass))\n        }\n        /* istanbul ignore next */\n        return ''\n    }\n\n    function concat (a, b) {\n        return a ? b ? (a + ' ' + b) : a : (b || '')\n    }\n\n    function stringifyClass (value) {\n        if (Array.isArray(value)) {\n            return stringifyArray(value)\n        }\n        if (isObject(value)) {\n            return stringifyObject(value)\n        }\n        if (typeof value === 'string') {\n            return value\n        }\n        /* istanbul ignore next */\n        return ''\n    }\n\n    function stringifyArray (value) {\n        var res = '';\n        var stringified;\n        for (var i = 0, l = value.length; i < l; i++) {\n            if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {\n                if (res) { res += ' '; }\n                res += stringified;\n            }\n        }\n        return res\n    }\n\n    function stringifyObject (value) {\n        var res = '';\n        for (var key in value) {\n            if (value[key]) {\n                if (res) { res += ' '; }\n                res += key;\n            }\n        }\n        return res\n    }\n\n    /*  */\n\n    var namespaceMap = {\n        svg: 'http://www.w3.org/2000/svg',\n        math: 'http://www.w3.org/1998/Math/MathML'\n    };\n\n    var isHTMLTag = makeMap(\n        'html,body,base,head,link,meta,style,title,' +\n        'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +\n        'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +\n        'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +\n        's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +\n        'embed,object,param,source,canvas,script,noscript,del,ins,' +\n        'caption,col,colgroup,table,thead,tbody,td,th,tr,' +\n        'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +\n        'output,progress,select,textarea,' +\n        'details,dialog,menu,menuitem,summary,' +\n        'content,element,shadow,template,blockquote,iframe,tfoot'\n    );\n\n    // this map is intentionally selective, only covering SVG elements that may\n    // contain child elements.\n    var isSVG = makeMap(\n        'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +\n        'foreignobject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +\n        'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',\n        true\n    );\n\n    var isPreTag = function (tag) { return tag === 'pre'; };\n\n    var isReservedTag = function (tag) {\n        return isHTMLTag(tag) || isSVG(tag)\n    };\n\n    function getTagNamespace (tag) {\n        if (isSVG(tag)) {\n            return 'svg'\n        }\n        // basic support for MathML\n        // note it doesn't support other MathML elements being component roots\n        if (tag === 'math') {\n            return 'math'\n        }\n    }\n\n    var unknownElementCache = Object.create(null);\n    function isUnknownElement (tag) {\n        /* istanbul ignore if */\n        if (!inBrowser) {\n            return true\n        }\n        if (isReservedTag(tag)) {\n            return false\n        }\n        tag = tag.toLowerCase();\n        /* istanbul ignore if */\n        if (unknownElementCache[tag] != null) {\n            return unknownElementCache[tag]\n        }\n        var el = document.createElement(tag);\n        if (tag.indexOf('-') > -1) {\n            // http://stackoverflow.com/a/28210364/1070244\n            return (unknownElementCache[tag] = (\n                el.constructor === window.HTMLUnknownElement ||\n                el.constructor === window.HTMLElement\n            ))\n        } else {\n            return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))\n        }\n    }\n\n    var isTextInputType = makeMap('text,number,password,search,email,tel,url');\n\n    /*  */\n\n    /**\n     * Query an element selector if it's not an element already.\n     */\n    function query (el) {\n        if (typeof el === 'string') {\n            var selected = document.querySelector(el);\n            if (!selected) {\n                warn(\n                    'Cannot find element: ' + el\n                );\n                return document.createElement('div')\n            }\n            return selected\n        } else {\n            return el\n        }\n    }\n\n    /*  */\n\n    function createElement$1 (tagName, vnode) {\n        var elm = document.createElement(tagName);\n        if (tagName !== 'select') {\n            return elm\n        }\n        // false or null will remove the attribute but undefined will not\n        if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {\n            elm.setAttribute('multiple', 'multiple');\n        }\n        return elm\n    }\n\n    function createElementNS (namespace, tagName) {\n        return document.createElementNS(namespaceMap[namespace], tagName)\n    }\n\n    function createTextNode (text) {\n        return document.createTextNode(text)\n    }\n\n    function createComment (text) {\n        return document.createComment(text)\n    }\n\n    function insertBefore (parentNode, newNode, referenceNode) {\n        parentNode.insertBefore(newNode, referenceNode);\n    }\n\n    function removeChild (node, child) {\n        node.removeChild(child);\n    }\n\n    function appendChild (node, child) {\n        node.appendChild(child);\n    }\n\n    function parentNode (node) {\n        return node.parentNode\n    }\n\n    function nextSibling (node) {\n        return node.nextSibling\n    }\n\n    function tagName (node) {\n        return node.tagName\n    }\n\n    function setTextContent (node, text) {\n        node.textContent = text;\n    }\n\n    function setStyleScope (node, scopeId) {\n        node.setAttribute(scopeId, '');\n    }\n\n    var nodeOps = /*#__PURE__*/Object.freeze({\n        createElement: createElement$1,\n        createElementNS: createElementNS,\n        createTextNode: createTextNode,\n        createComment: createComment,\n        insertBefore: insertBefore,\n        removeChild: removeChild,\n        appendChild: appendChild,\n        parentNode: parentNode,\n        nextSibling: nextSibling,\n        tagName: tagName,\n        setTextContent: setTextContent,\n        setStyleScope: setStyleScope\n    });\n\n    /*  */\n\n    var ref = {\n        create: function create (_, vnode) {\n            registerRef(vnode);\n        },\n        update: function update (oldVnode, vnode) {\n            if (oldVnode.data.ref !== vnode.data.ref) {\n                registerRef(oldVnode, true);\n                registerRef(vnode);\n            }\n        },\n        destroy: function destroy (vnode) {\n            registerRef(vnode, true);\n        }\n    };\n\n    function registerRef (vnode, isRemoval) {\n        var key = vnode.data.ref;\n        if (!isDef(key)) { return }\n\n        var vm = vnode.context;\n        var ref = vnode.componentInstance || vnode.elm;\n        var refs = vm.$refs;\n        if (isRemoval) {\n            if (Array.isArray(refs[key])) {\n                remove(refs[key], ref);\n            } else if (refs[key] === ref) {\n                refs[key] = undefined;\n            }\n        } else {\n            if (vnode.data.refInFor) {\n                if (!Array.isArray(refs[key])) {\n                    refs[key] = [ref];\n                } else if (refs[key].indexOf(ref) < 0) {\n                    // $flow-disable-line\n                    refs[key].push(ref);\n                }\n            } else {\n                refs[key] = ref;\n            }\n        }\n    }\n\n    /**\n     * Virtual DOM patching algorithm based on Snabbdom by\n     * Simon Friis Vindum (@paldepind)\n     * Licensed under the MIT License\n     * https://github.com/paldepind/snabbdom/blob/master/LICENSE\n     *\n     * modified by Evan You (@yyx990803)\n     *\n     * Not type-checking this because this file is perf-critical and the cost\n     * of making flow understand it is not worth it.\n     */\n\n    var emptyNode = new VNode('', {}, []);\n\n    var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];\n\n    function sameVnode (a, b) {\n        return (\n            a.key === b.key &&\n            a.asyncFactory === b.asyncFactory && (\n                (\n                    a.tag === b.tag &&\n                    a.isComment === b.isComment &&\n                    isDef(a.data) === isDef(b.data) &&\n                    sameInputType(a, b)\n                ) || (\n                    isTrue(a.isAsyncPlaceholder) &&\n                    isUndef(b.asyncFactory.error)\n                )\n            )\n        )\n    }\n\n    function sameInputType (a, b) {\n        if (a.tag !== 'input') { return true }\n        var i;\n        var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;\n        var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;\n        return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB)\n    }\n\n    function createKeyToOldIdx (children, beginIdx, endIdx) {\n        var i, key;\n        var map = {};\n        for (i = beginIdx; i <= endIdx; ++i) {\n            key = children[i].key;\n            if (isDef(key)) { map[key] = i; }\n        }\n        return map\n    }\n\n    function createPatchFunction (backend) {\n        var i, j;\n        var cbs = {};\n\n        var modules = backend.modules;\n        var nodeOps = backend.nodeOps;\n\n        for (i = 0; i < hooks.length; ++i) {\n            cbs[hooks[i]] = [];\n            for (j = 0; j < modules.length; ++j) {\n                if (isDef(modules[j][hooks[i]])) {\n                    cbs[hooks[i]].push(modules[j][hooks[i]]);\n                }\n            }\n        }\n\n        function emptyNodeAt (elm) {\n            return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)\n        }\n\n        function createRmCb (childElm, listeners) {\n            function remove$$1 () {\n                if (--remove$$1.listeners === 0) {\n                    removeNode(childElm);\n                }\n            }\n            remove$$1.listeners = listeners;\n            return remove$$1\n        }\n\n        function removeNode (el) {\n            var parent = nodeOps.parentNode(el);\n            // element may have already been removed due to v-html / v-text\n            if (isDef(parent)) {\n                nodeOps.removeChild(parent, el);\n            }\n        }\n\n        function isUnknownElement$$1 (vnode, inVPre) {\n            return (\n                !inVPre &&\n                !vnode.ns &&\n                !(\n                    config.ignoredElements.length &&\n                    config.ignoredElements.some(function (ignore) {\n                        return isRegExp(ignore)\n                            ? ignore.test(vnode.tag)\n                            : ignore === vnode.tag\n                    })\n                ) &&\n                config.isUnknownElement(vnode.tag)\n            )\n        }\n\n        var creatingElmInVPre = 0;\n\n        function createElm (\n            vnode,\n            insertedVnodeQueue,\n            parentElm,\n            refElm,\n            nested,\n            ownerArray,\n            index\n        ) {\n            if (isDef(vnode.elm) && isDef(ownerArray)) {\n                // This vnode was used in a previous render!\n                // now it's used as a new node, overwriting its elm would cause\n                // potential patch errors down the road when it's used as an insertion\n                // reference node. Instead, we clone the node on-demand before creating\n                // associated DOM element for it.\n                vnode = ownerArray[index] = cloneVNode(vnode);\n            }\n\n            vnode.isRootInsert = !nested; // for transition enter check\n            if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {\n                return\n            }\n\n            var data = vnode.data;\n            var children = vnode.children;\n            var tag = vnode.tag;\n            if (isDef(tag)) {\n                {\n                    if (data && data.pre) {\n                        creatingElmInVPre++;\n                    }\n                    if (isUnknownElement$$1(vnode, creatingElmInVPre)) {\n                        warn(\n                            'Unknown custom element: <' + tag + '> - did you ' +\n                            'register the component correctly? For recursive components, ' +\n                            'make sure to provide the \"name\" option.',\n                            vnode.context\n                        );\n                    }\n                }\n\n                vnode.elm = vnode.ns\n                    ? nodeOps.createElementNS(vnode.ns, tag)\n                    : nodeOps.createElement(tag, vnode);\n                setScope(vnode);\n\n                /* istanbul ignore if */\n                {\n                    createChildren(vnode, children, insertedVnodeQueue);\n                    if (isDef(data)) {\n                        invokeCreateHooks(vnode, insertedVnodeQueue);\n                    }\n                    insert(parentElm, vnode.elm, refElm);\n                }\n\n                if (data && data.pre) {\n                    creatingElmInVPre--;\n                }\n            } else if (isTrue(vnode.isComment)) {\n                vnode.elm = nodeOps.createComment(vnode.text);\n                insert(parentElm, vnode.elm, refElm);\n            } else {\n                vnode.elm = nodeOps.createTextNode(vnode.text);\n                insert(parentElm, vnode.elm, refElm);\n            }\n        }\n\n        function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {\n            var i = vnode.data;\n            if (isDef(i)) {\n                var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;\n                if (isDef(i = i.hook) && isDef(i = i.init)) {\n                    i(vnode, false /* hydrating */);\n                }\n                // after calling the init hook, if the vnode is a child component\n                // it should've created a child instance and mounted it. the child\n                // component also has set the placeholder vnode's elm.\n                // in that case we can just return the element and be done.\n                if (isDef(vnode.componentInstance)) {\n                    initComponent(vnode, insertedVnodeQueue);\n                    insert(parentElm, vnode.elm, refElm);\n                    if (isTrue(isReactivated)) {\n                        reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);\n                    }\n                    return true\n                }\n            }\n        }\n\n        function initComponent (vnode, insertedVnodeQueue) {\n            if (isDef(vnode.data.pendingInsert)) {\n                insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);\n                vnode.data.pendingInsert = null;\n            }\n            vnode.elm = vnode.componentInstance.$el;\n            if (isPatchable(vnode)) {\n                invokeCreateHooks(vnode, insertedVnodeQueue);\n                setScope(vnode);\n            } else {\n                // empty component root.\n                // skip all element-related modules except for ref (#3455)\n                registerRef(vnode);\n                // make sure to invoke the insert hook\n                insertedVnodeQueue.push(vnode);\n            }\n        }\n\n        function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {\n            var i;\n            // hack for #4339: a reactivated component with inner transition\n            // does not trigger because the inner node's created hooks are not called\n            // again. It's not ideal to involve module-specific logic in here but\n            // there doesn't seem to be a better way to do it.\n            var innerNode = vnode;\n            while (innerNode.componentInstance) {\n                innerNode = innerNode.componentInstance._vnode;\n                if (isDef(i = innerNode.data) && isDef(i = i.transition)) {\n                    for (i = 0; i < cbs.activate.length; ++i) {\n                        cbs.activate[i](emptyNode, innerNode);\n                    }\n                    insertedVnodeQueue.push(innerNode);\n                    break\n                }\n            }\n            // unlike a newly created component,\n            // a reactivated keep-alive component doesn't insert itself\n            insert(parentElm, vnode.elm, refElm);\n        }\n\n        function insert (parent, elm, ref$$1) {\n            if (isDef(parent)) {\n                if (isDef(ref$$1)) {\n                    if (nodeOps.parentNode(ref$$1) === parent) {\n                        nodeOps.insertBefore(parent, elm, ref$$1);\n                    }\n                } else {\n                    nodeOps.appendChild(parent, elm);\n                }\n            }\n        }\n\n        function createChildren (vnode, children, insertedVnodeQueue) {\n            if (Array.isArray(children)) {\n                {\n                    checkDuplicateKeys(children);\n                }\n                for (var i = 0; i < children.length; ++i) {\n                    createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i);\n                }\n            } else if (isPrimitive(vnode.text)) {\n                nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)));\n            }\n        }\n\n        function isPatchable (vnode) {\n            while (vnode.componentInstance) {\n                vnode = vnode.componentInstance._vnode;\n            }\n            return isDef(vnode.tag)\n        }\n\n        function invokeCreateHooks (vnode, insertedVnodeQueue) {\n            for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {\n                cbs.create[i$1](emptyNode, vnode);\n            }\n            i = vnode.data.hook; // Reuse variable\n            if (isDef(i)) {\n                if (isDef(i.create)) { i.create(emptyNode, vnode); }\n                if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }\n            }\n        }\n\n        // set scope id attribute for scoped CSS.\n        // this is implemented as a special case to avoid the overhead\n        // of going through the normal attribute patching process.\n        function setScope (vnode) {\n            var i;\n            if (isDef(i = vnode.fnScopeId)) {\n                nodeOps.setStyleScope(vnode.elm, i);\n            } else {\n                var ancestor = vnode;\n                while (ancestor) {\n                    if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n                        nodeOps.setStyleScope(vnode.elm, i);\n                    }\n                    ancestor = ancestor.parent;\n                }\n            }\n            // for slot content they should also get the scopeId from the host instance.\n            if (isDef(i = activeInstance) &&\n                i !== vnode.context &&\n                i !== vnode.fnContext &&\n                isDef(i = i.$options._scopeId)\n            ) {\n                nodeOps.setStyleScope(vnode.elm, i);\n            }\n        }\n\n        function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {\n            for (; startIdx <= endIdx; ++startIdx) {\n                createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx);\n            }\n        }\n\n        function invokeDestroyHook (vnode) {\n            var i, j;\n            var data = vnode.data;\n            if (isDef(data)) {\n                if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }\n                for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }\n            }\n            if (isDef(i = vnode.children)) {\n                for (j = 0; j < vnode.children.length; ++j) {\n                    invokeDestroyHook(vnode.children[j]);\n                }\n            }\n        }\n\n        function removeVnodes (vnodes, startIdx, endIdx) {\n            for (; startIdx <= endIdx; ++startIdx) {\n                var ch = vnodes[startIdx];\n                if (isDef(ch)) {\n                    if (isDef(ch.tag)) {\n                        removeAndInvokeRemoveHook(ch);\n                        invokeDestroyHook(ch);\n                    } else { // Text node\n                        removeNode(ch.elm);\n                    }\n                }\n            }\n        }\n\n        function removeAndInvokeRemoveHook (vnode, rm) {\n            if (isDef(rm) || isDef(vnode.data)) {\n                var i;\n                var listeners = cbs.remove.length + 1;\n                if (isDef(rm)) {\n                    // we have a recursively passed down rm callback\n                    // increase the listeners count\n                    rm.listeners += listeners;\n                } else {\n                    // directly removing\n                    rm = createRmCb(vnode.elm, listeners);\n                }\n                // recursively invoke hooks on child component root node\n                if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {\n                    removeAndInvokeRemoveHook(i, rm);\n                }\n                for (i = 0; i < cbs.remove.length; ++i) {\n                    cbs.remove[i](vnode, rm);\n                }\n                if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {\n                    i(vnode, rm);\n                } else {\n                    rm();\n                }\n            } else {\n                removeNode(vnode.elm);\n            }\n        }\n\n        function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {\n            var oldStartIdx = 0;\n            var newStartIdx = 0;\n            var oldEndIdx = oldCh.length - 1;\n            var oldStartVnode = oldCh[0];\n            var oldEndVnode = oldCh[oldEndIdx];\n            var newEndIdx = newCh.length - 1;\n            var newStartVnode = newCh[0];\n            var newEndVnode = newCh[newEndIdx];\n            var oldKeyToIdx, idxInOld, vnodeToMove, refElm;\n\n            // removeOnly is a special flag used only by <transition-group>\n            // to ensure removed elements stay in correct relative positions\n            // during leaving transitions\n            var canMove = !removeOnly;\n\n            {\n                checkDuplicateKeys(newCh);\n            }\n\n            while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n                if (isUndef(oldStartVnode)) {\n                    oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left\n                } else if (isUndef(oldEndVnode)) {\n                    oldEndVnode = oldCh[--oldEndIdx];\n                } else if (sameVnode(oldStartVnode, newStartVnode)) {\n                    patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);\n                    oldStartVnode = oldCh[++oldStartIdx];\n                    newStartVnode = newCh[++newStartIdx];\n                } else if (sameVnode(oldEndVnode, newEndVnode)) {\n                    patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);\n                    oldEndVnode = oldCh[--oldEndIdx];\n                    newEndVnode = newCh[--newEndIdx];\n                } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right\n                    patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);\n                    canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));\n                    oldStartVnode = oldCh[++oldStartIdx];\n                    newEndVnode = newCh[--newEndIdx];\n                } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left\n                    patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);\n                    canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);\n                    oldEndVnode = oldCh[--oldEndIdx];\n                    newStartVnode = newCh[++newStartIdx];\n                } else {\n                    if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }\n                    idxInOld = isDef(newStartVnode.key)\n                        ? oldKeyToIdx[newStartVnode.key]\n                        : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx);\n                    if (isUndef(idxInOld)) { // New element\n                        createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);\n                    } else {\n                        vnodeToMove = oldCh[idxInOld];\n                        if (sameVnode(vnodeToMove, newStartVnode)) {\n                            patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);\n                            oldCh[idxInOld] = undefined;\n                            canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm);\n                        } else {\n                            // same key but different element. treat as new element\n                            createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);\n                        }\n                    }\n                    newStartVnode = newCh[++newStartIdx];\n                }\n            }\n            if (oldStartIdx > oldEndIdx) {\n                refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;\n                addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);\n            } else if (newStartIdx > newEndIdx) {\n                removeVnodes(oldCh, oldStartIdx, oldEndIdx);\n            }\n        }\n\n        function checkDuplicateKeys (children) {\n            var seenKeys = {};\n            for (var i = 0; i < children.length; i++) {\n                var vnode = children[i];\n                var key = vnode.key;\n                if (isDef(key)) {\n                    if (seenKeys[key]) {\n                        warn(\n                            (\"Duplicate keys detected: '\" + key + \"'. This may cause an update error.\"),\n                            vnode.context\n                        );\n                    } else {\n                        seenKeys[key] = true;\n                    }\n                }\n            }\n        }\n\n        function findIdxInOld (node, oldCh, start, end) {\n            for (var i = start; i < end; i++) {\n                var c = oldCh[i];\n                if (isDef(c) && sameVnode(node, c)) { return i }\n            }\n        }\n\n        function patchVnode (\n            oldVnode,\n            vnode,\n            insertedVnodeQueue,\n            ownerArray,\n            index,\n            removeOnly\n        ) {\n            if (oldVnode === vnode) {\n                return\n            }\n\n            if (isDef(vnode.elm) && isDef(ownerArray)) {\n                // clone reused vnode\n                vnode = ownerArray[index] = cloneVNode(vnode);\n            }\n\n            var elm = vnode.elm = oldVnode.elm;\n\n            if (isTrue(oldVnode.isAsyncPlaceholder)) {\n                if (isDef(vnode.asyncFactory.resolved)) {\n                    hydrate(oldVnode.elm, vnode, insertedVnodeQueue);\n                } else {\n                    vnode.isAsyncPlaceholder = true;\n                }\n                return\n            }\n\n            // reuse element for static trees.\n            // note we only do this if the vnode is cloned -\n            // if the new node is not cloned it means the render functions have been\n            // reset by the hot-reload-api and we need to do a proper re-render.\n            if (isTrue(vnode.isStatic) &&\n                isTrue(oldVnode.isStatic) &&\n                vnode.key === oldVnode.key &&\n                (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))\n            ) {\n                vnode.componentInstance = oldVnode.componentInstance;\n                return\n            }\n\n            var i;\n            var data = vnode.data;\n            if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {\n                i(oldVnode, vnode);\n            }\n\n            var oldCh = oldVnode.children;\n            var ch = vnode.children;\n            if (isDef(data) && isPatchable(vnode)) {\n                for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }\n                if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }\n            }\n            if (isUndef(vnode.text)) {\n                if (isDef(oldCh) && isDef(ch)) {\n                    if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }\n                } else if (isDef(ch)) {\n                    {\n                        checkDuplicateKeys(ch);\n                    }\n                    if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }\n                    addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);\n                } else if (isDef(oldCh)) {\n                    removeVnodes(oldCh, 0, oldCh.length - 1);\n                } else if (isDef(oldVnode.text)) {\n                    nodeOps.setTextContent(elm, '');\n                }\n            } else if (oldVnode.text !== vnode.text) {\n                nodeOps.setTextContent(elm, vnode.text);\n            }\n            if (isDef(data)) {\n                if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }\n            }\n        }\n\n        function invokeInsertHook (vnode, queue, initial) {\n            // delay insert hooks for component root nodes, invoke them after the\n            // element is really inserted\n            if (isTrue(initial) && isDef(vnode.parent)) {\n                vnode.parent.data.pendingInsert = queue;\n            } else {\n                for (var i = 0; i < queue.length; ++i) {\n                    queue[i].data.hook.insert(queue[i]);\n                }\n            }\n        }\n\n        var hydrationBailed = false;\n        // list of modules that can skip create hook during hydration because they\n        // are already rendered on the client or has no need for initialization\n        // Note: style is excluded because it relies on initial clone for future\n        // deep updates (#7063).\n        var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key');\n\n        // Note: this is a browser-only function so we can assume elms are DOM nodes.\n        function hydrate (elm, vnode, insertedVnodeQueue, inVPre) {\n            var i;\n            var tag = vnode.tag;\n            var data = vnode.data;\n            var children = vnode.children;\n            inVPre = inVPre || (data && data.pre);\n            vnode.elm = elm;\n\n            if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {\n                vnode.isAsyncPlaceholder = true;\n                return true\n            }\n            // assert node match\n            {\n                if (!assertNodeMatch(elm, vnode, inVPre)) {\n                    return false\n                }\n            }\n            if (isDef(data)) {\n                if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }\n                if (isDef(i = vnode.componentInstance)) {\n                    // child component. it should have hydrated its own tree.\n                    initComponent(vnode, insertedVnodeQueue);\n                    return true\n                }\n            }\n            if (isDef(tag)) {\n                if (isDef(children)) {\n                    // empty element, allow client to pick up and populate children\n                    if (!elm.hasChildNodes()) {\n                        createChildren(vnode, children, insertedVnodeQueue);\n                    } else {\n                        // v-html and domProps: innerHTML\n                        if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {\n                            if (i !== elm.innerHTML) {\n                                /* istanbul ignore if */\n                                if (typeof console !== 'undefined' &&\n                                    !hydrationBailed\n                                ) {\n                                    hydrationBailed = true;\n                                    console.warn('Parent: ', elm);\n                                    console.warn('server innerHTML: ', i);\n                                    console.warn('client innerHTML: ', elm.innerHTML);\n                                }\n                                return false\n                            }\n                        } else {\n                            // iterate and compare children lists\n                            var childrenMatch = true;\n                            var childNode = elm.firstChild;\n                            for (var i$1 = 0; i$1 < children.length; i$1++) {\n                                if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) {\n                                    childrenMatch = false;\n                                    break\n                                }\n                                childNode = childNode.nextSibling;\n                            }\n                            // if childNode is not null, it means the actual childNodes list is\n                            // longer than the virtual children list.\n                            if (!childrenMatch || childNode) {\n                                /* istanbul ignore if */\n                                if (typeof console !== 'undefined' &&\n                                    !hydrationBailed\n                                ) {\n                                    hydrationBailed = true;\n                                    console.warn('Parent: ', elm);\n                                    console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);\n                                }\n                                return false\n                            }\n                        }\n                    }\n                }\n                if (isDef(data)) {\n                    var fullInvoke = false;\n                    for (var key in data) {\n                        if (!isRenderedModule(key)) {\n                            fullInvoke = true;\n                            invokeCreateHooks(vnode, insertedVnodeQueue);\n                            break\n                        }\n                    }\n                    if (!fullInvoke && data['class']) {\n                        // ensure collecting deps for deep class bindings for future updates\n                        traverse(data['class']);\n                    }\n                }\n            } else if (elm.data !== vnode.text) {\n                elm.data = vnode.text;\n            }\n            return true\n        }\n\n        function assertNodeMatch (node, vnode, inVPre) {\n            if (isDef(vnode.tag)) {\n                return vnode.tag.indexOf('vue-component') === 0 || (\n                    !isUnknownElement$$1(vnode, inVPre) &&\n                    vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())\n                )\n            } else {\n                return node.nodeType === (vnode.isComment ? 8 : 3)\n            }\n        }\n\n        return function patch (oldVnode, vnode, hydrating, removeOnly) {\n            if (isUndef(vnode)) {\n                if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); }\n                return\n            }\n\n            var isInitialPatch = false;\n            var insertedVnodeQueue = [];\n\n            if (isUndef(oldVnode)) {\n                // empty mount (likely as component), create new root element\n                isInitialPatch = true;\n                createElm(vnode, insertedVnodeQueue);\n            } else {\n                var isRealElement = isDef(oldVnode.nodeType);\n                if (!isRealElement && sameVnode(oldVnode, vnode)) {\n                    // patch existing root node\n                    patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly);\n                } else {\n                    if (isRealElement) {\n                        // mounting to a real element\n                        // check if this is server-rendered content and if we can perform\n                        // a successful hydration.\n                        if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {\n                            oldVnode.removeAttribute(SSR_ATTR);\n                            hydrating = true;\n                        }\n                        if (isTrue(hydrating)) {\n                            if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {\n                                invokeInsertHook(vnode, insertedVnodeQueue, true);\n                                return oldVnode\n                            } else {\n                                warn(\n                                    'The client-side rendered virtual DOM tree is not matching ' +\n                                    'server-rendered content. This is likely caused by incorrect ' +\n                                    'HTML markup, for example nesting block-level elements inside ' +\n                                    '<p>, or missing <tbody>. Bailing hydration and performing ' +\n                                    'full client-side render.'\n                                );\n                            }\n                        }\n                        // either not server-rendered, or hydration failed.\n                        // create an empty node and replace it\n                        oldVnode = emptyNodeAt(oldVnode);\n                    }\n\n                    // replacing existing element\n                    var oldElm = oldVnode.elm;\n                    var parentElm = nodeOps.parentNode(oldElm);\n\n                    // create new node\n                    createElm(\n                        vnode,\n                        insertedVnodeQueue,\n                        // extremely rare edge case: do not insert if old element is in a\n                        // leaving transition. Only happens when combining transition +\n                        // keep-alive + HOCs. (#4590)\n                        oldElm._leaveCb ? null : parentElm,\n                        nodeOps.nextSibling(oldElm)\n                    );\n\n                    // update parent placeholder node element, recursively\n                    if (isDef(vnode.parent)) {\n                        var ancestor = vnode.parent;\n                        var patchable = isPatchable(vnode);\n                        while (ancestor) {\n                            for (var i = 0; i < cbs.destroy.length; ++i) {\n                                cbs.destroy[i](ancestor);\n                            }\n                            ancestor.elm = vnode.elm;\n                            if (patchable) {\n                                for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {\n                                    cbs.create[i$1](emptyNode, ancestor);\n                                }\n                                // #6513\n                                // invoke insert hooks that may have been merged by create hooks.\n                                // e.g. for directives that uses the \"inserted\" hook.\n                                var insert = ancestor.data.hook.insert;\n                                if (insert.merged) {\n                                    // start at index 1 to avoid re-invoking component mounted hook\n                                    for (var i$2 = 1; i$2 < insert.fns.length; i$2++) {\n                                        insert.fns[i$2]();\n                                    }\n                                }\n                            } else {\n                                registerRef(ancestor);\n                            }\n                            ancestor = ancestor.parent;\n                        }\n                    }\n\n                    // destroy old node\n                    if (isDef(parentElm)) {\n                        removeVnodes([oldVnode], 0, 0);\n                    } else if (isDef(oldVnode.tag)) {\n                        invokeDestroyHook(oldVnode);\n                    }\n                }\n            }\n\n            invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);\n            return vnode.elm\n        }\n    }\n\n    /*  */\n\n    var directives = {\n        create: updateDirectives,\n        update: updateDirectives,\n        destroy: function unbindDirectives (vnode) {\n            updateDirectives(vnode, emptyNode);\n        }\n    };\n\n    function updateDirectives (oldVnode, vnode) {\n        if (oldVnode.data.directives || vnode.data.directives) {\n            _update(oldVnode, vnode);\n        }\n    }\n\n    function _update (oldVnode, vnode) {\n        var isCreate = oldVnode === emptyNode;\n        var isDestroy = vnode === emptyNode;\n        var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);\n        var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);\n\n        var dirsWithInsert = [];\n        var dirsWithPostpatch = [];\n\n        var key, oldDir, dir;\n        for (key in newDirs) {\n            oldDir = oldDirs[key];\n            dir = newDirs[key];\n            if (!oldDir) {\n                // new directive, bind\n                callHook$1(dir, 'bind', vnode, oldVnode);\n                if (dir.def && dir.def.inserted) {\n                    dirsWithInsert.push(dir);\n                }\n            } else {\n                // existing directive, update\n                dir.oldValue = oldDir.value;\n                dir.oldArg = oldDir.arg;\n                callHook$1(dir, 'update', vnode, oldVnode);\n                if (dir.def && dir.def.componentUpdated) {\n                    dirsWithPostpatch.push(dir);\n                }\n            }\n        }\n\n        if (dirsWithInsert.length) {\n            var callInsert = function () {\n                for (var i = 0; i < dirsWithInsert.length; i++) {\n                    callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);\n                }\n            };\n            if (isCreate) {\n                mergeVNodeHook(vnode, 'insert', callInsert);\n            } else {\n                callInsert();\n            }\n        }\n\n        if (dirsWithPostpatch.length) {\n            mergeVNodeHook(vnode, 'postpatch', function () {\n                for (var i = 0; i < dirsWithPostpatch.length; i++) {\n                    callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);\n                }\n            });\n        }\n\n        if (!isCreate) {\n            for (key in oldDirs) {\n                if (!newDirs[key]) {\n                    // no longer present, unbind\n                    callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);\n                }\n            }\n        }\n    }\n\n    var emptyModifiers = Object.create(null);\n\n    function normalizeDirectives$1 (\n        dirs,\n        vm\n    ) {\n        var res = Object.create(null);\n        if (!dirs) {\n            // $flow-disable-line\n            return res\n        }\n        var i, dir;\n        for (i = 0; i < dirs.length; i++) {\n            dir = dirs[i];\n            if (!dir.modifiers) {\n                // $flow-disable-line\n                dir.modifiers = emptyModifiers;\n            }\n            res[getRawDirName(dir)] = dir;\n            dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);\n        }\n        // $flow-disable-line\n        return res\n    }\n\n    function getRawDirName (dir) {\n        return dir.rawName || ((dir.name) + \".\" + (Object.keys(dir.modifiers || {}).join('.')))\n    }\n\n    function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {\n        var fn = dir.def && dir.def[hook];\n        if (fn) {\n            try {\n                fn(vnode.elm, dir, vnode, oldVnode, isDestroy);\n            } catch (e) {\n                handleError(e, vnode.context, (\"directive \" + (dir.name) + \" \" + hook + \" hook\"));\n            }\n        }\n    }\n\n    var baseModules = [\n        ref,\n        directives\n    ];\n\n    /*  */\n\n    function updateAttrs (oldVnode, vnode) {\n        var opts = vnode.componentOptions;\n        if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) {\n            return\n        }\n        if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {\n            return\n        }\n        var key, cur, old;\n        var elm = vnode.elm;\n        var oldAttrs = oldVnode.data.attrs || {};\n        var attrs = vnode.data.attrs || {};\n        // clone observed objects, as the user probably wants to mutate it\n        if (isDef(attrs.__ob__)) {\n            attrs = vnode.data.attrs = extend({}, attrs);\n        }\n\n        for (key in attrs) {\n            cur = attrs[key];\n            old = oldAttrs[key];\n            if (old !== cur) {\n                setAttr(elm, key, cur, vnode.data.pre);\n            }\n        }\n        // #4391: in IE9, setting type can reset value for input[type=radio]\n        // #6666: IE/Edge forces progress value down to 1 before setting a max\n        /* istanbul ignore if */\n        if ((isIE || isEdge) && attrs.value !== oldAttrs.value) {\n            setAttr(elm, 'value', attrs.value);\n        }\n        for (key in oldAttrs) {\n            if (isUndef(attrs[key])) {\n                if (isXlink(key)) {\n                    elm.removeAttributeNS(xlinkNS, getXlinkProp(key));\n                } else if (!isEnumeratedAttr(key)) {\n                    elm.removeAttribute(key);\n                }\n            }\n        }\n    }\n\n    function setAttr (el, key, value, isInPre) {\n        if (isInPre || el.tagName.indexOf('-') > -1) {\n            baseSetAttr(el, key, value);\n        } else if (isBooleanAttr(key)) {\n            // set attribute for blank value\n            // e.g. <option disabled>Select one</option>\n            if (isFalsyAttrValue(value)) {\n                el.removeAttribute(key);\n            } else {\n                // technically allowfullscreen is a boolean attribute for <iframe>,\n                // but Flash expects a value of \"true\" when used on <embed> tag\n                value = key === 'allowfullscreen' && el.tagName === 'EMBED'\n                    ? 'true'\n                    : key;\n                el.setAttribute(key, value);\n            }\n        } else if (isEnumeratedAttr(key)) {\n            el.setAttribute(key, convertEnumeratedValue(key, value));\n        } else if (isXlink(key)) {\n            if (isFalsyAttrValue(value)) {\n                el.removeAttributeNS(xlinkNS, getXlinkProp(key));\n            } else {\n                el.setAttributeNS(xlinkNS, key, value);\n            }\n        } else {\n            baseSetAttr(el, key, value);\n        }\n    }\n\n    function baseSetAttr (el, key, value) {\n        if (isFalsyAttrValue(value)) {\n            el.removeAttribute(key);\n        } else {\n            // #7138: IE10 & 11 fires input event when setting placeholder on\n            // <textarea>... block the first input event and remove the blocker\n            // immediately.\n            /* istanbul ignore if */\n            if (\n                isIE && !isIE9 &&\n                el.tagName === 'TEXTAREA' &&\n                key === 'placeholder' && value !== '' && !el.__ieph\n            ) {\n                var blocker = function (e) {\n                    e.stopImmediatePropagation();\n                    el.removeEventListener('input', blocker);\n                };\n                el.addEventListener('input', blocker);\n                // $flow-disable-line\n                el.__ieph = true; /* IE placeholder patched */\n            }\n            el.setAttribute(key, value);\n        }\n    }\n\n    var attrs = {\n        create: updateAttrs,\n        update: updateAttrs\n    };\n\n    /*  */\n\n    function updateClass (oldVnode, vnode) {\n        var el = vnode.elm;\n        var data = vnode.data;\n        var oldData = oldVnode.data;\n        if (\n            isUndef(data.staticClass) &&\n            isUndef(data.class) && (\n                isUndef(oldData) || (\n                    isUndef(oldData.staticClass) &&\n                    isUndef(oldData.class)\n                )\n            )\n        ) {\n            return\n        }\n\n        var cls = genClassForVnode(vnode);\n\n        // handle transition classes\n        var transitionClass = el._transitionClasses;\n        if (isDef(transitionClass)) {\n            cls = concat(cls, stringifyClass(transitionClass));\n        }\n\n        // set the class\n        if (cls !== el._prevClass) {\n            el.setAttribute('class', cls);\n            el._prevClass = cls;\n        }\n    }\n\n    var klass = {\n        create: updateClass,\n        update: updateClass\n    };\n\n    /*  */\n\n    var validDivisionCharRE = /[\\w).+\\-_$\\]]/;\n\n    function parseFilters (exp) {\n        var inSingle = false;\n        var inDouble = false;\n        var inTemplateString = false;\n        var inRegex = false;\n        var curly = 0;\n        var square = 0;\n        var paren = 0;\n        var lastFilterIndex = 0;\n        var c, prev, i, expression, filters;\n\n        for (i = 0; i < exp.length; i++) {\n            prev = c;\n            c = exp.charCodeAt(i);\n            if (inSingle) {\n                if (c === 0x27 && prev !== 0x5C) { inSingle = false; }\n            } else if (inDouble) {\n                if (c === 0x22 && prev !== 0x5C) { inDouble = false; }\n            } else if (inTemplateString) {\n                if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }\n            } else if (inRegex) {\n                if (c === 0x2f && prev !== 0x5C) { inRegex = false; }\n            } else if (\n                c === 0x7C && // pipe\n                exp.charCodeAt(i + 1) !== 0x7C &&\n                exp.charCodeAt(i - 1) !== 0x7C &&\n                !curly && !square && !paren\n            ) {\n                if (expression === undefined) {\n                    // first filter, end of expression\n                    lastFilterIndex = i + 1;\n                    expression = exp.slice(0, i).trim();\n                } else {\n                    pushFilter();\n                }\n            } else {\n                switch (c) {\n                    case 0x22: inDouble = true; break         // \"\n                    case 0x27: inSingle = true; break         // '\n                    case 0x60: inTemplateString = true; break // `\n                    case 0x28: paren++; break                 // (\n                    case 0x29: paren--; break                 // )\n                    case 0x5B: square++; break                // [\n                    case 0x5D: square--; break                // ]\n                    case 0x7B: curly++; break                 // {\n                    case 0x7D: curly--; break                 // }\n                }\n                if (c === 0x2f) { // /\n                    var j = i - 1;\n                    var p = (void 0);\n                    // find first non-whitespace prev char\n                    for (; j >= 0; j--) {\n                        p = exp.charAt(j);\n                        if (p !== ' ') { break }\n                    }\n                    if (!p || !validDivisionCharRE.test(p)) {\n                        inRegex = true;\n                    }\n                }\n            }\n        }\n\n        if (expression === undefined) {\n            expression = exp.slice(0, i).trim();\n        } else if (lastFilterIndex !== 0) {\n            pushFilter();\n        }\n\n        function pushFilter () {\n            (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());\n            lastFilterIndex = i + 1;\n        }\n\n        if (filters) {\n            for (i = 0; i < filters.length; i++) {\n                expression = wrapFilter(expression, filters[i]);\n            }\n        }\n\n        return expression\n    }\n\n    function wrapFilter (exp, filter) {\n        var i = filter.indexOf('(');\n        if (i < 0) {\n            // _f: resolveFilter\n            return (\"_f(\\\"\" + filter + \"\\\")(\" + exp + \")\")\n        } else {\n            var name = filter.slice(0, i);\n            var args = filter.slice(i + 1);\n            return (\"_f(\\\"\" + name + \"\\\")(\" + exp + (args !== ')' ? ',' + args : args))\n        }\n    }\n\n    /*  */\n\n\n\n    /* eslint-disable no-unused-vars */\n    function baseWarn (msg, range) {\n        console.error((\"[Vue compiler]: \" + msg));\n    }\n    /* eslint-enable no-unused-vars */\n\n    function pluckModuleFunction (\n        modules,\n        key\n    ) {\n        return modules\n            ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })\n            : []\n    }\n\n    function addProp (el, name, value, range, dynamic) {\n        (el.props || (el.props = [])).push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range));\n        el.plain = false;\n    }\n\n    function addAttr (el, name, value, range, dynamic) {\n        var attrs = dynamic\n            ? (el.dynamicAttrs || (el.dynamicAttrs = []))\n            : (el.attrs || (el.attrs = []));\n        attrs.push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range));\n        el.plain = false;\n    }\n\n    // add a raw attr (use this in preTransforms)\n    function addRawAttr (el, name, value, range) {\n        el.attrsMap[name] = value;\n        el.attrsList.push(rangeSetItem({ name: name, value: value }, range));\n    }\n\n    function addDirective (\n        el,\n        name,\n        rawName,\n        value,\n        arg,\n        isDynamicArg,\n        modifiers,\n        range\n    ) {\n        (el.directives || (el.directives = [])).push(rangeSetItem({\n            name: name,\n            rawName: rawName,\n            value: value,\n            arg: arg,\n            isDynamicArg: isDynamicArg,\n            modifiers: modifiers\n        }, range));\n        el.plain = false;\n    }\n\n    function prependModifierMarker (symbol, name, dynamic) {\n        return dynamic\n            ? (\"_p(\" + name + \",\\\"\" + symbol + \"\\\")\")\n            : symbol + name // mark the event as captured\n    }\n\n    function addHandler (\n        el,\n        name,\n        value,\n        modifiers,\n        important,\n        warn,\n        range,\n        dynamic\n    ) {\n        modifiers = modifiers || emptyObject;\n        // warn prevent and passive modifier\n        /* istanbul ignore if */\n        if (\n            warn &&\n            modifiers.prevent && modifiers.passive\n        ) {\n            warn(\n                'passive and prevent can\\'t be used together. ' +\n                'Passive handler can\\'t prevent default event.',\n                range\n            );\n        }\n\n        // normalize click.right and click.middle since they don't actually fire\n        // this is technically browser-specific, but at least for now browsers are\n        // the only target envs that have right/middle clicks.\n        if (modifiers.right) {\n            if (dynamic) {\n                name = \"(\" + name + \")==='click'?'contextmenu':(\" + name + \")\";\n            } else if (name === 'click') {\n                name = 'contextmenu';\n                delete modifiers.right;\n            }\n        } else if (modifiers.middle) {\n            if (dynamic) {\n                name = \"(\" + name + \")==='click'?'mouseup':(\" + name + \")\";\n            } else if (name === 'click') {\n                name = 'mouseup';\n            }\n        }\n\n        // check capture modifier\n        if (modifiers.capture) {\n            delete modifiers.capture;\n            name = prependModifierMarker('!', name, dynamic);\n        }\n        if (modifiers.once) {\n            delete modifiers.once;\n            name = prependModifierMarker('~', name, dynamic);\n        }\n        /* istanbul ignore if */\n        if (modifiers.passive) {\n            delete modifiers.passive;\n            name = prependModifierMarker('&', name, dynamic);\n        }\n\n        var events;\n        if (modifiers.native) {\n            delete modifiers.native;\n            events = el.nativeEvents || (el.nativeEvents = {});\n        } else {\n            events = el.events || (el.events = {});\n        }\n\n        var newHandler = rangeSetItem({ value: value.trim(), dynamic: dynamic }, range);\n        if (modifiers !== emptyObject) {\n            newHandler.modifiers = modifiers;\n        }\n\n        var handlers = events[name];\n        /* istanbul ignore if */\n        if (Array.isArray(handlers)) {\n            important ? handlers.unshift(newHandler) : handlers.push(newHandler);\n        } else if (handlers) {\n            events[name] = important ? [newHandler, handlers] : [handlers, newHandler];\n        } else {\n            events[name] = newHandler;\n        }\n\n        el.plain = false;\n    }\n\n    function getRawBindingAttr (\n        el,\n        name\n    ) {\n        return el.rawAttrsMap[':' + name] ||\n            el.rawAttrsMap['v-bind:' + name] ||\n            el.rawAttrsMap[name]\n    }\n\n    function getBindingAttr (\n        el,\n        name,\n        getStatic\n    ) {\n        var dynamicValue =\n            getAndRemoveAttr(el, ':' + name) ||\n            getAndRemoveAttr(el, 'v-bind:' + name);\n        if (dynamicValue != null) {\n            return parseFilters(dynamicValue)\n        } else if (getStatic !== false) {\n            var staticValue = getAndRemoveAttr(el, name);\n            if (staticValue != null) {\n                return JSON.stringify(staticValue)\n            }\n        }\n    }\n\n    // note: this only removes the attr from the Array (attrsList) so that it\n    // doesn't get processed by processAttrs.\n    // By default it does NOT remove it from the map (attrsMap) because the map is\n    // needed during codegen.\n    function getAndRemoveAttr (\n        el,\n        name,\n        removeFromMap\n    ) {\n        var val;\n        if ((val = el.attrsMap[name]) != null) {\n            var list = el.attrsList;\n            for (var i = 0, l = list.length; i < l; i++) {\n                if (list[i].name === name) {\n                    list.splice(i, 1);\n                    break\n                }\n            }\n        }\n        if (removeFromMap) {\n            delete el.attrsMap[name];\n        }\n        return val\n    }\n\n    function getAndRemoveAttrByRegex (\n        el,\n        name\n    ) {\n        var list = el.attrsList;\n        for (var i = 0, l = list.length; i < l; i++) {\n            var attr = list[i];\n            if (name.test(attr.name)) {\n                list.splice(i, 1);\n                return attr\n            }\n        }\n    }\n\n    function rangeSetItem (\n        item,\n        range\n    ) {\n        if (range) {\n            if (range.start != null) {\n                item.start = range.start;\n            }\n            if (range.end != null) {\n                item.end = range.end;\n            }\n        }\n        return item\n    }\n\n    /*  */\n\n    /**\n     * Cross-platform code generation for component v-model\n     */\n    function genComponentModel (\n        el,\n        value,\n        modifiers\n    ) {\n        var ref = modifiers || {};\n        var number = ref.number;\n        var trim = ref.trim;\n\n        var baseValueExpression = '$$v';\n        var valueExpression = baseValueExpression;\n        if (trim) {\n            valueExpression =\n                \"(typeof \" + baseValueExpression + \" === 'string'\" +\n                \"? \" + baseValueExpression + \".trim()\" +\n                \": \" + baseValueExpression + \")\";\n        }\n        if (number) {\n            valueExpression = \"_n(\" + valueExpression + \")\";\n        }\n        var assignment = genAssignmentCode(value, valueExpression);\n\n        el.model = {\n            value: (\"(\" + value + \")\"),\n            expression: JSON.stringify(value),\n            callback: (\"function (\" + baseValueExpression + \") {\" + assignment + \"}\")\n        };\n    }\n\n    /**\n     * Cross-platform codegen helper for generating v-model value assignment code.\n     */\n    function genAssignmentCode (\n        value,\n        assignment\n    ) {\n        var res = parseModel(value);\n        if (res.key === null) {\n            return (value + \"=\" + assignment)\n        } else {\n            return (\"$set(\" + (res.exp) + \", \" + (res.key) + \", \" + assignment + \")\")\n        }\n    }\n\n    /**\n     * Parse a v-model expression into a base path and a final key segment.\n     * Handles both dot-path and possible square brackets.\n     *\n     * Possible cases:\n     *\n     * - test\n     * - test[key]\n     * - test[test1[key]]\n     * - test[\"a\"][key]\n     * - xxx.test[a[a].test1[key]]\n     * - test.xxx.a[\"asa\"][test1[key]]\n     *\n     */\n\n    var len, str, chr, index$1, expressionPos, expressionEndPos;\n\n\n\n    function parseModel (val) {\n        // Fix https://github.com/vuejs/vue/pull/7730\n        // allow v-model=\"obj.val \" (trailing whitespace)\n        val = val.trim();\n        len = val.length;\n\n        if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {\n            index$1 = val.lastIndexOf('.');\n            if (index$1 > -1) {\n                return {\n                    exp: val.slice(0, index$1),\n                    key: '\"' + val.slice(index$1 + 1) + '\"'\n                }\n            } else {\n                return {\n                    exp: val,\n                    key: null\n                }\n            }\n        }\n\n        str = val;\n        index$1 = expressionPos = expressionEndPos = 0;\n\n        while (!eof()) {\n            chr = next();\n            /* istanbul ignore if */\n            if (isStringStart(chr)) {\n                parseString(chr);\n            } else if (chr === 0x5B) {\n                parseBracket(chr);\n            }\n        }\n\n        return {\n            exp: val.slice(0, expressionPos),\n            key: val.slice(expressionPos + 1, expressionEndPos)\n        }\n    }\n\n    function next () {\n        return str.charCodeAt(++index$1)\n    }\n\n    function eof () {\n        return index$1 >= len\n    }\n\n    function isStringStart (chr) {\n        return chr === 0x22 || chr === 0x27\n    }\n\n    function parseBracket (chr) {\n        var inBracket = 1;\n        expressionPos = index$1;\n        while (!eof()) {\n            chr = next();\n            if (isStringStart(chr)) {\n                parseString(chr);\n                continue\n            }\n            if (chr === 0x5B) { inBracket++; }\n            if (chr === 0x5D) { inBracket--; }\n            if (inBracket === 0) {\n                expressionEndPos = index$1;\n                break\n            }\n        }\n    }\n\n    function parseString (chr) {\n        var stringQuote = chr;\n        while (!eof()) {\n            chr = next();\n            if (chr === stringQuote) {\n                break\n            }\n        }\n    }\n\n    /*  */\n\n    var warn$1;\n\n    // in some cases, the event used has to be determined at runtime\n    // so we used some reserved tokens during compile.\n    var RANGE_TOKEN = '__r';\n    var CHECKBOX_RADIO_TOKEN = '__c';\n\n    function model (\n        el,\n        dir,\n        _warn\n    ) {\n        warn$1 = _warn;\n        var value = dir.value;\n        var modifiers = dir.modifiers;\n        var tag = el.tag;\n        var type = el.attrsMap.type;\n\n        {\n            // inputs with type=\"file\" are read only and setting the input's\n            // value will throw an error.\n            if (tag === 'input' && type === 'file') {\n                warn$1(\n                    \"<\" + (el.tag) + \" v-model=\\\"\" + value + \"\\\" type=\\\"file\\\">:\\n\" +\n                    \"File inputs are read only. Use a v-on:change listener instead.\",\n                    el.rawAttrsMap['v-model']\n                );\n            }\n        }\n\n        if (el.component) {\n            genComponentModel(el, value, modifiers);\n            // component v-model doesn't need extra runtime\n            return false\n        } else if (tag === 'select') {\n            genSelect(el, value, modifiers);\n        } else if (tag === 'input' && type === 'checkbox') {\n            genCheckboxModel(el, value, modifiers);\n        } else if (tag === 'input' && type === 'radio') {\n            genRadioModel(el, value, modifiers);\n        } else if (tag === 'input' || tag === 'textarea') {\n            genDefaultModel(el, value, modifiers);\n        } else if (!config.isReservedTag(tag)) {\n            genComponentModel(el, value, modifiers);\n            // component v-model doesn't need extra runtime\n            return false\n        } else {\n            warn$1(\n                \"<\" + (el.tag) + \" v-model=\\\"\" + value + \"\\\">: \" +\n                \"v-model is not supported on this element type. \" +\n                'If you are working with contenteditable, it\\'s recommended to ' +\n                'wrap a library dedicated for that purpose inside a custom component.',\n                el.rawAttrsMap['v-model']\n            );\n        }\n\n        // ensure runtime directive metadata\n        return true\n    }\n\n    function genCheckboxModel (\n        el,\n        value,\n        modifiers\n    ) {\n        var number = modifiers && modifiers.number;\n        var valueBinding = getBindingAttr(el, 'value') || 'null';\n        var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';\n        var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';\n        addProp(el, 'checked',\n            \"Array.isArray(\" + value + \")\" +\n            \"?_i(\" + value + \",\" + valueBinding + \")>-1\" + (\n                trueValueBinding === 'true'\n                    ? (\":(\" + value + \")\")\n                    : (\":_q(\" + value + \",\" + trueValueBinding + \")\")\n            )\n        );\n        addHandler(el, 'change',\n            \"var $$a=\" + value + \",\" +\n            '$$el=$event.target,' +\n            \"$$c=$$el.checked?(\" + trueValueBinding + \"):(\" + falseValueBinding + \");\" +\n            'if(Array.isArray($$a)){' +\n            \"var $$v=\" + (number ? '_n(' + valueBinding + ')' : valueBinding) + \",\" +\n            '$$i=_i($$a,$$v);' +\n            \"if($$el.checked){$$i<0&&(\" + (genAssignmentCode(value, '$$a.concat([$$v])')) + \")}\" +\n            \"else{$$i>-1&&(\" + (genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')) + \")}\" +\n            \"}else{\" + (genAssignmentCode(value, '$$c')) + \"}\",\n            null, true\n        );\n    }\n\n    function genRadioModel (\n        el,\n        value,\n        modifiers\n    ) {\n        var number = modifiers && modifiers.number;\n        var valueBinding = getBindingAttr(el, 'value') || 'null';\n        valueBinding = number ? (\"_n(\" + valueBinding + \")\") : valueBinding;\n        addProp(el, 'checked', (\"_q(\" + value + \",\" + valueBinding + \")\"));\n        addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true);\n    }\n\n    function genSelect (\n        el,\n        value,\n        modifiers\n    ) {\n        var number = modifiers && modifiers.number;\n        var selectedVal = \"Array.prototype.filter\" +\n            \".call($event.target.options,function(o){return o.selected})\" +\n            \".map(function(o){var val = \\\"_value\\\" in o ? o._value : o.value;\" +\n            \"return \" + (number ? '_n(val)' : 'val') + \"})\";\n\n        var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]';\n        var code = \"var $$selectedVal = \" + selectedVal + \";\";\n        code = code + \" \" + (genAssignmentCode(value, assignment));\n        addHandler(el, 'change', code, null, true);\n    }\n\n    function genDefaultModel (\n        el,\n        value,\n        modifiers\n    ) {\n        var type = el.attrsMap.type;\n\n        // warn if v-bind:value conflicts with v-model\n        // except for inputs with v-bind:type\n        {\n            var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value'];\n            var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];\n            if (value$1 && !typeBinding) {\n                var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value';\n                warn$1(\n                    binding + \"=\\\"\" + value$1 + \"\\\" conflicts with v-model on the same element \" +\n                    'because the latter already expands to a value binding internally',\n                    el.rawAttrsMap[binding]\n                );\n            }\n        }\n\n        var ref = modifiers || {};\n        var lazy = ref.lazy;\n        var number = ref.number;\n        var trim = ref.trim;\n        var needCompositionGuard = !lazy && type !== 'range';\n        var event = lazy\n            ? 'change'\n            : type === 'range'\n                ? RANGE_TOKEN\n                : 'input';\n\n        var valueExpression = '$event.target.value';\n        if (trim) {\n            valueExpression = \"$event.target.value.trim()\";\n        }\n        if (number) {\n            valueExpression = \"_n(\" + valueExpression + \")\";\n        }\n\n        var code = genAssignmentCode(value, valueExpression);\n        if (needCompositionGuard) {\n            code = \"if($event.target.composing)return;\" + code;\n        }\n\n        addProp(el, 'value', (\"(\" + value + \")\"));\n        addHandler(el, event, code, null, true);\n        if (trim || number) {\n            addHandler(el, 'blur', '$forceUpdate()');\n        }\n    }\n\n    /*  */\n\n    // normalize v-model event tokens that can only be determined at runtime.\n    // it's important to place the event as the first in the array because\n    // the whole point is ensuring the v-model callback gets called before\n    // user-attached handlers.\n    function normalizeEvents (on) {\n        /* istanbul ignore if */\n        if (isDef(on[RANGE_TOKEN])) {\n            // IE input[type=range] only supports `change` event\n            var event = isIE ? 'change' : 'input';\n            on[event] = [].concat(on[RANGE_TOKEN], on[event] || []);\n            delete on[RANGE_TOKEN];\n        }\n        // This was originally intended to fix #4521 but no longer necessary\n        // after 2.5. Keeping it for backwards compat with generated code from < 2.4\n        /* istanbul ignore if */\n        if (isDef(on[CHECKBOX_RADIO_TOKEN])) {\n            on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []);\n            delete on[CHECKBOX_RADIO_TOKEN];\n        }\n    }\n\n    var target$1;\n\n    function createOnceHandler$1 (event, handler, capture) {\n        var _target = target$1; // save current target element in closure\n        return function onceHandler () {\n            var res = handler.apply(null, arguments);\n            if (res !== null) {\n                remove$2(event, onceHandler, capture, _target);\n            }\n        }\n    }\n\n    // #9446: Firefox <= 53 (in particular, ESR 52) has incorrect Event.timeStamp\n    // implementation and does not fire microtasks in between event propagation, so\n    // safe to exclude.\n    var useMicrotaskFix = isUsingMicroTask && !(isFF && Number(isFF[1]) <= 53);\n\n    function add$1 (\n        name,\n        handler,\n        capture,\n        passive\n    ) {\n        // async edge case #6566: inner click event triggers patch, event handler\n        // attached to outer element during patch, and triggered again. This\n        // happens because browsers fire microtask ticks between event propagation.\n        // the solution is simple: we save the timestamp when a handler is attached,\n        // and the handler would only fire if the event passed to it was fired\n        // AFTER it was attached.\n        if (useMicrotaskFix) {\n            var attachedTimestamp = currentFlushTimestamp;\n            var original = handler;\n            handler = original._wrapper = function (e) {\n                if (\n                    // no bubbling, should always fire.\n                    // this is just a safety net in case event.timeStamp is unreliable in\n                    // certain weird environments...\n                    e.target === e.currentTarget ||\n                    // event is fired after handler attachment\n                    e.timeStamp >= attachedTimestamp ||\n                    // bail for environments that have buggy event.timeStamp implementations\n                    // #9462 iOS 9 bug: event.timeStamp is 0 after history.pushState\n                    // #9681 QtWebEngine event.timeStamp is negative value\n                    e.timeStamp <= 0 ||\n                    // #9448 bail if event is fired in another document in a multi-page\n                    // electron/nw.js app, since event.timeStamp will be using a different\n                    // starting reference\n                    e.target.ownerDocument !== document\n                ) {\n                    return original.apply(this, arguments)\n                }\n            };\n        }\n        target$1.addEventListener(\n            name,\n            handler,\n            supportsPassive\n                ? { capture: capture, passive: passive }\n                : capture\n        );\n    }\n\n    function remove$2 (\n        name,\n        handler,\n        capture,\n        _target\n    ) {\n        (_target || target$1).removeEventListener(\n            name,\n            handler._wrapper || handler,\n            capture\n        );\n    }\n\n    function updateDOMListeners (oldVnode, vnode) {\n        if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {\n            return\n        }\n        var on = vnode.data.on || {};\n        var oldOn = oldVnode.data.on || {};\n        target$1 = vnode.elm;\n        normalizeEvents(on);\n        updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context);\n        target$1 = undefined;\n    }\n\n    var events = {\n        create: updateDOMListeners,\n        update: updateDOMListeners\n    };\n\n    /*  */\n\n    var svgContainer;\n\n    function updateDOMProps (oldVnode, vnode) {\n        if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {\n            return\n        }\n        var key, cur;\n        var elm = vnode.elm;\n        var oldProps = oldVnode.data.domProps || {};\n        var props = vnode.data.domProps || {};\n        // clone observed objects, as the user probably wants to mutate it\n        if (isDef(props.__ob__)) {\n            props = vnode.data.domProps = extend({}, props);\n        }\n\n        for (key in oldProps) {\n            if (!(key in props)) {\n                elm[key] = '';\n            }\n        }\n\n        for (key in props) {\n            cur = props[key];\n            // ignore children if the node has textContent or innerHTML,\n            // as these will throw away existing DOM nodes and cause removal errors\n            // on subsequent patches (#3360)\n            if (key === 'textContent' || key === 'innerHTML') {\n                if (vnode.children) { vnode.children.length = 0; }\n                if (cur === oldProps[key]) { continue }\n                // #6601 work around Chrome version <= 55 bug where single textNode\n                // replaced by innerHTML/textContent retains its parentNode property\n                if (elm.childNodes.length === 1) {\n                    elm.removeChild(elm.childNodes[0]);\n                }\n            }\n\n            if (key === 'value' && elm.tagName !== 'PROGRESS') {\n                // store value as _value as well since\n                // non-string values will be stringified\n                elm._value = cur;\n                // avoid resetting cursor position when value is the same\n                var strCur = isUndef(cur) ? '' : String(cur);\n                if (shouldUpdateValue(elm, strCur)) {\n                    elm.value = strCur;\n                }\n            } else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) {\n                // IE doesn't support innerHTML for SVG elements\n                svgContainer = svgContainer || document.createElement('div');\n                svgContainer.innerHTML = \"<svg>\" + cur + \"</svg>\";\n                var svg = svgContainer.firstChild;\n                while (elm.firstChild) {\n                    elm.removeChild(elm.firstChild);\n                }\n                while (svg.firstChild) {\n                    elm.appendChild(svg.firstChild);\n                }\n            } else if (\n                // skip the update if old and new VDOM state is the same.\n                // `value` is handled separately because the DOM value may be temporarily\n                // out of sync with VDOM state due to focus, composition and modifiers.\n                // This  #4521 by skipping the unnecessary `checked` update.\n                cur !== oldProps[key]\n            ) {\n                // some property updates can throw\n                // e.g. `value` on <progress> w/ non-finite value\n                try {\n                    elm[key] = cur;\n                } catch (e) {}\n            }\n        }\n    }\n\n    // check platforms/web/util/attrs.js acceptValue\n\n\n    function shouldUpdateValue (elm, checkVal) {\n        return (!elm.composing && (\n            elm.tagName === 'OPTION' ||\n            isNotInFocusAndDirty(elm, checkVal) ||\n            isDirtyWithModifiers(elm, checkVal)\n        ))\n    }\n\n    function isNotInFocusAndDirty (elm, checkVal) {\n        // return true when textbox (.number and .trim) loses focus and its value is\n        // not equal to the updated value\n        var notInFocus = true;\n        // #6157\n        // work around IE bug when accessing document.activeElement in an iframe\n        try { notInFocus = document.activeElement !== elm; } catch (e) {}\n        return notInFocus && elm.value !== checkVal\n    }\n\n    function isDirtyWithModifiers (elm, newVal) {\n        var value = elm.value;\n        var modifiers = elm._vModifiers; // injected by v-model runtime\n        if (isDef(modifiers)) {\n            if (modifiers.number) {\n                return toNumber(value) !== toNumber(newVal)\n            }\n            if (modifiers.trim) {\n                return value.trim() !== newVal.trim()\n            }\n        }\n        return value !== newVal\n    }\n\n    var domProps = {\n        create: updateDOMProps,\n        update: updateDOMProps\n    };\n\n    /*  */\n\n    var parseStyleText = cached(function (cssText) {\n        var res = {};\n        var listDelimiter = /;(?![^(]*\\))/g;\n        var propertyDelimiter = /:(.+)/;\n        cssText.split(listDelimiter).forEach(function (item) {\n            if (item) {\n                var tmp = item.split(propertyDelimiter);\n                tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());\n            }\n        });\n        return res\n    });\n\n    // merge static and dynamic style data on the same vnode\n    function normalizeStyleData (data) {\n        var style = normalizeStyleBinding(data.style);\n        // static style is pre-processed into an object during compilation\n        // and is always a fresh object, so it's safe to merge into it\n        return data.staticStyle\n            ? extend(data.staticStyle, style)\n            : style\n    }\n\n    // normalize possible array / string values into Object\n    function normalizeStyleBinding (bindingStyle) {\n        if (Array.isArray(bindingStyle)) {\n            return toObject(bindingStyle)\n        }\n        if (typeof bindingStyle === 'string') {\n            return parseStyleText(bindingStyle)\n        }\n        return bindingStyle\n    }\n\n    /**\n     * parent component style should be after child's\n     * so that parent component's style could override it\n     */\n    function getStyle (vnode, checkChild) {\n        var res = {};\n        var styleData;\n\n        if (checkChild) {\n            var childNode = vnode;\n            while (childNode.componentInstance) {\n                childNode = childNode.componentInstance._vnode;\n                if (\n                    childNode && childNode.data &&\n                    (styleData = normalizeStyleData(childNode.data))\n                ) {\n                    extend(res, styleData);\n                }\n            }\n        }\n\n        if ((styleData = normalizeStyleData(vnode.data))) {\n            extend(res, styleData);\n        }\n\n        var parentNode = vnode;\n        while ((parentNode = parentNode.parent)) {\n            if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {\n                extend(res, styleData);\n            }\n        }\n        return res\n    }\n\n    /*  */\n\n    var cssVarRE = /^--/;\n    var importantRE = /\\s*!important$/;\n    var setProp = function (el, name, val) {\n        /* istanbul ignore if */\n        if (cssVarRE.test(name)) {\n            el.style.setProperty(name, val);\n        } else if (importantRE.test(val)) {\n            el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important');\n        } else {\n            var normalizedName = normalize(name);\n            if (Array.isArray(val)) {\n                // Support values array created by autoprefixer, e.g.\n                // {display: [\"-webkit-box\", \"-ms-flexbox\", \"flex\"]}\n                // Set them one by one, and the browser will only set those it can recognize\n                for (var i = 0, len = val.length; i < len; i++) {\n                    el.style[normalizedName] = val[i];\n                }\n            } else {\n                el.style[normalizedName] = val;\n            }\n        }\n    };\n\n    var vendorNames = ['Webkit', 'Moz', 'ms'];\n\n    var emptyStyle;\n    var normalize = cached(function (prop) {\n        emptyStyle = emptyStyle || document.createElement('div').style;\n        prop = camelize(prop);\n        if (prop !== 'filter' && (prop in emptyStyle)) {\n            return prop\n        }\n        var capName = prop.charAt(0).toUpperCase() + prop.slice(1);\n        for (var i = 0; i < vendorNames.length; i++) {\n            var name = vendorNames[i] + capName;\n            if (name in emptyStyle) {\n                return name\n            }\n        }\n    });\n\n    function updateStyle (oldVnode, vnode) {\n        var data = vnode.data;\n        var oldData = oldVnode.data;\n\n        if (isUndef(data.staticStyle) && isUndef(data.style) &&\n            isUndef(oldData.staticStyle) && isUndef(oldData.style)\n        ) {\n            return\n        }\n\n        var cur, name;\n        var el = vnode.elm;\n        var oldStaticStyle = oldData.staticStyle;\n        var oldStyleBinding = oldData.normalizedStyle || oldData.style || {};\n\n        // if static style exists, stylebinding already merged into it when doing normalizeStyleData\n        var oldStyle = oldStaticStyle || oldStyleBinding;\n\n        var style = normalizeStyleBinding(vnode.data.style) || {};\n\n        // store normalized style under a different key for next diff\n        // make sure to clone it if it's reactive, since the user likely wants\n        // to mutate it.\n        vnode.data.normalizedStyle = isDef(style.__ob__)\n            ? extend({}, style)\n            : style;\n\n        var newStyle = getStyle(vnode, true);\n\n        for (name in oldStyle) {\n            if (isUndef(newStyle[name])) {\n                setProp(el, name, '');\n            }\n        }\n        for (name in newStyle) {\n            cur = newStyle[name];\n            if (cur !== oldStyle[name]) {\n                // ie9 setting to null has no effect, must use empty string\n                setProp(el, name, cur == null ? '' : cur);\n            }\n        }\n    }\n\n    var style = {\n        create: updateStyle,\n        update: updateStyle\n    };\n\n    /*  */\n\n    var whitespaceRE = /\\s+/;\n\n    /**\n     * Add class with compatibility for SVG since classList is not supported on\n     * SVG elements in IE\n     */\n    function addClass (el, cls) {\n        /* istanbul ignore if */\n        if (!cls || !(cls = cls.trim())) {\n            return\n        }\n\n        /* istanbul ignore else */\n        if (el.classList) {\n            if (cls.indexOf(' ') > -1) {\n                cls.split(whitespaceRE).forEach(function (c) { return el.classList.add(c); });\n            } else {\n                el.classList.add(cls);\n            }\n        } else {\n            var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n            if (cur.indexOf(' ' + cls + ' ') < 0) {\n                el.setAttribute('class', (cur + cls).trim());\n            }\n        }\n    }\n\n    /**\n     * Remove class with compatibility for SVG since classList is not supported on\n     * SVG elements in IE\n     */\n    function removeClass (el, cls) {\n        /* istanbul ignore if */\n        if (!cls || !(cls = cls.trim())) {\n            return\n        }\n\n        /* istanbul ignore else */\n        if (el.classList) {\n            if (cls.indexOf(' ') > -1) {\n                cls.split(whitespaceRE).forEach(function (c) { return el.classList.remove(c); });\n            } else {\n                el.classList.remove(cls);\n            }\n            if (!el.classList.length) {\n                el.removeAttribute('class');\n            }\n        } else {\n            var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n            var tar = ' ' + cls + ' ';\n            while (cur.indexOf(tar) >= 0) {\n                cur = cur.replace(tar, ' ');\n            }\n            cur = cur.trim();\n            if (cur) {\n                el.setAttribute('class', cur);\n            } else {\n                el.removeAttribute('class');\n            }\n        }\n    }\n\n    /*  */\n\n    function resolveTransition (def$$1) {\n        if (!def$$1) {\n            return\n        }\n        /* istanbul ignore else */\n        if (typeof def$$1 === 'object') {\n            var res = {};\n            if (def$$1.css !== false) {\n                extend(res, autoCssTransition(def$$1.name || 'v'));\n            }\n            extend(res, def$$1);\n            return res\n        } else if (typeof def$$1 === 'string') {\n            return autoCssTransition(def$$1)\n        }\n    }\n\n    var autoCssTransition = cached(function (name) {\n        return {\n            enterClass: (name + \"-enter\"),\n            enterToClass: (name + \"-enter-to\"),\n            enterActiveClass: (name + \"-enter-active\"),\n            leaveClass: (name + \"-leave\"),\n            leaveToClass: (name + \"-leave-to\"),\n            leaveActiveClass: (name + \"-leave-active\")\n        }\n    });\n\n    var hasTransition = inBrowser && !isIE9;\n    var TRANSITION = 'transition';\n    var ANIMATION = 'animation';\n\n    // Transition property/event sniffing\n    var transitionProp = 'transition';\n    var transitionEndEvent = 'transitionend';\n    var animationProp = 'animation';\n    var animationEndEvent = 'animationend';\n    if (hasTransition) {\n        /* istanbul ignore if */\n        if (window.ontransitionend === undefined &&\n            window.onwebkittransitionend !== undefined\n        ) {\n            transitionProp = 'WebkitTransition';\n            transitionEndEvent = 'webkitTransitionEnd';\n        }\n        if (window.onanimationend === undefined &&\n            window.onwebkitanimationend !== undefined\n        ) {\n            animationProp = 'WebkitAnimation';\n            animationEndEvent = 'webkitAnimationEnd';\n        }\n    }\n\n    // binding to window is necessary to make hot reload work in IE in strict mode\n    var raf = inBrowser\n        ? window.requestAnimationFrame\n            ? window.requestAnimationFrame.bind(window)\n            : setTimeout\n        : /* istanbul ignore next */ function (fn) { return fn(); };\n\n    function nextFrame (fn) {\n        raf(function () {\n            raf(fn);\n        });\n    }\n\n    function addTransitionClass (el, cls) {\n        var transitionClasses = el._transitionClasses || (el._transitionClasses = []);\n        if (transitionClasses.indexOf(cls) < 0) {\n            transitionClasses.push(cls);\n            addClass(el, cls);\n        }\n    }\n\n    function removeTransitionClass (el, cls) {\n        if (el._transitionClasses) {\n            remove(el._transitionClasses, cls);\n        }\n        removeClass(el, cls);\n    }\n\n    function whenTransitionEnds (\n        el,\n        expectedType,\n        cb\n    ) {\n        var ref = getTransitionInfo(el, expectedType);\n        var type = ref.type;\n        var timeout = ref.timeout;\n        var propCount = ref.propCount;\n        if (!type) { return cb() }\n        var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;\n        var ended = 0;\n        var end = function () {\n            el.removeEventListener(event, onEnd);\n            cb();\n        };\n        var onEnd = function (e) {\n            if (e.target === el) {\n                if (++ended >= propCount) {\n                    end();\n                }\n            }\n        };\n        setTimeout(function () {\n            if (ended < propCount) {\n                end();\n            }\n        }, timeout + 1);\n        el.addEventListener(event, onEnd);\n    }\n\n    var transformRE = /\\b(transform|all)(,|$)/;\n\n    function getTransitionInfo (el, expectedType) {\n        var styles = window.getComputedStyle(el);\n        // JSDOM may return undefined for transition properties\n        var transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', ');\n        var transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', ');\n        var transitionTimeout = getTimeout(transitionDelays, transitionDurations);\n        var animationDelays = (styles[animationProp + 'Delay'] || '').split(', ');\n        var animationDurations = (styles[animationProp + 'Duration'] || '').split(', ');\n        var animationTimeout = getTimeout(animationDelays, animationDurations);\n\n        var type;\n        var timeout = 0;\n        var propCount = 0;\n        /* istanbul ignore if */\n        if (expectedType === TRANSITION) {\n            if (transitionTimeout > 0) {\n                type = TRANSITION;\n                timeout = transitionTimeout;\n                propCount = transitionDurations.length;\n            }\n        } else if (expectedType === ANIMATION) {\n            if (animationTimeout > 0) {\n                type = ANIMATION;\n                timeout = animationTimeout;\n                propCount = animationDurations.length;\n            }\n        } else {\n            timeout = Math.max(transitionTimeout, animationTimeout);\n            type = timeout > 0\n                ? transitionTimeout > animationTimeout\n                    ? TRANSITION\n                    : ANIMATION\n                : null;\n            propCount = type\n                ? type === TRANSITION\n                    ? transitionDurations.length\n                    : animationDurations.length\n                : 0;\n        }\n        var hasTransform =\n            type === TRANSITION &&\n            transformRE.test(styles[transitionProp + 'Property']);\n        return {\n            type: type,\n            timeout: timeout,\n            propCount: propCount,\n            hasTransform: hasTransform\n        }\n    }\n\n    function getTimeout (delays, durations) {\n        /* istanbul ignore next */\n        while (delays.length < durations.length) {\n            delays = delays.concat(delays);\n        }\n\n        return Math.max.apply(null, durations.map(function (d, i) {\n            return toMs(d) + toMs(delays[i])\n        }))\n    }\n\n    // Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers\n    // in a locale-dependent way, using a comma instead of a dot.\n    // If comma is not replaced with a dot, the input will be rounded down (i.e. acting\n    // as a floor function) causing unexpected behaviors\n    function toMs (s) {\n        return Number(s.slice(0, -1).replace(',', '.')) * 1000\n    }\n\n    /*  */\n\n    function enter (vnode, toggleDisplay) {\n        var el = vnode.elm;\n\n        // call leave callback now\n        if (isDef(el._leaveCb)) {\n            el._leaveCb.cancelled = true;\n            el._leaveCb();\n        }\n\n        var data = resolveTransition(vnode.data.transition);\n        if (isUndef(data)) {\n            return\n        }\n\n        /* istanbul ignore if */\n        if (isDef(el._enterCb) || el.nodeType !== 1) {\n            return\n        }\n\n        var css = data.css;\n        var type = data.type;\n        var enterClass = data.enterClass;\n        var enterToClass = data.enterToClass;\n        var enterActiveClass = data.enterActiveClass;\n        var appearClass = data.appearClass;\n        var appearToClass = data.appearToClass;\n        var appearActiveClass = data.appearActiveClass;\n        var beforeEnter = data.beforeEnter;\n        var enter = data.enter;\n        var afterEnter = data.afterEnter;\n        var enterCancelled = data.enterCancelled;\n        var beforeAppear = data.beforeAppear;\n        var appear = data.appear;\n        var afterAppear = data.afterAppear;\n        var appearCancelled = data.appearCancelled;\n        var duration = data.duration;\n\n        // activeInstance will always be the <transition> component managing this\n        // transition. One edge case to check is when the <transition> is placed\n        // as the root node of a child component. In that case we need to check\n        // <transition>'s parent for appear check.\n        var context = activeInstance;\n        var transitionNode = activeInstance.$vnode;\n        while (transitionNode && transitionNode.parent) {\n            context = transitionNode.context;\n            transitionNode = transitionNode.parent;\n        }\n\n        var isAppear = !context._isMounted || !vnode.isRootInsert;\n\n        if (isAppear && !appear && appear !== '') {\n            return\n        }\n\n        var startClass = isAppear && appearClass\n            ? appearClass\n            : enterClass;\n        var activeClass = isAppear && appearActiveClass\n            ? appearActiveClass\n            : enterActiveClass;\n        var toClass = isAppear && appearToClass\n            ? appearToClass\n            : enterToClass;\n\n        var beforeEnterHook = isAppear\n            ? (beforeAppear || beforeEnter)\n            : beforeEnter;\n        var enterHook = isAppear\n            ? (typeof appear === 'function' ? appear : enter)\n            : enter;\n        var afterEnterHook = isAppear\n            ? (afterAppear || afterEnter)\n            : afterEnter;\n        var enterCancelledHook = isAppear\n            ? (appearCancelled || enterCancelled)\n            : enterCancelled;\n\n        var explicitEnterDuration = toNumber(\n            isObject(duration)\n                ? duration.enter\n                : duration\n        );\n\n        if (explicitEnterDuration != null) {\n            checkDuration(explicitEnterDuration, 'enter', vnode);\n        }\n\n        var expectsCSS = css !== false && !isIE9;\n        var userWantsControl = getHookArgumentsLength(enterHook);\n\n        var cb = el._enterCb = once(function () {\n            if (expectsCSS) {\n                removeTransitionClass(el, toClass);\n                removeTransitionClass(el, activeClass);\n            }\n            if (cb.cancelled) {\n                if (expectsCSS) {\n                    removeTransitionClass(el, startClass);\n                }\n                enterCancelledHook && enterCancelledHook(el);\n            } else {\n                afterEnterHook && afterEnterHook(el);\n            }\n            el._enterCb = null;\n        });\n\n        if (!vnode.data.show) {\n            // remove pending leave element on enter by injecting an insert hook\n            mergeVNodeHook(vnode, 'insert', function () {\n                var parent = el.parentNode;\n                var pendingNode = parent && parent._pending && parent._pending[vnode.key];\n                if (pendingNode &&\n                    pendingNode.tag === vnode.tag &&\n                    pendingNode.elm._leaveCb\n                ) {\n                    pendingNode.elm._leaveCb();\n                }\n                enterHook && enterHook(el, cb);\n            });\n        }\n\n        // start enter transition\n        beforeEnterHook && beforeEnterHook(el);\n        if (expectsCSS) {\n            addTransitionClass(el, startClass);\n            addTransitionClass(el, activeClass);\n            nextFrame(function () {\n                removeTransitionClass(el, startClass);\n                if (!cb.cancelled) {\n                    addTransitionClass(el, toClass);\n                    if (!userWantsControl) {\n                        if (isValidDuration(explicitEnterDuration)) {\n                            setTimeout(cb, explicitEnterDuration);\n                        } else {\n                            whenTransitionEnds(el, type, cb);\n                        }\n                    }\n                }\n            });\n        }\n\n        if (vnode.data.show) {\n            toggleDisplay && toggleDisplay();\n            enterHook && enterHook(el, cb);\n        }\n\n        if (!expectsCSS && !userWantsControl) {\n            cb();\n        }\n    }\n\n    function leave (vnode, rm) {\n        var el = vnode.elm;\n\n        // call enter callback now\n        if (isDef(el._enterCb)) {\n            el._enterCb.cancelled = true;\n            el._enterCb();\n        }\n\n        var data = resolveTransition(vnode.data.transition);\n        if (isUndef(data) || el.nodeType !== 1) {\n            return rm()\n        }\n\n        /* istanbul ignore if */\n        if (isDef(el._leaveCb)) {\n            return\n        }\n\n        var css = data.css;\n        var type = data.type;\n        var leaveClass = data.leaveClass;\n        var leaveToClass = data.leaveToClass;\n        var leaveActiveClass = data.leaveActiveClass;\n        var beforeLeave = data.beforeLeave;\n        var leave = data.leave;\n        var afterLeave = data.afterLeave;\n        var leaveCancelled = data.leaveCancelled;\n        var delayLeave = data.delayLeave;\n        var duration = data.duration;\n\n        var expectsCSS = css !== false && !isIE9;\n        var userWantsControl = getHookArgumentsLength(leave);\n\n        var explicitLeaveDuration = toNumber(\n            isObject(duration)\n                ? duration.leave\n                : duration\n        );\n\n        if (isDef(explicitLeaveDuration)) {\n            checkDuration(explicitLeaveDuration, 'leave', vnode);\n        }\n\n        var cb = el._leaveCb = once(function () {\n            if (el.parentNode && el.parentNode._pending) {\n                el.parentNode._pending[vnode.key] = null;\n            }\n            if (expectsCSS) {\n                removeTransitionClass(el, leaveToClass);\n                removeTransitionClass(el, leaveActiveClass);\n            }\n            if (cb.cancelled) {\n                if (expectsCSS) {\n                    removeTransitionClass(el, leaveClass);\n                }\n                leaveCancelled && leaveCancelled(el);\n            } else {\n                rm();\n                afterLeave && afterLeave(el);\n            }\n            el._leaveCb = null;\n        });\n\n        if (delayLeave) {\n            delayLeave(performLeave);\n        } else {\n            performLeave();\n        }\n\n        function performLeave () {\n            // the delayed leave may have already been cancelled\n            if (cb.cancelled) {\n                return\n            }\n            // record leaving element\n            if (!vnode.data.show && el.parentNode) {\n                (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode;\n            }\n            beforeLeave && beforeLeave(el);\n            if (expectsCSS) {\n                addTransitionClass(el, leaveClass);\n                addTransitionClass(el, leaveActiveClass);\n                nextFrame(function () {\n                    removeTransitionClass(el, leaveClass);\n                    if (!cb.cancelled) {\n                        addTransitionClass(el, leaveToClass);\n                        if (!userWantsControl) {\n                            if (isValidDuration(explicitLeaveDuration)) {\n                                setTimeout(cb, explicitLeaveDuration);\n                            } else {\n                                whenTransitionEnds(el, type, cb);\n                            }\n                        }\n                    }\n                });\n            }\n            leave && leave(el, cb);\n            if (!expectsCSS && !userWantsControl) {\n                cb();\n            }\n        }\n    }\n\n    // only used in dev mode\n    function checkDuration (val, name, vnode) {\n        if (typeof val !== 'number') {\n            warn(\n                \"<transition> explicit \" + name + \" duration is not a valid number - \" +\n                \"got \" + (JSON.stringify(val)) + \".\",\n                vnode.context\n            );\n        } else if (isNaN(val)) {\n            warn(\n                \"<transition> explicit \" + name + \" duration is NaN - \" +\n                'the duration expression might be incorrect.',\n                vnode.context\n            );\n        }\n    }\n\n    function isValidDuration (val) {\n        return typeof val === 'number' && !isNaN(val)\n    }\n\n    /**\n     * Normalize a transition hook's argument length. The hook may be:\n     * - a merged hook (invoker) with the original in .fns\n     * - a wrapped component method (check ._length)\n     * - a plain function (.length)\n     */\n    function getHookArgumentsLength (fn) {\n        if (isUndef(fn)) {\n            return false\n        }\n        var invokerFns = fn.fns;\n        if (isDef(invokerFns)) {\n            // invoker\n            return getHookArgumentsLength(\n                Array.isArray(invokerFns)\n                    ? invokerFns[0]\n                    : invokerFns\n            )\n        } else {\n            return (fn._length || fn.length) > 1\n        }\n    }\n\n    function _enter (_, vnode) {\n        if (vnode.data.show !== true) {\n            enter(vnode);\n        }\n    }\n\n    var transition = inBrowser ? {\n        create: _enter,\n        activate: _enter,\n        remove: function remove$$1 (vnode, rm) {\n            /* istanbul ignore else */\n            if (vnode.data.show !== true) {\n                leave(vnode, rm);\n            } else {\n                rm();\n            }\n        }\n    } : {};\n\n    var platformModules = [\n        attrs,\n        klass,\n        events,\n        domProps,\n        style,\n        transition\n    ];\n\n    /*  */\n\n    // the directive module should be applied last, after all\n    // built-in modules have been applied.\n    var modules = platformModules.concat(baseModules);\n\n    var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules });\n\n    /**\n     * Not type checking this file because flow doesn't like attaching\n     * properties to Elements.\n     */\n\n    /* istanbul ignore if */\n    if (isIE9) {\n        // http://www.matts411.com/post/internet-explorer-9-oninput/\n        document.addEventListener('selectionchange', function () {\n            var el = document.activeElement;\n            if (el && el.vmodel) {\n                trigger(el, 'input');\n            }\n        });\n    }\n\n    var directive = {\n        inserted: function inserted (el, binding, vnode, oldVnode) {\n            if (vnode.tag === 'select') {\n                // #6903\n                if (oldVnode.elm && !oldVnode.elm._vOptions) {\n                    mergeVNodeHook(vnode, 'postpatch', function () {\n                        directive.componentUpdated(el, binding, vnode);\n                    });\n                } else {\n                    setSelected(el, binding, vnode.context);\n                }\n                el._vOptions = [].map.call(el.options, getValue);\n            } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) {\n                el._vModifiers = binding.modifiers;\n                if (!binding.modifiers.lazy) {\n                    el.addEventListener('compositionstart', onCompositionStart);\n                    el.addEventListener('compositionend', onCompositionEnd);\n                    // Safari < 10.2 & UIWebView doesn't fire compositionend when\n                    // switching focus before confirming composition choice\n                    // this also fixes the issue where some browsers e.g. iOS Chrome\n                    // fires \"change\" instead of \"input\" on autocomplete.\n                    el.addEventListener('change', onCompositionEnd);\n                    /* istanbul ignore if */\n                    if (isIE9) {\n                        el.vmodel = true;\n                    }\n                }\n            }\n        },\n\n        componentUpdated: function componentUpdated (el, binding, vnode) {\n            if (vnode.tag === 'select') {\n                setSelected(el, binding, vnode.context);\n                // in case the options rendered by v-for have changed,\n                // it's possible that the value is out-of-sync with the rendered options.\n                // detect such cases and filter out values that no longer has a matching\n                // option in the DOM.\n                var prevOptions = el._vOptions;\n                var curOptions = el._vOptions = [].map.call(el.options, getValue);\n                if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) {\n                    // trigger change event if\n                    // no matching option found for at least one value\n                    var needReset = el.multiple\n                        ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); })\n                        : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions);\n                    if (needReset) {\n                        trigger(el, 'change');\n                    }\n                }\n            }\n        }\n    };\n\n    function setSelected (el, binding, vm) {\n        actuallySetSelected(el, binding, vm);\n        /* istanbul ignore if */\n        if (isIE || isEdge) {\n            setTimeout(function () {\n                actuallySetSelected(el, binding, vm);\n            }, 0);\n        }\n    }\n\n    function actuallySetSelected (el, binding, vm) {\n        var value = binding.value;\n        var isMultiple = el.multiple;\n        if (isMultiple && !Array.isArray(value)) {\n            warn(\n                \"<select multiple v-model=\\\"\" + (binding.expression) + \"\\\"> \" +\n                \"expects an Array value for its binding, but got \" + (Object.prototype.toString.call(value).slice(8, -1)),\n                vm\n            );\n            return\n        }\n        var selected, option;\n        for (var i = 0, l = el.options.length; i < l; i++) {\n            option = el.options[i];\n            if (isMultiple) {\n                selected = looseIndexOf(value, getValue(option)) > -1;\n                if (option.selected !== selected) {\n                    option.selected = selected;\n                }\n            } else {\n                if (looseEqual(getValue(option), value)) {\n                    if (el.selectedIndex !== i) {\n                        el.selectedIndex = i;\n                    }\n                    return\n                }\n            }\n        }\n        if (!isMultiple) {\n            el.selectedIndex = -1;\n        }\n    }\n\n    function hasNoMatchingOption (value, options) {\n        return options.every(function (o) { return !looseEqual(o, value); })\n    }\n\n    function getValue (option) {\n        return '_value' in option\n            ? option._value\n            : option.value\n    }\n\n    function onCompositionStart (e) {\n        e.target.composing = true;\n    }\n\n    function onCompositionEnd (e) {\n        // prevent triggering an input event for no reason\n        if (!e.target.composing) { return }\n        e.target.composing = false;\n        trigger(e.target, 'input');\n    }\n\n    function trigger (el, type) {\n        var e = document.createEvent('HTMLEvents');\n        e.initEvent(type, true, true);\n        el.dispatchEvent(e);\n    }\n\n    /*  */\n\n    // recursively search for possible transition defined inside the component root\n    function locateNode (vnode) {\n        return vnode.componentInstance && (!vnode.data || !vnode.data.transition)\n            ? locateNode(vnode.componentInstance._vnode)\n            : vnode\n    }\n\n    var show = {\n        bind: function bind (el, ref, vnode) {\n            var value = ref.value;\n\n            vnode = locateNode(vnode);\n            var transition$$1 = vnode.data && vnode.data.transition;\n            var originalDisplay = el.__vOriginalDisplay =\n                el.style.display === 'none' ? '' : el.style.display;\n            if (value && transition$$1) {\n                vnode.data.show = true;\n                enter(vnode, function () {\n                    el.style.display = originalDisplay;\n                });\n            } else {\n                el.style.display = value ? originalDisplay : 'none';\n            }\n        },\n\n        update: function update (el, ref, vnode) {\n            var value = ref.value;\n            var oldValue = ref.oldValue;\n\n            /* istanbul ignore if */\n            if (!value === !oldValue) { return }\n            vnode = locateNode(vnode);\n            var transition$$1 = vnode.data && vnode.data.transition;\n            if (transition$$1) {\n                vnode.data.show = true;\n                if (value) {\n                    enter(vnode, function () {\n                        el.style.display = el.__vOriginalDisplay;\n                    });\n                } else {\n                    leave(vnode, function () {\n                        el.style.display = 'none';\n                    });\n                }\n            } else {\n                el.style.display = value ? el.__vOriginalDisplay : 'none';\n            }\n        },\n\n        unbind: function unbind (\n            el,\n            binding,\n            vnode,\n            oldVnode,\n            isDestroy\n        ) {\n            if (!isDestroy) {\n                el.style.display = el.__vOriginalDisplay;\n            }\n        }\n    };\n\n    var platformDirectives = {\n        model: directive,\n        show: show\n    };\n\n    /*  */\n\n    var transitionProps = {\n        name: String,\n        appear: Boolean,\n        css: Boolean,\n        mode: String,\n        type: String,\n        enterClass: String,\n        leaveClass: String,\n        enterToClass: String,\n        leaveToClass: String,\n        enterActiveClass: String,\n        leaveActiveClass: String,\n        appearClass: String,\n        appearActiveClass: String,\n        appearToClass: String,\n        duration: [Number, String, Object]\n    };\n\n    // in case the child is also an abstract component, e.g. <keep-alive>\n    // we want to recursively retrieve the real component to be rendered\n    function getRealChild (vnode) {\n        var compOptions = vnode && vnode.componentOptions;\n        if (compOptions && compOptions.Ctor.options.abstract) {\n            return getRealChild(getFirstComponentChild(compOptions.children))\n        } else {\n            return vnode\n        }\n    }\n\n    function extractTransitionData (comp) {\n        var data = {};\n        var options = comp.$options;\n        // props\n        for (var key in options.propsData) {\n            data[key] = comp[key];\n        }\n        // events.\n        // extract listeners and pass them directly to the transition methods\n        var listeners = options._parentListeners;\n        for (var key$1 in listeners) {\n            data[camelize(key$1)] = listeners[key$1];\n        }\n        return data\n    }\n\n    function placeholder (h, rawChild) {\n        if (/\\d-keep-alive$/.test(rawChild.tag)) {\n            return h('keep-alive', {\n                props: rawChild.componentOptions.propsData\n            })\n        }\n    }\n\n    function hasParentTransition (vnode) {\n        while ((vnode = vnode.parent)) {\n            if (vnode.data.transition) {\n                return true\n            }\n        }\n    }\n\n    function isSameChild (child, oldChild) {\n        return oldChild.key === child.key && oldChild.tag === child.tag\n    }\n\n    var isNotTextNode = function (c) { return c.tag || isAsyncPlaceholder(c); };\n\n    var isVShowDirective = function (d) { return d.name === 'show'; };\n\n    var Transition = {\n        name: 'transition',\n        props: transitionProps,\n        abstract: true,\n\n        render: function render (h) {\n            var this$1 = this;\n\n            var children = this.$slots.default;\n            if (!children) {\n                return\n            }\n\n            // filter out text nodes (possible whitespaces)\n            children = children.filter(isNotTextNode);\n            /* istanbul ignore if */\n            if (!children.length) {\n                return\n            }\n\n            // warn multiple elements\n            if (children.length > 1) {\n                warn(\n                    '<transition> can only be used on a single element. Use ' +\n                    '<transition-group> for lists.',\n                    this.$parent\n                );\n            }\n\n            var mode = this.mode;\n\n            // warn invalid mode\n            if (mode && mode !== 'in-out' && mode !== 'out-in'\n            ) {\n                warn(\n                    'invalid <transition> mode: ' + mode,\n                    this.$parent\n                );\n            }\n\n            var rawChild = children[0];\n\n            // if this is a component root node and the component's\n            // parent container node also has transition, skip.\n            if (hasParentTransition(this.$vnode)) {\n                return rawChild\n            }\n\n            // apply transition data to child\n            // use getRealChild() to ignore abstract components e.g. keep-alive\n            var child = getRealChild(rawChild);\n            /* istanbul ignore if */\n            if (!child) {\n                return rawChild\n            }\n\n            if (this._leaving) {\n                return placeholder(h, rawChild)\n            }\n\n            // ensure a key that is unique to the vnode type and to this transition\n            // component instance. This key will be used to remove pending leaving nodes\n            // during entering.\n            var id = \"__transition-\" + (this._uid) + \"-\";\n            child.key = child.key == null\n                ? child.isComment\n                    ? id + 'comment'\n                    : id + child.tag\n                : isPrimitive(child.key)\n                    ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)\n                    : child.key;\n\n            var data = (child.data || (child.data = {})).transition = extractTransitionData(this);\n            var oldRawChild = this._vnode;\n            var oldChild = getRealChild(oldRawChild);\n\n            // mark v-show\n            // so that the transition module can hand over the control to the directive\n            if (child.data.directives && child.data.directives.some(isVShowDirective)) {\n                child.data.show = true;\n            }\n\n            if (\n                oldChild &&\n                oldChild.data &&\n                !isSameChild(child, oldChild) &&\n                !isAsyncPlaceholder(oldChild) &&\n                // #6687 component root is a comment node\n                !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment)\n            ) {\n                // replace old child transition data with fresh one\n                // important for dynamic transitions!\n                var oldData = oldChild.data.transition = extend({}, data);\n                // handle transition mode\n                if (mode === 'out-in') {\n                    // return placeholder node and queue update when leave finishes\n                    this._leaving = true;\n                    mergeVNodeHook(oldData, 'afterLeave', function () {\n                        this$1._leaving = false;\n                        this$1.$forceUpdate();\n                    });\n                    return placeholder(h, rawChild)\n                } else if (mode === 'in-out') {\n                    if (isAsyncPlaceholder(child)) {\n                        return oldRawChild\n                    }\n                    var delayedLeave;\n                    var performLeave = function () { delayedLeave(); };\n                    mergeVNodeHook(data, 'afterEnter', performLeave);\n                    mergeVNodeHook(data, 'enterCancelled', performLeave);\n                    mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; });\n                }\n            }\n\n            return rawChild\n        }\n    };\n\n    /*  */\n\n    var props = extend({\n        tag: String,\n        moveClass: String\n    }, transitionProps);\n\n    delete props.mode;\n\n    var TransitionGroup = {\n        props: props,\n\n        beforeMount: function beforeMount () {\n            var this$1 = this;\n\n            var update = this._update;\n            this._update = function (vnode, hydrating) {\n                var restoreActiveInstance = setActiveInstance(this$1);\n                // force removing pass\n                this$1.__patch__(\n                    this$1._vnode,\n                    this$1.kept,\n                    false, // hydrating\n                    true // removeOnly (!important, avoids unnecessary moves)\n                );\n                this$1._vnode = this$1.kept;\n                restoreActiveInstance();\n                update.call(this$1, vnode, hydrating);\n            };\n        },\n\n        render: function render (h) {\n            var tag = this.tag || this.$vnode.data.tag || 'span';\n            var map = Object.create(null);\n            var prevChildren = this.prevChildren = this.children;\n            var rawChildren = this.$slots.default || [];\n            var children = this.children = [];\n            var transitionData = extractTransitionData(this);\n\n            for (var i = 0; i < rawChildren.length; i++) {\n                var c = rawChildren[i];\n                if (c.tag) {\n                    if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {\n                        children.push(c);\n                        map[c.key] = c\n                        ;(c.data || (c.data = {})).transition = transitionData;\n                    } else {\n                        var opts = c.componentOptions;\n                        var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag;\n                        warn((\"<transition-group> children must be keyed: <\" + name + \">\"));\n                    }\n                }\n            }\n\n            if (prevChildren) {\n                var kept = [];\n                var removed = [];\n                for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {\n                    var c$1 = prevChildren[i$1];\n                    c$1.data.transition = transitionData;\n                    c$1.data.pos = c$1.elm.getBoundingClientRect();\n                    if (map[c$1.key]) {\n                        kept.push(c$1);\n                    } else {\n                        removed.push(c$1);\n                    }\n                }\n                this.kept = h(tag, null, kept);\n                this.removed = removed;\n            }\n\n            return h(tag, null, children)\n        },\n\n        updated: function updated () {\n            var children = this.prevChildren;\n            var moveClass = this.moveClass || ((this.name || 'v') + '-move');\n            if (!children.length || !this.hasMove(children[0].elm, moveClass)) {\n                return\n            }\n\n            // we divide the work into three loops to avoid mixing DOM reads and writes\n            // in each iteration - which helps prevent layout thrashing.\n            children.forEach(callPendingCbs);\n            children.forEach(recordPosition);\n            children.forEach(applyTranslation);\n\n            // force reflow to put everything in position\n            // assign to this to avoid being removed in tree-shaking\n            // $flow-disable-line\n            this._reflow = document.body.offsetHeight;\n\n            children.forEach(function (c) {\n                if (c.data.moved) {\n                    var el = c.elm;\n                    var s = el.style;\n                    addTransitionClass(el, moveClass);\n                    s.transform = s.WebkitTransform = s.transitionDuration = '';\n                    el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {\n                        if (e && e.target !== el) {\n                            return\n                        }\n                        if (!e || /transform$/.test(e.propertyName)) {\n                            el.removeEventListener(transitionEndEvent, cb);\n                            el._moveCb = null;\n                            removeTransitionClass(el, moveClass);\n                        }\n                    });\n                }\n            });\n        },\n\n        methods: {\n            hasMove: function hasMove (el, moveClass) {\n                /* istanbul ignore if */\n                if (!hasTransition) {\n                    return false\n                }\n                /* istanbul ignore if */\n                if (this._hasMove) {\n                    return this._hasMove\n                }\n                // Detect whether an element with the move class applied has\n                // CSS transitions. Since the element may be inside an entering\n                // transition at this very moment, we make a clone of it and remove\n                // all other transition classes applied to ensure only the move class\n                // is applied.\n                var clone = el.cloneNode();\n                if (el._transitionClasses) {\n                    el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); });\n                }\n                addClass(clone, moveClass);\n                clone.style.display = 'none';\n                this.$el.appendChild(clone);\n                var info = getTransitionInfo(clone);\n                this.$el.removeChild(clone);\n                return (this._hasMove = info.hasTransform)\n            }\n        }\n    };\n\n    function callPendingCbs (c) {\n        /* istanbul ignore if */\n        if (c.elm._moveCb) {\n            c.elm._moveCb();\n        }\n        /* istanbul ignore if */\n        if (c.elm._enterCb) {\n            c.elm._enterCb();\n        }\n    }\n\n    function recordPosition (c) {\n        c.data.newPos = c.elm.getBoundingClientRect();\n    }\n\n    function applyTranslation (c) {\n        var oldPos = c.data.pos;\n        var newPos = c.data.newPos;\n        var dx = oldPos.left - newPos.left;\n        var dy = oldPos.top - newPos.top;\n        if (dx || dy) {\n            c.data.moved = true;\n            var s = c.elm.style;\n            s.transform = s.WebkitTransform = \"translate(\" + dx + \"px,\" + dy + \"px)\";\n            s.transitionDuration = '0s';\n        }\n    }\n\n    var platformComponents = {\n        Transition: Transition,\n        TransitionGroup: TransitionGroup\n    };\n\n    /*  */\n\n    // install platform specific utils\n    Vue.config.mustUseProp = mustUseProp;\n    Vue.config.isReservedTag = isReservedTag;\n    Vue.config.isReservedAttr = isReservedAttr;\n    Vue.config.getTagNamespace = getTagNamespace;\n    Vue.config.isUnknownElement = isUnknownElement;\n\n    // install platform runtime directives & components\n    extend(Vue.options.directives, platformDirectives);\n    extend(Vue.options.components, platformComponents);\n\n    // install platform patch function\n    Vue.prototype.__patch__ = inBrowser ? patch : noop;\n\n    // public mount method\n    Vue.prototype.$mount = function (\n        el,\n        hydrating\n    ) {\n        el = el && inBrowser ? query(el) : undefined;\n        return mountComponent(this, el, hydrating)\n    };\n\n    // devtools global hook\n    /* istanbul ignore next */\n    if (inBrowser) {\n        setTimeout(function () {\n            if (config.devtools) {\n                if (devtools) {\n                    devtools.emit('init', Vue);\n                } else {\n                    console[console.info ? 'info' : 'log'](\n                        'Download the Vue Devtools extension for a better development experience:\\n' +\n                        'https://github.com/vuejs/vue-devtools'\n                    );\n                }\n            }\n            if (config.productionTip !== false &&\n                typeof console !== 'undefined'\n            ) {\n                console[console.info ? 'info' : 'log'](\n                    \"You are running Vue in development mode.\\n\" +\n                    \"Make sure to turn on production mode when deploying for production.\\n\" +\n                    \"See more tips at https://vuejs.org/guide/deployment.html\"\n                );\n            }\n        }, 0);\n    }\n\n    /*  */\n\n    var defaultTagRE = /\\{\\{((?:.|\\r?\\n)+?)\\}\\}/g;\n    var regexEscapeRE = /[-.*+?^${}()|[\\]\\/\\\\]/g;\n\n    var buildRegex = cached(function (delimiters) {\n        var open = delimiters[0].replace(regexEscapeRE, '\\\\$&');\n        var close = delimiters[1].replace(regexEscapeRE, '\\\\$&');\n        return new RegExp(open + '((?:.|\\\\n)+?)' + close, 'g')\n    });\n\n\n\n    function parseText (\n        text,\n        delimiters\n    ) {\n        var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;\n        if (!tagRE.test(text)) {\n            return\n        }\n        var tokens = [];\n        var rawTokens = [];\n        var lastIndex = tagRE.lastIndex = 0;\n        var match, index, tokenValue;\n        while ((match = tagRE.exec(text))) {\n            index = match.index;\n            // push text token\n            if (index > lastIndex) {\n                rawTokens.push(tokenValue = text.slice(lastIndex, index));\n                tokens.push(JSON.stringify(tokenValue));\n            }\n            // tag token\n            var exp = parseFilters(match[1].trim());\n            tokens.push((\"_s(\" + exp + \")\"));\n            rawTokens.push({ '@binding': exp });\n            lastIndex = index + match[0].length;\n        }\n        if (lastIndex < text.length) {\n            rawTokens.push(tokenValue = text.slice(lastIndex));\n            tokens.push(JSON.stringify(tokenValue));\n        }\n        return {\n            expression: tokens.join('+'),\n            tokens: rawTokens\n        }\n    }\n\n    /*  */\n\n    function transformNode (el, options) {\n        var warn = options.warn || baseWarn;\n        var staticClass = getAndRemoveAttr(el, 'class');\n        if (staticClass) {\n            var res = parseText(staticClass, options.delimiters);\n            if (res) {\n                warn(\n                    \"class=\\\"\" + staticClass + \"\\\": \" +\n                    'Interpolation inside attributes has been removed. ' +\n                    'Use v-bind or the colon shorthand instead. For example, ' +\n                    'instead of <div class=\"{{ val }}\">, use <div :class=\"val\">.',\n                    el.rawAttrsMap['class']\n                );\n            }\n        }\n        if (staticClass) {\n            el.staticClass = JSON.stringify(staticClass);\n        }\n        var classBinding = getBindingAttr(el, 'class', false /* getStatic */);\n        if (classBinding) {\n            el.classBinding = classBinding;\n        }\n    }\n\n    function genData (el) {\n        var data = '';\n        if (el.staticClass) {\n            data += \"staticClass:\" + (el.staticClass) + \",\";\n        }\n        if (el.classBinding) {\n            data += \"class:\" + (el.classBinding) + \",\";\n        }\n        return data\n    }\n\n    var klass$1 = {\n        staticKeys: ['staticClass'],\n        transformNode: transformNode,\n        genData: genData\n    };\n\n    /*  */\n\n    function transformNode$1 (el, options) {\n        var warn = options.warn || baseWarn;\n        var staticStyle = getAndRemoveAttr(el, 'style');\n        if (staticStyle) {\n            /* istanbul ignore if */\n            {\n                var res = parseText(staticStyle, options.delimiters);\n                if (res) {\n                    warn(\n                        \"style=\\\"\" + staticStyle + \"\\\": \" +\n                        'Interpolation inside attributes has been removed. ' +\n                        'Use v-bind or the colon shorthand instead. For example, ' +\n                        'instead of <div style=\"{{ val }}\">, use <div :style=\"val\">.',\n                        el.rawAttrsMap['style']\n                    );\n                }\n            }\n            el.staticStyle = JSON.stringify(parseStyleText(staticStyle));\n        }\n\n        var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);\n        if (styleBinding) {\n            el.styleBinding = styleBinding;\n        }\n    }\n\n    function genData$1 (el) {\n        var data = '';\n        if (el.staticStyle) {\n            data += \"staticStyle:\" + (el.staticStyle) + \",\";\n        }\n        if (el.styleBinding) {\n            data += \"style:(\" + (el.styleBinding) + \"),\";\n        }\n        return data\n    }\n\n    var style$1 = {\n        staticKeys: ['staticStyle'],\n        transformNode: transformNode$1,\n        genData: genData$1\n    };\n\n    /*  */\n\n    var decoder;\n\n    var he = {\n        decode: function decode (html) {\n            decoder = decoder || document.createElement('div');\n            decoder.innerHTML = html;\n            return decoder.textContent\n        }\n    };\n\n    /*  */\n\n    var isUnaryTag = makeMap(\n        'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +\n        'link,meta,param,source,track,wbr'\n    );\n\n    // Elements that you can, intentionally, leave open\n    // (and which close themselves)\n    var canBeLeftOpenTag = makeMap(\n        'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'\n    );\n\n    // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3\n    // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content\n    var isNonPhrasingTag = makeMap(\n        'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +\n        'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +\n        'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +\n        'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +\n        'title,tr,track'\n    );\n\n    /**\n     * Not type-checking this file because it's mostly vendor code.\n     */\n\n        // Regular Expressions for parsing tags and attributes\n    var attribute = /^\\s*([^\\s\"'<>\\/=]+)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/;\n    var dynamicArgAttribute = /^\\s*((?:v-[\\w-]+:|@|:|#)\\[[^=]+?\\][^\\s\"'<>\\/=]*)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/;\n    var ncname = \"[a-zA-Z_][\\\\-\\\\.0-9_a-zA-Z\" + (unicodeRegExp.source) + \"]*\";\n    var qnameCapture = \"((?:\" + ncname + \"\\\\:)?\" + ncname + \")\";\n    var startTagOpen = new RegExp((\"^<\" + qnameCapture));\n    var startTagClose = /^\\s*(\\/?)>/;\n    var endTag = new RegExp((\"^<\\\\/\" + qnameCapture + \"[^>]*>\"));\n    var doctype = /^<!DOCTYPE [^>]+>/i;\n    // #7298: escape - to avoid being passed as HTML comment when inlined in page\n    var comment = /^<!\\--/;\n    var conditionalComment = /^<!\\[/;\n\n    // Special Elements (can contain anything)\n    var isPlainTextElement = makeMap('script,style,textarea', true);\n    var reCache = {};\n\n    var decodingMap = {\n        '&lt;': '<',\n        '&gt;': '>',\n        '&quot;': '\"',\n        '&amp;': '&',\n        '&#10;': '\\n',\n        '&#9;': '\\t',\n        '&#39;': \"'\"\n    };\n    var encodedAttr = /&(?:lt|gt|quot|amp|#39);/g;\n    var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g;\n\n    // #5992\n    var isIgnoreNewlineTag = makeMap('pre,textarea', true);\n    var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'; };\n\n    function decodeAttr (value, shouldDecodeNewlines) {\n        var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;\n        return value.replace(re, function (match) { return decodingMap[match]; })\n    }\n\n    function parseHTML (html, options) {\n        var stack = [];\n        var expectHTML = options.expectHTML;\n        var isUnaryTag$$1 = options.isUnaryTag || no;\n        var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no;\n        var index = 0;\n        var last, lastTag;\n        while (html) {\n            last = html;\n            // Make sure we're not in a plaintext content element like script/style\n            if (!lastTag || !isPlainTextElement(lastTag)) {\n                var textEnd = html.indexOf('<');\n                if (textEnd === 0) {\n                    // Comment:\n                    if (comment.test(html)) {\n                        var commentEnd = html.indexOf('-->');\n\n                        if (commentEnd >= 0) {\n                            if (options.shouldKeepComment) {\n                                options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3);\n                            }\n                            advance(commentEnd + 3);\n                            continue\n                        }\n                    }\n\n                    // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment\n                    if (conditionalComment.test(html)) {\n                        var conditionalEnd = html.indexOf(']>');\n\n                        if (conditionalEnd >= 0) {\n                            advance(conditionalEnd + 2);\n                            continue\n                        }\n                    }\n\n                    // Doctype:\n                    var doctypeMatch = html.match(doctype);\n                    if (doctypeMatch) {\n                        advance(doctypeMatch[0].length);\n                        continue\n                    }\n\n                    // End tag:\n                    var endTagMatch = html.match(endTag);\n                    if (endTagMatch) {\n                        var curIndex = index;\n                        advance(endTagMatch[0].length);\n                        parseEndTag(endTagMatch[1], curIndex, index);\n                        continue\n                    }\n\n                    // Start tag:\n                    var startTagMatch = parseStartTag();\n                    if (startTagMatch) {\n                        handleStartTag(startTagMatch);\n                        if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) {\n                            advance(1);\n                        }\n                        continue\n                    }\n                }\n\n                var text = (void 0), rest = (void 0), next = (void 0);\n                if (textEnd >= 0) {\n                    rest = html.slice(textEnd);\n                    while (\n                        !endTag.test(rest) &&\n                        !startTagOpen.test(rest) &&\n                        !comment.test(rest) &&\n                        !conditionalComment.test(rest)\n                        ) {\n                        // < in plain text, be forgiving and treat it as text\n                        next = rest.indexOf('<', 1);\n                        if (next < 0) { break }\n                        textEnd += next;\n                        rest = html.slice(textEnd);\n                    }\n                    text = html.substring(0, textEnd);\n                }\n\n                if (textEnd < 0) {\n                    text = html;\n                }\n\n                if (text) {\n                    advance(text.length);\n                }\n\n                if (options.chars && text) {\n                    options.chars(text, index - text.length, index);\n                }\n            } else {\n                var endTagLength = 0;\n                var stackedTag = lastTag.toLowerCase();\n                var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\\\s\\\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));\n                var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {\n                    endTagLength = endTag.length;\n                    if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {\n                        text = text\n                            .replace(/<!\\--([\\s\\S]*?)-->/g, '$1') // #7298\n                            .replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g, '$1');\n                    }\n                    if (shouldIgnoreFirstNewline(stackedTag, text)) {\n                        text = text.slice(1);\n                    }\n                    if (options.chars) {\n                        options.chars(text);\n                    }\n                    return ''\n                });\n                index += html.length - rest$1.length;\n                html = rest$1;\n                parseEndTag(stackedTag, index - endTagLength, index);\n            }\n\n            if (html === last) {\n                options.chars && options.chars(html);\n                if (!stack.length && options.warn) {\n                    options.warn((\"Mal-formatted tag at end of template: \\\"\" + html + \"\\\"\"), { start: index + html.length });\n                }\n                break\n            }\n        }\n\n        // Clean up any remaining tags\n        parseEndTag();\n\n        function advance (n) {\n            index += n;\n            html = html.substring(n);\n        }\n\n        function parseStartTag () {\n            var start = html.match(startTagOpen);\n            if (start) {\n                var match = {\n                    tagName: start[1],\n                    attrs: [],\n                    start: index\n                };\n                advance(start[0].length);\n                var end, attr;\n                while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) {\n                    attr.start = index;\n                    advance(attr[0].length);\n                    attr.end = index;\n                    match.attrs.push(attr);\n                }\n                if (end) {\n                    match.unarySlash = end[1];\n                    advance(end[0].length);\n                    match.end = index;\n                    return match\n                }\n            }\n        }\n\n        function handleStartTag (match) {\n            var tagName = match.tagName;\n            var unarySlash = match.unarySlash;\n\n            if (expectHTML) {\n                if (lastTag === 'p' && isNonPhrasingTag(tagName)) {\n                    parseEndTag(lastTag);\n                }\n                if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) {\n                    parseEndTag(tagName);\n                }\n            }\n\n            var unary = isUnaryTag$$1(tagName) || !!unarySlash;\n\n            var l = match.attrs.length;\n            var attrs = new Array(l);\n            for (var i = 0; i < l; i++) {\n                var args = match.attrs[i];\n                var value = args[3] || args[4] || args[5] || '';\n                var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'\n                    ? options.shouldDecodeNewlinesForHref\n                    : options.shouldDecodeNewlines;\n                attrs[i] = {\n                    name: args[1],\n                    value: decodeAttr(value, shouldDecodeNewlines)\n                };\n                if (options.outputSourceRange) {\n                    attrs[i].start = args.start + args[0].match(/^\\s*/).length;\n                    attrs[i].end = args.end;\n                }\n            }\n\n            if (!unary) {\n                stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end });\n                lastTag = tagName;\n            }\n\n            if (options.start) {\n                options.start(tagName, attrs, unary, match.start, match.end);\n            }\n        }\n\n        function parseEndTag (tagName, start, end) {\n            var pos, lowerCasedTagName;\n            if (start == null) { start = index; }\n            if (end == null) { end = index; }\n\n            // Find the closest opened tag of the same type\n            if (tagName) {\n                lowerCasedTagName = tagName.toLowerCase();\n                for (pos = stack.length - 1; pos >= 0; pos--) {\n                    if (stack[pos].lowerCasedTag === lowerCasedTagName) {\n                        break\n                    }\n                }\n            } else {\n                // If no tag name is provided, clean shop\n                pos = 0;\n            }\n\n            if (pos >= 0) {\n                // Close all the open elements, up the stack\n                for (var i = stack.length - 1; i >= pos; i--) {\n                    if (i > pos || !tagName &&\n                        options.warn\n                    ) {\n                        options.warn(\n                            (\"tag <\" + (stack[i].tag) + \"> has no matching end tag.\"),\n                            { start: stack[i].start, end: stack[i].end }\n                        );\n                    }\n                    if (options.end) {\n                        options.end(stack[i].tag, start, end);\n                    }\n                }\n\n                // Remove the open elements from the stack\n                stack.length = pos;\n                lastTag = pos && stack[pos - 1].tag;\n            } else if (lowerCasedTagName === 'br') {\n                if (options.start) {\n                    options.start(tagName, [], true, start, end);\n                }\n            } else if (lowerCasedTagName === 'p') {\n                if (options.start) {\n                    options.start(tagName, [], false, start, end);\n                }\n                if (options.end) {\n                    options.end(tagName, start, end);\n                }\n            }\n        }\n    }\n\n    /*  */\n\n    var onRE = /^@|^v-on:/;\n    var dirRE = /^v-|^@|^:|^#/;\n    var forAliasRE = /([\\s\\S]*?)\\s+(?:in|of)\\s+([\\s\\S]*)/;\n    var forIteratorRE = /,([^,\\}\\]]*)(?:,([^,\\}\\]]*))?$/;\n    var stripParensRE = /^\\(|\\)$/g;\n    var dynamicArgRE = /^\\[.*\\]$/;\n\n    var argRE = /:(.*)$/;\n    var bindRE = /^:|^\\.|^v-bind:/;\n    var modifierRE = /\\.[^.\\]]+(?=[^\\]]*$)/g;\n\n    var slotRE = /^v-slot(:|$)|^#/;\n\n    var lineBreakRE = /[\\r\\n]/;\n    var whitespaceRE$1 = /[ \\f\\t\\r\\n]+/g;\n\n    var invalidAttributeRE = /[\\s\"'<>\\/=]/;\n\n    var decodeHTMLCached = cached(he.decode);\n\n    var emptySlotScopeToken = \"_empty_\";\n\n    // configurable state\n    var warn$2;\n    var delimiters;\n    var transforms;\n    var preTransforms;\n    var postTransforms;\n    var platformIsPreTag;\n    var platformMustUseProp;\n    var platformGetTagNamespace;\n    var maybeComponent;\n\n    function createASTElement (\n        tag,\n        attrs,\n        parent\n    ) {\n        return {\n            type: 1,\n            tag: tag,\n            attrsList: attrs,\n            attrsMap: makeAttrsMap(attrs),\n            rawAttrsMap: {},\n            parent: parent,\n            children: []\n        }\n    }\n\n    /**\n     * Convert HTML string to AST.\n     */\n    function parse (\n        template,\n        options\n    ) {\n        warn$2 = options.warn || baseWarn;\n\n        platformIsPreTag = options.isPreTag || no;\n        platformMustUseProp = options.mustUseProp || no;\n        platformGetTagNamespace = options.getTagNamespace || no;\n        var isReservedTag = options.isReservedTag || no;\n        maybeComponent = function (el) { return !!(\n            el.component ||\n            el.attrsMap[':is'] ||\n            el.attrsMap['v-bind:is'] ||\n            !(el.attrsMap.is ? isReservedTag(el.attrsMap.is) : isReservedTag(el.tag))\n        ); };\n        transforms = pluckModuleFunction(options.modules, 'transformNode');\n        preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');\n        postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');\n\n        delimiters = options.delimiters;\n\n        var stack = [];\n        var preserveWhitespace = options.preserveWhitespace !== false;\n        var whitespaceOption = options.whitespace;\n        var root;\n        var currentParent;\n        var inVPre = false;\n        var inPre = false;\n        var warned = false;\n\n        function warnOnce (msg, range) {\n            if (!warned) {\n                warned = true;\n                warn$2(msg, range);\n            }\n        }\n\n        function closeElement (element) {\n            trimEndingWhitespace(element);\n            if (!inVPre && !element.processed) {\n                element = processElement(element, options);\n            }\n            // tree management\n            if (!stack.length && element !== root) {\n                // allow root elements with v-if, v-else-if and v-else\n                if (root.if && (element.elseif || element.else)) {\n                    {\n                        checkRootConstraints(element);\n                    }\n                    addIfCondition(root, {\n                        exp: element.elseif,\n                        block: element\n                    });\n                } else {\n                    warnOnce(\n                        \"Component template should contain exactly one root element. \" +\n                        \"If you are using v-if on multiple elements, \" +\n                        \"use v-else-if to chain them instead.\",\n                        { start: element.start }\n                    );\n                }\n            }\n            if (currentParent && !element.forbidden) {\n                if (element.elseif || element.else) {\n                    processIfConditions(element, currentParent);\n                } else {\n                    if (element.slotScope) {\n                        // scoped slot\n                        // keep it in the children list so that v-else(-if) conditions can\n                        // find it as the prev node.\n                        var name = element.slotTarget || '\"default\"'\n                        ;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;\n                    }\n                    currentParent.children.push(element);\n                    element.parent = currentParent;\n                }\n            }\n\n            // final children cleanup\n            // filter out scoped slots\n            element.children = element.children.filter(function (c) { return !(c).slotScope; });\n            // remove trailing whitespace node again\n            trimEndingWhitespace(element);\n\n            // check pre state\n            if (element.pre) {\n                inVPre = false;\n            }\n            if (platformIsPreTag(element.tag)) {\n                inPre = false;\n            }\n            // apply post-transforms\n            for (var i = 0; i < postTransforms.length; i++) {\n                postTransforms[i](element, options);\n            }\n        }\n\n        function trimEndingWhitespace (el) {\n            // remove trailing whitespace node\n            if (!inPre) {\n                var lastNode;\n                while (\n                    (lastNode = el.children[el.children.length - 1]) &&\n                    lastNode.type === 3 &&\n                    lastNode.text === ' '\n                    ) {\n                    el.children.pop();\n                }\n            }\n        }\n\n        function checkRootConstraints (el) {\n            if (el.tag === 'slot' || el.tag === 'template') {\n                warnOnce(\n                    \"Cannot use <\" + (el.tag) + \"> as component root element because it may \" +\n                    'contain multiple nodes.',\n                    { start: el.start }\n                );\n            }\n            if (el.attrsMap.hasOwnProperty('v-for')) {\n                warnOnce(\n                    'Cannot use v-for on stateful component root element because ' +\n                    'it renders multiple elements.',\n                    el.rawAttrsMap['v-for']\n                );\n            }\n        }\n\n        parseHTML(template, {\n            warn: warn$2,\n            expectHTML: options.expectHTML,\n            isUnaryTag: options.isUnaryTag,\n            canBeLeftOpenTag: options.canBeLeftOpenTag,\n            shouldDecodeNewlines: options.shouldDecodeNewlines,\n            shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,\n            shouldKeepComment: options.comments,\n            outputSourceRange: options.outputSourceRange,\n            start: function start (tag, attrs, unary, start$1, end) {\n                // check namespace.\n                // inherit parent ns if there is one\n                var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);\n\n                // handle IE svg bug\n                /* istanbul ignore if */\n                if (isIE && ns === 'svg') {\n                    attrs = guardIESVGBug(attrs);\n                }\n\n                var element = createASTElement(tag, attrs, currentParent);\n                if (ns) {\n                    element.ns = ns;\n                }\n\n                {\n                    if (options.outputSourceRange) {\n                        element.start = start$1;\n                        element.end = end;\n                        element.rawAttrsMap = element.attrsList.reduce(function (cumulated, attr) {\n                            cumulated[attr.name] = attr;\n                            return cumulated\n                        }, {});\n                    }\n                    attrs.forEach(function (attr) {\n                        if (invalidAttributeRE.test(attr.name)) {\n                            warn$2(\n                                \"Invalid dynamic argument expression: attribute names cannot contain \" +\n                                \"spaces, quotes, <, >, / or =.\",\n                                {\n                                    start: attr.start + attr.name.indexOf(\"[\"),\n                                    end: attr.start + attr.name.length\n                                }\n                            );\n                        }\n                    });\n                }\n\n                if (isForbiddenTag(element) && !isServerRendering()) {\n                    element.forbidden = true;\n                    warn$2(\n                        'Templates should only be responsible for mapping the state to the ' +\n                        'UI. Avoid placing tags with side-effects in your templates, such as ' +\n                        \"<\" + tag + \">\" + ', as they will not be parsed.',\n                        { start: element.start }\n                    );\n                }\n\n                // apply pre-transforms\n                for (var i = 0; i < preTransforms.length; i++) {\n                    element = preTransforms[i](element, options) || element;\n                }\n\n                if (!inVPre) {\n                    processPre(element);\n                    if (element.pre) {\n                        inVPre = true;\n                    }\n                }\n                if (platformIsPreTag(element.tag)) {\n                    inPre = true;\n                }\n                if (inVPre) {\n                    processRawAttrs(element);\n                } else if (!element.processed) {\n                    // structural directives\n                    processFor(element);\n                    processIf(element);\n                    processOnce(element);\n                }\n\n                if (!root) {\n                    root = element;\n                    {\n                        checkRootConstraints(root);\n                    }\n                }\n\n                if (!unary) {\n                    currentParent = element;\n                    stack.push(element);\n                } else {\n                    closeElement(element);\n                }\n            },\n\n            end: function end (tag, start, end$1) {\n                var element = stack[stack.length - 1];\n                // pop stack\n                stack.length -= 1;\n                currentParent = stack[stack.length - 1];\n                if (options.outputSourceRange) {\n                    element.end = end$1;\n                }\n                closeElement(element);\n            },\n\n            chars: function chars (text, start, end) {\n                if (!currentParent) {\n                    {\n                        if (text === template) {\n                            warnOnce(\n                                'Component template requires a root element, rather than just text.',\n                                { start: start }\n                            );\n                        } else if ((text = text.trim())) {\n                            warnOnce(\n                                (\"text \\\"\" + text + \"\\\" outside root element will be ignored.\"),\n                                { start: start }\n                            );\n                        }\n                    }\n                    return\n                }\n                // IE textarea placeholder bug\n                /* istanbul ignore if */\n                if (isIE &&\n                    currentParent.tag === 'textarea' &&\n                    currentParent.attrsMap.placeholder === text\n                ) {\n                    return\n                }\n                var children = currentParent.children;\n                if (inPre || text.trim()) {\n                    text = isTextTag(currentParent) ? text : decodeHTMLCached(text);\n                } else if (!children.length) {\n                    // remove the whitespace-only node right after an opening tag\n                    text = '';\n                } else if (whitespaceOption) {\n                    if (whitespaceOption === 'condense') {\n                        // in condense mode, remove the whitespace node if it contains\n                        // line break, otherwise condense to a single space\n                        text = lineBreakRE.test(text) ? '' : ' ';\n                    } else {\n                        text = ' ';\n                    }\n                } else {\n                    text = preserveWhitespace ? ' ' : '';\n                }\n                if (text) {\n                    if (!inPre && whitespaceOption === 'condense') {\n                        // condense consecutive whitespaces into single space\n                        text = text.replace(whitespaceRE$1, ' ');\n                    }\n                    var res;\n                    var child;\n                    if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) {\n                        child = {\n                            type: 2,\n                            expression: res.expression,\n                            tokens: res.tokens,\n                            text: text\n                        };\n                    } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {\n                        child = {\n                            type: 3,\n                            text: text\n                        };\n                    }\n                    if (child) {\n                        if (options.outputSourceRange) {\n                            child.start = start;\n                            child.end = end;\n                        }\n                        children.push(child);\n                    }\n                }\n            },\n            comment: function comment (text, start, end) {\n                // adding anything as a sibling to the root node is forbidden\n                // comments should still be allowed, but ignored\n                if (currentParent) {\n                    var child = {\n                        type: 3,\n                        text: text,\n                        isComment: true\n                    };\n                    if (options.outputSourceRange) {\n                        child.start = start;\n                        child.end = end;\n                    }\n                    currentParent.children.push(child);\n                }\n            }\n        });\n        return root\n    }\n\n    function processPre (el) {\n        if (getAndRemoveAttr(el, 'v-pre') != null) {\n            el.pre = true;\n        }\n    }\n\n    function processRawAttrs (el) {\n        var list = el.attrsList;\n        var len = list.length;\n        if (len) {\n            var attrs = el.attrs = new Array(len);\n            for (var i = 0; i < len; i++) {\n                attrs[i] = {\n                    name: list[i].name,\n                    value: JSON.stringify(list[i].value)\n                };\n                if (list[i].start != null) {\n                    attrs[i].start = list[i].start;\n                    attrs[i].end = list[i].end;\n                }\n            }\n        } else if (!el.pre) {\n            // non root node in pre blocks with no attributes\n            el.plain = true;\n        }\n    }\n\n    function processElement (\n        element,\n        options\n    ) {\n        processKey(element);\n\n        // determine whether this is a plain element after\n        // removing structural attributes\n        element.plain = (\n            !element.key &&\n            !element.scopedSlots &&\n            !element.attrsList.length\n        );\n\n        processRef(element);\n        processSlotContent(element);\n        processSlotOutlet(element);\n        processComponent(element);\n        for (var i = 0; i < transforms.length; i++) {\n            element = transforms[i](element, options) || element;\n        }\n        processAttrs(element);\n        return element\n    }\n\n    function processKey (el) {\n        var exp = getBindingAttr(el, 'key');\n        if (exp) {\n            {\n                if (el.tag === 'template') {\n                    warn$2(\n                        \"<template> cannot be keyed. Place the key on real elements instead.\",\n                        getRawBindingAttr(el, 'key')\n                    );\n                }\n                if (el.for) {\n                    var iterator = el.iterator2 || el.iterator1;\n                    var parent = el.parent;\n                    if (iterator && iterator === exp && parent && parent.tag === 'transition-group') {\n                        warn$2(\n                            \"Do not use v-for index as key on <transition-group> children, \" +\n                            \"this is the same as not using keys.\",\n                            getRawBindingAttr(el, 'key'),\n                            true /* tip */\n                        );\n                    }\n                }\n            }\n            el.key = exp;\n        }\n    }\n\n    function processRef (el) {\n        var ref = getBindingAttr(el, 'ref');\n        if (ref) {\n            el.ref = ref;\n            el.refInFor = checkInFor(el);\n        }\n    }\n\n    function processFor (el) {\n        var exp;\n        if ((exp = getAndRemoveAttr(el, 'v-for'))) {\n            var res = parseFor(exp);\n            if (res) {\n                extend(el, res);\n            } else {\n                warn$2(\n                    (\"Invalid v-for expression: \" + exp),\n                    el.rawAttrsMap['v-for']\n                );\n            }\n        }\n    }\n\n\n\n    function parseFor (exp) {\n        var inMatch = exp.match(forAliasRE);\n        if (!inMatch) { return }\n        var res = {};\n        res.for = inMatch[2].trim();\n        var alias = inMatch[1].trim().replace(stripParensRE, '');\n        var iteratorMatch = alias.match(forIteratorRE);\n        if (iteratorMatch) {\n            res.alias = alias.replace(forIteratorRE, '').trim();\n            res.iterator1 = iteratorMatch[1].trim();\n            if (iteratorMatch[2]) {\n                res.iterator2 = iteratorMatch[2].trim();\n            }\n        } else {\n            res.alias = alias;\n        }\n        return res\n    }\n\n    function processIf (el) {\n        var exp = getAndRemoveAttr(el, 'v-if');\n        if (exp) {\n            el.if = exp;\n            addIfCondition(el, {\n                exp: exp,\n                block: el\n            });\n        } else {\n            if (getAndRemoveAttr(el, 'v-else') != null) {\n                el.else = true;\n            }\n            var elseif = getAndRemoveAttr(el, 'v-else-if');\n            if (elseif) {\n                el.elseif = elseif;\n            }\n        }\n    }\n\n    function processIfConditions (el, parent) {\n        var prev = findPrevElement(parent.children);\n        if (prev && prev.if) {\n            addIfCondition(prev, {\n                exp: el.elseif,\n                block: el\n            });\n        } else {\n            warn$2(\n                \"v-\" + (el.elseif ? ('else-if=\"' + el.elseif + '\"') : 'else') + \" \" +\n                \"used on element <\" + (el.tag) + \"> without corresponding v-if.\",\n                el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else']\n            );\n        }\n    }\n\n    function findPrevElement (children) {\n        var i = children.length;\n        while (i--) {\n            if (children[i].type === 1) {\n                return children[i]\n            } else {\n                if (children[i].text !== ' ') {\n                    warn$2(\n                        \"text \\\"\" + (children[i].text.trim()) + \"\\\" between v-if and v-else(-if) \" +\n                        \"will be ignored.\",\n                        children[i]\n                    );\n                }\n                children.pop();\n            }\n        }\n    }\n\n    function addIfCondition (el, condition) {\n        if (!el.ifConditions) {\n            el.ifConditions = [];\n        }\n        el.ifConditions.push(condition);\n    }\n\n    function processOnce (el) {\n        var once$$1 = getAndRemoveAttr(el, 'v-once');\n        if (once$$1 != null) {\n            el.once = true;\n        }\n    }\n\n    // handle content being passed to a component as slot,\n    // e.g. <template slot=\"xxx\">, <div slot-scope=\"xxx\">\n    function processSlotContent (el) {\n        var slotScope;\n        if (el.tag === 'template') {\n            slotScope = getAndRemoveAttr(el, 'scope');\n            /* istanbul ignore if */\n            if (slotScope) {\n                warn$2(\n                    \"the \\\"scope\\\" attribute for scoped slots have been deprecated and \" +\n                    \"replaced by \\\"slot-scope\\\" since 2.5. The new \\\"slot-scope\\\" attribute \" +\n                    \"can also be used on plain elements in addition to <template> to \" +\n                    \"denote scoped slots.\",\n                    el.rawAttrsMap['scope'],\n                    true\n                );\n            }\n            el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope');\n        } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) {\n            /* istanbul ignore if */\n            if (el.attrsMap['v-for']) {\n                warn$2(\n                    \"Ambiguous combined usage of slot-scope and v-for on <\" + (el.tag) + \"> \" +\n                    \"(v-for takes higher priority). Use a wrapper <template> for the \" +\n                    \"scoped slot to make it clearer.\",\n                    el.rawAttrsMap['slot-scope'],\n                    true\n                );\n            }\n            el.slotScope = slotScope;\n        }\n\n        // slot=\"xxx\"\n        var slotTarget = getBindingAttr(el, 'slot');\n        if (slotTarget) {\n            el.slotTarget = slotTarget === '\"\"' ? '\"default\"' : slotTarget;\n            el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']);\n            // preserve slot as an attribute for native shadow DOM compat\n            // only for non-scoped slots.\n            if (el.tag !== 'template' && !el.slotScope) {\n                addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot'));\n            }\n        }\n\n        // 2.6 v-slot syntax\n        {\n            if (el.tag === 'template') {\n                // v-slot on <template>\n                var slotBinding = getAndRemoveAttrByRegex(el, slotRE);\n                if (slotBinding) {\n                    {\n                        if (el.slotTarget || el.slotScope) {\n                            warn$2(\n                                \"Unexpected mixed usage of different slot syntaxes.\",\n                                el\n                            );\n                        }\n                        if (el.parent && !maybeComponent(el.parent)) {\n                            warn$2(\n                                \"<template v-slot> can only appear at the root level inside \" +\n                                \"the receiving component\",\n                                el\n                            );\n                        }\n                    }\n                    var ref = getSlotName(slotBinding);\n                    var name = ref.name;\n                    var dynamic = ref.dynamic;\n                    el.slotTarget = name;\n                    el.slotTargetDynamic = dynamic;\n                    el.slotScope = slotBinding.value || emptySlotScopeToken; // force it into a scoped slot for perf\n                }\n            } else {\n                // v-slot on component, denotes default slot\n                var slotBinding$1 = getAndRemoveAttrByRegex(el, slotRE);\n                if (slotBinding$1) {\n                    {\n                        if (!maybeComponent(el)) {\n                            warn$2(\n                                \"v-slot can only be used on components or <template>.\",\n                                slotBinding$1\n                            );\n                        }\n                        if (el.slotScope || el.slotTarget) {\n                            warn$2(\n                                \"Unexpected mixed usage of different slot syntaxes.\",\n                                el\n                            );\n                        }\n                        if (el.scopedSlots) {\n                            warn$2(\n                                \"To avoid scope ambiguity, the default slot should also use \" +\n                                \"<template> syntax when there are other named slots.\",\n                                slotBinding$1\n                            );\n                        }\n                    }\n                    // add the component's children to its default slot\n                    var slots = el.scopedSlots || (el.scopedSlots = {});\n                    var ref$1 = getSlotName(slotBinding$1);\n                    var name$1 = ref$1.name;\n                    var dynamic$1 = ref$1.dynamic;\n                    var slotContainer = slots[name$1] = createASTElement('template', [], el);\n                    slotContainer.slotTarget = name$1;\n                    slotContainer.slotTargetDynamic = dynamic$1;\n                    slotContainer.children = el.children.filter(function (c) {\n                        if (!c.slotScope) {\n                            c.parent = slotContainer;\n                            return true\n                        }\n                    });\n                    slotContainer.slotScope = slotBinding$1.value || emptySlotScopeToken;\n                    // remove children as they are returned from scopedSlots now\n                    el.children = [];\n                    // mark el non-plain so data gets generated\n                    el.plain = false;\n                }\n            }\n        }\n    }\n\n    function getSlotName (binding) {\n        var name = binding.name.replace(slotRE, '');\n        if (!name) {\n            if (binding.name[0] !== '#') {\n                name = 'default';\n            } else {\n                warn$2(\n                    \"v-slot shorthand syntax requires a slot name.\",\n                    binding\n                );\n            }\n        }\n        return dynamicArgRE.test(name)\n            // dynamic [name]\n            ? { name: name.slice(1, -1), dynamic: true }\n            // static name\n            : { name: (\"\\\"\" + name + \"\\\"\"), dynamic: false }\n    }\n\n    // handle <slot/> outlets\n    function processSlotOutlet (el) {\n        if (el.tag === 'slot') {\n            el.slotName = getBindingAttr(el, 'name');\n            if (el.key) {\n                warn$2(\n                    \"`key` does not work on <slot> because slots are abstract outlets \" +\n                    \"and can possibly expand into multiple elements. \" +\n                    \"Use the key on a wrapping element instead.\",\n                    getRawBindingAttr(el, 'key')\n                );\n            }\n        }\n    }\n\n    function processComponent (el) {\n        var binding;\n        if ((binding = getBindingAttr(el, 'is'))) {\n            el.component = binding;\n        }\n        if (getAndRemoveAttr(el, 'inline-template') != null) {\n            el.inlineTemplate = true;\n        }\n    }\n\n    function processAttrs (el) {\n        var list = el.attrsList;\n        var i, l, name, rawName, value, modifiers, syncGen, isDynamic;\n        for (i = 0, l = list.length; i < l; i++) {\n            name = rawName = list[i].name;\n            value = list[i].value;\n            if (dirRE.test(name)) {\n                // mark element as dynamic\n                el.hasBindings = true;\n                // modifiers\n                modifiers = parseModifiers(name.replace(dirRE, ''));\n                // support .foo shorthand syntax for the .prop modifier\n                if (modifiers) {\n                    name = name.replace(modifierRE, '');\n                }\n                if (bindRE.test(name)) { // v-bind\n                    name = name.replace(bindRE, '');\n                    value = parseFilters(value);\n                    isDynamic = dynamicArgRE.test(name);\n                    if (isDynamic) {\n                        name = name.slice(1, -1);\n                    }\n                    if (\n                        value.trim().length === 0\n                    ) {\n                        warn$2(\n                            (\"The value for a v-bind expression cannot be empty. Found in \\\"v-bind:\" + name + \"\\\"\")\n                        );\n                    }\n                    if (modifiers) {\n                        if (modifiers.prop && !isDynamic) {\n                            name = camelize(name);\n                            if (name === 'innerHtml') { name = 'innerHTML'; }\n                        }\n                        if (modifiers.camel && !isDynamic) {\n                            name = camelize(name);\n                        }\n                        if (modifiers.sync) {\n                            syncGen = genAssignmentCode(value, \"$event\");\n                            if (!isDynamic) {\n                                addHandler(\n                                    el,\n                                    (\"update:\" + (camelize(name))),\n                                    syncGen,\n                                    null,\n                                    false,\n                                    warn$2,\n                                    list[i]\n                                );\n                                if (hyphenate(name) !== camelize(name)) {\n                                    addHandler(\n                                        el,\n                                        (\"update:\" + (hyphenate(name))),\n                                        syncGen,\n                                        null,\n                                        false,\n                                        warn$2,\n                                        list[i]\n                                    );\n                                }\n                            } else {\n                                // handler w/ dynamic event name\n                                addHandler(\n                                    el,\n                                    (\"\\\"update:\\\"+(\" + name + \")\"),\n                                    syncGen,\n                                    null,\n                                    false,\n                                    warn$2,\n                                    list[i],\n                                    true // dynamic\n                                );\n                            }\n                        }\n                    }\n                    if ((modifiers && modifiers.prop) || (\n                        !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)\n                    )) {\n                        addProp(el, name, value, list[i], isDynamic);\n                    } else {\n                        addAttr(el, name, value, list[i], isDynamic);\n                    }\n                } else if (onRE.test(name)) { // v-on\n                    name = name.replace(onRE, '');\n                    isDynamic = dynamicArgRE.test(name);\n                    if (isDynamic) {\n                        name = name.slice(1, -1);\n                    }\n                    addHandler(el, name, value, modifiers, false, warn$2, list[i], isDynamic);\n                } else { // normal directives\n                    name = name.replace(dirRE, '');\n                    // parse arg\n                    var argMatch = name.match(argRE);\n                    var arg = argMatch && argMatch[1];\n                    isDynamic = false;\n                    if (arg) {\n                        name = name.slice(0, -(arg.length + 1));\n                        if (dynamicArgRE.test(arg)) {\n                            arg = arg.slice(1, -1);\n                            isDynamic = true;\n                        }\n                    }\n                    addDirective(el, name, rawName, value, arg, isDynamic, modifiers, list[i]);\n                    if (name === 'model') {\n                        checkForAliasModel(el, value);\n                    }\n                }\n            } else {\n                // literal attribute\n                {\n                    var res = parseText(value, delimiters);\n                    if (res) {\n                        warn$2(\n                            name + \"=\\\"\" + value + \"\\\": \" +\n                            'Interpolation inside attributes has been removed. ' +\n                            'Use v-bind or the colon shorthand instead. For example, ' +\n                            'instead of <div id=\"{{ val }}\">, use <div :id=\"val\">.',\n                            list[i]\n                        );\n                    }\n                }\n                addAttr(el, name, JSON.stringify(value), list[i]);\n                // #6887 firefox doesn't update muted state if set via attribute\n                // even immediately after element creation\n                if (!el.component &&\n                    name === 'muted' &&\n                    platformMustUseProp(el.tag, el.attrsMap.type, name)) {\n                    addProp(el, name, 'true', list[i]);\n                }\n            }\n        }\n    }\n\n    function checkInFor (el) {\n        var parent = el;\n        while (parent) {\n            if (parent.for !== undefined) {\n                return true\n            }\n            parent = parent.parent;\n        }\n        return false\n    }\n\n    function parseModifiers (name) {\n        var match = name.match(modifierRE);\n        if (match) {\n            var ret = {};\n            match.forEach(function (m) { ret[m.slice(1)] = true; });\n            return ret\n        }\n    }\n\n    function makeAttrsMap (attrs) {\n        var map = {};\n        for (var i = 0, l = attrs.length; i < l; i++) {\n            if (\n                map[attrs[i].name] && !isIE && !isEdge\n            ) {\n                warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]);\n            }\n            map[attrs[i].name] = attrs[i].value;\n        }\n        return map\n    }\n\n    // for script (e.g. type=\"x/template\") or style, do not decode content\n    function isTextTag (el) {\n        return el.tag === 'script' || el.tag === 'style'\n    }\n\n    function isForbiddenTag (el) {\n        return (\n            el.tag === 'style' ||\n            (el.tag === 'script' && (\n                !el.attrsMap.type ||\n                el.attrsMap.type === 'text/javascript'\n            ))\n        )\n    }\n\n    var ieNSBug = /^xmlns:NS\\d+/;\n    var ieNSPrefix = /^NS\\d+:/;\n\n    /* istanbul ignore next */\n    function guardIESVGBug (attrs) {\n        var res = [];\n        for (var i = 0; i < attrs.length; i++) {\n            var attr = attrs[i];\n            if (!ieNSBug.test(attr.name)) {\n                attr.name = attr.name.replace(ieNSPrefix, '');\n                res.push(attr);\n            }\n        }\n        return res\n    }\n\n    function checkForAliasModel (el, value) {\n        var _el = el;\n        while (_el) {\n            if (_el.for && _el.alias === value) {\n                warn$2(\n                    \"<\" + (el.tag) + \" v-model=\\\"\" + value + \"\\\">: \" +\n                    \"You are binding v-model directly to a v-for iteration alias. \" +\n                    \"This will not be able to modify the v-for source array because \" +\n                    \"writing to the alias is like modifying a function local variable. \" +\n                    \"Consider using an array of objects and use v-model on an object property instead.\",\n                    el.rawAttrsMap['v-model']\n                );\n            }\n            _el = _el.parent;\n        }\n    }\n\n    /*  */\n\n    function preTransformNode (el, options) {\n        if (el.tag === 'input') {\n            var map = el.attrsMap;\n            if (!map['v-model']) {\n                return\n            }\n\n            var typeBinding;\n            if (map[':type'] || map['v-bind:type']) {\n                typeBinding = getBindingAttr(el, 'type');\n            }\n            if (!map.type && !typeBinding && map['v-bind']) {\n                typeBinding = \"(\" + (map['v-bind']) + \").type\";\n            }\n\n            if (typeBinding) {\n                var ifCondition = getAndRemoveAttr(el, 'v-if', true);\n                var ifConditionExtra = ifCondition ? (\"&&(\" + ifCondition + \")\") : \"\";\n                var hasElse = getAndRemoveAttr(el, 'v-else', true) != null;\n                var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true);\n                // 1. checkbox\n                var branch0 = cloneASTElement(el);\n                // process for on the main node\n                processFor(branch0);\n                addRawAttr(branch0, 'type', 'checkbox');\n                processElement(branch0, options);\n                branch0.processed = true; // prevent it from double-processed\n                branch0.if = \"(\" + typeBinding + \")==='checkbox'\" + ifConditionExtra;\n                addIfCondition(branch0, {\n                    exp: branch0.if,\n                    block: branch0\n                });\n                // 2. add radio else-if condition\n                var branch1 = cloneASTElement(el);\n                getAndRemoveAttr(branch1, 'v-for', true);\n                addRawAttr(branch1, 'type', 'radio');\n                processElement(branch1, options);\n                addIfCondition(branch0, {\n                    exp: \"(\" + typeBinding + \")==='radio'\" + ifConditionExtra,\n                    block: branch1\n                });\n                // 3. other\n                var branch2 = cloneASTElement(el);\n                getAndRemoveAttr(branch2, 'v-for', true);\n                addRawAttr(branch2, ':type', typeBinding);\n                processElement(branch2, options);\n                addIfCondition(branch0, {\n                    exp: ifCondition,\n                    block: branch2\n                });\n\n                if (hasElse) {\n                    branch0.else = true;\n                } else if (elseIfCondition) {\n                    branch0.elseif = elseIfCondition;\n                }\n\n                return branch0\n            }\n        }\n    }\n\n    function cloneASTElement (el) {\n        return createASTElement(el.tag, el.attrsList.slice(), el.parent)\n    }\n\n    var model$1 = {\n        preTransformNode: preTransformNode\n    };\n\n    var modules$1 = [\n        klass$1,\n        style$1,\n        model$1\n    ];\n\n    /*  */\n\n    function text (el, dir) {\n        if (dir.value) {\n            addProp(el, 'textContent', (\"_s(\" + (dir.value) + \")\"), dir);\n        }\n    }\n\n    /*  */\n\n    function html (el, dir) {\n        if (dir.value) {\n            addProp(el, 'innerHTML', (\"_s(\" + (dir.value) + \")\"), dir);\n        }\n    }\n\n    var directives$1 = {\n        model: model,\n        text: text,\n        html: html\n    };\n\n    /*  */\n\n    var baseOptions = {\n        expectHTML: true,\n        modules: modules$1,\n        directives: directives$1,\n        isPreTag: isPreTag,\n        isUnaryTag: isUnaryTag,\n        mustUseProp: mustUseProp,\n        canBeLeftOpenTag: canBeLeftOpenTag,\n        isReservedTag: isReservedTag,\n        getTagNamespace: getTagNamespace,\n        staticKeys: genStaticKeys(modules$1)\n    };\n\n    /*  */\n\n    var isStaticKey;\n    var isPlatformReservedTag;\n\n    var genStaticKeysCached = cached(genStaticKeys$1);\n\n    /**\n     * Goal of the optimizer: walk the generated template AST tree\n     * and detect sub-trees that are purely static, i.e. parts of\n     * the DOM that never needs to change.\n     *\n     * Once we detect these sub-trees, we can:\n     *\n     * 1. Hoist them into constants, so that we no longer need to\n     *    create fresh nodes for them on each re-render;\n     * 2. Completely skip them in the patching process.\n     */\n    function optimize (root, options) {\n        if (!root) { return }\n        isStaticKey = genStaticKeysCached(options.staticKeys || '');\n        isPlatformReservedTag = options.isReservedTag || no;\n        // first pass: mark all non-static nodes.\n        markStatic$1(root);\n        // second pass: mark static roots.\n        markStaticRoots(root, false);\n    }\n\n    function genStaticKeys$1 (keys) {\n        return makeMap(\n            'type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' +\n            (keys ? ',' + keys : '')\n        )\n    }\n\n    function markStatic$1 (node) {\n        node.static = isStatic(node);\n        if (node.type === 1) {\n            // do not make component slot content static. this avoids\n            // 1. components not able to mutate slot nodes\n            // 2. static slot content fails for hot-reloading\n            if (\n                !isPlatformReservedTag(node.tag) &&\n                node.tag !== 'slot' &&\n                node.attrsMap['inline-template'] == null\n            ) {\n                return\n            }\n            for (var i = 0, l = node.children.length; i < l; i++) {\n                var child = node.children[i];\n                markStatic$1(child);\n                if (!child.static) {\n                    node.static = false;\n                }\n            }\n            if (node.ifConditions) {\n                for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n                    var block = node.ifConditions[i$1].block;\n                    markStatic$1(block);\n                    if (!block.static) {\n                        node.static = false;\n                    }\n                }\n            }\n        }\n    }\n\n    function markStaticRoots (node, isInFor) {\n        if (node.type === 1) {\n            if (node.static || node.once) {\n                node.staticInFor = isInFor;\n            }\n            // For a node to qualify as a static root, it should have children that\n            // are not just static text. Otherwise the cost of hoisting out will\n            // outweigh the benefits and it's better off to just always render it fresh.\n            if (node.static && node.children.length && !(\n                node.children.length === 1 &&\n                node.children[0].type === 3\n            )) {\n                node.staticRoot = true;\n                return\n            } else {\n                node.staticRoot = false;\n            }\n            if (node.children) {\n                for (var i = 0, l = node.children.length; i < l; i++) {\n                    markStaticRoots(node.children[i], isInFor || !!node.for);\n                }\n            }\n            if (node.ifConditions) {\n                for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n                    markStaticRoots(node.ifConditions[i$1].block, isInFor);\n                }\n            }\n        }\n    }\n\n    function isStatic (node) {\n        if (node.type === 2) { // expression\n            return false\n        }\n        if (node.type === 3) { // text\n            return true\n        }\n        return !!(node.pre || (\n            !node.hasBindings && // no dynamic bindings\n            !node.if && !node.for && // not v-if or v-for or v-else\n            !isBuiltInTag(node.tag) && // not a built-in\n            isPlatformReservedTag(node.tag) && // not a component\n            !isDirectChildOfTemplateFor(node) &&\n            Object.keys(node).every(isStaticKey)\n        ))\n    }\n\n    function isDirectChildOfTemplateFor (node) {\n        while (node.parent) {\n            node = node.parent;\n            if (node.tag !== 'template') {\n                return false\n            }\n            if (node.for) {\n                return true\n            }\n        }\n        return false\n    }\n\n    /*  */\n\n    var fnExpRE = /^([\\w$_]+|\\([^)]*?\\))\\s*=>|^function(?:\\s+[\\w$]+)?\\s*\\(/;\n    var fnInvokeRE = /\\([^)]*?\\);*$/;\n    var simplePathRE = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*|\\['[^']*?']|\\[\"[^\"]*?\"]|\\[\\d+]|\\[[A-Za-z_$][\\w$]*])*$/;\n\n    // KeyboardEvent.keyCode aliases\n    var keyCodes = {\n        esc: 27,\n        tab: 9,\n        enter: 13,\n        space: 32,\n        up: 38,\n        left: 37,\n        right: 39,\n        down: 40,\n        'delete': [8, 46]\n    };\n\n    // KeyboardEvent.key aliases\n    var keyNames = {\n        // #7880: IE11 and Edge use `Esc` for Escape key name.\n        esc: ['Esc', 'Escape'],\n        tab: 'Tab',\n        enter: 'Enter',\n        // #9112: IE11 uses `Spacebar` for Space key name.\n        space: [' ', 'Spacebar'],\n        // #7806: IE11 uses key names without `Arrow` prefix for arrow keys.\n        up: ['Up', 'ArrowUp'],\n        left: ['Left', 'ArrowLeft'],\n        right: ['Right', 'ArrowRight'],\n        down: ['Down', 'ArrowDown'],\n        // #9112: IE11 uses `Del` for Delete key name.\n        'delete': ['Backspace', 'Delete', 'Del']\n    };\n\n    // #4868: modifiers that prevent the execution of the listener\n    // need to explicitly return null so that we can determine whether to remove\n    // the listener for .once\n    var genGuard = function (condition) { return (\"if(\" + condition + \")return null;\"); };\n\n    var modifierCode = {\n        stop: '$event.stopPropagation();',\n        prevent: '$event.preventDefault();',\n        self: genGuard(\"$event.target !== $event.currentTarget\"),\n        ctrl: genGuard(\"!$event.ctrlKey\"),\n        shift: genGuard(\"!$event.shiftKey\"),\n        alt: genGuard(\"!$event.altKey\"),\n        meta: genGuard(\"!$event.metaKey\"),\n        left: genGuard(\"'button' in $event && $event.button !== 0\"),\n        middle: genGuard(\"'button' in $event && $event.button !== 1\"),\n        right: genGuard(\"'button' in $event && $event.button !== 2\")\n    };\n\n    function genHandlers (\n        events,\n        isNative\n    ) {\n        var prefix = isNative ? 'nativeOn:' : 'on:';\n        var staticHandlers = \"\";\n        var dynamicHandlers = \"\";\n        for (var name in events) {\n            var handlerCode = genHandler(events[name]);\n            if (events[name] && events[name].dynamic) {\n                dynamicHandlers += name + \",\" + handlerCode + \",\";\n            } else {\n                staticHandlers += \"\\\"\" + name + \"\\\":\" + handlerCode + \",\";\n            }\n        }\n        staticHandlers = \"{\" + (staticHandlers.slice(0, -1)) + \"}\";\n        if (dynamicHandlers) {\n            return prefix + \"_d(\" + staticHandlers + \",[\" + (dynamicHandlers.slice(0, -1)) + \"])\"\n        } else {\n            return prefix + staticHandlers\n        }\n    }\n\n    function genHandler (handler) {\n        if (!handler) {\n            return 'function(){}'\n        }\n\n        if (Array.isArray(handler)) {\n            return (\"[\" + (handler.map(function (handler) { return genHandler(handler); }).join(',')) + \"]\")\n        }\n\n        var isMethodPath = simplePathRE.test(handler.value);\n        var isFunctionExpression = fnExpRE.test(handler.value);\n        var isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, ''));\n\n        if (!handler.modifiers) {\n            if (isMethodPath || isFunctionExpression) {\n                return handler.value\n            }\n            return (\"function($event){\" + (isFunctionInvocation ? (\"return \" + (handler.value)) : handler.value) + \"}\") // inline statement\n        } else {\n            var code = '';\n            var genModifierCode = '';\n            var keys = [];\n            for (var key in handler.modifiers) {\n                if (modifierCode[key]) {\n                    genModifierCode += modifierCode[key];\n                    // left/right\n                    if (keyCodes[key]) {\n                        keys.push(key);\n                    }\n                } else if (key === 'exact') {\n                    var modifiers = (handler.modifiers);\n                    genModifierCode += genGuard(\n                        ['ctrl', 'shift', 'alt', 'meta']\n                            .filter(function (keyModifier) { return !modifiers[keyModifier]; })\n                            .map(function (keyModifier) { return (\"$event.\" + keyModifier + \"Key\"); })\n                            .join('||')\n                    );\n                } else {\n                    keys.push(key);\n                }\n            }\n            if (keys.length) {\n                code += genKeyFilter(keys);\n            }\n            // Make sure modifiers like prevent and stop get executed after key filtering\n            if (genModifierCode) {\n                code += genModifierCode;\n            }\n            var handlerCode = isMethodPath\n                ? (\"return \" + (handler.value) + \".apply(null, arguments)\")\n                : isFunctionExpression\n                    ? (\"return (\" + (handler.value) + \").apply(null, arguments)\")\n                    : isFunctionInvocation\n                        ? (\"return \" + (handler.value))\n                        : handler.value;\n            return (\"function($event){\" + code + handlerCode + \"}\")\n        }\n    }\n\n    function genKeyFilter (keys) {\n        return (\n            // make sure the key filters only apply to KeyboardEvents\n            // #9441: can't use 'keyCode' in $event because Chrome autofill fires fake\n            // key events that do not have keyCode property...\n            \"if(!$event.type.indexOf('key')&&\" +\n            (keys.map(genFilterCode).join('&&')) + \")return null;\"\n        )\n    }\n\n    function genFilterCode (key) {\n        var keyVal = parseInt(key, 10);\n        if (keyVal) {\n            return (\"$event.keyCode!==\" + keyVal)\n        }\n        var keyCode = keyCodes[key];\n        var keyName = keyNames[key];\n        return (\n            \"_k($event.keyCode,\" +\n            (JSON.stringify(key)) + \",\" +\n            (JSON.stringify(keyCode)) + \",\" +\n            \"$event.key,\" +\n            \"\" + (JSON.stringify(keyName)) +\n            \")\"\n        )\n    }\n\n    /*  */\n\n    function on (el, dir) {\n        if (dir.modifiers) {\n            warn(\"v-on without argument does not support modifiers.\");\n        }\n        el.wrapListeners = function (code) { return (\"_g(\" + code + \",\" + (dir.value) + \")\"); };\n    }\n\n    /*  */\n\n    function bind$1 (el, dir) {\n        el.wrapData = function (code) {\n            return (\"_b(\" + code + \",'\" + (el.tag) + \"',\" + (dir.value) + \",\" + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + \")\")\n        };\n    }\n\n    /*  */\n\n    var baseDirectives = {\n        on: on,\n        bind: bind$1,\n        cloak: noop\n    };\n\n    /*  */\n\n\n\n\n\n    var CodegenState = function CodegenState (options) {\n        this.options = options;\n        this.warn = options.warn || baseWarn;\n        this.transforms = pluckModuleFunction(options.modules, 'transformCode');\n        this.dataGenFns = pluckModuleFunction(options.modules, 'genData');\n        this.directives = extend(extend({}, baseDirectives), options.directives);\n        var isReservedTag = options.isReservedTag || no;\n        this.maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); };\n        this.onceId = 0;\n        this.staticRenderFns = [];\n        this.pre = false;\n    };\n\n\n\n    function generate (\n        ast,\n        options\n    ) {\n        var state = new CodegenState(options);\n        // fix #11483, Root level <script> tags should not be rendered.\n        var code = ast ? (ast.tag === 'script' ? 'null' : genElement(ast, state)) : '_c(\"div\")';\n        return {\n            render: (\"with(this){return \" + code + \"}\"),\n            staticRenderFns: state.staticRenderFns\n        }\n    }\n\n    function genElement (el, state) {\n        if (el.parent) {\n            el.pre = el.pre || el.parent.pre;\n        }\n\n        if (el.staticRoot && !el.staticProcessed) {\n            return genStatic(el, state)\n        } else if (el.once && !el.onceProcessed) {\n            return genOnce(el, state)\n        } else if (el.for && !el.forProcessed) {\n            return genFor(el, state)\n        } else if (el.if && !el.ifProcessed) {\n            return genIf(el, state)\n        } else if (el.tag === 'template' && !el.slotTarget && !state.pre) {\n            return genChildren(el, state) || 'void 0'\n        } else if (el.tag === 'slot') {\n            return genSlot(el, state)\n        } else {\n            // component or element\n            var code;\n            if (el.component) {\n                code = genComponent(el.component, el, state);\n            } else {\n                var data;\n                if (!el.plain || (el.pre && state.maybeComponent(el))) {\n                    data = genData$2(el, state);\n                }\n\n                var children = el.inlineTemplate ? null : genChildren(el, state, true);\n                code = \"_c('\" + (el.tag) + \"'\" + (data ? (\",\" + data) : '') + (children ? (\",\" + children) : '') + \")\";\n            }\n            // module transforms\n            for (var i = 0; i < state.transforms.length; i++) {\n                code = state.transforms[i](el, code);\n            }\n            return code\n        }\n    }\n\n    // hoist static sub-trees out\n    function genStatic (el, state) {\n        el.staticProcessed = true;\n        // Some elements (templates) need to behave differently inside of a v-pre\n        // node.  All pre nodes are static roots, so we can use this as a location to\n        // wrap a state change and reset it upon exiting the pre node.\n        var originalPreState = state.pre;\n        if (el.pre) {\n            state.pre = el.pre;\n        }\n        state.staticRenderFns.push((\"with(this){return \" + (genElement(el, state)) + \"}\"));\n        state.pre = originalPreState;\n        return (\"_m(\" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + \")\")\n    }\n\n    // v-once\n    function genOnce (el, state) {\n        el.onceProcessed = true;\n        if (el.if && !el.ifProcessed) {\n            return genIf(el, state)\n        } else if (el.staticInFor) {\n            var key = '';\n            var parent = el.parent;\n            while (parent) {\n                if (parent.for) {\n                    key = parent.key;\n                    break\n                }\n                parent = parent.parent;\n            }\n            if (!key) {\n                state.warn(\n                    \"v-once can only be used inside v-for that is keyed. \",\n                    el.rawAttrsMap['v-once']\n                );\n                return genElement(el, state)\n            }\n            return (\"_o(\" + (genElement(el, state)) + \",\" + (state.onceId++) + \",\" + key + \")\")\n        } else {\n            return genStatic(el, state)\n        }\n    }\n\n    function genIf (\n        el,\n        state,\n        altGen,\n        altEmpty\n    ) {\n        el.ifProcessed = true; // avoid recursion\n        return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)\n    }\n\n    function genIfConditions (\n        conditions,\n        state,\n        altGen,\n        altEmpty\n    ) {\n        if (!conditions.length) {\n            return altEmpty || '_e()'\n        }\n\n        var condition = conditions.shift();\n        if (condition.exp) {\n            return (\"(\" + (condition.exp) + \")?\" + (genTernaryExp(condition.block)) + \":\" + (genIfConditions(conditions, state, altGen, altEmpty)))\n        } else {\n            return (\"\" + (genTernaryExp(condition.block)))\n        }\n\n        // v-if with v-once should generate code like (a)?_m(0):_m(1)\n        function genTernaryExp (el) {\n            return altGen\n                ? altGen(el, state)\n                : el.once\n                    ? genOnce(el, state)\n                    : genElement(el, state)\n        }\n    }\n\n    function genFor (\n        el,\n        state,\n        altGen,\n        altHelper\n    ) {\n        var exp = el.for;\n        var alias = el.alias;\n        var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n        var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n\n        if (state.maybeComponent(el) &&\n            el.tag !== 'slot' &&\n            el.tag !== 'template' &&\n            !el.key\n        ) {\n            state.warn(\n                \"<\" + (el.tag) + \" v-for=\\\"\" + alias + \" in \" + exp + \"\\\">: component lists rendered with \" +\n                \"v-for should have explicit keys. \" +\n                \"See https://vuejs.org/guide/list.html#key for more info.\",\n                el.rawAttrsMap['v-for'],\n                true /* tip */\n            );\n        }\n\n        el.forProcessed = true; // avoid recursion\n        return (altHelper || '_l') + \"((\" + exp + \"),\" +\n            \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n            \"return \" + ((altGen || genElement)(el, state)) +\n            '})'\n    }\n\n    function genData$2 (el, state) {\n        var data = '{';\n\n        // directives first.\n        // directives may mutate the el's other properties before they are generated.\n        var dirs = genDirectives(el, state);\n        if (dirs) { data += dirs + ','; }\n\n        // key\n        if (el.key) {\n            data += \"key:\" + (el.key) + \",\";\n        }\n        // ref\n        if (el.ref) {\n            data += \"ref:\" + (el.ref) + \",\";\n        }\n        if (el.refInFor) {\n            data += \"refInFor:true,\";\n        }\n        // pre\n        if (el.pre) {\n            data += \"pre:true,\";\n        }\n        // record original tag name for components using \"is\" attribute\n        if (el.component) {\n            data += \"tag:\\\"\" + (el.tag) + \"\\\",\";\n        }\n        // module data generation functions\n        for (var i = 0; i < state.dataGenFns.length; i++) {\n            data += state.dataGenFns[i](el);\n        }\n        // attributes\n        if (el.attrs) {\n            data += \"attrs:\" + (genProps(el.attrs)) + \",\";\n        }\n        // DOM props\n        if (el.props) {\n            data += \"domProps:\" + (genProps(el.props)) + \",\";\n        }\n        // event handlers\n        if (el.events) {\n            data += (genHandlers(el.events, false)) + \",\";\n        }\n        if (el.nativeEvents) {\n            data += (genHandlers(el.nativeEvents, true)) + \",\";\n        }\n        // slot target\n        // only for non-scoped slots\n        if (el.slotTarget && !el.slotScope) {\n            data += \"slot:\" + (el.slotTarget) + \",\";\n        }\n        // scoped slots\n        if (el.scopedSlots) {\n            data += (genScopedSlots(el, el.scopedSlots, state)) + \",\";\n        }\n        // component v-model\n        if (el.model) {\n            data += \"model:{value:\" + (el.model.value) + \",callback:\" + (el.model.callback) + \",expression:\" + (el.model.expression) + \"},\";\n        }\n        // inline-template\n        if (el.inlineTemplate) {\n            var inlineTemplate = genInlineTemplate(el, state);\n            if (inlineTemplate) {\n                data += inlineTemplate + \",\";\n            }\n        }\n        data = data.replace(/,$/, '') + '}';\n        // v-bind dynamic argument wrap\n        // v-bind with dynamic arguments must be applied using the same v-bind object\n        // merge helper so that class/style/mustUseProp attrs are handled correctly.\n        if (el.dynamicAttrs) {\n            data = \"_b(\" + data + \",\\\"\" + (el.tag) + \"\\\",\" + (genProps(el.dynamicAttrs)) + \")\";\n        }\n        // v-bind data wrap\n        if (el.wrapData) {\n            data = el.wrapData(data);\n        }\n        // v-on data wrap\n        if (el.wrapListeners) {\n            data = el.wrapListeners(data);\n        }\n        return data\n    }\n\n    function genDirectives (el, state) {\n        var dirs = el.directives;\n        if (!dirs) { return }\n        var res = 'directives:[';\n        var hasRuntime = false;\n        var i, l, dir, needRuntime;\n        for (i = 0, l = dirs.length; i < l; i++) {\n            dir = dirs[i];\n            needRuntime = true;\n            var gen = state.directives[dir.name];\n            if (gen) {\n                // compile-time directive that manipulates AST.\n                // returns true if it also needs a runtime counterpart.\n                needRuntime = !!gen(el, dir, state.warn);\n            }\n            if (needRuntime) {\n                hasRuntime = true;\n                res += \"{name:\\\"\" + (dir.name) + \"\\\",rawName:\\\"\" + (dir.rawName) + \"\\\"\" + (dir.value ? (\",value:(\" + (dir.value) + \"),expression:\" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (\",arg:\" + (dir.isDynamicArg ? dir.arg : (\"\\\"\" + (dir.arg) + \"\\\"\"))) : '') + (dir.modifiers ? (\",modifiers:\" + (JSON.stringify(dir.modifiers))) : '') + \"},\";\n            }\n        }\n        if (hasRuntime) {\n            return res.slice(0, -1) + ']'\n        }\n    }\n\n    function genInlineTemplate (el, state) {\n        var ast = el.children[0];\n        if (el.children.length !== 1 || ast.type !== 1) {\n            state.warn(\n                'Inline-template components must have exactly one child element.',\n                { start: el.start }\n            );\n        }\n        if (ast && ast.type === 1) {\n            var inlineRenderFns = generate(ast, state.options);\n            return (\"inlineTemplate:{render:function(){\" + (inlineRenderFns.render) + \"},staticRenderFns:[\" + (inlineRenderFns.staticRenderFns.map(function (code) { return (\"function(){\" + code + \"}\"); }).join(',')) + \"]}\")\n        }\n    }\n\n    function genScopedSlots (\n        el,\n        slots,\n        state\n    ) {\n        // by default scoped slots are considered \"stable\", this allows child\n        // components with only scoped slots to skip forced updates from parent.\n        // but in some cases we have to bail-out of this optimization\n        // for example if the slot contains dynamic names, has v-if or v-for on them...\n        var needsForceUpdate = el.for || Object.keys(slots).some(function (key) {\n            var slot = slots[key];\n            return (\n                slot.slotTargetDynamic ||\n                slot.if ||\n                slot.for ||\n                containsSlotChild(slot) // is passing down slot from parent which may be dynamic\n            )\n        });\n\n        // #9534: if a component with scoped slots is inside a conditional branch,\n        // it's possible for the same component to be reused but with different\n        // compiled slot content. To avoid that, we generate a unique key based on\n        // the generated code of all the slot contents.\n        var needsKey = !!el.if;\n\n        // OR when it is inside another scoped slot or v-for (the reactivity may be\n        // disconnected due to the intermediate scope variable)\n        // #9438, #9506\n        // TODO: this can be further optimized by properly analyzing in-scope bindings\n        // and skip force updating ones that do not actually use scope variables.\n        if (!needsForceUpdate) {\n            var parent = el.parent;\n            while (parent) {\n                if (\n                    (parent.slotScope && parent.slotScope !== emptySlotScopeToken) ||\n                    parent.for\n                ) {\n                    needsForceUpdate = true;\n                    break\n                }\n                if (parent.if) {\n                    needsKey = true;\n                }\n                parent = parent.parent;\n            }\n        }\n\n        var generatedSlots = Object.keys(slots)\n            .map(function (key) { return genScopedSlot(slots[key], state); })\n            .join(',');\n\n        return (\"scopedSlots:_u([\" + generatedSlots + \"]\" + (needsForceUpdate ? \",null,true\" : \"\") + (!needsForceUpdate && needsKey ? (\",null,false,\" + (hash(generatedSlots))) : \"\") + \")\")\n    }\n\n    function hash(str) {\n        var hash = 5381;\n        var i = str.length;\n        while(i) {\n            hash = (hash * 33) ^ str.charCodeAt(--i);\n        }\n        return hash >>> 0\n    }\n\n    function containsSlotChild (el) {\n        if (el.type === 1) {\n            if (el.tag === 'slot') {\n                return true\n            }\n            return el.children.some(containsSlotChild)\n        }\n        return false\n    }\n\n    function genScopedSlot (\n        el,\n        state\n    ) {\n        var isLegacySyntax = el.attrsMap['slot-scope'];\n        if (el.if && !el.ifProcessed && !isLegacySyntax) {\n            return genIf(el, state, genScopedSlot, \"null\")\n        }\n        if (el.for && !el.forProcessed) {\n            return genFor(el, state, genScopedSlot)\n        }\n        var slotScope = el.slotScope === emptySlotScopeToken\n            ? \"\"\n            : String(el.slotScope);\n        var fn = \"function(\" + slotScope + \"){\" +\n            \"return \" + (el.tag === 'template'\n                ? el.if && isLegacySyntax\n                    ? (\"(\" + (el.if) + \")?\" + (genChildren(el, state) || 'undefined') + \":undefined\")\n                    : genChildren(el, state) || 'undefined'\n                : genElement(el, state)) + \"}\";\n        // reverse proxy v-slot without scope on this.$slots\n        var reverseProxy = slotScope ? \"\" : \",proxy:true\";\n        return (\"{key:\" + (el.slotTarget || \"\\\"default\\\"\") + \",fn:\" + fn + reverseProxy + \"}\")\n    }\n\n    function genChildren (\n        el,\n        state,\n        checkSkip,\n        altGenElement,\n        altGenNode\n    ) {\n        var children = el.children;\n        if (children.length) {\n            var el$1 = children[0];\n            // optimize single v-for\n            if (children.length === 1 &&\n                el$1.for &&\n                el$1.tag !== 'template' &&\n                el$1.tag !== 'slot'\n            ) {\n                var normalizationType = checkSkip\n                    ? state.maybeComponent(el$1) ? \",1\" : \",0\"\n                    : \"\";\n                return (\"\" + ((altGenElement || genElement)(el$1, state)) + normalizationType)\n            }\n            var normalizationType$1 = checkSkip\n                ? getNormalizationType(children, state.maybeComponent)\n                : 0;\n            var gen = altGenNode || genNode;\n            return (\"[\" + (children.map(function (c) { return gen(c, state); }).join(',')) + \"]\" + (normalizationType$1 ? (\",\" + normalizationType$1) : ''))\n        }\n    }\n\n    // determine the normalization needed for the children array.\n    // 0: no normalization needed\n    // 1: simple normalization needed (possible 1-level deep nested array)\n    // 2: full normalization needed\n    function getNormalizationType (\n        children,\n        maybeComponent\n    ) {\n        var res = 0;\n        for (var i = 0; i < children.length; i++) {\n            var el = children[i];\n            if (el.type !== 1) {\n                continue\n            }\n            if (needsNormalization(el) ||\n                (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {\n                res = 2;\n                break\n            }\n            if (maybeComponent(el) ||\n                (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {\n                res = 1;\n            }\n        }\n        return res\n    }\n\n    function needsNormalization (el) {\n        return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'\n    }\n\n    function genNode (node, state) {\n        if (node.type === 1) {\n            return genElement(node, state)\n        } else if (node.type === 3 && node.isComment) {\n            return genComment(node)\n        } else {\n            return genText(node)\n        }\n    }\n\n    function genText (text) {\n        return (\"_v(\" + (text.type === 2\n            ? text.expression // no need for () because already wrapped in _s()\n            : transformSpecialNewlines(JSON.stringify(text.text))) + \")\")\n    }\n\n    function genComment (comment) {\n        return (\"_e(\" + (JSON.stringify(comment.text)) + \")\")\n    }\n\n    function genSlot (el, state) {\n        var slotName = el.slotName || '\"default\"';\n        var children = genChildren(el, state);\n        var res = \"_t(\" + slotName + (children ? (\",function(){return \" + children + \"}\") : '');\n        var attrs = el.attrs || el.dynamicAttrs\n            ? genProps((el.attrs || []).concat(el.dynamicAttrs || []).map(function (attr) { return ({\n                // slot props are camelized\n                name: camelize(attr.name),\n                value: attr.value,\n                dynamic: attr.dynamic\n            }); }))\n            : null;\n        var bind$$1 = el.attrsMap['v-bind'];\n        if ((attrs || bind$$1) && !children) {\n            res += \",null\";\n        }\n        if (attrs) {\n            res += \",\" + attrs;\n        }\n        if (bind$$1) {\n            res += (attrs ? '' : ',null') + \",\" + bind$$1;\n        }\n        return res + ')'\n    }\n\n    // componentName is el.component, take it as argument to shun flow's pessimistic refinement\n    function genComponent (\n        componentName,\n        el,\n        state\n    ) {\n        var children = el.inlineTemplate ? null : genChildren(el, state, true);\n        return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n    }\n\n    function genProps (props) {\n        var staticProps = \"\";\n        var dynamicProps = \"\";\n        for (var i = 0; i < props.length; i++) {\n            var prop = props[i];\n            var value = transformSpecialNewlines(prop.value);\n            if (prop.dynamic) {\n                dynamicProps += (prop.name) + \",\" + value + \",\";\n            } else {\n                staticProps += \"\\\"\" + (prop.name) + \"\\\":\" + value + \",\";\n            }\n        }\n        staticProps = \"{\" + (staticProps.slice(0, -1)) + \"}\";\n        if (dynamicProps) {\n            return (\"_d(\" + staticProps + \",[\" + (dynamicProps.slice(0, -1)) + \"])\")\n        } else {\n            return staticProps\n        }\n    }\n\n    // #3895, #4268\n    function transformSpecialNewlines (text) {\n        return text\n            .replace(/\\u2028/g, '\\\\u2028')\n            .replace(/\\u2029/g, '\\\\u2029')\n    }\n\n    /*  */\n\n\n\n    // these keywords should not appear inside expressions, but operators like\n    // typeof, instanceof and in are allowed\n    var prohibitedKeywordRE = new RegExp('\\\\b' + (\n        'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +\n        'super,throw,while,yield,delete,export,import,return,switch,default,' +\n        'extends,finally,continue,debugger,function,arguments'\n    ).split(',').join('\\\\b|\\\\b') + '\\\\b');\n\n    // these unary operators should not be used as property/method names\n    var unaryOperatorsRE = new RegExp('\\\\b' + (\n        'delete,typeof,void'\n    ).split(',').join('\\\\s*\\\\([^\\\\)]*\\\\)|\\\\b') + '\\\\s*\\\\([^\\\\)]*\\\\)');\n\n    // strip strings in expressions\n    var stripStringRE = /'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*\\$\\{|\\}(?:[^`\\\\]|\\\\.)*`|`(?:[^`\\\\]|\\\\.)*`/g;\n\n    // detect problematic expressions in a template\n    function detectErrors (ast, warn) {\n        if (ast) {\n            checkNode(ast, warn);\n        }\n    }\n\n    function checkNode (node, warn) {\n        if (node.type === 1) {\n            for (var name in node.attrsMap) {\n                if (dirRE.test(name)) {\n                    var value = node.attrsMap[name];\n                    if (value) {\n                        var range = node.rawAttrsMap[name];\n                        if (name === 'v-for') {\n                            checkFor(node, (\"v-for=\\\"\" + value + \"\\\"\"), warn, range);\n                        } else if (name === 'v-slot' || name[0] === '#') {\n                            checkFunctionParameterExpression(value, (name + \"=\\\"\" + value + \"\\\"\"), warn, range);\n                        } else if (onRE.test(name)) {\n                            checkEvent(value, (name + \"=\\\"\" + value + \"\\\"\"), warn, range);\n                        } else {\n                            checkExpression(value, (name + \"=\\\"\" + value + \"\\\"\"), warn, range);\n                        }\n                    }\n                }\n            }\n            if (node.children) {\n                for (var i = 0; i < node.children.length; i++) {\n                    checkNode(node.children[i], warn);\n                }\n            }\n        } else if (node.type === 2) {\n            checkExpression(node.expression, node.text, warn, node);\n        }\n    }\n\n    function checkEvent (exp, text, warn, range) {\n        var stripped = exp.replace(stripStringRE, '');\n        var keywordMatch = stripped.match(unaryOperatorsRE);\n        if (keywordMatch && stripped.charAt(keywordMatch.index - 1) !== '$') {\n            warn(\n                \"avoid using JavaScript unary operator as property name: \" +\n                \"\\\"\" + (keywordMatch[0]) + \"\\\" in expression \" + (text.trim()),\n                range\n            );\n        }\n        checkExpression(exp, text, warn, range);\n    }\n\n    function checkFor (node, text, warn, range) {\n        checkExpression(node.for || '', text, warn, range);\n        checkIdentifier(node.alias, 'v-for alias', text, warn, range);\n        checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range);\n        checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range);\n    }\n\n    function checkIdentifier (\n        ident,\n        type,\n        text,\n        warn,\n        range\n    ) {\n        if (typeof ident === 'string') {\n            try {\n                new Function((\"var \" + ident + \"=_\"));\n            } catch (e) {\n                warn((\"invalid \" + type + \" \\\"\" + ident + \"\\\" in expression: \" + (text.trim())), range);\n            }\n        }\n    }\n\n    function checkExpression (exp, text, warn, range) {\n        try {\n            new Function((\"return \" + exp));\n        } catch (e) {\n            var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);\n            if (keywordMatch) {\n                warn(\n                    \"avoid using JavaScript keyword as property name: \" +\n                    \"\\\"\" + (keywordMatch[0]) + \"\\\"\\n  Raw expression: \" + (text.trim()),\n                    range\n                );\n            } else {\n                warn(\n                    \"invalid expression: \" + (e.message) + \" in\\n\\n\" +\n                    \"    \" + exp + \"\\n\\n\" +\n                    \"  Raw expression: \" + (text.trim()) + \"\\n\",\n                    range\n                );\n            }\n        }\n    }\n\n    function checkFunctionParameterExpression (exp, text, warn, range) {\n        try {\n            new Function(exp, '');\n        } catch (e) {\n            warn(\n                \"invalid function parameter expression: \" + (e.message) + \" in\\n\\n\" +\n                \"    \" + exp + \"\\n\\n\" +\n                \"  Raw expression: \" + (text.trim()) + \"\\n\",\n                range\n            );\n        }\n    }\n\n    /*  */\n\n    var range = 2;\n\n    function generateCodeFrame (\n        source,\n        start,\n        end\n    ) {\n        if ( start === void 0 ) start = 0;\n        if ( end === void 0 ) end = source.length;\n\n        var lines = source.split(/\\r?\\n/);\n        var count = 0;\n        var res = [];\n        for (var i = 0; i < lines.length; i++) {\n            count += lines[i].length + 1;\n            if (count >= start) {\n                for (var j = i - range; j <= i + range || end > count; j++) {\n                    if (j < 0 || j >= lines.length) { continue }\n                    res.push((\"\" + (j + 1) + (repeat$1(\" \", 3 - String(j + 1).length)) + \"|  \" + (lines[j])));\n                    var lineLength = lines[j].length;\n                    if (j === i) {\n                        // push underline\n                        var pad = start - (count - lineLength) + 1;\n                        var length = end > count ? lineLength - pad : end - start;\n                        res.push(\"   |  \" + repeat$1(\" \", pad) + repeat$1(\"^\", length));\n                    } else if (j > i) {\n                        if (end > count) {\n                            var length$1 = Math.min(end - count, lineLength);\n                            res.push(\"   |  \" + repeat$1(\"^\", length$1));\n                        }\n                        count += lineLength + 1;\n                    }\n                }\n                break\n            }\n        }\n        return res.join('\\n')\n    }\n\n    function repeat$1 (str, n) {\n        var result = '';\n        if (n > 0) {\n            while (true) { // eslint-disable-line\n                if (n & 1) { result += str; }\n                n >>>= 1;\n                if (n <= 0) { break }\n                str += str;\n            }\n        }\n        return result\n    }\n\n    /*  */\n\n\n\n    function createFunction (code, errors) {\n        try {\n            return new Function(code)\n        } catch (err) {\n            errors.push({ err: err, code: code });\n            return noop\n        }\n    }\n\n    function createCompileToFunctionFn (compile) {\n        var cache = Object.create(null);\n\n        return function compileToFunctions (\n            template,\n            options,\n            vm\n        ) {\n            options = extend({}, options);\n            var warn$$1 = options.warn || warn;\n            delete options.warn;\n\n            /* istanbul ignore if */\n            {\n                // detect possible CSP restriction\n                try {\n                    new Function('return 1');\n                } catch (e) {\n                    if (e.toString().match(/unsafe-eval|CSP/)) {\n                        warn$$1(\n                            'It seems you are using the standalone build of Vue.js in an ' +\n                            'environment with Content Security Policy that prohibits unsafe-eval. ' +\n                            'The template compiler cannot work in this environment. Consider ' +\n                            'relaxing the policy to allow unsafe-eval or pre-compiling your ' +\n                            'templates into render functions.'\n                        );\n                    }\n                }\n            }\n\n            // check cache\n            var key = options.delimiters\n                ? String(options.delimiters) + template\n                : template;\n            if (cache[key]) {\n                return cache[key]\n            }\n\n            // compile\n            var compiled = compile(template, options);\n\n            // check compilation errors/tips\n            {\n                if (compiled.errors && compiled.errors.length) {\n                    if (options.outputSourceRange) {\n                        compiled.errors.forEach(function (e) {\n                            warn$$1(\n                                \"Error compiling template:\\n\\n\" + (e.msg) + \"\\n\\n\" +\n                                generateCodeFrame(template, e.start, e.end),\n                                vm\n                            );\n                        });\n                    } else {\n                        warn$$1(\n                            \"Error compiling template:\\n\\n\" + template + \"\\n\\n\" +\n                            compiled.errors.map(function (e) { return (\"- \" + e); }).join('\\n') + '\\n',\n                            vm\n                        );\n                    }\n                }\n                if (compiled.tips && compiled.tips.length) {\n                    if (options.outputSourceRange) {\n                        compiled.tips.forEach(function (e) { return tip(e.msg, vm); });\n                    } else {\n                        compiled.tips.forEach(function (msg) { return tip(msg, vm); });\n                    }\n                }\n            }\n\n            // turn code into functions\n            var res = {};\n            var fnGenErrors = [];\n            res.render = createFunction(compiled.render, fnGenErrors);\n            res.staticRenderFns = compiled.staticRenderFns.map(function (code) {\n                return createFunction(code, fnGenErrors)\n            });\n\n            // check function generation errors.\n            // this should only happen if there is a bug in the compiler itself.\n            // mostly for codegen development use\n            /* istanbul ignore if */\n            {\n                if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {\n                    warn$$1(\n                        \"Failed to generate render function:\\n\\n\" +\n                        fnGenErrors.map(function (ref) {\n                            var err = ref.err;\n                            var code = ref.code;\n\n                            return ((err.toString()) + \" in\\n\\n\" + code + \"\\n\");\n                        }).join('\\n'),\n                        vm\n                    );\n                }\n            }\n\n            return (cache[key] = res)\n        }\n    }\n\n    /*  */\n\n    function createCompilerCreator (baseCompile) {\n        return function createCompiler (baseOptions) {\n            function compile (\n                template,\n                options\n            ) {\n                var finalOptions = Object.create(baseOptions);\n                var errors = [];\n                var tips = [];\n\n                var warn = function (msg, range, tip) {\n                    (tip ? tips : errors).push(msg);\n                };\n\n                if (options) {\n                    if (options.outputSourceRange) {\n                        // $flow-disable-line\n                        var leadingSpaceLength = template.match(/^\\s*/)[0].length;\n\n                        warn = function (msg, range, tip) {\n                            var data = { msg: msg };\n                            if (range) {\n                                if (range.start != null) {\n                                    data.start = range.start + leadingSpaceLength;\n                                }\n                                if (range.end != null) {\n                                    data.end = range.end + leadingSpaceLength;\n                                }\n                            }\n                            (tip ? tips : errors).push(data);\n                        };\n                    }\n                    // merge custom modules\n                    if (options.modules) {\n                        finalOptions.modules =\n                            (baseOptions.modules || []).concat(options.modules);\n                    }\n                    // merge custom directives\n                    if (options.directives) {\n                        finalOptions.directives = extend(\n                            Object.create(baseOptions.directives || null),\n                            options.directives\n                        );\n                    }\n                    // copy other options\n                    for (var key in options) {\n                        if (key !== 'modules' && key !== 'directives') {\n                            finalOptions[key] = options[key];\n                        }\n                    }\n                }\n\n                finalOptions.warn = warn;\n\n                var compiled = baseCompile(template.trim(), finalOptions);\n                {\n                    detectErrors(compiled.ast, warn);\n                }\n                compiled.errors = errors;\n                compiled.tips = tips;\n                return compiled\n            }\n\n            return {\n                compile: compile,\n                compileToFunctions: createCompileToFunctionFn(compile)\n            }\n        }\n    }\n\n    /*  */\n\n    // `createCompilerCreator` allows creating compilers that use alternative\n    // parser/optimizer/codegen, e.g the SSR optimizing compiler.\n    // Here we just export a default compiler using the default parts.\n    var createCompiler = createCompilerCreator(function baseCompile (\n        template,\n        options\n    ) {\n        var ast = parse(template.trim(), options);\n        if (options.optimize !== false) {\n            optimize(ast, options);\n        }\n        var code = generate(ast, options);\n        return {\n            ast: ast,\n            render: code.render,\n            staticRenderFns: code.staticRenderFns\n        }\n    });\n\n    /*  */\n\n    var ref$1 = createCompiler(baseOptions);\n    var compile = ref$1.compile;\n    var compileToFunctions = ref$1.compileToFunctions;\n\n    /*  */\n\n    // check whether current browser encodes a char inside attribute values\n    var div;\n    function getShouldDecode (href) {\n        div = div || document.createElement('div');\n        div.innerHTML = href ? \"<a href=\\\"\\n\\\"/>\" : \"<div a=\\\"\\n\\\"/>\";\n        return div.innerHTML.indexOf('&#10;') > 0\n    }\n\n    // #3663: IE encodes newlines inside attribute values while other browsers don't\n    var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false;\n    // #6828: chrome encodes content in a[href]\n    var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false;\n\n    /*  */\n\n    var idToTemplate = cached(function (id) {\n        var el = query(id);\n        return el && el.innerHTML\n    });\n\n    var mount = Vue.prototype.$mount;\n    Vue.prototype.$mount = function (\n        el,\n        hydrating\n    ) {\n        el = el && query(el);\n\n        /* istanbul ignore if */\n        if (el === document.body || el === document.documentElement) {\n            warn(\n                \"Do not mount Vue to <html> or <body> - mount to normal elements instead.\"\n            );\n            return this\n        }\n\n        var options = this.$options;\n        // resolve template/el and convert to render function\n        if (!options.render) {\n            var template = options.template;\n            if (template) {\n                if (typeof template === 'string') {\n                    if (template.charAt(0) === '#') {\n                        template = idToTemplate(template);\n                        /* istanbul ignore if */\n                        if (!template) {\n                            warn(\n                                (\"Template element not found or is empty: \" + (options.template)),\n                                this\n                            );\n                        }\n                    }\n                } else if (template.nodeType) {\n                    template = template.innerHTML;\n                } else {\n                    {\n                        warn('invalid template option:' + template, this);\n                    }\n                    return this\n                }\n            } else if (el) {\n                template = getOuterHTML(el);\n            }\n            if (template) {\n                /* istanbul ignore if */\n                if (config.performance && mark) {\n                    mark('compile');\n                }\n\n                var ref = compileToFunctions(template, {\n                    outputSourceRange: \"development\" !== 'production',\n                    shouldDecodeNewlines: shouldDecodeNewlines,\n                    shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref,\n                    delimiters: options.delimiters,\n                    comments: options.comments\n                }, this);\n                var render = ref.render;\n                var staticRenderFns = ref.staticRenderFns;\n                options.render = render;\n                options.staticRenderFns = staticRenderFns;\n\n                /* istanbul ignore if */\n                if (config.performance && mark) {\n                    mark('compile end');\n                    measure((\"vue \" + (this._name) + \" compile\"), 'compile', 'compile end');\n                }\n            }\n        }\n        return mount.call(this, el, hydrating)\n    };\n\n    /**\n     * Get outerHTML of elements, taking care\n     * of SVG elements in IE as well.\n     */\n    function getOuterHTML (el) {\n        if (el.outerHTML) {\n            return el.outerHTML\n        } else {\n            var container = document.createElement('div');\n            container.appendChild(el.cloneNode(true));\n            return container.innerHTML\n        }\n    }\n\n    Vue.compile = compileToFunctions;\n\n    return Vue;\n\n}));\n"
  },
  {
    "path": "src/renderer/lib/vue.js",
    "content": "/*!\n * Vue.js v2.6.14\n * (c) 2014-2021 Evan You\n * Released under the MIT License.\n */\n!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=e||self).Vue=t()}(this,function(){\"use strict\";var e=Object.freeze({});function t(e){return null==e}function n(e){return null!=e}function r(e){return!0===e}function i(e){return\"string\"==typeof e||\"number\"==typeof e||\"symbol\"==typeof e||\"boolean\"==typeof e}function o(e){return null!==e&&\"object\"==typeof e}var a=Object.prototype.toString;function s(e){return\"[object Object]\"===a.call(e)}function c(e){var t=parseFloat(String(e));return t>=0&&Math.floor(t)===t&&isFinite(e)}function u(e){return n(e)&&\"function\"==typeof e.then&&\"function\"==typeof e.catch}function l(e){return null==e?\"\":Array.isArray(e)||s(e)&&e.toString===a?JSON.stringify(e,null,2):String(e)}function f(e){var t=parseFloat(e);return isNaN(t)?e:t}function p(e,t){for(var n=Object.create(null),r=e.split(\",\"),i=0;i<r.length;i++)n[r[i]]=!0;return t?function(e){return n[e.toLowerCase()]}:function(e){return n[e]}}var d=p(\"slot,component\",!0),v=p(\"key,ref,slot,slot-scope,is\");function h(e,t){if(e.length){var n=e.indexOf(t);if(n>-1)return e.splice(n,1)}}var m=Object.prototype.hasOwnProperty;function y(e,t){return m.call(e,t)}function g(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}}var _=/-(\\w)/g,b=g(function(e){return e.replace(_,function(e,t){return t?t.toUpperCase():\"\"})}),$=g(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),w=/\\B([A-Z])/g,C=g(function(e){return e.replace(w,\"-$1\").toLowerCase()});var x=Function.prototype.bind?function(e,t){return e.bind(t)}:function(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n};function k(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function A(e,t){for(var n in t)e[n]=t[n];return e}function O(e){for(var t={},n=0;n<e.length;n++)e[n]&&A(t,e[n]);return t}function S(e,t,n){}var T=function(e,t,n){return!1},N=function(e){return e};function E(e,t){if(e===t)return!0;var n=o(e),r=o(t);if(!n||!r)return!n&&!r&&String(e)===String(t);try{var i=Array.isArray(e),a=Array.isArray(t);if(i&&a)return e.length===t.length&&e.every(function(e,n){return E(e,t[n])});if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(i||a)return!1;var s=Object.keys(e),c=Object.keys(t);return s.length===c.length&&s.every(function(n){return E(e[n],t[n])})}catch(e){return!1}}function j(e,t){for(var n=0;n<e.length;n++)if(E(e[n],t))return n;return-1}function D(e){var t=!1;return function(){t||(t=!0,e.apply(this,arguments))}}var L=\"data-server-rendered\",I=[\"component\",\"directive\",\"filter\"],M=[\"beforeCreate\",\"created\",\"beforeMount\",\"mounted\",\"beforeUpdate\",\"updated\",\"beforeDestroy\",\"destroyed\",\"activated\",\"deactivated\",\"errorCaptured\",\"serverPrefetch\"],F={optionMergeStrategies:Object.create(null),silent:!1,productionTip:!1,devtools:!1,performance:!1,errorHandler:null,warnHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:T,isReservedAttr:T,isUnknownElement:T,getTagNamespace:S,parsePlatformTagName:N,mustUseProp:T,async:!0,_lifecycleHooks:M},P=/a-zA-Z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD/;function R(e,t,n,r){Object.defineProperty(e,t,{value:n,enumerable:!!r,writable:!0,configurable:!0})}var H=new RegExp(\"[^\"+P.source+\".$_\\\\d]\");var B,U=\"__proto__\"in{},V=\"undefined\"!=typeof window,z=\"undefined\"!=typeof WXEnvironment&&!!WXEnvironment.platform,K=z&&WXEnvironment.platform.toLowerCase(),J=V&&window.navigator.userAgent.toLowerCase(),q=J&&/msie|trident/.test(J),W=J&&J.indexOf(\"msie 9.0\")>0,Z=J&&J.indexOf(\"edge/\")>0,G=(J&&J.indexOf(\"android\"),J&&/iphone|ipad|ipod|ios/.test(J)||\"ios\"===K),X=(J&&/chrome\\/\\d+/.test(J),J&&/phantomjs/.test(J),J&&J.match(/firefox\\/(\\d+)/)),Y={}.watch,Q=!1;if(V)try{var ee={};Object.defineProperty(ee,\"passive\",{get:function(){Q=!0}}),window.addEventListener(\"test-passive\",null,ee)}catch(e){}var te=function(){return void 0===B&&(B=!V&&!z&&\"undefined\"!=typeof global&&(global.process&&\"server\"===global.process.env.VUE_ENV)),B},ne=V&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function re(e){return\"function\"==typeof e&&/native code/.test(e.toString())}var ie,oe=\"undefined\"!=typeof Symbol&&re(Symbol)&&\"undefined\"!=typeof Reflect&&re(Reflect.ownKeys);ie=\"undefined\"!=typeof Set&&re(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return!0===this.set[e]},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var ae=S,se=0,ce=function(){this.id=se++,this.subs=[]};ce.prototype.addSub=function(e){this.subs.push(e)},ce.prototype.removeSub=function(e){h(this.subs,e)},ce.prototype.depend=function(){ce.target&&ce.target.addDep(this)},ce.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t<n;t++)e[t].update()},ce.target=null;var ue=[];function le(e){ue.push(e),ce.target=e}function fe(){ue.pop(),ce.target=ue[ue.length-1]}var pe=function(e,t,n,r,i,o,a,s){this.tag=e,this.data=t,this.children=n,this.text=r,this.elm=i,this.ns=void 0,this.context=o,this.fnContext=void 0,this.fnOptions=void 0,this.fnScopeId=void 0,this.key=t&&t.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1,this.asyncFactory=s,this.asyncMeta=void 0,this.isAsyncPlaceholder=!1},de={child:{configurable:!0}};de.child.get=function(){return this.componentInstance},Object.defineProperties(pe.prototype,de);var ve=function(e){void 0===e&&(e=\"\");var t=new pe;return t.text=e,t.isComment=!0,t};function he(e){return new pe(void 0,void 0,void 0,String(e))}function me(e){var t=new pe(e.tag,e.data,e.children&&e.children.slice(),e.text,e.elm,e.context,e.componentOptions,e.asyncFactory);return t.ns=e.ns,t.isStatic=e.isStatic,t.key=e.key,t.isComment=e.isComment,t.fnContext=e.fnContext,t.fnOptions=e.fnOptions,t.fnScopeId=e.fnScopeId,t.asyncMeta=e.asyncMeta,t.isCloned=!0,t}var ye=Array.prototype,ge=Object.create(ye);[\"push\",\"pop\",\"shift\",\"unshift\",\"splice\",\"sort\",\"reverse\"].forEach(function(e){var t=ye[e];R(ge,e,function(){for(var n=[],r=arguments.length;r--;)n[r]=arguments[r];var i,o=t.apply(this,n),a=this.__ob__;switch(e){case\"push\":case\"unshift\":i=n;break;case\"splice\":i=n.slice(2)}return i&&a.observeArray(i),a.dep.notify(),o})});var _e=Object.getOwnPropertyNames(ge),be=!0;function $e(e){be=e}var we=function(e){var t;this.value=e,this.dep=new ce,this.vmCount=0,R(e,\"__ob__\",this),Array.isArray(e)?(U?(t=ge,e.__proto__=t):function(e,t,n){for(var r=0,i=n.length;r<i;r++){var o=n[r];R(e,o,t[o])}}(e,ge,_e),this.observeArray(e)):this.walk(e)};function Ce(e,t){var n;if(o(e)&&!(e instanceof pe))return y(e,\"__ob__\")&&e.__ob__ instanceof we?n=e.__ob__:be&&!te()&&(Array.isArray(e)||s(e))&&Object.isExtensible(e)&&!e._isVue&&(n=new we(e)),t&&n&&n.vmCount++,n}function xe(e,t,n,r,i){var o=new ce,a=Object.getOwnPropertyDescriptor(e,t);if(!a||!1!==a.configurable){var s=a&&a.get,c=a&&a.set;s&&!c||2!==arguments.length||(n=e[t]);var u=!i&&Ce(n);Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:function(){var t=s?s.call(e):n;return ce.target&&(o.depend(),u&&(u.dep.depend(),Array.isArray(t)&&function e(t){for(var n=void 0,r=0,i=t.length;r<i;r++)(n=t[r])&&n.__ob__&&n.__ob__.dep.depend(),Array.isArray(n)&&e(n)}(t))),t},set:function(t){var r=s?s.call(e):n;t===r||t!=t&&r!=r||s&&!c||(c?c.call(e,t):n=t,u=!i&&Ce(t),o.notify())}})}}function ke(e,t,n){if(Array.isArray(e)&&c(t))return e.length=Math.max(e.length,t),e.splice(t,1,n),n;if(t in e&&!(t in Object.prototype))return e[t]=n,n;var r=e.__ob__;return e._isVue||r&&r.vmCount?n:r?(xe(r.value,t,n),r.dep.notify(),n):(e[t]=n,n)}function Ae(e,t){if(Array.isArray(e)&&c(t))e.splice(t,1);else{var n=e.__ob__;e._isVue||n&&n.vmCount||y(e,t)&&(delete e[t],n&&n.dep.notify())}}we.prototype.walk=function(e){for(var t=Object.keys(e),n=0;n<t.length;n++)xe(e,t[n])},we.prototype.observeArray=function(e){for(var t=0,n=e.length;t<n;t++)Ce(e[t])};var Oe=F.optionMergeStrategies;function Se(e,t){if(!t)return e;for(var n,r,i,o=oe?Reflect.ownKeys(t):Object.keys(t),a=0;a<o.length;a++)\"__ob__\"!==(n=o[a])&&(r=e[n],i=t[n],y(e,n)?r!==i&&s(r)&&s(i)&&Se(r,i):ke(e,n,i));return e}function Te(e,t,n){return n?function(){var r=\"function\"==typeof t?t.call(n,n):t,i=\"function\"==typeof e?e.call(n,n):e;return r?Se(r,i):i}:t?e?function(){return Se(\"function\"==typeof t?t.call(this,this):t,\"function\"==typeof e?e.call(this,this):e)}:t:e}function Ne(e,t){var n=t?e?e.concat(t):Array.isArray(t)?t:[t]:e;return n?function(e){for(var t=[],n=0;n<e.length;n++)-1===t.indexOf(e[n])&&t.push(e[n]);return t}(n):n}function Ee(e,t,n,r){var i=Object.create(e||null);return t?A(i,t):i}Oe.data=function(e,t,n){return n?Te(e,t,n):t&&\"function\"!=typeof t?e:Te(e,t)},M.forEach(function(e){Oe[e]=Ne}),I.forEach(function(e){Oe[e+\"s\"]=Ee}),Oe.watch=function(e,t,n,r){if(e===Y&&(e=void 0),t===Y&&(t=void 0),!t)return Object.create(e||null);if(!e)return t;var i={};for(var o in A(i,e),t){var a=i[o],s=t[o];a&&!Array.isArray(a)&&(a=[a]),i[o]=a?a.concat(s):Array.isArray(s)?s:[s]}return i},Oe.props=Oe.methods=Oe.inject=Oe.computed=function(e,t,n,r){if(!e)return t;var i=Object.create(null);return A(i,e),t&&A(i,t),i},Oe.provide=Te;var je=function(e,t){return void 0===t?e:t};function De(e,t,n){if(\"function\"==typeof t&&(t=t.options),function(e,t){var n=e.props;if(n){var r,i,o={};if(Array.isArray(n))for(r=n.length;r--;)\"string\"==typeof(i=n[r])&&(o[b(i)]={type:null});else if(s(n))for(var a in n)i=n[a],o[b(a)]=s(i)?i:{type:i};e.props=o}}(t),function(e,t){var n=e.inject;if(n){var r=e.inject={};if(Array.isArray(n))for(var i=0;i<n.length;i++)r[n[i]]={from:n[i]};else if(s(n))for(var o in n){var a=n[o];r[o]=s(a)?A({from:o},a):{from:a}}}}(t),function(e){var t=e.directives;if(t)for(var n in t){var r=t[n];\"function\"==typeof r&&(t[n]={bind:r,update:r})}}(t),!t._base&&(t.extends&&(e=De(e,t.extends,n)),t.mixins))for(var r=0,i=t.mixins.length;r<i;r++)e=De(e,t.mixins[r],n);var o,a={};for(o in e)c(o);for(o in t)y(e,o)||c(o);function c(r){var i=Oe[r]||je;a[r]=i(e[r],t[r],n,r)}return a}function Le(e,t,n,r){if(\"string\"==typeof n){var i=e[t];if(y(i,n))return i[n];var o=b(n);if(y(i,o))return i[o];var a=$(o);return y(i,a)?i[a]:i[n]||i[o]||i[a]}}function Ie(e,t,n,r){var i=t[e],o=!y(n,e),a=n[e],s=Re(Boolean,i.type);if(s>-1)if(o&&!y(i,\"default\"))a=!1;else if(\"\"===a||a===C(e)){var c=Re(String,i.type);(c<0||s<c)&&(a=!0)}if(void 0===a){a=function(e,t,n){if(!y(t,\"default\"))return;var r=t.default;if(e&&e.$options.propsData&&void 0===e.$options.propsData[n]&&void 0!==e._props[n])return e._props[n];return\"function\"==typeof r&&\"Function\"!==Fe(t.type)?r.call(e):r}(r,i,e);var u=be;$e(!0),Ce(a),$e(u)}return a}var Me=/^\\s*function (\\w+)/;function Fe(e){var t=e&&e.toString().match(Me);return t?t[1]:\"\"}function Pe(e,t){return Fe(e)===Fe(t)}function Re(e,t){if(!Array.isArray(t))return Pe(t,e)?0:-1;for(var n=0,r=t.length;n<r;n++)if(Pe(t[n],e))return n;return-1}function He(e,t,n){le();try{if(t)for(var r=t;r=r.$parent;){var i=r.$options.errorCaptured;if(i)for(var o=0;o<i.length;o++)try{if(!1===i[o].call(r,e,t,n))return}catch(e){Ue(e,r,\"errorCaptured hook\")}}Ue(e,t,n)}finally{fe()}}function Be(e,t,n,r,i){var o;try{(o=n?e.apply(t,n):e.call(t))&&!o._isVue&&u(o)&&!o._handled&&(o.catch(function(e){return He(e,r,i+\" (Promise/async)\")}),o._handled=!0)}catch(e){He(e,r,i)}return o}function Ue(e,t,n){if(F.errorHandler)try{return F.errorHandler.call(null,e,t,n)}catch(t){t!==e&&Ve(t,null,\"config.errorHandler\")}Ve(e,t,n)}function Ve(e,t,n){if(!V&&!z||\"undefined\"==typeof console)throw e;console.error(e)}var ze,Ke=!1,Je=[],qe=!1;function We(){qe=!1;var e=Je.slice(0);Je.length=0;for(var t=0;t<e.length;t++)e[t]()}if(\"undefined\"!=typeof Promise&&re(Promise)){var Ze=Promise.resolve();ze=function(){Ze.then(We),G&&setTimeout(S)},Ke=!0}else if(q||\"undefined\"==typeof MutationObserver||!re(MutationObserver)&&\"[object MutationObserverConstructor]\"!==MutationObserver.toString())ze=\"undefined\"!=typeof setImmediate&&re(setImmediate)?function(){setImmediate(We)}:function(){setTimeout(We,0)};else{var Ge=1,Xe=new MutationObserver(We),Ye=document.createTextNode(String(Ge));Xe.observe(Ye,{characterData:!0}),ze=function(){Ge=(Ge+1)%2,Ye.data=String(Ge)},Ke=!0}function Qe(e,t){var n;if(Je.push(function(){if(e)try{e.call(t)}catch(e){He(e,t,\"nextTick\")}else n&&n(t)}),qe||(qe=!0,ze()),!e&&\"undefined\"!=typeof Promise)return new Promise(function(e){n=e})}var et=new ie;function tt(e){!function e(t,n){var r,i;var a=Array.isArray(t);if(!a&&!o(t)||Object.isFrozen(t)||t instanceof pe)return;if(t.__ob__){var s=t.__ob__.dep.id;if(n.has(s))return;n.add(s)}if(a)for(r=t.length;r--;)e(t[r],n);else for(i=Object.keys(t),r=i.length;r--;)e(t[i[r]],n)}(e,et),et.clear()}var nt=g(function(e){var t=\"&\"===e.charAt(0),n=\"~\"===(e=t?e.slice(1):e).charAt(0),r=\"!\"===(e=n?e.slice(1):e).charAt(0);return{name:e=r?e.slice(1):e,once:n,capture:r,passive:t}});function rt(e,t){function n(){var e=arguments,r=n.fns;if(!Array.isArray(r))return Be(r,null,arguments,t,\"v-on handler\");for(var i=r.slice(),o=0;o<i.length;o++)Be(i[o],null,e,t,\"v-on handler\")}return n.fns=e,n}function it(e,n,i,o,a,s){var c,u,l,f;for(c in e)u=e[c],l=n[c],f=nt(c),t(u)||(t(l)?(t(u.fns)&&(u=e[c]=rt(u,s)),r(f.once)&&(u=e[c]=a(f.name,u,f.capture)),i(f.name,u,f.capture,f.passive,f.params)):u!==l&&(l.fns=u,e[c]=l));for(c in n)t(e[c])&&o((f=nt(c)).name,n[c],f.capture)}function ot(e,i,o){var a;e instanceof pe&&(e=e.data.hook||(e.data.hook={}));var s=e[i];function c(){o.apply(this,arguments),h(a.fns,c)}t(s)?a=rt([c]):n(s.fns)&&r(s.merged)?(a=s).fns.push(c):a=rt([s,c]),a.merged=!0,e[i]=a}function at(e,t,r,i,o){if(n(t)){if(y(t,r))return e[r]=t[r],o||delete t[r],!0;if(y(t,i))return e[r]=t[i],o||delete t[i],!0}return!1}function st(e){return i(e)?[he(e)]:Array.isArray(e)?function e(o,a){var s=[];var c,u,l,f;for(c=0;c<o.length;c++)t(u=o[c])||\"boolean\"==typeof u||(l=s.length-1,f=s[l],Array.isArray(u)?u.length>0&&(ct((u=e(u,(a||\"\")+\"_\"+c))[0])&&ct(f)&&(s[l]=he(f.text+u[0].text),u.shift()),s.push.apply(s,u)):i(u)?ct(f)?s[l]=he(f.text+u):\"\"!==u&&s.push(he(u)):ct(u)&&ct(f)?s[l]=he(f.text+u.text):(r(o._isVList)&&n(u.tag)&&t(u.key)&&n(a)&&(u.key=\"__vlist\"+a+\"_\"+c+\"__\"),s.push(u)));return s}(e):void 0}function ct(e){return n(e)&&n(e.text)&&!1===e.isComment}function ut(e,t){if(e){for(var n=Object.create(null),r=oe?Reflect.ownKeys(e):Object.keys(e),i=0;i<r.length;i++){var o=r[i];if(\"__ob__\"!==o){for(var a=e[o].from,s=t;s;){if(s._provided&&y(s._provided,a)){n[o]=s._provided[a];break}s=s.$parent}if(!s&&\"default\"in e[o]){var c=e[o].default;n[o]=\"function\"==typeof c?c.call(t):c}}}return n}}function lt(e,t){if(!e||!e.length)return{};for(var n={},r=0,i=e.length;r<i;r++){var o=e[r],a=o.data;if(a&&a.attrs&&a.attrs.slot&&delete a.attrs.slot,o.context!==t&&o.fnContext!==t||!a||null==a.slot)(n.default||(n.default=[])).push(o);else{var s=a.slot,c=n[s]||(n[s]=[]);\"template\"===o.tag?c.push.apply(c,o.children||[]):c.push(o)}}for(var u in n)n[u].every(ft)&&delete n[u];return n}function ft(e){return e.isComment&&!e.asyncFactory||\" \"===e.text}function pt(e){return e.isComment&&e.asyncFactory}function dt(t,n,r){var i,o=Object.keys(n).length>0,a=t?!!t.$stable:!o,s=t&&t.$key;if(t){if(t._normalized)return t._normalized;if(a&&r&&r!==e&&s===r.$key&&!o&&!r.$hasNormal)return r;for(var c in i={},t)t[c]&&\"$\"!==c[0]&&(i[c]=vt(n,c,t[c]))}else i={};for(var u in n)u in i||(i[u]=ht(n,u));return t&&Object.isExtensible(t)&&(t._normalized=i),R(i,\"$stable\",a),R(i,\"$key\",s),R(i,\"$hasNormal\",o),i}function vt(e,t,n){var r=function(){var e=arguments.length?n.apply(null,arguments):n({}),t=(e=e&&\"object\"==typeof e&&!Array.isArray(e)?[e]:st(e))&&e[0];return e&&(!t||1===e.length&&t.isComment&&!pt(t))?void 0:e};return n.proxy&&Object.defineProperty(e,t,{get:r,enumerable:!0,configurable:!0}),r}function ht(e,t){return function(){return e[t]}}function mt(e,t){var r,i,a,s,c;if(Array.isArray(e)||\"string\"==typeof e)for(r=new Array(e.length),i=0,a=e.length;i<a;i++)r[i]=t(e[i],i);else if(\"number\"==typeof e)for(r=new Array(e),i=0;i<e;i++)r[i]=t(i+1,i);else if(o(e))if(oe&&e[Symbol.iterator]){r=[];for(var u=e[Symbol.iterator](),l=u.next();!l.done;)r.push(t(l.value,r.length)),l=u.next()}else for(s=Object.keys(e),r=new Array(s.length),i=0,a=s.length;i<a;i++)c=s[i],r[i]=t(e[c],c,i);return n(r)||(r=[]),r._isVList=!0,r}function yt(e,t,n,r){var i,o=this.$scopedSlots[e];o?(n=n||{},r&&(n=A(A({},r),n)),i=o(n)||(\"function\"==typeof t?t():t)):i=this.$slots[e]||(\"function\"==typeof t?t():t);var a=n&&n.slot;return a?this.$createElement(\"template\",{slot:a},i):i}function gt(e){return Le(this.$options,\"filters\",e)||N}function _t(e,t){return Array.isArray(e)?-1===e.indexOf(t):e!==t}function bt(e,t,n,r,i){var o=F.keyCodes[t]||n;return i&&r&&!F.keyCodes[t]?_t(i,r):o?_t(o,e):r?C(r)!==t:void 0===e}function $t(e,t,n,r,i){if(n)if(o(n)){var a;Array.isArray(n)&&(n=O(n));var s=function(o){if(\"class\"===o||\"style\"===o||v(o))a=e;else{var s=e.attrs&&e.attrs.type;a=r||F.mustUseProp(t,s,o)?e.domProps||(e.domProps={}):e.attrs||(e.attrs={})}var c=b(o),u=C(o);c in a||u in a||(a[o]=n[o],i&&((e.on||(e.on={}))[\"update:\"+o]=function(e){n[o]=e}))};for(var c in n)s(c)}else;return e}function wt(e,t){var n=this._staticTrees||(this._staticTrees=[]),r=n[e];return r&&!t?r:(xt(r=n[e]=this.$options.staticRenderFns[e].call(this._renderProxy,null,this),\"__static__\"+e,!1),r)}function Ct(e,t,n){return xt(e,\"__once__\"+t+(n?\"_\"+n:\"\"),!0),e}function xt(e,t,n){if(Array.isArray(e))for(var r=0;r<e.length;r++)e[r]&&\"string\"!=typeof e[r]&&kt(e[r],t+\"_\"+r,n);else kt(e,t,n)}function kt(e,t,n){e.isStatic=!0,e.key=t,e.isOnce=n}function At(e,t){if(t)if(s(t)){var n=e.on=e.on?A({},e.on):{};for(var r in t){var i=n[r],o=t[r];n[r]=i?[].concat(i,o):o}}else;return e}function Ot(e,t,n,r){t=t||{$stable:!n};for(var i=0;i<e.length;i++){var o=e[i];Array.isArray(o)?Ot(o,t,n):o&&(o.proxy&&(o.fn.proxy=!0),t[o.key]=o.fn)}return r&&(t.$key=r),t}function St(e,t){for(var n=0;n<t.length;n+=2){var r=t[n];\"string\"==typeof r&&r&&(e[t[n]]=t[n+1])}return e}function Tt(e,t){return\"string\"==typeof e?t+e:e}function Nt(e){e._o=Ct,e._n=f,e._s=l,e._l=mt,e._t=yt,e._q=E,e._i=j,e._m=wt,e._f=gt,e._k=bt,e._b=$t,e._v=he,e._e=ve,e._u=Ot,e._g=At,e._d=St,e._p=Tt}function Et(t,n,i,o,a){var s,c=this,u=a.options;y(o,\"_uid\")?(s=Object.create(o))._original=o:(s=o,o=o._original);var l=r(u._compiled),f=!l;this.data=t,this.props=n,this.children=i,this.parent=o,this.listeners=t.on||e,this.injections=ut(u.inject,o),this.slots=function(){return c.$slots||dt(t.scopedSlots,c.$slots=lt(i,o)),c.$slots},Object.defineProperty(this,\"scopedSlots\",{enumerable:!0,get:function(){return dt(t.scopedSlots,this.slots())}}),l&&(this.$options=u,this.$slots=this.slots(),this.$scopedSlots=dt(t.scopedSlots,this.$slots)),u._scopeId?this._c=function(e,t,n,r){var i=Ht(s,e,t,n,r,f);return i&&!Array.isArray(i)&&(i.fnScopeId=u._scopeId,i.fnContext=o),i}:this._c=function(e,t,n,r){return Ht(s,e,t,n,r,f)}}function jt(e,t,n,r,i){var o=me(e);return o.fnContext=n,o.fnOptions=r,t.slot&&((o.data||(o.data={})).slot=t.slot),o}function Dt(e,t){for(var n in t)e[b(n)]=t[n]}Nt(Et.prototype);var Lt={init:function(e,t){if(e.componentInstance&&!e.componentInstance._isDestroyed&&e.data.keepAlive){var r=e;Lt.prepatch(r,r)}else{(e.componentInstance=function(e,t){var r={_isComponent:!0,_parentVnode:e,parent:t},i=e.data.inlineTemplate;n(i)&&(r.render=i.render,r.staticRenderFns=i.staticRenderFns);return new e.componentOptions.Ctor(r)}(e,Zt)).$mount(t?e.elm:void 0,t)}},prepatch:function(t,n){var r=n.componentOptions;!function(t,n,r,i,o){var a=i.data.scopedSlots,s=t.$scopedSlots,c=!!(a&&!a.$stable||s!==e&&!s.$stable||a&&t.$scopedSlots.$key!==a.$key||!a&&t.$scopedSlots.$key),u=!!(o||t.$options._renderChildren||c);t.$options._parentVnode=i,t.$vnode=i,t._vnode&&(t._vnode.parent=i);if(t.$options._renderChildren=o,t.$attrs=i.data.attrs||e,t.$listeners=r||e,n&&t.$options.props){$e(!1);for(var l=t._props,f=t.$options._propKeys||[],p=0;p<f.length;p++){var d=f[p],v=t.$options.props;l[d]=Ie(d,v,n,t)}$e(!0),t.$options.propsData=n}r=r||e;var h=t.$options._parentListeners;t.$options._parentListeners=r,Wt(t,r,h),u&&(t.$slots=lt(o,i.context),t.$forceUpdate())}(n.componentInstance=t.componentInstance,r.propsData,r.listeners,n,r.children)},insert:function(e){var t,n=e.context,r=e.componentInstance;r._isMounted||(r._isMounted=!0,Qt(r,\"mounted\")),e.data.keepAlive&&(n._isMounted?((t=r)._inactive=!1,tn.push(t)):Yt(r,!0))},destroy:function(e){var t=e.componentInstance;t._isDestroyed||(e.data.keepAlive?function e(t,n){if(n&&(t._directInactive=!0,Xt(t)))return;if(!t._inactive){t._inactive=!0;for(var r=0;r<t.$children.length;r++)e(t.$children[r]);Qt(t,\"deactivated\")}}(t,!0):t.$destroy())}},It=Object.keys(Lt);function Mt(i,a,s,c,l){if(!t(i)){var f=s.$options._base;if(o(i)&&(i=f.extend(i)),\"function\"==typeof i){var p;if(t(i.cid)&&void 0===(i=function(e,i){if(r(e.error)&&n(e.errorComp))return e.errorComp;if(n(e.resolved))return e.resolved;var a=Ut;a&&n(e.owners)&&-1===e.owners.indexOf(a)&&e.owners.push(a);if(r(e.loading)&&n(e.loadingComp))return e.loadingComp;if(a&&!n(e.owners)){var s=e.owners=[a],c=!0,l=null,f=null;a.$on(\"hook:destroyed\",function(){return h(s,a)});var p=function(e){for(var t=0,n=s.length;t<n;t++)s[t].$forceUpdate();e&&(s.length=0,null!==l&&(clearTimeout(l),l=null),null!==f&&(clearTimeout(f),f=null))},d=D(function(t){e.resolved=Vt(t,i),c?s.length=0:p(!0)}),v=D(function(t){n(e.errorComp)&&(e.error=!0,p(!0))}),m=e(d,v);return o(m)&&(u(m)?t(e.resolved)&&m.then(d,v):u(m.component)&&(m.component.then(d,v),n(m.error)&&(e.errorComp=Vt(m.error,i)),n(m.loading)&&(e.loadingComp=Vt(m.loading,i),0===m.delay?e.loading=!0:l=setTimeout(function(){l=null,t(e.resolved)&&t(e.error)&&(e.loading=!0,p(!1))},m.delay||200)),n(m.timeout)&&(f=setTimeout(function(){f=null,t(e.resolved)&&v(null)},m.timeout)))),c=!1,e.loading?e.loadingComp:e.resolved}}(p=i,f)))return function(e,t,n,r,i){var o=ve();return o.asyncFactory=e,o.asyncMeta={data:t,context:n,children:r,tag:i},o}(p,a,s,c,l);a=a||{},wn(i),n(a.model)&&function(e,t){var r=e.model&&e.model.prop||\"value\",i=e.model&&e.model.event||\"input\";(t.attrs||(t.attrs={}))[r]=t.model.value;var o=t.on||(t.on={}),a=o[i],s=t.model.callback;n(a)?(Array.isArray(a)?-1===a.indexOf(s):a!==s)&&(o[i]=[s].concat(a)):o[i]=s}(i.options,a);var d=function(e,r,i){var o=r.options.props;if(!t(o)){var a={},s=e.attrs,c=e.props;if(n(s)||n(c))for(var u in o){var l=C(u);at(a,c,u,l,!0)||at(a,s,u,l,!1)}return a}}(a,i);if(r(i.options.functional))return function(t,r,i,o,a){var s=t.options,c={},u=s.props;if(n(u))for(var l in u)c[l]=Ie(l,u,r||e);else n(i.attrs)&&Dt(c,i.attrs),n(i.props)&&Dt(c,i.props);var f=new Et(i,c,a,o,t),p=s.render.call(null,f._c,f);if(p instanceof pe)return jt(p,i,f.parent,s);if(Array.isArray(p)){for(var d=st(p)||[],v=new Array(d.length),h=0;h<d.length;h++)v[h]=jt(d[h],i,f.parent,s);return v}}(i,d,a,s,c);var v=a.on;if(a.on=a.nativeOn,r(i.options.abstract)){var m=a.slot;a={},m&&(a.slot=m)}!function(e){for(var t=e.hook||(e.hook={}),n=0;n<It.length;n++){var r=It[n],i=t[r],o=Lt[r];i===o||i&&i._merged||(t[r]=i?Ft(o,i):o)}}(a);var y=i.options.name||l;return new pe(\"vue-component-\"+i.cid+(y?\"-\"+y:\"\"),a,void 0,void 0,void 0,s,{Ctor:i,propsData:d,listeners:v,tag:l,children:c},p)}}}function Ft(e,t){var n=function(n,r){e(n,r),t(n,r)};return n._merged=!0,n}var Pt=1,Rt=2;function Ht(e,a,s,c,u,l){return(Array.isArray(s)||i(s))&&(u=c,c=s,s=void 0),r(l)&&(u=Rt),function(e,i,a,s,c){if(n(a)&&n(a.__ob__))return ve();n(a)&&n(a.is)&&(i=a.is);if(!i)return ve();Array.isArray(s)&&\"function\"==typeof s[0]&&((a=a||{}).scopedSlots={default:s[0]},s.length=0);c===Rt?s=st(s):c===Pt&&(s=function(e){for(var t=0;t<e.length;t++)if(Array.isArray(e[t]))return Array.prototype.concat.apply([],e);return e}(s));var u,l;if(\"string\"==typeof i){var f;l=e.$vnode&&e.$vnode.ns||F.getTagNamespace(i),u=F.isReservedTag(i)?new pe(F.parsePlatformTagName(i),a,s,void 0,void 0,e):a&&a.pre||!n(f=Le(e.$options,\"components\",i))?new pe(i,a,s,void 0,void 0,e):Mt(f,a,e,s,i)}else u=Mt(i,a,e,s);return Array.isArray(u)?u:n(u)?(n(l)&&function e(i,o,a){i.ns=o;\"foreignObject\"===i.tag&&(o=void 0,a=!0);if(n(i.children))for(var s=0,c=i.children.length;s<c;s++){var u=i.children[s];n(u.tag)&&(t(u.ns)||r(a)&&\"svg\"!==u.tag)&&e(u,o,a)}}(u,l),n(a)&&function(e){o(e.style)&&tt(e.style);o(e.class)&&tt(e.class)}(a),u):ve()}(e,a,s,c,u)}var Bt,Ut=null;function Vt(e,t){return(e.__esModule||oe&&\"Module\"===e[Symbol.toStringTag])&&(e=e.default),o(e)?t.extend(e):e}function zt(e){if(Array.isArray(e))for(var t=0;t<e.length;t++){var r=e[t];if(n(r)&&(n(r.componentOptions)||pt(r)))return r}}function Kt(e,t){Bt.$on(e,t)}function Jt(e,t){Bt.$off(e,t)}function qt(e,t){var n=Bt;return function r(){null!==t.apply(null,arguments)&&n.$off(e,r)}}function Wt(e,t,n){Bt=e,it(t,n||{},Kt,Jt,qt,e),Bt=void 0}var Zt=null;function Gt(e){var t=Zt;return Zt=e,function(){Zt=t}}function Xt(e){for(;e&&(e=e.$parent);)if(e._inactive)return!0;return!1}function Yt(e,t){if(t){if(e._directInactive=!1,Xt(e))return}else if(e._directInactive)return;if(e._inactive||null===e._inactive){e._inactive=!1;for(var n=0;n<e.$children.length;n++)Yt(e.$children[n]);Qt(e,\"activated\")}}function Qt(e,t){le();var n=e.$options[t],r=t+\" hook\";if(n)for(var i=0,o=n.length;i<o;i++)Be(n[i],e,null,e,r);e._hasHookEvent&&e.$emit(\"hook:\"+t),fe()}var en=[],tn=[],nn={},rn=!1,on=!1,an=0;var sn=0,cn=Date.now;if(V&&!q){var un=window.performance;un&&\"function\"==typeof un.now&&cn()>document.createEvent(\"Event\").timeStamp&&(cn=function(){return un.now()})}function ln(){var e,t;for(sn=cn(),on=!0,en.sort(function(e,t){return e.id-t.id}),an=0;an<en.length;an++)(e=en[an]).before&&e.before(),t=e.id,nn[t]=null,e.run();var n=tn.slice(),r=en.slice();an=en.length=tn.length=0,nn={},rn=on=!1,function(e){for(var t=0;t<e.length;t++)e[t]._inactive=!0,Yt(e[t],!0)}(n),function(e){var t=e.length;for(;t--;){var n=e[t],r=n.vm;r._watcher===n&&r._isMounted&&!r._isDestroyed&&Qt(r,\"updated\")}}(r),ne&&F.devtools&&ne.emit(\"flush\")}var fn=0,pn=function(e,t,n,r,i){this.vm=e,i&&(e._watcher=this),e._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync,this.before=r.before):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++fn,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new ie,this.newDepIds=new ie,this.expression=\"\",\"function\"==typeof t?this.getter=t:(this.getter=function(e){if(!H.test(e)){var t=e.split(\".\");return function(e){for(var n=0;n<t.length;n++){if(!e)return;e=e[t[n]]}return e}}}(t),this.getter||(this.getter=S)),this.value=this.lazy?void 0:this.get()};pn.prototype.get=function(){var e;le(this);var t=this.vm;try{e=this.getter.call(t,t)}catch(e){if(!this.user)throw e;He(e,t,'getter for watcher \"'+this.expression+'\"')}finally{this.deep&&tt(e),fe(),this.cleanupDeps()}return e},pn.prototype.addDep=function(e){var t=e.id;this.newDepIds.has(t)||(this.newDepIds.add(t),this.newDeps.push(e),this.depIds.has(t)||e.addSub(this))},pn.prototype.cleanupDeps=function(){for(var e=this.deps.length;e--;){var t=this.deps[e];this.newDepIds.has(t.id)||t.removeSub(this)}var n=this.depIds;this.depIds=this.newDepIds,this.newDepIds=n,this.newDepIds.clear(),n=this.deps,this.deps=this.newDeps,this.newDeps=n,this.newDeps.length=0},pn.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():function(e){var t=e.id;if(null==nn[t]){if(nn[t]=!0,on){for(var n=en.length-1;n>an&&en[n].id>e.id;)n--;en.splice(n+1,0,e)}else en.push(e);rn||(rn=!0,Qe(ln))}}(this)},pn.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||o(e)||this.deep){var t=this.value;if(this.value=e,this.user){var n='callback for watcher \"'+this.expression+'\"';Be(this.cb,this.vm,[e,t],this.vm,n)}else this.cb.call(this.vm,e,t)}}},pn.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},pn.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},pn.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||h(this.vm._watchers,this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1}};var dn={enumerable:!0,configurable:!0,get:S,set:S};function vn(e,t,n){dn.get=function(){return this[t][n]},dn.set=function(e){this[t][n]=e},Object.defineProperty(e,n,dn)}function hn(e){e._watchers=[];var t=e.$options;t.props&&function(e,t){var n=e.$options.propsData||{},r=e._props={},i=e.$options._propKeys=[];e.$parent&&$e(!1);var o=function(o){i.push(o);var a=Ie(o,t,n,e);xe(r,o,a),o in e||vn(e,\"_props\",o)};for(var a in t)o(a);$e(!0)}(e,t.props),t.methods&&function(e,t){e.$options.props;for(var n in t)e[n]=\"function\"!=typeof t[n]?S:x(t[n],e)}(e,t.methods),t.data?function(e){var t=e.$options.data;s(t=e._data=\"function\"==typeof t?function(e,t){le();try{return e.call(t,t)}catch(e){return He(e,t,\"data()\"),{}}finally{fe()}}(t,e):t||{})||(t={});var n=Object.keys(t),r=e.$options.props,i=(e.$options.methods,n.length);for(;i--;){var o=n[i];r&&y(r,o)||(a=void 0,36!==(a=(o+\"\").charCodeAt(0))&&95!==a&&vn(e,\"_data\",o))}var a;Ce(t,!0)}(e):Ce(e._data={},!0),t.computed&&function(e,t){var n=e._computedWatchers=Object.create(null),r=te();for(var i in t){var o=t[i],a=\"function\"==typeof o?o:o.get;r||(n[i]=new pn(e,a||S,S,mn)),i in e||yn(e,i,o)}}(e,t.computed),t.watch&&t.watch!==Y&&function(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i<r.length;i++)bn(e,n,r[i]);else bn(e,n,r)}}(e,t.watch)}var mn={lazy:!0};function yn(e,t,n){var r=!te();\"function\"==typeof n?(dn.get=r?gn(t):_n(n),dn.set=S):(dn.get=n.get?r&&!1!==n.cache?gn(t):_n(n.get):S,dn.set=n.set||S),Object.defineProperty(e,t,dn)}function gn(e){return function(){var t=this._computedWatchers&&this._computedWatchers[e];if(t)return t.dirty&&t.evaluate(),ce.target&&t.depend(),t.value}}function _n(e){return function(){return e.call(this,this)}}function bn(e,t,n,r){return s(n)&&(r=n,n=n.handler),\"string\"==typeof n&&(n=e[n]),e.$watch(t,n,r)}var $n=0;function wn(e){var t=e.options;if(e.super){var n=wn(e.super);if(n!==e.superOptions){e.superOptions=n;var r=function(e){var t,n=e.options,r=e.sealedOptions;for(var i in n)n[i]!==r[i]&&(t||(t={}),t[i]=n[i]);return t}(e);r&&A(e.extendOptions,r),(t=e.options=De(n,e.extendOptions)).name&&(t.components[t.name]=e)}}return t}function Cn(e){this._init(e)}function xn(e){e.cid=0;var t=1;e.extend=function(e){e=e||{};var n=this,r=n.cid,i=e._Ctor||(e._Ctor={});if(i[r])return i[r];var o=e.name||n.options.name,a=function(e){this._init(e)};return(a.prototype=Object.create(n.prototype)).constructor=a,a.cid=t++,a.options=De(n.options,e),a.super=n,a.options.props&&function(e){var t=e.options.props;for(var n in t)vn(e.prototype,\"_props\",n)}(a),a.options.computed&&function(e){var t=e.options.computed;for(var n in t)yn(e.prototype,n,t[n])}(a),a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,I.forEach(function(e){a[e]=n[e]}),o&&(a.options.components[o]=a),a.superOptions=n.options,a.extendOptions=e,a.sealedOptions=A({},a.options),i[r]=a,a}}function kn(e){return e&&(e.Ctor.options.name||e.tag)}function An(e,t){return Array.isArray(e)?e.indexOf(t)>-1:\"string\"==typeof e?e.split(\",\").indexOf(t)>-1:(n=e,\"[object RegExp]\"===a.call(n)&&e.test(t));var n}function On(e,t){var n=e.cache,r=e.keys,i=e._vnode;for(var o in n){var a=n[o];if(a){var s=a.name;s&&!t(s)&&Sn(n,o,r,i)}}}function Sn(e,t,n,r){var i=e[t];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),e[t]=null,h(n,t)}!function(t){t.prototype._init=function(t){var n=this;n._uid=$n++,n._isVue=!0,t&&t._isComponent?function(e,t){var n=e.$options=Object.create(e.constructor.options),r=t._parentVnode;n.parent=t.parent,n._parentVnode=r;var i=r.componentOptions;n.propsData=i.propsData,n._parentListeners=i.listeners,n._renderChildren=i.children,n._componentTag=i.tag,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}(n,t):n.$options=De(wn(n.constructor),t||{},n),n._renderProxy=n,n._self=n,function(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}(n),function(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&Wt(e,t)}(n),function(t){t._vnode=null,t._staticTrees=null;var n=t.$options,r=t.$vnode=n._parentVnode,i=r&&r.context;t.$slots=lt(n._renderChildren,i),t.$scopedSlots=e,t._c=function(e,n,r,i){return Ht(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Ht(t,e,n,r,i,!0)};var o=r&&r.data;xe(t,\"$attrs\",o&&o.attrs||e,null,!0),xe(t,\"$listeners\",n._parentListeners||e,null,!0)}(n),Qt(n,\"beforeCreate\"),function(e){var t=ut(e.$options.inject,e);t&&($e(!1),Object.keys(t).forEach(function(n){xe(e,n,t[n])}),$e(!0))}(n),hn(n),function(e){var t=e.$options.provide;t&&(e._provided=\"function\"==typeof t?t.call(e):t)}(n),Qt(n,\"created\"),n.$options.el&&n.$mount(n.$options.el)}}(Cn),function(e){var t={get:function(){return this._data}},n={get:function(){return this._props}};Object.defineProperty(e.prototype,\"$data\",t),Object.defineProperty(e.prototype,\"$props\",n),e.prototype.$set=ke,e.prototype.$delete=Ae,e.prototype.$watch=function(e,t,n){if(s(t))return bn(this,e,t,n);(n=n||{}).user=!0;var r=new pn(this,e,t,n);if(n.immediate){var i='callback for immediate watcher \"'+r.expression+'\"';le(),Be(t,this,[r.value],this,i),fe()}return function(){r.teardown()}}}(Cn),function(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this;if(Array.isArray(e))for(var i=0,o=e.length;i<o;i++)r.$on(e[i],n);else(r._events[e]||(r._events[e]=[])).push(n),t.test(e)&&(r._hasHookEvent=!0);return r},e.prototype.$once=function(e,t){var n=this;function r(){n.$off(e,r),t.apply(n,arguments)}return r.fn=t,n.$on(e,r),n},e.prototype.$off=function(e,t){var n=this;if(!arguments.length)return n._events=Object.create(null),n;if(Array.isArray(e)){for(var r=0,i=e.length;r<i;r++)n.$off(e[r],t);return n}var o,a=n._events[e];if(!a)return n;if(!t)return n._events[e]=null,n;for(var s=a.length;s--;)if((o=a[s])===t||o.fn===t){a.splice(s,1);break}return n},e.prototype.$emit=function(e){var t=this._events[e];if(t){t=t.length>1?k(t):t;for(var n=k(arguments,1),r='event handler for \"'+e+'\"',i=0,o=t.length;i<o;i++)Be(t[i],this,n,this,r)}return this}}(Cn),function(e){e.prototype._update=function(e,t){var n=this,r=n.$el,i=n._vnode,o=Gt(n);n._vnode=e,n.$el=i?n.__patch__(i,e):n.__patch__(n.$el,e,t,!1),o(),r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},e.prototype.$forceUpdate=function(){this._watcher&&this._watcher.update()},e.prototype.$destroy=function(){var e=this;if(!e._isBeingDestroyed){Qt(e,\"beforeDestroy\"),e._isBeingDestroyed=!0;var t=e.$parent;!t||t._isBeingDestroyed||e.$options.abstract||h(t.$children,e),e._watcher&&e._watcher.teardown();for(var n=e._watchers.length;n--;)e._watchers[n].teardown();e._data.__ob__&&e._data.__ob__.vmCount--,e._isDestroyed=!0,e.__patch__(e._vnode,null),Qt(e,\"destroyed\"),e.$off(),e.$el&&(e.$el.__vue__=null),e.$vnode&&(e.$vnode.parent=null)}}}(Cn),function(e){Nt(e.prototype),e.prototype.$nextTick=function(e){return Qe(e,this)},e.prototype._render=function(){var e,t=this,n=t.$options,r=n.render,i=n._parentVnode;i&&(t.$scopedSlots=dt(i.data.scopedSlots,t.$slots,t.$scopedSlots)),t.$vnode=i;try{Ut=t,e=r.call(t._renderProxy,t.$createElement)}catch(n){He(n,t,\"render\"),e=t._vnode}finally{Ut=null}return Array.isArray(e)&&1===e.length&&(e=e[0]),e instanceof pe||(e=ve()),e.parent=i,e}}(Cn);var Tn=[String,RegExp,Array],Nn={KeepAlive:{name:\"keep-alive\",abstract:!0,props:{include:Tn,exclude:Tn,max:[String,Number]},methods:{cacheVNode:function(){var e=this.cache,t=this.keys,n=this.vnodeToCache,r=this.keyToCache;if(n){var i=n.tag,o=n.componentInstance,a=n.componentOptions;e[r]={name:kn(a),tag:i,componentInstance:o},t.push(r),this.max&&t.length>parseInt(this.max)&&Sn(e,t[0],t,this._vnode),this.vnodeToCache=null}}},created:function(){this.cache=Object.create(null),this.keys=[]},destroyed:function(){for(var e in this.cache)Sn(this.cache,e,this.keys)},mounted:function(){var e=this;this.cacheVNode(),this.$watch(\"include\",function(t){On(e,function(e){return An(t,e)})}),this.$watch(\"exclude\",function(t){On(e,function(e){return!An(t,e)})})},updated:function(){this.cacheVNode()},render:function(){var e=this.$slots.default,t=zt(e),n=t&&t.componentOptions;if(n){var r=kn(n),i=this.include,o=this.exclude;if(i&&(!r||!An(i,r))||o&&r&&An(o,r))return t;var a=this.cache,s=this.keys,c=null==t.key?n.Ctor.cid+(n.tag?\"::\"+n.tag:\"\"):t.key;a[c]?(t.componentInstance=a[c].componentInstance,h(s,c),s.push(c)):(this.vnodeToCache=t,this.keyToCache=c),t.data.keepAlive=!0}return t||e&&e[0]}}};!function(e){var t={get:function(){return F}};Object.defineProperty(e,\"config\",t),e.util={warn:ae,extend:A,mergeOptions:De,defineReactive:xe},e.set=ke,e.delete=Ae,e.nextTick=Qe,e.observable=function(e){return Ce(e),e},e.options=Object.create(null),I.forEach(function(t){e.options[t+\"s\"]=Object.create(null)}),e.options._base=e,A(e.options.components,Nn),function(e){e.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(t.indexOf(e)>-1)return this;var n=k(arguments,1);return n.unshift(this),\"function\"==typeof e.install?e.install.apply(e,n):\"function\"==typeof e&&e.apply(null,n),t.push(e),this}}(e),function(e){e.mixin=function(e){return this.options=De(this.options,e),this}}(e),xn(e),function(e){I.forEach(function(t){e[t]=function(e,n){return n?(\"component\"===t&&s(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),\"directive\"===t&&\"function\"==typeof n&&(n={bind:n,update:n}),this.options[t+\"s\"][e]=n,n):this.options[t+\"s\"][e]}})}(e)}(Cn),Object.defineProperty(Cn.prototype,\"$isServer\",{get:te}),Object.defineProperty(Cn.prototype,\"$ssrContext\",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(Cn,\"FunctionalRenderContext\",{value:Et}),Cn.version=\"2.6.14\";var En=p(\"style,class\"),jn=p(\"input,textarea,option,select,progress\"),Dn=function(e,t,n){return\"value\"===n&&jn(e)&&\"button\"!==t||\"selected\"===n&&\"option\"===e||\"checked\"===n&&\"input\"===e||\"muted\"===n&&\"video\"===e},Ln=p(\"contenteditable,draggable,spellcheck\"),In=p(\"events,caret,typing,plaintext-only\"),Mn=function(e,t){return Bn(t)||\"false\"===t?\"false\":\"contenteditable\"===e&&In(t)?t:\"true\"},Fn=p(\"allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible\"),Pn=\"http://www.w3.org/1999/xlink\",Rn=function(e){return\":\"===e.charAt(5)&&\"xlink\"===e.slice(0,5)},Hn=function(e){return Rn(e)?e.slice(6,e.length):\"\"},Bn=function(e){return null==e||!1===e};function Un(e){for(var t=e.data,r=e,i=e;n(i.componentInstance);)(i=i.componentInstance._vnode)&&i.data&&(t=Vn(i.data,t));for(;n(r=r.parent);)r&&r.data&&(t=Vn(t,r.data));return function(e,t){if(n(e)||n(t))return zn(e,Kn(t));return\"\"}(t.staticClass,t.class)}function Vn(e,t){return{staticClass:zn(e.staticClass,t.staticClass),class:n(e.class)?[e.class,t.class]:t.class}}function zn(e,t){return e?t?e+\" \"+t:e:t||\"\"}function Kn(e){return Array.isArray(e)?function(e){for(var t,r=\"\",i=0,o=e.length;i<o;i++)n(t=Kn(e[i]))&&\"\"!==t&&(r&&(r+=\" \"),r+=t);return r}(e):o(e)?function(e){var t=\"\";for(var n in e)e[n]&&(t&&(t+=\" \"),t+=n);return t}(e):\"string\"==typeof e?e:\"\"}var Jn={svg:\"http://www.w3.org/2000/svg\",math:\"http://www.w3.org/1998/Math/MathML\"},qn=p(\"html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template,blockquote,iframe,tfoot\"),Wn=p(\"svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,foreignobject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view\",!0),Zn=function(e){return qn(e)||Wn(e)};function Gn(e){return Wn(e)?\"svg\":\"math\"===e?\"math\":void 0}var Xn=Object.create(null);var Yn=p(\"text,number,password,search,email,tel,url\");function Qn(e){if(\"string\"==typeof e){var t=document.querySelector(e);return t||document.createElement(\"div\")}return e}var er=Object.freeze({createElement:function(e,t){var n=document.createElement(e);return\"select\"!==e?n:(t.data&&t.data.attrs&&void 0!==t.data.attrs.multiple&&n.setAttribute(\"multiple\",\"multiple\"),n)},createElementNS:function(e,t){return document.createElementNS(Jn[e],t)},createTextNode:function(e){return document.createTextNode(e)},createComment:function(e){return document.createComment(e)},insertBefore:function(e,t,n){e.insertBefore(t,n)},removeChild:function(e,t){e.removeChild(t)},appendChild:function(e,t){e.appendChild(t)},parentNode:function(e){return e.parentNode},nextSibling:function(e){return e.nextSibling},tagName:function(e){return e.tagName},setTextContent:function(e,t){e.textContent=t},setStyleScope:function(e,t){e.setAttribute(t,\"\")}}),tr={create:function(e,t){nr(t)},update:function(e,t){e.data.ref!==t.data.ref&&(nr(e,!0),nr(t))},destroy:function(e){nr(e,!0)}};function nr(e,t){var r=e.data.ref;if(n(r)){var i=e.context,o=e.componentInstance||e.elm,a=i.$refs;t?Array.isArray(a[r])?h(a[r],o):a[r]===o&&(a[r]=void 0):e.data.refInFor?Array.isArray(a[r])?a[r].indexOf(o)<0&&a[r].push(o):a[r]=[o]:a[r]=o}}var rr=new pe(\"\",{},[]),ir=[\"create\",\"activate\",\"update\",\"remove\",\"destroy\"];function or(e,i){return e.key===i.key&&e.asyncFactory===i.asyncFactory&&(e.tag===i.tag&&e.isComment===i.isComment&&n(e.data)===n(i.data)&&function(e,t){if(\"input\"!==e.tag)return!0;var r,i=n(r=e.data)&&n(r=r.attrs)&&r.type,o=n(r=t.data)&&n(r=r.attrs)&&r.type;return i===o||Yn(i)&&Yn(o)}(e,i)||r(e.isAsyncPlaceholder)&&t(i.asyncFactory.error))}function ar(e,t,r){var i,o,a={};for(i=t;i<=r;++i)n(o=e[i].key)&&(a[o]=i);return a}var sr={create:cr,update:cr,destroy:function(e){cr(e,rr)}};function cr(e,t){(e.data.directives||t.data.directives)&&function(e,t){var n,r,i,o=e===rr,a=t===rr,s=lr(e.data.directives,e.context),c=lr(t.data.directives,t.context),u=[],l=[];for(n in c)r=s[n],i=c[n],r?(i.oldValue=r.value,i.oldArg=r.arg,pr(i,\"update\",t,e),i.def&&i.def.componentUpdated&&l.push(i)):(pr(i,\"bind\",t,e),i.def&&i.def.inserted&&u.push(i));if(u.length){var f=function(){for(var n=0;n<u.length;n++)pr(u[n],\"inserted\",t,e)};o?ot(t,\"insert\",f):f()}l.length&&ot(t,\"postpatch\",function(){for(var n=0;n<l.length;n++)pr(l[n],\"componentUpdated\",t,e)});if(!o)for(n in s)c[n]||pr(s[n],\"unbind\",e,e,a)}(e,t)}var ur=Object.create(null);function lr(e,t){var n,r,i=Object.create(null);if(!e)return i;for(n=0;n<e.length;n++)(r=e[n]).modifiers||(r.modifiers=ur),i[fr(r)]=r,r.def=Le(t.$options,\"directives\",r.name);return i}function fr(e){return e.rawName||e.name+\".\"+Object.keys(e.modifiers||{}).join(\".\")}function pr(e,t,n,r,i){var o=e.def&&e.def[t];if(o)try{o(n.elm,e,n,r,i)}catch(r){He(r,n.context,\"directive \"+e.name+\" \"+t+\" hook\")}}var dr=[tr,sr];function vr(e,r){var i=r.componentOptions;if(!(n(i)&&!1===i.Ctor.options.inheritAttrs||t(e.data.attrs)&&t(r.data.attrs))){var o,a,s=r.elm,c=e.data.attrs||{},u=r.data.attrs||{};for(o in n(u.__ob__)&&(u=r.data.attrs=A({},u)),u)a=u[o],c[o]!==a&&hr(s,o,a,r.data.pre);for(o in(q||Z)&&u.value!==c.value&&hr(s,\"value\",u.value),c)t(u[o])&&(Rn(o)?s.removeAttributeNS(Pn,Hn(o)):Ln(o)||s.removeAttribute(o))}}function hr(e,t,n,r){r||e.tagName.indexOf(\"-\")>-1?mr(e,t,n):Fn(t)?Bn(n)?e.removeAttribute(t):(n=\"allowfullscreen\"===t&&\"EMBED\"===e.tagName?\"true\":t,e.setAttribute(t,n)):Ln(t)?e.setAttribute(t,Mn(t,n)):Rn(t)?Bn(n)?e.removeAttributeNS(Pn,Hn(t)):e.setAttributeNS(Pn,t,n):mr(e,t,n)}function mr(e,t,n){if(Bn(n))e.removeAttribute(t);else{if(q&&!W&&\"TEXTAREA\"===e.tagName&&\"placeholder\"===t&&\"\"!==n&&!e.__ieph){var r=function(t){t.stopImmediatePropagation(),e.removeEventListener(\"input\",r)};e.addEventListener(\"input\",r),e.__ieph=!0}e.setAttribute(t,n)}}var yr={create:vr,update:vr};function gr(e,r){var i=r.elm,o=r.data,a=e.data;if(!(t(o.staticClass)&&t(o.class)&&(t(a)||t(a.staticClass)&&t(a.class)))){var s=Un(r),c=i._transitionClasses;n(c)&&(s=zn(s,Kn(c))),s!==i._prevClass&&(i.setAttribute(\"class\",s),i._prevClass=s)}}var _r,br,$r,wr,Cr,xr,kr={create:gr,update:gr},Ar=/[\\w).+\\-_$\\]]/;function Or(e){var t,n,r,i,o,a=!1,s=!1,c=!1,u=!1,l=0,f=0,p=0,d=0;for(r=0;r<e.length;r++)if(n=t,t=e.charCodeAt(r),a)39===t&&92!==n&&(a=!1);else if(s)34===t&&92!==n&&(s=!1);else if(c)96===t&&92!==n&&(c=!1);else if(u)47===t&&92!==n&&(u=!1);else if(124!==t||124===e.charCodeAt(r+1)||124===e.charCodeAt(r-1)||l||f||p){switch(t){case 34:s=!0;break;case 39:a=!0;break;case 96:c=!0;break;case 40:p++;break;case 41:p--;break;case 91:f++;break;case 93:f--;break;case 123:l++;break;case 125:l--}if(47===t){for(var v=r-1,h=void 0;v>=0&&\" \"===(h=e.charAt(v));v--);h&&Ar.test(h)||(u=!0)}}else void 0===i?(d=r+1,i=e.slice(0,r).trim()):m();function m(){(o||(o=[])).push(e.slice(d,r).trim()),d=r+1}if(void 0===i?i=e.slice(0,r).trim():0!==d&&m(),o)for(r=0;r<o.length;r++)i=Sr(i,o[r]);return i}function Sr(e,t){var n=t.indexOf(\"(\");if(n<0)return'_f(\"'+t+'\")('+e+\")\";var r=t.slice(0,n),i=t.slice(n+1);return'_f(\"'+r+'\")('+e+(\")\"!==i?\",\"+i:i)}function Tr(e,t){console.error(\"[Vue compiler]: \"+e)}function Nr(e,t){return e?e.map(function(e){return e[t]}).filter(function(e){return e}):[]}function Er(e,t,n,r,i){(e.props||(e.props=[])).push(Hr({name:t,value:n,dynamic:i},r)),e.plain=!1}function jr(e,t,n,r,i){(i?e.dynamicAttrs||(e.dynamicAttrs=[]):e.attrs||(e.attrs=[])).push(Hr({name:t,value:n,dynamic:i},r)),e.plain=!1}function Dr(e,t,n,r){e.attrsMap[t]=n,e.attrsList.push(Hr({name:t,value:n},r))}function Lr(e,t,n,r,i,o,a,s){(e.directives||(e.directives=[])).push(Hr({name:t,rawName:n,value:r,arg:i,isDynamicArg:o,modifiers:a},s)),e.plain=!1}function Ir(e,t,n){return n?\"_p(\"+t+',\"'+e+'\")':e+t}function Mr(t,n,r,i,o,a,s,c){var u;(i=i||e).right?c?n=\"(\"+n+\")==='click'?'contextmenu':(\"+n+\")\":\"click\"===n&&(n=\"contextmenu\",delete i.right):i.middle&&(c?n=\"(\"+n+\")==='click'?'mouseup':(\"+n+\")\":\"click\"===n&&(n=\"mouseup\")),i.capture&&(delete i.capture,n=Ir(\"!\",n,c)),i.once&&(delete i.once,n=Ir(\"~\",n,c)),i.passive&&(delete i.passive,n=Ir(\"&\",n,c)),i.native?(delete i.native,u=t.nativeEvents||(t.nativeEvents={})):u=t.events||(t.events={});var l=Hr({value:r.trim(),dynamic:c},s);i!==e&&(l.modifiers=i);var f=u[n];Array.isArray(f)?o?f.unshift(l):f.push(l):u[n]=f?o?[l,f]:[f,l]:l,t.plain=!1}function Fr(e,t,n){var r=Pr(e,\":\"+t)||Pr(e,\"v-bind:\"+t);if(null!=r)return Or(r);if(!1!==n){var i=Pr(e,t);if(null!=i)return JSON.stringify(i)}}function Pr(e,t,n){var r;if(null!=(r=e.attrsMap[t]))for(var i=e.attrsList,o=0,a=i.length;o<a;o++)if(i[o].name===t){i.splice(o,1);break}return n&&delete e.attrsMap[t],r}function Rr(e,t){for(var n=e.attrsList,r=0,i=n.length;r<i;r++){var o=n[r];if(t.test(o.name))return n.splice(r,1),o}}function Hr(e,t){return t&&(null!=t.start&&(e.start=t.start),null!=t.end&&(e.end=t.end)),e}function Br(e,t,n){var r=n||{},i=r.number,o=\"$$v\";r.trim&&(o=\"(typeof $$v === 'string'? $$v.trim(): $$v)\"),i&&(o=\"_n(\"+o+\")\");var a=Ur(t,o);e.model={value:\"(\"+t+\")\",expression:JSON.stringify(t),callback:\"function ($$v) {\"+a+\"}\"}}function Ur(e,t){var n=function(e){if(e=e.trim(),_r=e.length,e.indexOf(\"[\")<0||e.lastIndexOf(\"]\")<_r-1)return(wr=e.lastIndexOf(\".\"))>-1?{exp:e.slice(0,wr),key:'\"'+e.slice(wr+1)+'\"'}:{exp:e,key:null};br=e,wr=Cr=xr=0;for(;!zr();)Kr($r=Vr())?qr($r):91===$r&&Jr($r);return{exp:e.slice(0,Cr),key:e.slice(Cr+1,xr)}}(e);return null===n.key?e+\"=\"+t:\"$set(\"+n.exp+\", \"+n.key+\", \"+t+\")\"}function Vr(){return br.charCodeAt(++wr)}function zr(){return wr>=_r}function Kr(e){return 34===e||39===e}function Jr(e){var t=1;for(Cr=wr;!zr();)if(Kr(e=Vr()))qr(e);else if(91===e&&t++,93===e&&t--,0===t){xr=wr;break}}function qr(e){for(var t=e;!zr()&&(e=Vr())!==t;);}var Wr,Zr=\"__r\",Gr=\"__c\";function Xr(e,t,n){var r=Wr;return function i(){null!==t.apply(null,arguments)&&ei(e,i,n,r)}}var Yr=Ke&&!(X&&Number(X[1])<=53);function Qr(e,t,n,r){if(Yr){var i=sn,o=t;t=o._wrapper=function(e){if(e.target===e.currentTarget||e.timeStamp>=i||e.timeStamp<=0||e.target.ownerDocument!==document)return o.apply(this,arguments)}}Wr.addEventListener(e,t,Q?{capture:n,passive:r}:n)}function ei(e,t,n,r){(r||Wr).removeEventListener(e,t._wrapper||t,n)}function ti(e,r){if(!t(e.data.on)||!t(r.data.on)){var i=r.data.on||{},o=e.data.on||{};Wr=r.elm,function(e){if(n(e[Zr])){var t=q?\"change\":\"input\";e[t]=[].concat(e[Zr],e[t]||[]),delete e[Zr]}n(e[Gr])&&(e.change=[].concat(e[Gr],e.change||[]),delete e[Gr])}(i),it(i,o,Qr,ei,Xr,r.context),Wr=void 0}}var ni,ri={create:ti,update:ti};function ii(e,r){if(!t(e.data.domProps)||!t(r.data.domProps)){var i,o,a=r.elm,s=e.data.domProps||{},c=r.data.domProps||{};for(i in n(c.__ob__)&&(c=r.data.domProps=A({},c)),s)i in c||(a[i]=\"\");for(i in c){if(o=c[i],\"textContent\"===i||\"innerHTML\"===i){if(r.children&&(r.children.length=0),o===s[i])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if(\"value\"===i&&\"PROGRESS\"!==a.tagName){a._value=o;var u=t(o)?\"\":String(o);oi(a,u)&&(a.value=u)}else if(\"innerHTML\"===i&&Wn(a.tagName)&&t(a.innerHTML)){(ni=ni||document.createElement(\"div\")).innerHTML=\"<svg>\"+o+\"</svg>\";for(var l=ni.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;l.firstChild;)a.appendChild(l.firstChild)}else if(o!==s[i])try{a[i]=o}catch(e){}}}}function oi(e,t){return!e.composing&&(\"OPTION\"===e.tagName||function(e,t){var n=!0;try{n=document.activeElement!==e}catch(e){}return n&&e.value!==t}(e,t)||function(e,t){var r=e.value,i=e._vModifiers;if(n(i)){if(i.number)return f(r)!==f(t);if(i.trim)return r.trim()!==t.trim()}return r!==t}(e,t))}var ai={create:ii,update:ii},si=g(function(e){var t={},n=/:(.+)/;return e.split(/;(?![^(]*\\))/g).forEach(function(e){if(e){var r=e.split(n);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t});function ci(e){var t=ui(e.style);return e.staticStyle?A(e.staticStyle,t):t}function ui(e){return Array.isArray(e)?O(e):\"string\"==typeof e?si(e):e}var li,fi=/^--/,pi=/\\s*!important$/,di=function(e,t,n){if(fi.test(t))e.style.setProperty(t,n);else if(pi.test(n))e.style.setProperty(C(t),n.replace(pi,\"\"),\"important\");else{var r=hi(t);if(Array.isArray(n))for(var i=0,o=n.length;i<o;i++)e.style[r]=n[i];else e.style[r]=n}},vi=[\"Webkit\",\"Moz\",\"ms\"],hi=g(function(e){if(li=li||document.createElement(\"div\").style,\"filter\"!==(e=b(e))&&e in li)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=0;n<vi.length;n++){var r=vi[n]+t;if(r in li)return r}});function mi(e,r){var i=r.data,o=e.data;if(!(t(i.staticStyle)&&t(i.style)&&t(o.staticStyle)&&t(o.style))){var a,s,c=r.elm,u=o.staticStyle,l=o.normalizedStyle||o.style||{},f=u||l,p=ui(r.data.style)||{};r.data.normalizedStyle=n(p.__ob__)?A({},p):p;var d=function(e,t){var n,r={};if(t)for(var i=e;i.componentInstance;)(i=i.componentInstance._vnode)&&i.data&&(n=ci(i.data))&&A(r,n);(n=ci(e.data))&&A(r,n);for(var o=e;o=o.parent;)o.data&&(n=ci(o.data))&&A(r,n);return r}(r,!0);for(s in f)t(d[s])&&di(c,s,\"\");for(s in d)(a=d[s])!==f[s]&&di(c,s,null==a?\"\":a)}}var yi={create:mi,update:mi},gi=/\\s+/;function _i(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(\" \")>-1?t.split(gi).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=\" \"+(e.getAttribute(\"class\")||\"\")+\" \";n.indexOf(\" \"+t+\" \")<0&&e.setAttribute(\"class\",(n+t).trim())}}function bi(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(\" \")>-1?t.split(gi).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t),e.classList.length||e.removeAttribute(\"class\");else{for(var n=\" \"+(e.getAttribute(\"class\")||\"\")+\" \",r=\" \"+t+\" \";n.indexOf(r)>=0;)n=n.replace(r,\" \");(n=n.trim())?e.setAttribute(\"class\",n):e.removeAttribute(\"class\")}}function $i(e){if(e){if(\"object\"==typeof e){var t={};return!1!==e.css&&A(t,wi(e.name||\"v\")),A(t,e),t}return\"string\"==typeof e?wi(e):void 0}}var wi=g(function(e){return{enterClass:e+\"-enter\",enterToClass:e+\"-enter-to\",enterActiveClass:e+\"-enter-active\",leaveClass:e+\"-leave\",leaveToClass:e+\"-leave-to\",leaveActiveClass:e+\"-leave-active\"}}),Ci=V&&!W,xi=\"transition\",ki=\"animation\",Ai=\"transition\",Oi=\"transitionend\",Si=\"animation\",Ti=\"animationend\";Ci&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(Ai=\"WebkitTransition\",Oi=\"webkitTransitionEnd\"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Si=\"WebkitAnimation\",Ti=\"webkitAnimationEnd\"));var Ni=V?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(e){return e()};function Ei(e){Ni(function(){Ni(e)})}function ji(e,t){var n=e._transitionClasses||(e._transitionClasses=[]);n.indexOf(t)<0&&(n.push(t),_i(e,t))}function Di(e,t){e._transitionClasses&&h(e._transitionClasses,t),bi(e,t)}function Li(e,t,n){var r=Mi(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===xi?Oi:Ti,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c<a&&u()},o+1),e.addEventListener(s,l)}var Ii=/\\b(transform|all)(,|$)/;function Mi(e,t){var n,r=window.getComputedStyle(e),i=(r[Ai+\"Delay\"]||\"\").split(\", \"),o=(r[Ai+\"Duration\"]||\"\").split(\", \"),a=Fi(i,o),s=(r[Si+\"Delay\"]||\"\").split(\", \"),c=(r[Si+\"Duration\"]||\"\").split(\", \"),u=Fi(s,c),l=0,f=0;return t===xi?a>0&&(n=xi,l=a,f=o.length):t===ki?u>0&&(n=ki,l=u,f=c.length):f=(n=(l=Math.max(a,u))>0?a>u?xi:ki:null)?n===xi?o.length:c.length:0,{type:n,timeout:l,propCount:f,hasTransform:n===xi&&Ii.test(r[Ai+\"Property\"])}}function Fi(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max.apply(null,t.map(function(t,n){return Pi(t)+Pi(e[n])}))}function Pi(e){return 1e3*Number(e.slice(0,-1).replace(\",\",\".\"))}function Ri(e,r){var i=e.elm;n(i._leaveCb)&&(i._leaveCb.cancelled=!0,i._leaveCb());var a=$i(e.data.transition);if(!t(a)&&!n(i._enterCb)&&1===i.nodeType){for(var s=a.css,c=a.type,u=a.enterClass,l=a.enterToClass,p=a.enterActiveClass,d=a.appearClass,v=a.appearToClass,h=a.appearActiveClass,m=a.beforeEnter,y=a.enter,g=a.afterEnter,_=a.enterCancelled,b=a.beforeAppear,$=a.appear,w=a.afterAppear,C=a.appearCancelled,x=a.duration,k=Zt,A=Zt.$vnode;A&&A.parent;)k=A.context,A=A.parent;var O=!k._isMounted||!e.isRootInsert;if(!O||$||\"\"===$){var S=O&&d?d:u,T=O&&h?h:p,N=O&&v?v:l,E=O&&b||m,j=O&&\"function\"==typeof $?$:y,L=O&&w||g,I=O&&C||_,M=f(o(x)?x.enter:x),F=!1!==s&&!W,P=Ui(j),R=i._enterCb=D(function(){F&&(Di(i,N),Di(i,T)),R.cancelled?(F&&Di(i,S),I&&I(i)):L&&L(i),i._enterCb=null});e.data.show||ot(e,\"insert\",function(){var t=i.parentNode,n=t&&t._pending&&t._pending[e.key];n&&n.tag===e.tag&&n.elm._leaveCb&&n.elm._leaveCb(),j&&j(i,R)}),E&&E(i),F&&(ji(i,S),ji(i,T),Ei(function(){Di(i,S),R.cancelled||(ji(i,N),P||(Bi(M)?setTimeout(R,M):Li(i,c,R)))})),e.data.show&&(r&&r(),j&&j(i,R)),F||P||R()}}}function Hi(e,r){var i=e.elm;n(i._enterCb)&&(i._enterCb.cancelled=!0,i._enterCb());var a=$i(e.data.transition);if(t(a)||1!==i.nodeType)return r();if(!n(i._leaveCb)){var s=a.css,c=a.type,u=a.leaveClass,l=a.leaveToClass,p=a.leaveActiveClass,d=a.beforeLeave,v=a.leave,h=a.afterLeave,m=a.leaveCancelled,y=a.delayLeave,g=a.duration,_=!1!==s&&!W,b=Ui(v),$=f(o(g)?g.leave:g),w=i._leaveCb=D(function(){i.parentNode&&i.parentNode._pending&&(i.parentNode._pending[e.key]=null),_&&(Di(i,l),Di(i,p)),w.cancelled?(_&&Di(i,u),m&&m(i)):(r(),h&&h(i)),i._leaveCb=null});y?y(C):C()}function C(){w.cancelled||(!e.data.show&&i.parentNode&&((i.parentNode._pending||(i.parentNode._pending={}))[e.key]=e),d&&d(i),_&&(ji(i,u),ji(i,p),Ei(function(){Di(i,u),w.cancelled||(ji(i,l),b||(Bi($)?setTimeout(w,$):Li(i,c,w)))})),v&&v(i,w),_||b||w())}}function Bi(e){return\"number\"==typeof e&&!isNaN(e)}function Ui(e){if(t(e))return!1;var r=e.fns;return n(r)?Ui(Array.isArray(r)?r[0]:r):(e._length||e.length)>1}function Vi(e,t){!0!==t.data.show&&Ri(t)}var zi=function(e){var o,a,s={},c=e.modules,u=e.nodeOps;for(o=0;o<ir.length;++o)for(s[ir[o]]=[],a=0;a<c.length;++a)n(c[a][ir[o]])&&s[ir[o]].push(c[a][ir[o]]);function l(e){var t=u.parentNode(e);n(t)&&u.removeChild(t,e)}function f(e,t,i,o,a,c,l){if(n(e.elm)&&n(c)&&(e=c[l]=me(e)),e.isRootInsert=!a,!function(e,t,i,o){var a=e.data;if(n(a)){var c=n(e.componentInstance)&&a.keepAlive;if(n(a=a.hook)&&n(a=a.init)&&a(e,!1),n(e.componentInstance))return d(e,t),v(i,e.elm,o),r(c)&&function(e,t,r,i){for(var o,a=e;a.componentInstance;)if(a=a.componentInstance._vnode,n(o=a.data)&&n(o=o.transition)){for(o=0;o<s.activate.length;++o)s.activate[o](rr,a);t.push(a);break}v(r,e.elm,i)}(e,t,i,o),!0}}(e,t,i,o)){var f=e.data,p=e.children,m=e.tag;n(m)?(e.elm=e.ns?u.createElementNS(e.ns,m):u.createElement(m,e),g(e),h(e,p,t),n(f)&&y(e,t),v(i,e.elm,o)):r(e.isComment)?(e.elm=u.createComment(e.text),v(i,e.elm,o)):(e.elm=u.createTextNode(e.text),v(i,e.elm,o))}}function d(e,t){n(e.data.pendingInsert)&&(t.push.apply(t,e.data.pendingInsert),e.data.pendingInsert=null),e.elm=e.componentInstance.$el,m(e)?(y(e,t),g(e)):(nr(e),t.push(e))}function v(e,t,r){n(e)&&(n(r)?u.parentNode(r)===e&&u.insertBefore(e,t,r):u.appendChild(e,t))}function h(e,t,n){if(Array.isArray(t))for(var r=0;r<t.length;++r)f(t[r],n,e.elm,null,!0,t,r);else i(e.text)&&u.appendChild(e.elm,u.createTextNode(String(e.text)))}function m(e){for(;e.componentInstance;)e=e.componentInstance._vnode;return n(e.tag)}function y(e,t){for(var r=0;r<s.create.length;++r)s.create[r](rr,e);n(o=e.data.hook)&&(n(o.create)&&o.create(rr,e),n(o.insert)&&t.push(e))}function g(e){var t;if(n(t=e.fnScopeId))u.setStyleScope(e.elm,t);else for(var r=e;r;)n(t=r.context)&&n(t=t.$options._scopeId)&&u.setStyleScope(e.elm,t),r=r.parent;n(t=Zt)&&t!==e.context&&t!==e.fnContext&&n(t=t.$options._scopeId)&&u.setStyleScope(e.elm,t)}function _(e,t,n,r,i,o){for(;r<=i;++r)f(n[r],o,e,t,!1,n,r)}function b(e){var t,r,i=e.data;if(n(i))for(n(t=i.hook)&&n(t=t.destroy)&&t(e),t=0;t<s.destroy.length;++t)s.destroy[t](e);if(n(t=e.children))for(r=0;r<e.children.length;++r)b(e.children[r])}function $(e,t,r){for(;t<=r;++t){var i=e[t];n(i)&&(n(i.tag)?(w(i),b(i)):l(i.elm))}}function w(e,t){if(n(t)||n(e.data)){var r,i=s.remove.length+1;for(n(t)?t.listeners+=i:t=function(e,t){function n(){0==--n.listeners&&l(e)}return n.listeners=t,n}(e.elm,i),n(r=e.componentInstance)&&n(r=r._vnode)&&n(r.data)&&w(r,t),r=0;r<s.remove.length;++r)s.remove[r](e,t);n(r=e.data.hook)&&n(r=r.remove)?r(e,t):t()}else l(e.elm)}function C(e,t,r,i){for(var o=r;o<i;o++){var a=t[o];if(n(a)&&or(e,a))return o}}function x(e,i,o,a,c,l){if(e!==i){n(i.elm)&&n(a)&&(i=a[c]=me(i));var p=i.elm=e.elm;if(r(e.isAsyncPlaceholder))n(i.asyncFactory.resolved)?O(e.elm,i,o):i.isAsyncPlaceholder=!0;else if(r(i.isStatic)&&r(e.isStatic)&&i.key===e.key&&(r(i.isCloned)||r(i.isOnce)))i.componentInstance=e.componentInstance;else{var d,v=i.data;n(v)&&n(d=v.hook)&&n(d=d.prepatch)&&d(e,i);var h=e.children,y=i.children;if(n(v)&&m(i)){for(d=0;d<s.update.length;++d)s.update[d](e,i);n(d=v.hook)&&n(d=d.update)&&d(e,i)}t(i.text)?n(h)&&n(y)?h!==y&&function(e,r,i,o,a){for(var s,c,l,p=0,d=0,v=r.length-1,h=r[0],m=r[v],y=i.length-1,g=i[0],b=i[y],w=!a;p<=v&&d<=y;)t(h)?h=r[++p]:t(m)?m=r[--v]:or(h,g)?(x(h,g,o,i,d),h=r[++p],g=i[++d]):or(m,b)?(x(m,b,o,i,y),m=r[--v],b=i[--y]):or(h,b)?(x(h,b,o,i,y),w&&u.insertBefore(e,h.elm,u.nextSibling(m.elm)),h=r[++p],b=i[--y]):or(m,g)?(x(m,g,o,i,d),w&&u.insertBefore(e,m.elm,h.elm),m=r[--v],g=i[++d]):(t(s)&&(s=ar(r,p,v)),t(c=n(g.key)?s[g.key]:C(g,r,p,v))?f(g,o,e,h.elm,!1,i,d):or(l=r[c],g)?(x(l,g,o,i,d),r[c]=void 0,w&&u.insertBefore(e,l.elm,h.elm)):f(g,o,e,h.elm,!1,i,d),g=i[++d]);p>v?_(e,t(i[y+1])?null:i[y+1].elm,i,d,y,o):d>y&&$(r,p,v)}(p,h,y,o,l):n(y)?(n(e.text)&&u.setTextContent(p,\"\"),_(p,null,y,0,y.length-1,o)):n(h)?$(h,0,h.length-1):n(e.text)&&u.setTextContent(p,\"\"):e.text!==i.text&&u.setTextContent(p,i.text),n(v)&&n(d=v.hook)&&n(d=d.postpatch)&&d(e,i)}}}function k(e,t,i){if(r(i)&&n(e.parent))e.parent.data.pendingInsert=t;else for(var o=0;o<t.length;++o)t[o].data.hook.insert(t[o])}var A=p(\"attrs,class,staticClass,staticStyle,key\");function O(e,t,i,o){var a,s=t.tag,c=t.data,u=t.children;if(o=o||c&&c.pre,t.elm=e,r(t.isComment)&&n(t.asyncFactory))return t.isAsyncPlaceholder=!0,!0;if(n(c)&&(n(a=c.hook)&&n(a=a.init)&&a(t,!0),n(a=t.componentInstance)))return d(t,i),!0;if(n(s)){if(n(u))if(e.hasChildNodes())if(n(a=c)&&n(a=a.domProps)&&n(a=a.innerHTML)){if(a!==e.innerHTML)return!1}else{for(var l=!0,f=e.firstChild,p=0;p<u.length;p++){if(!f||!O(f,u[p],i,o)){l=!1;break}f=f.nextSibling}if(!l||f)return!1}else h(t,u,i);if(n(c)){var v=!1;for(var m in c)if(!A(m)){v=!0,y(t,i);break}!v&&c.class&&tt(c.class)}}else e.data!==t.text&&(e.data=t.text);return!0}return function(e,i,o,a){if(!t(i)){var c,l=!1,p=[];if(t(e))l=!0,f(i,p);else{var d=n(e.nodeType);if(!d&&or(e,i))x(e,i,p,null,null,a);else{if(d){if(1===e.nodeType&&e.hasAttribute(L)&&(e.removeAttribute(L),o=!0),r(o)&&O(e,i,p))return k(i,p,!0),e;c=e,e=new pe(u.tagName(c).toLowerCase(),{},[],void 0,c)}var v=e.elm,h=u.parentNode(v);if(f(i,p,v._leaveCb?null:h,u.nextSibling(v)),n(i.parent))for(var y=i.parent,g=m(i);y;){for(var _=0;_<s.destroy.length;++_)s.destroy[_](y);if(y.elm=i.elm,g){for(var w=0;w<s.create.length;++w)s.create[w](rr,y);var C=y.data.hook.insert;if(C.merged)for(var A=1;A<C.fns.length;A++)C.fns[A]()}else nr(y);y=y.parent}n(h)?$([e],0,0):n(e.tag)&&b(e)}}return k(i,p,l),i.elm}n(e)&&b(e)}}({nodeOps:er,modules:[yr,kr,ri,ai,yi,V?{create:Vi,activate:Vi,remove:function(e,t){!0!==e.data.show?Hi(e,t):t()}}:{}].concat(dr)});W&&document.addEventListener(\"selectionchange\",function(){var e=document.activeElement;e&&e.vmodel&&Yi(e,\"input\")});var Ki={inserted:function(e,t,n,r){\"select\"===n.tag?(r.elm&&!r.elm._vOptions?ot(n,\"postpatch\",function(){Ki.componentUpdated(e,t,n)}):Ji(e,t,n.context),e._vOptions=[].map.call(e.options,Zi)):(\"textarea\"===n.tag||Yn(e.type))&&(e._vModifiers=t.modifiers,t.modifiers.lazy||(e.addEventListener(\"compositionstart\",Gi),e.addEventListener(\"compositionend\",Xi),e.addEventListener(\"change\",Xi),W&&(e.vmodel=!0)))},componentUpdated:function(e,t,n){if(\"select\"===n.tag){Ji(e,t,n.context);var r=e._vOptions,i=e._vOptions=[].map.call(e.options,Zi);if(i.some(function(e,t){return!E(e,r[t])}))(e.multiple?t.value.some(function(e){return Wi(e,i)}):t.value!==t.oldValue&&Wi(t.value,i))&&Yi(e,\"change\")}}};function Ji(e,t,n){qi(e,t,n),(q||Z)&&setTimeout(function(){qi(e,t,n)},0)}function qi(e,t,n){var r=t.value,i=e.multiple;if(!i||Array.isArray(r)){for(var o,a,s=0,c=e.options.length;s<c;s++)if(a=e.options[s],i)o=j(r,Zi(a))>-1,a.selected!==o&&(a.selected=o);else if(E(Zi(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function Wi(e,t){return t.every(function(t){return!E(t,e)})}function Zi(e){return\"_value\"in e?e._value:e.value}function Gi(e){e.target.composing=!0}function Xi(e){e.target.composing&&(e.target.composing=!1,Yi(e.target,\"input\"))}function Yi(e,t){var n=document.createEvent(\"HTMLEvents\");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function Qi(e){return!e.componentInstance||e.data&&e.data.transition?e:Qi(e.componentInstance._vnode)}var eo={model:Ki,show:{bind:function(e,t,n){var r=t.value,i=(n=Qi(n)).data&&n.data.transition,o=e.__vOriginalDisplay=\"none\"===e.style.display?\"\":e.style.display;r&&i?(n.data.show=!0,Ri(n,function(){e.style.display=o})):e.style.display=r?o:\"none\"},update:function(e,t,n){var r=t.value;!r!=!t.oldValue&&((n=Qi(n)).data&&n.data.transition?(n.data.show=!0,r?Ri(n,function(){e.style.display=e.__vOriginalDisplay}):Hi(n,function(){e.style.display=\"none\"})):e.style.display=r?e.__vOriginalDisplay:\"none\")},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}}},to={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function no(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?no(zt(t.children)):e}function ro(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[b(o)]=i[o];return t}function io(e,t){if(/\\d-keep-alive$/.test(t.tag))return e(\"keep-alive\",{props:t.componentOptions.propsData})}var oo=function(e){return e.tag||pt(e)},ao=function(e){return\"show\"===e.name},so={name:\"transition\",props:to,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(oo)).length){var r=this.mode,o=n[0];if(function(e){for(;e=e.parent;)if(e.data.transition)return!0}(this.$vnode))return o;var a=no(o);if(!a)return o;if(this._leaving)return io(e,o);var s=\"__transition-\"+this._uid+\"-\";a.key=null==a.key?a.isComment?s+\"comment\":s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key;var c=(a.data||(a.data={})).transition=ro(this),u=this._vnode,l=no(u);if(a.data.directives&&a.data.directives.some(ao)&&(a.data.show=!0),l&&l.data&&!function(e,t){return t.key===e.key&&t.tag===e.tag}(a,l)&&!pt(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=A({},c);if(\"out-in\"===r)return this._leaving=!0,ot(f,\"afterLeave\",function(){t._leaving=!1,t.$forceUpdate()}),io(e,o);if(\"in-out\"===r){if(pt(a))return u;var p,d=function(){p()};ot(c,\"afterEnter\",d),ot(c,\"enterCancelled\",d),ot(f,\"delayLeave\",function(e){p=e})}}return o}}},co=A({tag:String,moveClass:String},to);function uo(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function lo(e){e.data.newPos=e.elm.getBoundingClientRect()}function fo(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform=\"translate(\"+r+\"px,\"+i+\"px)\",o.transitionDuration=\"0s\"}}delete co.mode;var po={Transition:so,TransitionGroup:{props:co,beforeMount:function(){var e=this,t=this._update;this._update=function(n,r){var i=Gt(e);e.__patch__(e._vnode,e.kept,!1,!0),e._vnode=e.kept,i(),t.call(e,n,r)}},render:function(e){for(var t=this.tag||this.$vnode.data.tag||\"span\",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=ro(this),s=0;s<i.length;s++){var c=i[s];c.tag&&null!=c.key&&0!==String(c.key).indexOf(\"__vlist\")&&(o.push(c),n[c.key]=c,(c.data||(c.data={})).transition=a)}if(r){for(var u=[],l=[],f=0;f<r.length;f++){var p=r[f];p.data.transition=a,p.data.pos=p.elm.getBoundingClientRect(),n[p.key]?u.push(p):l.push(p)}this.kept=e(t,null,u),this.removed=l}return e(t,null,o)},updated:function(){var e=this.prevChildren,t=this.moveClass||(this.name||\"v\")+\"-move\";e.length&&this.hasMove(e[0].elm,t)&&(e.forEach(uo),e.forEach(lo),e.forEach(fo),this._reflow=document.body.offsetHeight,e.forEach(function(e){if(e.data.moved){var n=e.elm,r=n.style;ji(n,t),r.transform=r.WebkitTransform=r.transitionDuration=\"\",n.addEventListener(Oi,n._moveCb=function e(r){r&&r.target!==n||r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(Oi,e),n._moveCb=null,Di(n,t))})}}))},methods:{hasMove:function(e,t){if(!Ci)return!1;if(this._hasMove)return this._hasMove;var n=e.cloneNode();e._transitionClasses&&e._transitionClasses.forEach(function(e){bi(n,e)}),_i(n,t),n.style.display=\"none\",this.$el.appendChild(n);var r=Mi(n);return this.$el.removeChild(n),this._hasMove=r.hasTransform}}}};Cn.config.mustUseProp=Dn,Cn.config.isReservedTag=Zn,Cn.config.isReservedAttr=En,Cn.config.getTagNamespace=Gn,Cn.config.isUnknownElement=function(e){if(!V)return!0;if(Zn(e))return!1;if(e=e.toLowerCase(),null!=Xn[e])return Xn[e];var t=document.createElement(e);return e.indexOf(\"-\")>-1?Xn[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:Xn[e]=/HTMLUnknownElement/.test(t.toString())},A(Cn.options.directives,eo),A(Cn.options.components,po),Cn.prototype.__patch__=V?zi:S,Cn.prototype.$mount=function(e,t){return function(e,t,n){var r;return e.$el=t,e.$options.render||(e.$options.render=ve),Qt(e,\"beforeMount\"),r=function(){e._update(e._render(),n)},new pn(e,r,S,{before:function(){e._isMounted&&!e._isDestroyed&&Qt(e,\"beforeUpdate\")}},!0),n=!1,null==e.$vnode&&(e._isMounted=!0,Qt(e,\"mounted\")),e}(this,e=e&&V?Qn(e):void 0,t)},V&&setTimeout(function(){F.devtools&&ne&&ne.emit(\"init\",Cn)},0);var vo=/\\{\\{((?:.|\\r?\\n)+?)\\}\\}/g,ho=/[-.*+?^${}()|[\\]\\/\\\\]/g,mo=g(function(e){var t=e[0].replace(ho,\"\\\\$&\"),n=e[1].replace(ho,\"\\\\$&\");return new RegExp(t+\"((?:.|\\\\n)+?)\"+n,\"g\")});var yo={staticKeys:[\"staticClass\"],transformNode:function(e,t){t.warn;var n=Pr(e,\"class\");n&&(e.staticClass=JSON.stringify(n));var r=Fr(e,\"class\",!1);r&&(e.classBinding=r)},genData:function(e){var t=\"\";return e.staticClass&&(t+=\"staticClass:\"+e.staticClass+\",\"),e.classBinding&&(t+=\"class:\"+e.classBinding+\",\"),t}};var go,_o={staticKeys:[\"staticStyle\"],transformNode:function(e,t){t.warn;var n=Pr(e,\"style\");n&&(e.staticStyle=JSON.stringify(si(n)));var r=Fr(e,\"style\",!1);r&&(e.styleBinding=r)},genData:function(e){var t=\"\";return e.staticStyle&&(t+=\"staticStyle:\"+e.staticStyle+\",\"),e.styleBinding&&(t+=\"style:(\"+e.styleBinding+\"),\"),t}},bo=function(e){return(go=go||document.createElement(\"div\")).innerHTML=e,go.textContent},$o=p(\"area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr\"),wo=p(\"colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source\"),Co=p(\"address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track\"),xo=/^\\s*([^\\s\"'<>\\/=]+)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/,ko=/^\\s*((?:v-[\\w-]+:|@|:|#)\\[[^=]+?\\][^\\s\"'<>\\/=]*)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/,Ao=\"[a-zA-Z_][\\\\-\\\\.0-9_a-zA-Z\"+P.source+\"]*\",Oo=\"((?:\"+Ao+\"\\\\:)?\"+Ao+\")\",So=new RegExp(\"^<\"+Oo),To=/^\\s*(\\/?)>/,No=new RegExp(\"^<\\\\/\"+Oo+\"[^>]*>\"),Eo=/^<!DOCTYPE [^>]+>/i,jo=/^<!\\--/,Do=/^<!\\[/,Lo=p(\"script,style,textarea\",!0),Io={},Mo={\"&lt;\":\"<\",\"&gt;\":\">\",\"&quot;\":'\"',\"&amp;\":\"&\",\"&#10;\":\"\\n\",\"&#9;\":\"\\t\",\"&#39;\":\"'\"},Fo=/&(?:lt|gt|quot|amp|#39);/g,Po=/&(?:lt|gt|quot|amp|#39|#10|#9);/g,Ro=p(\"pre,textarea\",!0),Ho=function(e,t){return e&&Ro(e)&&\"\\n\"===t[0]};function Bo(e,t){var n=t?Po:Fo;return e.replace(n,function(e){return Mo[e]})}var Uo,Vo,zo,Ko,Jo,qo,Wo,Zo,Go=/^@|^v-on:/,Xo=/^v-|^@|^:|^#/,Yo=/([\\s\\S]*?)\\s+(?:in|of)\\s+([\\s\\S]*)/,Qo=/,([^,\\}\\]]*)(?:,([^,\\}\\]]*))?$/,ea=/^\\(|\\)$/g,ta=/^\\[.*\\]$/,na=/:(.*)$/,ra=/^:|^\\.|^v-bind:/,ia=/\\.[^.\\]]+(?=[^\\]]*$)/g,oa=/^v-slot(:|$)|^#/,aa=/[\\r\\n]/,sa=/[ \\f\\t\\r\\n]+/g,ca=g(bo),ua=\"_empty_\";function la(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:ya(t),rawAttrsMap:{},parent:n,children:[]}}function fa(e,t){Uo=t.warn||Tr,qo=t.isPreTag||T,Wo=t.mustUseProp||T,Zo=t.getTagNamespace||T;t.isReservedTag;zo=Nr(t.modules,\"transformNode\"),Ko=Nr(t.modules,\"preTransformNode\"),Jo=Nr(t.modules,\"postTransformNode\"),Vo=t.delimiters;var n,r,i=[],o=!1!==t.preserveWhitespace,a=t.whitespace,s=!1,c=!1;function u(e){if(l(e),s||e.processed||(e=pa(e,t)),i.length||e===n||n.if&&(e.elseif||e.else)&&va(n,{exp:e.elseif,block:e}),r&&!e.forbidden)if(e.elseif||e.else)a=e,(u=function(e){var t=e.length;for(;t--;){if(1===e[t].type)return e[t];e.pop()}}(r.children))&&u.if&&va(u,{exp:a.elseif,block:a});else{if(e.slotScope){var o=e.slotTarget||'\"default\"';(r.scopedSlots||(r.scopedSlots={}))[o]=e}r.children.push(e),e.parent=r}var a,u;e.children=e.children.filter(function(e){return!e.slotScope}),l(e),e.pre&&(s=!1),qo(e.tag)&&(c=!1);for(var f=0;f<Jo.length;f++)Jo[f](e,t)}function l(e){if(!c)for(var t;(t=e.children[e.children.length-1])&&3===t.type&&\" \"===t.text;)e.children.pop()}return function(e,t){for(var n,r,i=[],o=t.expectHTML,a=t.isUnaryTag||T,s=t.canBeLeftOpenTag||T,c=0;e;){if(n=e,r&&Lo(r)){var u=0,l=r.toLowerCase(),f=Io[l]||(Io[l]=new RegExp(\"([\\\\s\\\\S]*?)(</\"+l+\"[^>]*>)\",\"i\")),p=e.replace(f,function(e,n,r){return u=r.length,Lo(l)||\"noscript\"===l||(n=n.replace(/<!\\--([\\s\\S]*?)-->/g,\"$1\").replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g,\"$1\")),Ho(l,n)&&(n=n.slice(1)),t.chars&&t.chars(n),\"\"});c+=e.length-p.length,e=p,A(l,c-u,c)}else{var d=e.indexOf(\"<\");if(0===d){if(jo.test(e)){var v=e.indexOf(\"--\\x3e\");if(v>=0){t.shouldKeepComment&&t.comment(e.substring(4,v),c,c+v+3),C(v+3);continue}}if(Do.test(e)){var h=e.indexOf(\"]>\");if(h>=0){C(h+2);continue}}var m=e.match(Eo);if(m){C(m[0].length);continue}var y=e.match(No);if(y){var g=c;C(y[0].length),A(y[1],g,c);continue}var _=x();if(_){k(_),Ho(_.tagName,e)&&C(1);continue}}var b=void 0,$=void 0,w=void 0;if(d>=0){for($=e.slice(d);!(No.test($)||So.test($)||jo.test($)||Do.test($)||(w=$.indexOf(\"<\",1))<0);)d+=w,$=e.slice(d);b=e.substring(0,d)}d<0&&(b=e),b&&C(b.length),t.chars&&b&&t.chars(b,c-b.length,c)}if(e===n){t.chars&&t.chars(e);break}}function C(t){c+=t,e=e.substring(t)}function x(){var t=e.match(So);if(t){var n,r,i={tagName:t[1],attrs:[],start:c};for(C(t[0].length);!(n=e.match(To))&&(r=e.match(ko)||e.match(xo));)r.start=c,C(r[0].length),r.end=c,i.attrs.push(r);if(n)return i.unarySlash=n[1],C(n[0].length),i.end=c,i}}function k(e){var n=e.tagName,c=e.unarySlash;o&&(\"p\"===r&&Co(n)&&A(r),s(n)&&r===n&&A(n));for(var u=a(n)||!!c,l=e.attrs.length,f=new Array(l),p=0;p<l;p++){var d=e.attrs[p],v=d[3]||d[4]||d[5]||\"\",h=\"a\"===n&&\"href\"===d[1]?t.shouldDecodeNewlinesForHref:t.shouldDecodeNewlines;f[p]={name:d[1],value:Bo(v,h)}}u||(i.push({tag:n,lowerCasedTag:n.toLowerCase(),attrs:f,start:e.start,end:e.end}),r=n),t.start&&t.start(n,f,u,e.start,e.end)}function A(e,n,o){var a,s;if(null==n&&(n=c),null==o&&(o=c),e)for(s=e.toLowerCase(),a=i.length-1;a>=0&&i[a].lowerCasedTag!==s;a--);else a=0;if(a>=0){for(var u=i.length-1;u>=a;u--)t.end&&t.end(i[u].tag,n,o);i.length=a,r=a&&i[a-1].tag}else\"br\"===s?t.start&&t.start(e,[],!0,n,o):\"p\"===s&&(t.start&&t.start(e,[],!1,n,o),t.end&&t.end(e,n,o))}A()}(e,{warn:Uo,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,canBeLeftOpenTag:t.canBeLeftOpenTag,shouldDecodeNewlines:t.shouldDecodeNewlines,shouldDecodeNewlinesForHref:t.shouldDecodeNewlinesForHref,shouldKeepComment:t.comments,outputSourceRange:t.outputSourceRange,start:function(e,o,a,l,f){var p=r&&r.ns||Zo(e);q&&\"svg\"===p&&(o=function(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];ga.test(r.name)||(r.name=r.name.replace(_a,\"\"),t.push(r))}return t}(o));var d,v=la(e,o,r);p&&(v.ns=p),\"style\"!==(d=v).tag&&(\"script\"!==d.tag||d.attrsMap.type&&\"text/javascript\"!==d.attrsMap.type)||te()||(v.forbidden=!0);for(var h=0;h<Ko.length;h++)v=Ko[h](v,t)||v;s||(!function(e){null!=Pr(e,\"v-pre\")&&(e.pre=!0)}(v),v.pre&&(s=!0)),qo(v.tag)&&(c=!0),s?function(e){var t=e.attrsList,n=t.length;if(n)for(var r=e.attrs=new Array(n),i=0;i<n;i++)r[i]={name:t[i].name,value:JSON.stringify(t[i].value)},null!=t[i].start&&(r[i].start=t[i].start,r[i].end=t[i].end);else e.pre||(e.plain=!0)}(v):v.processed||(da(v),function(e){var t=Pr(e,\"v-if\");if(t)e.if=t,va(e,{exp:t,block:e});else{null!=Pr(e,\"v-else\")&&(e.else=!0);var n=Pr(e,\"v-else-if\");n&&(e.elseif=n)}}(v),function(e){null!=Pr(e,\"v-once\")&&(e.once=!0)}(v)),n||(n=v),a?u(v):(r=v,i.push(v))},end:function(e,t,n){var o=i[i.length-1];i.length-=1,r=i[i.length-1],u(o)},chars:function(e,t,n){if(r&&(!q||\"textarea\"!==r.tag||r.attrsMap.placeholder!==e)){var i,u,l,f=r.children;if(e=c||e.trim()?\"script\"===(i=r).tag||\"style\"===i.tag?e:ca(e):f.length?a?\"condense\"===a&&aa.test(e)?\"\":\" \":o?\" \":\"\":\"\")c||\"condense\"!==a||(e=e.replace(sa,\" \")),!s&&\" \"!==e&&(u=function(e,t){var n=t?mo(t):vo;if(n.test(e)){for(var r,i,o,a=[],s=[],c=n.lastIndex=0;r=n.exec(e);){(i=r.index)>c&&(s.push(o=e.slice(c,i)),a.push(JSON.stringify(o)));var u=Or(r[1].trim());a.push(\"_s(\"+u+\")\"),s.push({\"@binding\":u}),c=i+r[0].length}return c<e.length&&(s.push(o=e.slice(c)),a.push(JSON.stringify(o))),{expression:a.join(\"+\"),tokens:s}}}(e,Vo))?l={type:2,expression:u.expression,tokens:u.tokens,text:e}:\" \"===e&&f.length&&\" \"===f[f.length-1].text||(l={type:3,text:e}),l&&f.push(l)}},comment:function(e,t,n){if(r){var i={type:3,text:e,isComment:!0};r.children.push(i)}}}),n}function pa(e,t){var n,r;(r=Fr(n=e,\"key\"))&&(n.key=r),e.plain=!e.key&&!e.scopedSlots&&!e.attrsList.length,function(e){var t=Fr(e,\"ref\");t&&(e.ref=t,e.refInFor=function(e){var t=e;for(;t;){if(void 0!==t.for)return!0;t=t.parent}return!1}(e))}(e),function(e){var t;\"template\"===e.tag?(t=Pr(e,\"scope\"),e.slotScope=t||Pr(e,\"slot-scope\")):(t=Pr(e,\"slot-scope\"))&&(e.slotScope=t);var n=Fr(e,\"slot\");n&&(e.slotTarget='\"\"'===n?'\"default\"':n,e.slotTargetDynamic=!(!e.attrsMap[\":slot\"]&&!e.attrsMap[\"v-bind:slot\"]),\"template\"===e.tag||e.slotScope||jr(e,\"slot\",n,function(e,t){return e.rawAttrsMap[\":\"+t]||e.rawAttrsMap[\"v-bind:\"+t]||e.rawAttrsMap[t]}(e,\"slot\")));if(\"template\"===e.tag){var r=Rr(e,oa);if(r){var i=ha(r),o=i.name,a=i.dynamic;e.slotTarget=o,e.slotTargetDynamic=a,e.slotScope=r.value||ua}}else{var s=Rr(e,oa);if(s){var c=e.scopedSlots||(e.scopedSlots={}),u=ha(s),l=u.name,f=u.dynamic,p=c[l]=la(\"template\",[],e);p.slotTarget=l,p.slotTargetDynamic=f,p.children=e.children.filter(function(e){if(!e.slotScope)return e.parent=p,!0}),p.slotScope=s.value||ua,e.children=[],e.plain=!1}}}(e),function(e){\"slot\"===e.tag&&(e.slotName=Fr(e,\"name\"))}(e),function(e){var t;(t=Fr(e,\"is\"))&&(e.component=t);null!=Pr(e,\"inline-template\")&&(e.inlineTemplate=!0)}(e);for(var i=0;i<zo.length;i++)e=zo[i](e,t)||e;return function(e){var t,n,r,i,o,a,s,c,u=e.attrsList;for(t=0,n=u.length;t<n;t++)if(r=i=u[t].name,o=u[t].value,Xo.test(r))if(e.hasBindings=!0,(a=ma(r.replace(Xo,\"\")))&&(r=r.replace(ia,\"\")),ra.test(r))r=r.replace(ra,\"\"),o=Or(o),(c=ta.test(r))&&(r=r.slice(1,-1)),a&&(a.prop&&!c&&\"innerHtml\"===(r=b(r))&&(r=\"innerHTML\"),a.camel&&!c&&(r=b(r)),a.sync&&(s=Ur(o,\"$event\"),c?Mr(e,'\"update:\"+('+r+\")\",s,null,!1,0,u[t],!0):(Mr(e,\"update:\"+b(r),s,null,!1,0,u[t]),C(r)!==b(r)&&Mr(e,\"update:\"+C(r),s,null,!1,0,u[t])))),a&&a.prop||!e.component&&Wo(e.tag,e.attrsMap.type,r)?Er(e,r,o,u[t],c):jr(e,r,o,u[t],c);else if(Go.test(r))r=r.replace(Go,\"\"),(c=ta.test(r))&&(r=r.slice(1,-1)),Mr(e,r,o,a,!1,0,u[t],c);else{var l=(r=r.replace(Xo,\"\")).match(na),f=l&&l[1];c=!1,f&&(r=r.slice(0,-(f.length+1)),ta.test(f)&&(f=f.slice(1,-1),c=!0)),Lr(e,r,i,o,f,c,a,u[t])}else jr(e,r,JSON.stringify(o),u[t]),!e.component&&\"muted\"===r&&Wo(e.tag,e.attrsMap.type,r)&&Er(e,r,\"true\",u[t])}(e),e}function da(e){var t;if(t=Pr(e,\"v-for\")){var n=function(e){var t=e.match(Yo);if(!t)return;var n={};n.for=t[2].trim();var r=t[1].trim().replace(ea,\"\"),i=r.match(Qo);i?(n.alias=r.replace(Qo,\"\").trim(),n.iterator1=i[1].trim(),i[2]&&(n.iterator2=i[2].trim())):n.alias=r;return n}(t);n&&A(e,n)}}function va(e,t){e.ifConditions||(e.ifConditions=[]),e.ifConditions.push(t)}function ha(e){var t=e.name.replace(oa,\"\");return t||\"#\"!==e.name[0]&&(t=\"default\"),ta.test(t)?{name:t.slice(1,-1),dynamic:!0}:{name:'\"'+t+'\"',dynamic:!1}}function ma(e){var t=e.match(ia);if(t){var n={};return t.forEach(function(e){n[e.slice(1)]=!0}),n}}function ya(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n].name]=e[n].value;return t}var ga=/^xmlns:NS\\d+/,_a=/^NS\\d+:/;function ba(e){return la(e.tag,e.attrsList.slice(),e.parent)}var $a=[yo,_o,{preTransformNode:function(e,t){if(\"input\"===e.tag){var n,r=e.attrsMap;if(!r[\"v-model\"])return;if((r[\":type\"]||r[\"v-bind:type\"])&&(n=Fr(e,\"type\")),r.type||n||!r[\"v-bind\"]||(n=\"(\"+r[\"v-bind\"]+\").type\"),n){var i=Pr(e,\"v-if\",!0),o=i?\"&&(\"+i+\")\":\"\",a=null!=Pr(e,\"v-else\",!0),s=Pr(e,\"v-else-if\",!0),c=ba(e);da(c),Dr(c,\"type\",\"checkbox\"),pa(c,t),c.processed=!0,c.if=\"(\"+n+\")==='checkbox'\"+o,va(c,{exp:c.if,block:c});var u=ba(e);Pr(u,\"v-for\",!0),Dr(u,\"type\",\"radio\"),pa(u,t),va(c,{exp:\"(\"+n+\")==='radio'\"+o,block:u});var l=ba(e);return Pr(l,\"v-for\",!0),Dr(l,\":type\",n),pa(l,t),va(c,{exp:i,block:l}),a?c.else=!0:s&&(c.elseif=s),c}}}}];var wa,Ca,xa={expectHTML:!0,modules:$a,directives:{model:function(e,t,n){var r=t.value,i=t.modifiers,o=e.tag,a=e.attrsMap.type;if(e.component)return Br(e,r,i),!1;if(\"select\"===o)!function(e,t,n){var r='var $$selectedVal = Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = \"_value\" in o ? o._value : o.value;return '+(n&&n.number?\"_n(val)\":\"val\")+\"});\";r=r+\" \"+Ur(t,\"$event.target.multiple ? $$selectedVal : $$selectedVal[0]\"),Mr(e,\"change\",r,null,!0)}(e,r,i);else if(\"input\"===o&&\"checkbox\"===a)!function(e,t,n){var r=n&&n.number,i=Fr(e,\"value\")||\"null\",o=Fr(e,\"true-value\")||\"true\",a=Fr(e,\"false-value\")||\"false\";Er(e,\"checked\",\"Array.isArray(\"+t+\")?_i(\"+t+\",\"+i+\")>-1\"+(\"true\"===o?\":(\"+t+\")\":\":_q(\"+t+\",\"+o+\")\")),Mr(e,\"change\",\"var $$a=\"+t+\",$$el=$event.target,$$c=$$el.checked?(\"+o+\"):(\"+a+\");if(Array.isArray($$a)){var $$v=\"+(r?\"_n(\"+i+\")\":i)+\",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&(\"+Ur(t,\"$$a.concat([$$v])\")+\")}else{$$i>-1&&(\"+Ur(t,\"$$a.slice(0,$$i).concat($$a.slice($$i+1))\")+\")}}else{\"+Ur(t,\"$$c\")+\"}\",null,!0)}(e,r,i);else if(\"input\"===o&&\"radio\"===a)!function(e,t,n){var r=n&&n.number,i=Fr(e,\"value\")||\"null\";Er(e,\"checked\",\"_q(\"+t+\",\"+(i=r?\"_n(\"+i+\")\":i)+\")\"),Mr(e,\"change\",Ur(t,i),null,!0)}(e,r,i);else if(\"input\"===o||\"textarea\"===o)!function(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&\"range\"!==r,u=o?\"change\":\"range\"===r?Zr:\"input\",l=\"$event.target.value\";s&&(l=\"$event.target.value.trim()\"),a&&(l=\"_n(\"+l+\")\");var f=Ur(t,l);c&&(f=\"if($event.target.composing)return;\"+f),Er(e,\"value\",\"(\"+t+\")\"),Mr(e,u,f,null,!0),(s||a)&&Mr(e,\"blur\",\"$forceUpdate()\")}(e,r,i);else if(!F.isReservedTag(o))return Br(e,r,i),!1;return!0},text:function(e,t){t.value&&Er(e,\"textContent\",\"_s(\"+t.value+\")\",t)},html:function(e,t){t.value&&Er(e,\"innerHTML\",\"_s(\"+t.value+\")\",t)}},isPreTag:function(e){return\"pre\"===e},isUnaryTag:$o,mustUseProp:Dn,canBeLeftOpenTag:wo,isReservedTag:Zn,getTagNamespace:Gn,staticKeys:function(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(\",\")}($a)},ka=g(function(e){return p(\"type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap\"+(e?\",\"+e:\"\"))});function Aa(e,t){e&&(wa=ka(t.staticKeys||\"\"),Ca=t.isReservedTag||T,function e(t){t.static=function(e){if(2===e.type)return!1;if(3===e.type)return!0;return!(!e.pre&&(e.hasBindings||e.if||e.for||d(e.tag)||!Ca(e.tag)||function(e){for(;e.parent;){if(\"template\"!==(e=e.parent).tag)return!1;if(e.for)return!0}return!1}(e)||!Object.keys(e).every(wa)))}(t);if(1===t.type){if(!Ca(t.tag)&&\"slot\"!==t.tag&&null==t.attrsMap[\"inline-template\"])return;for(var n=0,r=t.children.length;n<r;n++){var i=t.children[n];e(i),i.static||(t.static=!1)}if(t.ifConditions)for(var o=1,a=t.ifConditions.length;o<a;o++){var s=t.ifConditions[o].block;e(s),s.static||(t.static=!1)}}}(e),function e(t,n){if(1===t.type){if((t.static||t.once)&&(t.staticInFor=n),t.static&&t.children.length&&(1!==t.children.length||3!==t.children[0].type))return void(t.staticRoot=!0);if(t.staticRoot=!1,t.children)for(var r=0,i=t.children.length;r<i;r++)e(t.children[r],n||!!t.for);if(t.ifConditions)for(var o=1,a=t.ifConditions.length;o<a;o++)e(t.ifConditions[o].block,n)}}(e,!1))}var Oa=/^([\\w$_]+|\\([^)]*?\\))\\s*=>|^function(?:\\s+[\\w$]+)?\\s*\\(/,Sa=/\\([^)]*?\\);*$/,Ta=/^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*|\\['[^']*?']|\\[\"[^\"]*?\"]|\\[\\d+]|\\[[A-Za-z_$][\\w$]*])*$/,Na={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},Ea={esc:[\"Esc\",\"Escape\"],tab:\"Tab\",enter:\"Enter\",space:[\" \",\"Spacebar\"],up:[\"Up\",\"ArrowUp\"],left:[\"Left\",\"ArrowLeft\"],right:[\"Right\",\"ArrowRight\"],down:[\"Down\",\"ArrowDown\"],delete:[\"Backspace\",\"Delete\",\"Del\"]},ja=function(e){return\"if(\"+e+\")return null;\"},Da={stop:\"$event.stopPropagation();\",prevent:\"$event.preventDefault();\",self:ja(\"$event.target !== $event.currentTarget\"),ctrl:ja(\"!$event.ctrlKey\"),shift:ja(\"!$event.shiftKey\"),alt:ja(\"!$event.altKey\"),meta:ja(\"!$event.metaKey\"),left:ja(\"'button' in $event && $event.button !== 0\"),middle:ja(\"'button' in $event && $event.button !== 1\"),right:ja(\"'button' in $event && $event.button !== 2\")};function La(e,t){var n=t?\"nativeOn:\":\"on:\",r=\"\",i=\"\";for(var o in e){var a=Ia(e[o]);e[o]&&e[o].dynamic?i+=o+\",\"+a+\",\":r+='\"'+o+'\":'+a+\",\"}return r=\"{\"+r.slice(0,-1)+\"}\",i?n+\"_d(\"+r+\",[\"+i.slice(0,-1)+\"])\":n+r}function Ia(e){if(!e)return\"function(){}\";if(Array.isArray(e))return\"[\"+e.map(function(e){return Ia(e)}).join(\",\")+\"]\";var t=Ta.test(e.value),n=Oa.test(e.value),r=Ta.test(e.value.replace(Sa,\"\"));if(e.modifiers){var i=\"\",o=\"\",a=[];for(var s in e.modifiers)if(Da[s])o+=Da[s],Na[s]&&a.push(s);else if(\"exact\"===s){var c=e.modifiers;o+=ja([\"ctrl\",\"shift\",\"alt\",\"meta\"].filter(function(e){return!c[e]}).map(function(e){return\"$event.\"+e+\"Key\"}).join(\"||\"))}else a.push(s);return a.length&&(i+=function(e){return\"if(!$event.type.indexOf('key')&&\"+e.map(Ma).join(\"&&\")+\")return null;\"}(a)),o&&(i+=o),\"function($event){\"+i+(t?\"return \"+e.value+\".apply(null, arguments)\":n?\"return (\"+e.value+\").apply(null, arguments)\":r?\"return \"+e.value:e.value)+\"}\"}return t||n?e.value:\"function($event){\"+(r?\"return \"+e.value:e.value)+\"}\"}function Ma(e){var t=parseInt(e,10);if(t)return\"$event.keyCode!==\"+t;var n=Na[e],r=Ea[e];return\"_k($event.keyCode,\"+JSON.stringify(e)+\",\"+JSON.stringify(n)+\",$event.key,\"+JSON.stringify(r)+\")\"}var Fa={on:function(e,t){e.wrapListeners=function(e){return\"_g(\"+e+\",\"+t.value+\")\"}},bind:function(e,t){e.wrapData=function(n){return\"_b(\"+n+\",'\"+e.tag+\"',\"+t.value+\",\"+(t.modifiers&&t.modifiers.prop?\"true\":\"false\")+(t.modifiers&&t.modifiers.sync?\",true\":\"\")+\")\"}},cloak:S},Pa=function(e){this.options=e,this.warn=e.warn||Tr,this.transforms=Nr(e.modules,\"transformCode\"),this.dataGenFns=Nr(e.modules,\"genData\"),this.directives=A(A({},Fa),e.directives);var t=e.isReservedTag||T;this.maybeComponent=function(e){return!!e.component||!t(e.tag)},this.onceId=0,this.staticRenderFns=[],this.pre=!1};function Ra(e,t){var n=new Pa(t);return{render:\"with(this){return \"+(e?\"script\"===e.tag?\"null\":Ha(e,n):'_c(\"div\")')+\"}\",staticRenderFns:n.staticRenderFns}}function Ha(e,t){if(e.parent&&(e.pre=e.pre||e.parent.pre),e.staticRoot&&!e.staticProcessed)return Ba(e,t);if(e.once&&!e.onceProcessed)return Ua(e,t);if(e.for&&!e.forProcessed)return za(e,t);if(e.if&&!e.ifProcessed)return Va(e,t);if(\"template\"!==e.tag||e.slotTarget||t.pre){if(\"slot\"===e.tag)return function(e,t){var n=e.slotName||'\"default\"',r=Wa(e,t),i=\"_t(\"+n+(r?\",function(){return \"+r+\"}\":\"\"),o=e.attrs||e.dynamicAttrs?Xa((e.attrs||[]).concat(e.dynamicAttrs||[]).map(function(e){return{name:b(e.name),value:e.value,dynamic:e.dynamic}})):null,a=e.attrsMap[\"v-bind\"];!o&&!a||r||(i+=\",null\");o&&(i+=\",\"+o);a&&(i+=(o?\"\":\",null\")+\",\"+a);return i+\")\"}(e,t);var n;if(e.component)n=function(e,t,n){var r=t.inlineTemplate?null:Wa(t,n,!0);return\"_c(\"+e+\",\"+Ka(t,n)+(r?\",\"+r:\"\")+\")\"}(e.component,e,t);else{var r;(!e.plain||e.pre&&t.maybeComponent(e))&&(r=Ka(e,t));var i=e.inlineTemplate?null:Wa(e,t,!0);n=\"_c('\"+e.tag+\"'\"+(r?\",\"+r:\"\")+(i?\",\"+i:\"\")+\")\"}for(var o=0;o<t.transforms.length;o++)n=t.transforms[o](e,n);return n}return Wa(e,t)||\"void 0\"}function Ba(e,t){e.staticProcessed=!0;var n=t.pre;return e.pre&&(t.pre=e.pre),t.staticRenderFns.push(\"with(this){return \"+Ha(e,t)+\"}\"),t.pre=n,\"_m(\"+(t.staticRenderFns.length-1)+(e.staticInFor?\",true\":\"\")+\")\"}function Ua(e,t){if(e.onceProcessed=!0,e.if&&!e.ifProcessed)return Va(e,t);if(e.staticInFor){for(var n=\"\",r=e.parent;r;){if(r.for){n=r.key;break}r=r.parent}return n?\"_o(\"+Ha(e,t)+\",\"+t.onceId+++\",\"+n+\")\":Ha(e,t)}return Ba(e,t)}function Va(e,t,n,r){return e.ifProcessed=!0,function e(t,n,r,i){if(!t.length)return i||\"_e()\";var o=t.shift();return o.exp?\"(\"+o.exp+\")?\"+a(o.block)+\":\"+e(t,n,r,i):\"\"+a(o.block);function a(e){return r?r(e,n):e.once?Ua(e,n):Ha(e,n)}}(e.ifConditions.slice(),t,n,r)}function za(e,t,n,r){var i=e.for,o=e.alias,a=e.iterator1?\",\"+e.iterator1:\"\",s=e.iterator2?\",\"+e.iterator2:\"\";return e.forProcessed=!0,(r||\"_l\")+\"((\"+i+\"),function(\"+o+a+s+\"){return \"+(n||Ha)(e,t)+\"})\"}function Ka(e,t){var n=\"{\",r=function(e,t){var n=e.directives;if(!n)return;var r,i,o,a,s=\"directives:[\",c=!1;for(r=0,i=n.length;r<i;r++){o=n[r],a=!0;var u=t.directives[o.name];u&&(a=!!u(e,o,t.warn)),a&&(c=!0,s+='{name:\"'+o.name+'\",rawName:\"'+o.rawName+'\"'+(o.value?\",value:(\"+o.value+\"),expression:\"+JSON.stringify(o.value):\"\")+(o.arg?\",arg:\"+(o.isDynamicArg?o.arg:'\"'+o.arg+'\"'):\"\")+(o.modifiers?\",modifiers:\"+JSON.stringify(o.modifiers):\"\")+\"},\")}if(c)return s.slice(0,-1)+\"]\"}(e,t);r&&(n+=r+\",\"),e.key&&(n+=\"key:\"+e.key+\",\"),e.ref&&(n+=\"ref:\"+e.ref+\",\"),e.refInFor&&(n+=\"refInFor:true,\"),e.pre&&(n+=\"pre:true,\"),e.component&&(n+='tag:\"'+e.tag+'\",');for(var i=0;i<t.dataGenFns.length;i++)n+=t.dataGenFns[i](e);if(e.attrs&&(n+=\"attrs:\"+Xa(e.attrs)+\",\"),e.props&&(n+=\"domProps:\"+Xa(e.props)+\",\"),e.events&&(n+=La(e.events,!1)+\",\"),e.nativeEvents&&(n+=La(e.nativeEvents,!0)+\",\"),e.slotTarget&&!e.slotScope&&(n+=\"slot:\"+e.slotTarget+\",\"),e.scopedSlots&&(n+=function(e,t,n){var r=e.for||Object.keys(t).some(function(e){var n=t[e];return n.slotTargetDynamic||n.if||n.for||Ja(n)}),i=!!e.if;if(!r)for(var o=e.parent;o;){if(o.slotScope&&o.slotScope!==ua||o.for){r=!0;break}o.if&&(i=!0),o=o.parent}var a=Object.keys(t).map(function(e){return qa(t[e],n)}).join(\",\");return\"scopedSlots:_u([\"+a+\"]\"+(r?\",null,true\":\"\")+(!r&&i?\",null,false,\"+function(e){var t=5381,n=e.length;for(;n;)t=33*t^e.charCodeAt(--n);return t>>>0}(a):\"\")+\")\"}(e,e.scopedSlots,t)+\",\"),e.model&&(n+=\"model:{value:\"+e.model.value+\",callback:\"+e.model.callback+\",expression:\"+e.model.expression+\"},\"),e.inlineTemplate){var o=function(e,t){var n=e.children[0];if(n&&1===n.type){var r=Ra(n,t.options);return\"inlineTemplate:{render:function(){\"+r.render+\"},staticRenderFns:[\"+r.staticRenderFns.map(function(e){return\"function(){\"+e+\"}\"}).join(\",\")+\"]}\"}}(e,t);o&&(n+=o+\",\")}return n=n.replace(/,$/,\"\")+\"}\",e.dynamicAttrs&&(n=\"_b(\"+n+',\"'+e.tag+'\",'+Xa(e.dynamicAttrs)+\")\"),e.wrapData&&(n=e.wrapData(n)),e.wrapListeners&&(n=e.wrapListeners(n)),n}function Ja(e){return 1===e.type&&(\"slot\"===e.tag||e.children.some(Ja))}function qa(e,t){var n=e.attrsMap[\"slot-scope\"];if(e.if&&!e.ifProcessed&&!n)return Va(e,t,qa,\"null\");if(e.for&&!e.forProcessed)return za(e,t,qa);var r=e.slotScope===ua?\"\":String(e.slotScope),i=\"function(\"+r+\"){return \"+(\"template\"===e.tag?e.if&&n?\"(\"+e.if+\")?\"+(Wa(e,t)||\"undefined\")+\":undefined\":Wa(e,t)||\"undefined\":Ha(e,t))+\"}\",o=r?\"\":\",proxy:true\";return\"{key:\"+(e.slotTarget||'\"default\"')+\",fn:\"+i+o+\"}\"}function Wa(e,t,n,r,i){var o=e.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&\"template\"!==a.tag&&\"slot\"!==a.tag){var s=n?t.maybeComponent(a)?\",1\":\",0\":\"\";return\"\"+(r||Ha)(a,t)+s}var c=n?function(e,t){for(var n=0,r=0;r<e.length;r++){var i=e[r];if(1===i.type){if(Za(i)||i.ifConditions&&i.ifConditions.some(function(e){return Za(e.block)})){n=2;break}(t(i)||i.ifConditions&&i.ifConditions.some(function(e){return t(e.block)}))&&(n=1)}}return n}(o,t.maybeComponent):0,u=i||Ga;return\"[\"+o.map(function(e){return u(e,t)}).join(\",\")+\"]\"+(c?\",\"+c:\"\")}}function Za(e){return void 0!==e.for||\"template\"===e.tag||\"slot\"===e.tag}function Ga(e,t){return 1===e.type?Ha(e,t):3===e.type&&e.isComment?(r=e,\"_e(\"+JSON.stringify(r.text)+\")\"):\"_v(\"+(2===(n=e).type?n.expression:Ya(JSON.stringify(n.text)))+\")\";var n,r}function Xa(e){for(var t=\"\",n=\"\",r=0;r<e.length;r++){var i=e[r],o=Ya(i.value);i.dynamic?n+=i.name+\",\"+o+\",\":t+='\"'+i.name+'\":'+o+\",\"}return t=\"{\"+t.slice(0,-1)+\"}\",n?\"_d(\"+t+\",[\"+n.slice(0,-1)+\"])\":t}function Ya(e){return e.replace(/\\u2028/g,\"\\\\u2028\").replace(/\\u2029/g,\"\\\\u2029\")}new RegExp(\"\\\\b\"+\"do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments\".split(\",\").join(\"\\\\b|\\\\b\")+\"\\\\b\");function Qa(e,t){try{return new Function(e)}catch(n){return t.push({err:n,code:e}),S}}function es(e){var t=Object.create(null);return function(n,r,i){(r=A({},r)).warn;delete r.warn;var o=r.delimiters?String(r.delimiters)+n:n;if(t[o])return t[o];var a=e(n,r),s={},c=[];return s.render=Qa(a.render,c),s.staticRenderFns=a.staticRenderFns.map(function(e){return Qa(e,c)}),t[o]=s}}var ts,ns,rs=(ts=function(e,t){var n=fa(e.trim(),t);!1!==t.optimize&&Aa(n,t);var r=Ra(n,t);return{ast:n,render:r.render,staticRenderFns:r.staticRenderFns}},function(e){function t(t,n){var r=Object.create(e),i=[],o=[];if(n)for(var a in n.modules&&(r.modules=(e.modules||[]).concat(n.modules)),n.directives&&(r.directives=A(Object.create(e.directives||null),n.directives)),n)\"modules\"!==a&&\"directives\"!==a&&(r[a]=n[a]);r.warn=function(e,t,n){(n?o:i).push(e)};var s=ts(t.trim(),r);return s.errors=i,s.tips=o,s}return{compile:t,compileToFunctions:es(t)}})(xa),is=(rs.compile,rs.compileToFunctions);function os(e){return(ns=ns||document.createElement(\"div\")).innerHTML=e?'<a href=\"\\n\"/>':'<div a=\"\\n\"/>',ns.innerHTML.indexOf(\"&#10;\")>0}var as=!!V&&os(!1),ss=!!V&&os(!0),cs=g(function(e){var t=Qn(e);return t&&t.innerHTML}),us=Cn.prototype.$mount;return Cn.prototype.$mount=function(e,t){if((e=e&&Qn(e))===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if(\"string\"==typeof r)\"#\"===r.charAt(0)&&(r=cs(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=function(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement(\"div\");return t.appendChild(e.cloneNode(!0)),t.innerHTML}(e));if(r){var i=is(r,{outputSourceRange:!1,shouldDecodeNewlines:as,shouldDecodeNewlinesForHref:ss,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return us.call(this,e,t)},Cn.compile=is,Cn});"
  },
  {
    "path": "src/renderer/main/app.js",
    "content": "import { app } from \"./vueapp.js\";\nimport { CiderCache } from \"./cidercache.js\";\nimport { CiderFrontAPI } from \"./ciderfrontapi.js\";\nimport { simulateGamepad } from \"./gamepad.js\";\nimport { CiderAudio } from \"../audio/cideraudio.js\";\nimport { Events } from \"./events.js\";\nimport { wsapi } from \"./wsapi_interop.js\";\nimport { MusicKitTools } from \"./musickittools.js\";\nimport { spawnMica } from \"./mica.js\";\nimport { svgIcon } from \"./components/svg-icon.js\";\nimport { sidebarLibraryItem } from \"./components/sidebar-library-item.js\";\nimport { i18nEditor } from \"./components/i18n-editor.js\";\n\n// Define window objects\nwindow.app = app;\nwindow.MusicKitTools = MusicKitTools;\nwindow.CiderAudio = CiderAudio;\nwindow.CiderCache = CiderCache;\nwindow.CiderFrontAPI = CiderFrontAPI;\nwindow.wsapi = wsapi;\n\nif (app.cfg.advanced.disableLogging === true) {\n  window.console = {\n    log: function () {},\n    error: function () {},\n    warn: function () {},\n    assert: function () {},\n    debug: function () {},\n  };\n}\n\n// Mount Vue to #app\napp.$mount(\"#app\");\n\n// Init CiderAudio and force audiocontext\nif (app.cfg.advanced.AudioContext != true) {\n  app.cfg.advanced.AudioContext = true;\n  window.location.reload();\n}\n\nCiderAudio.init();\n\n// Import gamepad support\napp.simulateGamepad = simulateGamepad;\napp.spawnMica = spawnMica;\n\nEvents.InitEvents();\n"
  },
  {
    "path": "src/renderer/main/cidercache.js",
    "content": "const CiderCache = {\n  async getCache(file) {\n    let cache = await ipcRenderer.sendSync(\"get-cache\", file);\n    if (isJson(cache)) {\n      cache = JSON.parse(cache);\n      if (Object.keys(cache).length === 0) {\n        cache = false;\n      }\n    } else {\n      cache = false;\n    }\n    return cache;\n  },\n  async putCache(file, data) {\n    console.log(`Caching ${file}`);\n    ipcRenderer.invoke(\"put-cache\", {\n      file: file,\n      data: JSON.stringify(data),\n    });\n    return true;\n  },\n};\n\nexport { CiderCache };\n"
  },
  {
    "path": "src/renderer/main/ciderfrontapi.js",
    "content": "const CiderFrontAPI = {\n  Objects: {\n    MenuEntry: function () {\n      this.id = \"\";\n      this.name = \"\";\n      this.onClick = () => {};\n      this.top = false;\n    },\n  },\n  AddMenuEntry(entry) {\n    if (entry?.top) {\n      app.pluginMenuTopEntries.push(entry);\n    } else {\n      app.pluginMenuEntries.push(entry);\n    }\n    app.pluginInstalled = true;\n  },\n  StyleSheets: {\n    Add(href) {\n      console.log(\"Adding stylesheet: \" + href);\n      let id = uuidv4();\n      let link = document.createElement(\"link\");\n      link.rel = \"stylesheet/less\";\n      link.type = \"text/css\";\n      link.href = href;\n      link.setAttribute(\"css-id\", id);\n      // insert the link before document.querySelector(\"#userTheme\") in head\n      document.querySelector(\"head\").insertBefore(link, document.querySelector(\"#userTheme\"));\n      less.registerStylesheetsImmediately();\n      less.refresh(true, true, true);\n      return link;\n    },\n  },\n};\n\nexport { CiderFrontAPI };\n"
  },
  {
    "path": "src/renderer/main/components/i18n-editor.js",
    "content": "import { html } from \"../html.js\";\n\nexport const i18nEditor = Vue.component(\"i18n-editor\", {\n  // language=HTML\n  template: html`\n    <div class=\"content-inner i18n-page\">\n      <div class=\"row nopadding\">\n        <div class=\"col nopadding\">\n          <h1>i18n Editor</h1>\n        </div>\n        <div class=\"col-auto nopadding selectCol\">\n          <select class=\"md-select\" @change=\"$root.setLz('');$root.setLzManual()\" v-model=\"$root.cfg.general.language\">\n            <optgroup :label=\"index\" v-for=\"(categories, index) in getLanguages()\">\n              <option v-for=\"lang in categories\" :value=\"lang.code\">{{lang.nameNative}} ({{lang.nameEnglish }})</option>\n            </optgroup>\n          </select>\n          <button class=\"md-btn\" @click=\"exportLz\">Export</button>\n        </div>\n      </div>\n      <hr />\n      <div class=\"md-option-container\">\n        <template v-for=\"(val, key) in baseLz\">\n          <div class=\"md-option-line\" v-if=\"$root.lz[key]\">\n            <div class=\"md-option-segment\">{{ key }}</div>\n            <div class=\"md-option-segment\">\n              <template v-if='typeof $root.lz[key] == \"object\"'>\n                <div v-for=\"(variant, vkey) in $root.lz[key]\">\n                  {{variant}}\n                  <input type=\"text\" v-model=\"$root.lz[key][vkey]\" />\n                </div>\n              </template>\n              <textarea type=\"text\" v-model=\"$root.lz[key]\" v-else></textarea>\n            </div>\n          </div>\n          <div class=\"md-option-line\" v-else>\n            <div class=\"md-option-segment\">\n              <b>{{ key }}</b>\n            </div>\n            <div class=\"md-option-segment\">\n              <textarea type=\"text\" v-model=\"$root.lz[key]\" :placeholder=\"val\"></textarea>\n            </div>\n          </div>\n        </template>\n      </div>\n    </div>\n  `,\n  data() {\n    return {\n      listing: ipcRenderer.sendSync(\"get-i18n-listing\"),\n      baseLz: ipcRenderer.sendSync(\"get-i18n\", \"en_US\"),\n    };\n  },\n  methods: {\n    exportLz() {\n      bootbox.alert(`<textarea spellcheck='false' style=\"width:100%;height: 300px;\">${JSON.stringify(app.lz, true, \" \")}</textarea>`);\n      notyf.success(\"Copied to clipboard\");\n      navigator.clipboard.writeText(JSON.stringify(app.lz, true, \" \")).then((r) => console.debug(\"Copied to clipboard.\"));\n    },\n    getLanguages: function () {\n      let langs = this.$root.lzListing;\n      let categories = {\n        main: [],\n        fun: [],\n        unsorted: [],\n      };\n      // sort by category if category is undefined or empty put it in \"unsorted\"\n      for (let i = 0; i < langs.length; i++) {\n        if (langs[i].category === undefined || langs[i].category === \"\") {\n          categories.unsorted.push(langs[i]);\n        } else {\n          categories[langs[i].category].push(langs[i]);\n        }\n      }\n      // return\n      return categories;\n    },\n  },\n});\n"
  },
  {
    "path": "src/renderer/main/components/sidebar-library-item.js",
    "content": "import { html } from \"../html.js\";\n\nexport const sidebarLibraryItem = Vue.component(\"sidebar-library-item\", {\n  template: html`\n    <button class=\"app-sidebar-item\" :class=\"$root.getSidebarItemClass(page)\" @click=\"$root.setWindowHash(page)\">\n      <svg-icon :url=\"svgIconData\" :name=\"'sidebar-' + svgIconName\" v-if=\"svgIconData != ''\" />\n      <span class=\"sidebar-item-text\">{{ name }}</span>\n    </button>\n  `,\n  props: {\n    name: {\n      type: String,\n      required: true,\n    },\n    page: {\n      type: String,\n      required: true,\n    },\n    svgIcon: {\n      type: String,\n      required: false,\n      default: \"\",\n    },\n    svgIconName: {\n      type: String,\n      required: false,\n    },\n    cdClick: {\n      type: Function,\n      required: false,\n    },\n  },\n  data: function () {\n    return {\n      app: app,\n      svgIconData: \"\",\n    };\n  },\n  async mounted() {\n    if (this.svgIcon) {\n      this.svgIconData = this.svgIcon;\n    }\n  },\n  methods: {},\n});\n"
  },
  {
    "path": "src/renderer/main/components/svg-icon.js",
    "content": "import { html } from \"../html.js\";\n\nexport const svgIcon = Vue.component(\"svg-icon\", {\n  template: html` <div class=\"_svg-icon\" :class=\"classes\" :svg-name=\"name\" :style=\"{'--icon': 'url(' + url + ')'}\"></div> `,\n  props: {\n    name: {\n      type: String,\n      required: false,\n    },\n    classes: {\n      type: String,\n      required: false,\n    },\n    url: {\n      type: String,\n      required: true,\n      default: \"./assets/repeat.svg\",\n    },\n  },\n});\n"
  },
  {
    "path": "src/renderer/main/events.js",
    "content": "const Events = {\n  InitEvents() {\n    const app = window.app;\n\n    // add event listener for when window.location.hash changes\n    window.addEventListener(\"hashchange\", function () {\n      app.page = \"blank\";\n      setTimeout(() => {\n        app.appRoute(window.location.hash);\n      }, 100);\n    });\n\n    window.addEventListener(\"mouseup\", (e) => {\n      if (e.button === 3) {\n        e.preventDefault();\n        app.navigateBack();\n      } else if (e.button === 4) {\n        e.preventDefault();\n        app.navigateForward();\n      }\n    });\n\n    document.addEventListener(\"keydown\", async function (event) {\n      // CTRL + R\n      if (event.keyCode === 82 && event.ctrlKey) {\n        event.preventDefault();\n        app.confirm(app.getLz(\"term.reload\"), (res) => {\n          if (res) {\n            window.location.reload();\n          }\n        });\n      }\n      // CTRL + SHIFT + R\n      if (event.keyCode === 82 && event.ctrlKey && event.shiftKey) {\n        event.preventDefault();\n        window.location.reload();\n      }\n      // CTRL + E\n      if (event.keyCode === 69 && event.ctrlKey) {\n        app.invokeDrawer(\"queue\");\n      }\n      // CTRL+H\n      if (event.keyCode === 72 && event.ctrlKey) {\n        app.appRoute(\"home\");\n      }\n      // CTRL+SHIFT+H\n      if (event.ctrlKey && event.shiftKey && event.keyCode == 72) {\n        let hist = await app.mk.api.v3.music(`/v1/me/recent/played/tracks`, {\n          l: app.mklang,\n        });\n        app.showCollection(hist.data, app.getLz(\"term.history\"));\n      }\n      // CTRL+F10\n      if (event.ctrlKey && event.keyCode == 121) {\n        try {\n          app.mk._services.mediaItemPlayback._currentPlayer.stop();\n        } catch (e) {}\n        try {\n          app.mk._services.mediaItemPlayback._currentPlayer.destroy();\n        } catch (e) {}\n        try {\n          this.radiohls.destroy();\n          this.radiohls = null;\n        } catch (_) {}\n        try {\n          let searchInt = setInterval(function () {\n            if (document.getElementById(\"apple-music-player\")) {\n              //AudioOutputs.eqReady = true;\n              document.getElementById(\"apple-music-player\").crossOrigin = \"anonymous\";\n              CiderAudio.source = CiderAudio.context.createMediaElementSource(document.getElementById(\"apple-music-player\"));\n              CiderAudio.source.connect(CiderAudio.audioNodes.intelliGainComp);\n              clearInterval(searchInt);\n            }\n          }, 1000);\n        } catch (e) {}\n      }\n      // CTRL+F11\n      if (event.ctrlKey && event.keyCode == 122) {\n        try {\n          ipcRenderer.send(\"detachDT\", \"\");\n        } catch (e) {}\n      }\n      // Prevent Scrolling on spacebar\n      if (event.keyCode === 32 && event.target === document.body) {\n        event.preventDefault();\n        app.SpacePause();\n      }\n    });\n\n    // Hang Timer\n    app.hangtimer = setTimeout(() => {\n      if (confirm(\"Cider is not responding. Reload the app?\")) {\n        window.location.reload();\n      }\n    }, 10000);\n\n    // Refresh Focus\n    function refreshFocus() {\n      if (document.hasFocus() == false) {\n        app.windowFocus(false);\n      } else {\n        app.windowFocus(true);\n      }\n      setTimeout(refreshFocus, 200);\n    }\n\n    refreshFocus();\n  },\n};\n\nexport { Events };\n"
  },
  {
    "path": "src/renderer/main/gamepad.js",
    "content": "function simulateGamepad() {\n  const app = window.app;\n  app.chrome.showCursor = true;\n  let cursorPos = [0, 0];\n  let intTabIndex = 0;\n  const cursorSpeedPvt = 8;\n  const cursorSize = 16;\n  let scrollSpeed = 8;\n  let buttonPressDelay = 500;\n  let stickDeadZone = 0.2;\n  let scrollGroup = null;\n  let scrollGroupY = null;\n  let elementFocusEnabled = true;\n  let start;\n\n  let cursorSpeed = cursorSpeedPvt;\n\n  let lastButtonPress = {};\n\n  var sounds = {\n    Confirm: new Audio(\"./sounds/confirm.ogg\"),\n    Menu: new Audio(\"./sounds/btn1.ogg\"),\n    Hover: new Audio(\"./sounds/hover.ogg\"),\n  };\n\n  let element = document.elementFromPoint(0, 0);\n  let elementType = 0;\n\n  function appLoop() {\n    var gamepads = navigator.getGamepads ? navigator.getGamepads() : navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : [];\n    if (!gamepads) {\n      return;\n    }\n\n    var gp = gamepads[0];\n\n    //  LEFT STICK\n    if (gp.axes[0] > stickDeadZone) {\n      cursorPos[0] += gp.axes[0] * cursorSpeed;\n    } else if (gp.axes[0] < -stickDeadZone) {\n      cursorPos[0] += gp.axes[0] * cursorSpeed;\n    }\n\n    if (gp.axes[1] > stickDeadZone) {\n      cursorPos[1] += gp.axes[1] * cursorSpeed;\n    } else if (gp.axes[1] < -stickDeadZone) {\n      cursorPos[1] += gp.axes[1] * cursorSpeed;\n    }\n\n    if (cursorPos[0] < cursorSize) {\n      cursorPos[0] = cursorSize;\n    }\n    if (cursorPos[1] < cursorSize) {\n      cursorPos[1] = cursorSize;\n    }\n    if (cursorPos[0] > window.innerWidth - cursorSize) {\n      cursorPos[0] = window.innerWidth - cursorSize;\n    }\n    if (cursorPos[1] > window.innerHeight - cursorSize) {\n      cursorPos[1] = window.innerHeight - cursorSize;\n    }\n\n    // RIGHT STICK.\n    if (scrollGroupY) {\n      if (gp.axes[3] > stickDeadZone) {\n        $(scrollGroupY).scrollTop($(scrollGroupY).scrollTop() + gp.axes[3] * scrollSpeed);\n        elementFocusEnabled = false;\n      } else if (gp.axes[3] < -stickDeadZone) {\n        $(scrollGroupY).scrollTop($(scrollGroupY).scrollTop() + gp.axes[3] * scrollSpeed);\n        elementFocusEnabled = false;\n      } else {\n        elementFocusEnabled = true;\n      }\n    }\n\n    if (scrollGroup) {\n      if (gp.axes[2] > stickDeadZone) {\n        $(scrollGroup).scrollLeft($(scrollGroup).scrollLeft() + gp.axes[2] * scrollSpeed);\n        elementFocusEnabled = false;\n      } else if (gp.axes[2] < -stickDeadZone) {\n        $(scrollGroup).scrollLeft($(scrollGroup).scrollLeft() + gp.axes[2] * scrollSpeed);\n        elementFocusEnabled = false;\n      } else {\n        elementFocusEnabled = true;\n      }\n    }\n\n    $(\".cursor\").css({\n      top: cursorPos[1] + \"px\",\n      left: cursorPos[0] + \"px\",\n      display: \"block\",\n    });\n\n    // A BUTTON\n    if (gp.buttons[0].pressed) {\n      if (!lastButtonPress[\"A\"]) {\n        lastButtonPress[\"A\"] = 0;\n      }\n      if (Date.now() - lastButtonPress[\"A\"] > buttonPressDelay) {\n        lastButtonPress[\"A\"] = Date.now();\n        sounds.Confirm.play();\n        if (elementType == 0) {\n          document.activeElement.dispatchEvent(new Event(\"click\"));\n          document.activeElement.dispatchEvent(new Event(\"controller-click\"));\n        } else {\n          element.dispatchEvent(new Event(\"click\"));\n          element.dispatchEvent(new Event(\"controller-click\"));\n        }\n      }\n    }\n\n    // B BUTTON\n    if (gp.buttons[1].pressed) {\n      if (!lastButtonPress[\"B\"]) {\n        lastButtonPress[\"B\"] = 0;\n      }\n      if (Date.now() - lastButtonPress[\"B\"] > buttonPressDelay) {\n        lastButtonPress[\"B\"] = Date.now();\n        if (elementType == 0) {\n          document.activeElement.dispatchEvent(new Event(\"contextmenu\"));\n          setTimeout(() => {\n            if ($(\".menu-option\").length > 0) {\n              let bounds = $(\".menu-option\")[0].getBoundingClientRect();\n              cursorPos[0] = bounds.left + bounds.width / 2;\n              cursorPos[1] = bounds.top + bounds.height / 2;\n            }\n          }, 100);\n        } else {\n          element.dispatchEvent(new Event(\"contextmenu\"));\n        }\n      }\n    }\n\n    // right bumper\n    if (gp.buttons[5].pressed) {\n      if (!lastButtonPress[\"RB\"]) {\n        lastButtonPress[\"RB\"] = 0;\n      }\n      if (Date.now() - lastButtonPress[\"RB\"] > buttonPressDelay) {\n        lastButtonPress[\"RB\"] = Date.now();\n        app.navigateForward();\n      }\n    }\n\n    // left bumper\n    if (gp.buttons[4].pressed) {\n      if (!lastButtonPress[\"LB\"]) {\n        lastButtonPress[\"LB\"] = 0;\n      }\n      if (Date.now() - lastButtonPress[\"LB\"] > buttonPressDelay) {\n        lastButtonPress[\"LB\"] = Date.now();\n        app.navigateBack();\n      }\n    }\n\n    // cursor hover\n    if (elementFocusEnabled) {\n      element = document.elementFromPoint(cursorPos[0], cursorPos[1]);\n    }\n\n    if (element) {\n      let closest = element.closest(\"[tabindex], input, button, a\");\n\n      // VERT SCROLL\n      let scrollGroupCloY = element.closest(`[scrollaxis=\"y\"]`);\n      if (scrollGroupCloY) {\n        scrollGroupY = scrollGroupCloY;\n      }\n\n      //  HOZ SCROLL\n      let scrollGroupClo = element.closest(\".v-hl-container\");\n\n      if (scrollGroupClo) {\n        if (scrollGroupClo.classList.contains(\"v-hl-container\")) {\n          scrollGroup = scrollGroupClo;\n          scrollGroup.style[\"scroll-snap-type\"] = \"unset\";\n        } else {\n          scrollGroup.style[\"scroll-snap-type\"] = \"\";\n          scrollGroup = null;\n        }\n      }\n\n      if (closest) {\n        elementType = 0;\n        closest.focus();\n      } else {\n        if (closest) {\n          closest.blur();\n        }\n        elementType = 1;\n        element.focus();\n      }\n      cursorSpeed = cursorSpeedPvt;\n      if (!element.classList.contains(\"app-chrome\") && !element.classList.contains(\"app-content\")) {\n        cursorSpeed = cursorSpeedPvt;\n      }\n      // console.log($._data($(element), \"events\"))\n    } else {\n      cursorSpeed = 12;\n    }\n    // console.log(gp.axes[0], gp.axes[1])\n    start = requestAnimationFrame(appLoop);\n  }\n\n  // controller pairing\n  notyf.error(\"Press the button on your controller to pair it to Cider.\");\n  window.addEventListener(\n    \"gamepadconnected\",\n    function (e) {\n      console.log(\"Gamepad connected at index %d: %s. %d buttons, %d axes.\", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length);\n      notyf.success(\"Pairing successful!\");\n      appLoop();\n    },\n    { once: true },\n  );\n\n  document.addEventListener(\"keydown\", (e) => {\n    sounds.Confirm.currentTime = 0;\n    sounds.Menu.currentTime = 0;\n    sounds.Hover.currentTime = 0;\n    let tabbable = $(\"[tabindex]\");\n    console.log(e.key);\n    switch (e.key) {\n      default:\n        break;\n      case \"ArrowLeft\":\n        e.preventDefault();\n\n        cursorPos[0] -= cursorSpeed;\n        break;\n      case \"ArrowRight\":\n        e.preventDefault();\n\n        cursorPos[0] += cursorSpeed;\n        break;\n      case \"ArrowUp\":\n        e.preventDefault();\n\n        cursorPos[1] -= cursorSpeed;\n        // sounds.Hover.play()\n        // if (intTabIndex <= 0) {\n        //     intTabIndex = 0\n        // } else {\n        //     intTabIndex--\n        // }\n        // $(tabbable[intTabIndex]).focus()\n        // $(\"#app-content\").scrollTop($(document.activeElement).offset().top)\n        break;\n      case \"ArrowDown\":\n        e.preventDefault();\n\n        cursorPos[1] += cursorSpeed;\n        // if (intTabIndex < tabbable.length) {\n        //     intTabIndex++\n        // } else {\n        //     intTabIndex = tabbable.length\n        // }\n        // $(tabbable[intTabIndex]).focus()\n        // $(\"#app-content\").scrollTop($(document.activeElement).offset().top)\n        break;\n      case \"c\":\n        app.resetState();\n        break;\n      case \"x\":\n        // set cursorPos to the top right of the screen\n        // sounds.Menu.play()\n        if (elementType == 0) {\n          document.activeElement.dispatchEvent(new Event(\"contextmenu\"));\n        } else {\n          element.dispatchEvent(new Event(\"contextmenu\"));\n        }\n\n        e.preventDefault();\n        break;\n      case \"z\":\n        sounds.Confirm.play();\n        if (elementType == 0) {\n          document.activeElement.dispatchEvent(new Event(\"click\"));\n          document.activeElement.dispatchEvent(new Event(\"controller-click\"));\n        } else {\n          element.dispatchEvent(new Event(\"click\"));\n          element.dispatchEvent(new Event(\"controller-click\"));\n        }\n\n        e.preventDefault();\n        break;\n    }\n\n    $(\".cursor\").css({\n      top: cursorPos[1] + \"px\",\n      left: cursorPos[0] + \"px\",\n    });\n    function lerp(a, b, n) {\n      return (1 - n) * a + n * b;\n    }\n\n    element = document.elementFromPoint(cursorPos[0], cursorPos[1]);\n\n    if (element) {\n      let closest = element.closest(\"[tabindex], input, button, a\");\n      if (closest) {\n        elementType = 0;\n        closest.focus();\n      } else {\n        elementType = 1;\n        element.focus();\n      }\n    }\n    console.log(element);\n  });\n}\n\nexport { simulateGamepad };\n"
  },
  {
    "path": "src/renderer/main/html.js",
    "content": "export function html(str) {\n  return str[0];\n}\n"
  },
  {
    "path": "src/renderer/main/mica.js",
    "content": "import { CiderCache } from \"./cidercache.js\";\n\nasync function spawnMica() {\n  if (typeof window.micaSpawned !== \"undefined\") {\n    return;\n  } else {\n    window.micaSpawned = true;\n  }\n  const micaDiv = document.createElement(\"div\");\n  const blurIterations = 6;\n  micaDiv.id = \"micaEffect\";\n  micaDiv.style.position = \"fixed\";\n  micaDiv.style.top = \"0\";\n  micaDiv.style.left = \"0\";\n  micaDiv.style.right = \"0\";\n  micaDiv.style.bottom = \"0\";\n  micaDiv.style.zIndex = -1;\n\n  let lastScreenX;\n  let lastScreenY;\n  let lastScreenWidth;\n  let lastScreenHeight;\n\n  let imgSrc = \"\";\n  let micaCache = await CiderCache.getCache(\"mica-cache\");\n  if (!micaCache) {\n    micaCache = {\n      path: \"\",\n      data: \"\",\n    };\n  }\n  if (micaCache.path == imgSrc.path) {\n    imgSrc = micaCache;\n  } else {\n    imgSrc = await ipcRenderer.sendSync(\"get-wallpaper\", {\n      blurAmount: 256,\n    });\n    CiderCache.putCache(\"mica-cache\", imgSrc);\n  }\n  let canvas = document.createElement(\"canvas\");\n  let ctx = canvas.getContext(\"2d\");\n  let img = new Image();\n  micaDiv.style.backgroundImage = `url(${imgSrc.data})`;\n  document.body.appendChild(micaDiv);\n\n  function onScreenMove(cb) {\n    function detectScreenMove() {\n      if (lastScreenY !== window.screenY || lastScreenX !== window.screenX) {\n        lastScreenY = window.screenY;\n        lastScreenX = window.screenX;\n        cb();\n      }\n      // window size change\n      if (lastScreenWidth !== window.innerWidth || lastScreenHeight !== window.innerHeight) {\n        lastScreenWidth = window.innerWidth;\n        lastScreenHeight = window.innerHeight;\n        cb();\n      }\n      if (true) {\n        requestAnimationFrame(detectScreenMove);\n      }\n    }\n\n    if (true) {\n      requestAnimationFrame(detectScreenMove);\n    }\n  }\n\n  onScreenMove(function () {\n    const screenHeight = window.screen.height;\n    const screenWidth = window.screen.width;\n    const windowHeight = window.innerHeight;\n    const windowWidth = window.innerWidth;\n    const ratio = windowWidth / windowHeight;\n    const x = window.screenX;\n    const y = window.screenY;\n    micaDiv.style.backgroundSize = `${screenWidth}px ${screenHeight}px`;\n    // micaDiv.style.backgroundPosition = `-${x}px -${y}px`;\n    if (x < 0) {\n      micaDiv.style.backgroundPosition = `${screenWidth + x}px -${y}px`;\n    } else {\n      micaDiv.style.backgroundPosition = `-${x}px -${y}px`;\n    }\n  });\n  return true;\n}\n\nexport { spawnMica };\n"
  },
  {
    "path": "src/renderer/main/musickittools.js",
    "content": "const MusicKitTools = {\n  async v3Backend({ route = \"\", getBody = {}, options = {} }) {\n    return await await ipcRenderer.invoke(\"mkv3\", {\n      token: MusicKit.getInstance().developerToken,\n      route: route,\n      mediaToken: MusicKit.getInstance().musicUserToken,\n      GETBody: getBody,\n    });\n  },\n  async v3Continuous({ href, options = {}, reqOptions = {}, onProgress = () => {}, onError = () => {}, onSuccess = () => {} } = {}) {\n    let returnData = [];\n\n    async function sendReq(href, options) {\n      const response = await app.mk.api.v3.music(href, options).catch((error) => onError);\n\n      returnData = returnData.concat(response.data.data);\n      if (response.data.next) {\n        onProgress({\n          response: response,\n          total: returnData.length,\n        });\n        try {\n          await sendReq(response.data.next, options);\n        } catch (e) {\n          await sendReq(response.data.next, options);\n        }\n      }\n    }\n\n    await sendReq(href, options);\n    onSuccess(returnData);\n    return returnData;\n  },\n  getHeader() {\n    return new Headers({\n      Authorization: \"Bearer \" + MusicKit.getInstance().developerToken,\n      Accept: \"application/json\",\n      \"Content-Type\": \"application/json\",\n      \"Music-User-Token\": \"\" + MusicKit.getInstance().musicUserToken,\n    });\n  },\n};\n\nexport { MusicKitTools };\n"
  },
  {
    "path": "src/renderer/main/vueapp.js",
    "content": "import { store } from \"./vuex-store.js\";\n\nVue.use(VueHorizontal);\nVue.use(VueObserveVisibility);\nVue.use(BootstrapVue);\n/* @namespace */\nconst app = new Vue({\n  store: store,\n  data: {\n    version: ipcRenderer.sendSync(\"get-version\"),\n    appMode: \"player\",\n    ipcRenderer: ipcRenderer,\n    cfg: ipcRenderer.sendSync(\"getStore\"),\n    isDev: ipcRenderer.sendSync(\"is-dev\"),\n    clientPort: ipcRenderer.sendSync(\"get-port\"),\n    drawertest: false,\n    platform: \"\",\n    mk: {},\n    pluginInstalled: false,\n    pluginMenuEntries: [],\n    pluginMenuTopEntries: [],\n    lz: ipcRenderer.sendSync(\"get-i18n\", \"en\"),\n    lzListing: ipcRenderer.sendSync(\"get-i18n-listing\"),\n    radiohls: null,\n    search: {\n      term: \"\",\n      cursor: -1,\n      hints: [],\n      showHints: false,\n      showSearchView: false,\n      results: {},\n      resultsSocial: {},\n      resultsLibrary: {},\n      limit: 10,\n    },\n    fullscreenLyrics: false,\n    fullscreenState: ipcRenderer.sendSync(\"getFullScreen\"),\n    playerLCD: {\n      playbackDuration: 0,\n      desiredDuration: 0,\n      userInteraction: false,\n    },\n    drawer: {\n      open: false,\n      panel: \"\",\n    },\n    browsepage: [],\n    listennow: [],\n    madeforyou: [],\n    radio: [],\n    mklang: \"en\",\n    webview: {\n      url: \"\",\n      title: \"\",\n      loading: false,\n    },\n    showingPlaylist: [],\n    appleCurator: [],\n    multiroom: [],\n    artistPage: {\n      data: {},\n    },\n    library: {\n      backgroundNotification: {\n        show: false,\n        message: \"\",\n        total: 0,\n        progress: 0,\n      },\n      songs: {\n        sortingOptions: {\n          albumName: \"0\",\n          artistName: \"0\",\n          name: \"0\",\n          genre: \"0\",\n          releaseDate: \"0\",\n          durationInMillis: \"0\",\n          dateAdded: \"0\",\n        },\n        sorting: \"name\",\n        sortOrder: \"asc\",\n        listing: [],\n        meta: { total: 0, progress: 0 },\n        search: \"\",\n        displayListing: [],\n        downloadState: 0, // 0 = not started, 1 = in progress, 2 = complete, 3 = empty library\n      },\n      albums: {\n        sortingOptions: {\n          artistName: \"0\",\n          name: \"0\",\n          genre: \"0\",\n          releaseDate: \"0\",\n        },\n        viewAs: \"covers\",\n        sorting: [\"dateAdded\", \"name\"], // [0] = recentlyadded page, [1] = albums page\n        sortOrder: [\"desc\", \"asc\"], // [0] = recentlyadded page, [1] = albums page\n        listing: [],\n        meta: { total: 0, progress: 0 },\n        search: \"\",\n        displayListing: [],\n        downloadState: 0, // 0 = not started, 1 = in progress, 2 = complete, 3 = empty library\n      },\n      artists: {\n        sortingOptions: {\n          artistName: \"0\",\n          name: \"0\",\n          genre: \"0\",\n          releaseDate: \"0\",\n        },\n        viewAs: \"covers\",\n        sorting: [\"dateAdded\", \"name\"], // [0] = recentlyadded page, [1] = albums page\n        sortOrder: [\"desc\", \"asc\"], // [0] = recentlyadded page, [1] = albums page\n        listing: [],\n        meta: { total: 0, progress: 0 },\n        search: \"\",\n        displayListing: [],\n        downloadState: 0, // 0 = not started, 1 = in progress, 2 = complete, 3 = empty library\n      },\n      localsongs: [],\n    },\n    playlists: {\n      listing: [],\n      details: {},\n      loadingState: 0, // 0 loading, 1 loaded, 2 error\n      id: \"\",\n      trackMapping: {},\n    },\n    webremoteurl: \"\",\n    webremoteqr: \"\",\n    mxmtoken: \"\",\n    mkIsReady: false,\n    animateBackground: false,\n    currentArtUrl: \"\",\n    currentArtUrlRaw: \"\",\n    mvViewMode: \"full\",\n    lyricon: false,\n    currentTrackID: \"\",\n    lyrics: [],\n    currentLyricsLine: 0,\n    richlyrics: [],\n    lyricsMediaItem: {},\n    lyricsDebug: {\n      current: 0,\n      start: 0,\n      end: 0,\n    },\n    lyricOffset: 0,\n    v3: {\n      requestBody: {\n        platform: \"web\",\n      },\n    },\n    tmpHeight: \"\",\n    tmpWidth: \"\",\n    tmpX: \"\",\n    tmpY: \"\",\n    miniTmpX: \"\",\n    miniTmpY: \"\",\n    tmpVar: [],\n    notification: false,\n    hintscontext: false,\n    chrome: {\n      sidebarCollapsed: false,\n      nativeControls: false,\n      contentScrollPosY: 0,\n      appliedTheme: {\n        location: \"\",\n        info: {},\n      },\n      windowState: \"normal\",\n      desiredPageTransition: \"wpfade_transform\",\n      hideUserInfo: ipcRenderer.sendSync(\"is-dev\") || false,\n      artworkReady: false,\n      userinfo: {\n        id: \"\",\n        attributes: {\n          name: \"Cider User\",\n          handle: \"CiderUser\",\n          artwork: { url: \"./assets/logocut.png\" },\n        },\n      },\n      forceDirectives: {},\n      menuOpened: false,\n      maximized: false,\n      drawerOpened: false,\n      drawerState: \"queue\",\n      topChromeVisible: true,\n      progresshover: false,\n      windowControlPosition: \"right\",\n      contentAreaScrolling: true,\n      showCursor: false,\n      noC2Upgrade: localStorage.getItem(\"noC2Upgrade\") == \"true\" ? true : false,\n    },\n    collectionList: {\n      response: {},\n      title: \"\",\n      type: \"\",\n    },\n    MVsource: null,\n    currentSongInfo: {},\n    page: \"\",\n    pageHistory: [],\n    songstest: false,\n    hangtimer: null,\n    selectedMediaItems: [],\n    routes: [\"browse\", \"listen_now\", \"radio\"],\n    musicBaseUrl: \"https://api.music.apple.com/\",\n    modals: {\n      addToPlaylist: false,\n      spatialProperties: false,\n      qrcode: false,\n      equalizer: false,\n      audioSettings: false,\n      pluginMenu: false,\n      audioControls: false,\n      audioPlaybackRate: false,\n      showPlaylist: false,\n      castMenu: false,\n      pathMenu: false,\n      moreInfo: false,\n      airplayPW: false,\n      settings: false,\n      c2Upgrade: false,\n    },\n    socialBadges: {\n      badgeMap: {},\n      version: \"\",\n      mediaItems: [],\n      mediaItemDLState: 0, // 0 = not started, 1 = in progress, 2 = complete\n    },\n    menuPanel: {\n      visible: false,\n      event: null,\n      content: {\n        name: \"\",\n        items: {},\n        headerItems: {},\n      },\n    },\n    pauseButtonTimer: null,\n    activeCasts: [],\n    pluginPages: {\n      page: \"hello-world\",\n      pages: [],\n    },\n    moreinfodata: [],\n    notyf: notyf,\n    idleTimer: null,\n    idleState: false,\n    appVisible: true,\n    currentAirPlayCodeID: \"\",\n    airplayTrys: [],\n  },\n  watch: {\n    cfg: {\n      handler: function (val, oldVal) {\n        console.debug(`Config changed: ${JSON.stringify(val)}`);\n        ipcRenderer.send(\"setStore\", val);\n      },\n      deep: true,\n    },\n    \"cfg.connectivity.discord_rpc.enabled\"(newValue) {\n      ipcRenderer.send(\"discordrpc:reload\", newValue);\n    },\n    \"mk.privateEnabled\"(newValue) {\n      ipcRenderer.send(\"onPrivacyModeChange\", newValue);\n    },\n    page: () => {\n      // document.getElementById(\"app-content\").scrollTo(0, 0);\n      app.resetState();\n    },\n    showingPlaylist: () => {\n      if (!app.modals.showPlaylist) {\n        // document.getElementById(\"app-content\").scrollTo(0, 0);\n        app.resetState();\n      }\n    },\n    artistPage: () => {\n      // document.getElementById(\"app-content\").scrollTo(0, 0);\n      app.resetState();\n    },\n  },\n  mounted() {\n    window.addEventListener(\n      \"hashchange\",\n      function (event) {\n        let currentPath = window.location.hash.slice(1);\n        console.debug(\"hashchange\", currentPath);\n      },\n      false,\n    );\n  },\n  methods: {\n    _fetch(url, opts = {}) {\n      if (app.cfg.advanced.experiments.includes(\"cider_mirror\") === true) {\n        if (url.includes(\"api.github.com/\")) {\n          return fetch(url.replace(\"api.github.com/\", \"mirror.api.cider.sh/v2/api/\"), opts);\n        } else if (url.includes(\"raw.githubusercontent.com/\")) {\n          return fetch(url.replace(\"raw.githubusercontent.com/\", \"mirror.api.cider.sh/v2/raw/\"), opts);\n        } else {\n          return fetch(url, opts);\n        }\n      } else {\n        return fetch(url, opts);\n      }\n    },\n    setWindowHash(route = \"\") {\n      this.setPagePos();\n      window.location.hash = `#${route}`;\n    },\n    monitorMusickit() {\n      if (!app.cfg.musickit) return;\n\n      for (const [attr, value] of Object.entries(app.cfg.musickit[\"stored-attributes\"])) {\n        console.log(`Musickit value: ` + app.mk[attr]);\n        console.log(`Config value: ` + value);\n        if (value !== \"\" && app.mk[attr] !== value) {\n          app.mk[attr] = value;\n        }\n        this.$watch(`mk.${attr}`, (val) => {\n          console.log(`MK ${attr} changed to ${val}`);\n          app.cfg.musickit[\"stored-attributes\"][attr] = val;\n        });\n      }\n      const ERROR_CODES = [\"drmUnsupported\", \"mediaPlaybackError\"];\n      /* MusicKit.Events */\n      ERROR_CODES.forEach((code) => {\n        MusicKit.getInstance().addEventListener(MusicKit.Events[code], (e) => {\n          console.error(`[MusicKit] MusicKit Error ${code}`);\n          console.error({ e: e });\n          app.notyf.open({\n            duration: 20000,\n            type: \"error\",\n            className: \"notyf-info\",\n            message: `<small>${app.getLz(\"error.musickitError\")} \\n</small><code>${code.toUpperCase()}</code>`,\n          });\n        });\n      });\n    },\n    async oobeInit() {\n      this.appMode = \"oobe\";\n      for (const [k, v] of Object.entries(ipcRenderer.sendSync(\"get-i18n-listing\"))) {\n        if (v.code === navigator.language.replace(\"-\", \"_\")) {\n          this.cfg.general.language = v.code;\n          break;\n        }\n      }\n      this.setLz(this.cfg.general.language);\n      this.setLzManual();\n      clearTimeout(this.hangtimer);\n      document.body.removeAttribute(\"loading\");\n      ipcRenderer.invoke(\"renderer-ready\", true);\n      document.querySelector(\"#LOADER\").remove();\n\n      ipcRenderer.on(\"recv-cookies\", function (_event, cookies) {\n        console.log(\"[appIPC] recv-cookies\");\n        Object.keys(cookies).forEach((key) => {\n          localStorage.setItem(key, cookies[key]);\n        });\n        localStorage.setItem(\"seenOOBE\", 1);\n        window.location.reload();\n      });\n    },\n    getAppStyle() {\n      let finalStyle = {};\n      if (this.cfg.visual.window_background_style === \"color\") {\n        finalStyle[\"background-color\"] = this.cfg.visual.windowColor;\n      }\n      if (this.cfg.visual.customAccentColor) {\n        finalStyle[\"--keyColor\"] = this.cfg.visual.accentColor;\n        finalStyle[\"--songProgressColor\"] = this.cfg.visual.accentColor;\n      } else if (this.cfg.visual.purplePodcastPlaybackBar && MusicKit.getInstance().nowPlayingItem?.type == \"podcast-episodes\") {\n        finalStyle[\"--songProgressColor\"] = \"#6929D0\";\n      }\n      return finalStyle;\n    },\n    setTimeout(func, time) {\n      return setTimeout(func, time);\n    },\n    songLinkShare(amUrl) {\n      notyf.open({\n        type: \"info\",\n        className: \"notyf-info\",\n        message: app.getLz(\"term.song.link.generate\"),\n      });\n      let self = this;\n      let httpRequest = new XMLHttpRequest();\n      httpRequest.open(\"GET\", `https://api.song.link/v1-alpha.1/links?url=${amUrl}&userCountry=US`, true);\n      httpRequest.send();\n      httpRequest.onreadystatechange = function () {\n        if (httpRequest.readyState === 4) {\n          if (httpRequest.status === 200) {\n            let response = JSON.parse(httpRequest.responseText);\n            console.debug(response);\n            self.copyToClipboard(response.pageUrl);\n          } else {\n            console.warn(\"There was a problem with the request.\");\n            notyf.error(app.getLz(\"term.requestError\"));\n          }\n        }\n      };\n    },\n    formatVolumeTooltip() {\n      let advancedTooltip = this.cfg.audio.dBSPL ? (Number(this.cfg.audio.dBSPLcalibration) + Math.log10(this.mk.volume) * 20).toFixed(2) + \" dB SPL\" : (Math.log10(this.mk.volume) * 20).toFixed(2) + \" dBFS\";\n      return this.cfg.audio.advanced ? advancedTooltip : (this.mk.volume * 100).toFixed(0) + \"%\";\n    },\n    mainMenuVisibility(val) {\n      if (val) {\n        this.mk.isAuthorized ? (this.chrome.menuOpened = !this.chrome.menuOpened) : false;\n        if (!this.mk.isAuthorized) {\n          ipcRenderer.send(\"auth-window\");\n        }\n      } else {\n        setTimeout(() => {\n          this.chrome.menuOpened = false;\n        }, 100);\n      }\n    },\n    stringTemplateParser(expression, valueObj) {\n      const templateMatcher = /{{\\s?([^{}\\s]*)\\s?}}/g;\n      let text = expression.replace(templateMatcher, (substring, value, index) => {\n        value = valueObj[value];\n        return value;\n      });\n      return text;\n      // stringTemplateParser('my name is {{name}} and age is {{age}}', {name: 'Tom', age:100})\n    },\n    async setLz(lang) {\n      if (lang == \"\") {\n        lang = this.cfg.general.language;\n      }\n      this.lz = ipcRenderer.sendSync(\"get-i18n\", lang);\n      this.mklang = await this.MKJSLang();\n      try {\n        this.listennow.timestamp = 0;\n        this.browsepage.timestamp = 0;\n        this.radio.timestamp = 0;\n      } catch (e) {}\n    },\n    /**\n     * Grabs translation for localization.\n     * @param {string} message - The key to grab the translated term\n     * @param {object} options - Optional options\n     * @author booploops#7139\n     * @memberOf app\n     */\n    getLz(message, options = {}) {\n      if (this.lz[message]) {\n        if (options[\"count\"]) {\n          if (typeof this.lz[message] === \"object\") {\n            let type = window.fastPluralRules.getPluralFormNameForCardinalByLocale(this.cfg.general.language.replace(\"_\", \"-\"), options[\"count\"]);\n            return this.lz[message][type] ?? this.lz[message][Object.keys(this.lz[message])[0]] ?? this.lz[message];\n          } else {\n            // fallback English plural forms ( old i18n )\n            if (options[\"count\"] > 1) {\n              return this.lz[message + \"s\"] ?? this.lz[message];\n            } else {\n              return this.lz[message] ?? this.lz[message + \"s\"];\n            }\n          }\n        } else if (typeof this.lz[message] === \"object\") {\n          return this.lz[message][Object.keys(this.lz[message])[0]];\n        }\n        return this.lz[message];\n      } else {\n        return message;\n      }\n    },\n    getProfileLz(type, name) {\n      // For Spatial and CAR.\n      let result = \"\";\n\n      // Hard-coded shiz\n      switch (name) {\n        case \"Maikiwi\":\n          return \"Maikiwi\";\n          break;\n\n        case \"Maikiwi+\":\n          return \"Maikiwi+\";\n          break;\n\n        case \"Minimal+\":\n          return this.getLz(\"settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization.profile.minimal\") + \"+\";\n          break;\n\n        case \"live\":\n          return \"LIVE\";\n          break;\n      }\n      switch (type) {\n        case \"CAR\":\n          result = this.getLz(\"settings.option.audio.enableAdvancedFunctionality.atmosphereRealizerMode.\" + name);\n          if (result === \"settings.option.audio.enableAdvancedFunctionality.atmosphereRealizerMode.\" + name) {\n            return name;\n          } else {\n            return result;\n          }\n          break;\n        case \"CTS\":\n          result = this.getLz(\"settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization.profile.\" + name.toLowerCase());\n          if (result === \"settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization.profile.\" + name.toLowerCase()) {\n            return name;\n          } else {\n            return result;\n          }\n          break;\n        default:\n          return name;\n      }\n    },\n    setLzManual() {\n      app.$data.library.songs.sortingOptions = {\n        albumName: app.getLz(\"term.sortBy.album\"),\n        artistName: app.getLz(\"term.sortBy.artist\"),\n        name: app.getLz(\"term.sortBy.name\"),\n        genre: app.getLz(\"term.sortBy.genre\"),\n        releaseDate: app.getLz(\"term.sortBy.releaseDate\"),\n        durationInMillis: app.getLz(\"term.sortBy.duration\"),\n        dateAdded: app.getLz(\"term.sortBy.dateAdded\"),\n      };\n\n      app.$data.library.albums.sortingOptions = {\n        artistName: app.getLz(\"term.sortBy.artist\"),\n        name: app.getLz(\"term.sortBy.name\"),\n        genre: app.getLz(\"term.sortBy.genre\"),\n        releaseDate: app.getLz(\"term.sortBy.releaseDate\"),\n        dateAdded: app.getLz(\"term.sortBy.dateAdded\"),\n      };\n\n      app.$data.library.artists.sortingOptions = {\n        artistName: app.getLz(\"term.sortBy.artist\"),\n        name: app.getLz(\"term.sortBy.name\"),\n        genre: app.getLz(\"term.sortBy.genre\"),\n        releaseDate: app.getLz(\"term.sortBy.releaseDate\"),\n      };\n\n      this.lz.repeat = {\n        0: this.lz[\"term.repeat.all\"] ?? this.lz[\"term.repeat\"],\n        1: this.lz[\"term.repeat.none\"] ?? this.lz[\"term.disableRepeat\"],\n        2: this.lz[\"term.repeat.one\"] ?? this.lz[\"term.enableRepeatOne\"],\n      };\n    },\n    async showSocialListeningTo() {\n      let contentIds = Object.keys(app.socialBadges.badgeMap);\n      app.showCollection({ data: this.socialBadges.mediaItems }, \"Friends Listening To\", \"albums\");\n      if (this.socialBadges.mediaItemDLState == 1 || this.socialBadges.mediaItemDLState == 2) {\n        return;\n      }\n      this.socialBadges.mediaItemDLState = 2;\n      await asyncForEach(contentIds, async (item) => {\n        try {\n          let type = \"albums\";\n          if (item.includes(\"pl.\")) {\n            type = \"playlists\";\n          }\n          if (item.includes(\"ra.\")) {\n            type = \"stations\";\n          }\n          let found = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/${type}/${item}`);\n          this.socialBadges.mediaItems.push(found.data.data[0]);\n        } catch (e) {}\n      });\n    },\n    quit() {\n      ipcRenderer.invoke(\"quit-app\");\n    },\n    async openAppleMusicURL(url) {\n      let properties = MusicKit.formattedMediaURL(url);\n      let item = {\n        id: properties.contentId,\n        attributes: {\n          playParams: {\n            id: properties.contentId,\n            kind: properties.kind,\n          },\n        },\n        type: properties.kind,\n        kind: properties.kind,\n      };\n      app.routeView(item);\n    },\n    saveFile(fileName, urlFile) {\n      let a = document.createElement(\"a\");\n      a.style = \"display: none\";\n      document.body.appendChild(a);\n      a.href = urlFile;\n      a.download = fileName;\n      a.click();\n      window.URL.revokeObjectURL(url);\n      a.remove();\n    },\n    async showMenuPanel(data, event) {\n      app.menuPanel.visible = true;\n      app.menuPanel.content.name = data.name ?? \"\";\n      app.menuPanel.content.items = data.items ?? {};\n      app.menuPanel.content.headerItems = data.headerItems ?? {};\n      if (event) {\n        app.menuPanel.event = event;\n      }\n    },\n    async getSvgIcon(url) {\n      let response = await fetch(url);\n      let data = await response.text();\n      return data;\n    },\n    getSocialBadges(cb = () => {}) {\n      let self = this;\n      try {\n        app.mk.api.v3.music(\"/v1/social/badging-map\").then((data) => {\n          self.socialBadges.badgeMap = data.data.results.badgingMap;\n          cb(data.data.results.badgingMap);\n        });\n      } catch (ex) {\n        this.socialBadges.badgeMap = {};\n      }\n    },\n    addFavorite(id, type) {\n      this.cfg.home.favoriteItems.push({\n        id: id,\n        type: type,\n      });\n    },\n    modularUITest(val = false) {\n      this.fullscreenLyrics = val;\n      if (val) {\n        document.querySelector(\"#app-main\").classList.add(\"modular-fs\");\n      } else {\n        document.querySelector(\"#app-main\").classList.remove(\"modular-fs\");\n      }\n    },\n    navigateBack() {\n      this.setPagePos();\n      this.resumePagePos();\n      this.chrome.desiredPageTransition = \"wpfade_transform_backwards\";\n      return new Promise((resolve, reject) => {\n        history.back();\n        setTimeout(() => {\n          resolve((this.chrome.desiredPageTransition = \"wpfade_transform\"));\n        }, 100);\n      });\n    },\n    goToGrouping(url = \"https://music.apple.com/WebObjects/MZStore.woa/wa/viewGrouping?cc=us&id=34\") {\n      this.setPagePos();\n      this.resumePagePos();\n      if (url.includes(\"viewTop\")) {\n        window.location.hash = `#charts/top`;\n      } else {\n        const id = url.split(\"id=\")[1];\n        if (id != null) {\n          window.location.hash = `#groupings/${id}`;\n        } else {\n          const params = new Proxy(new URLSearchParams(new URL(url).search), {\n            get: (searchParams, prop) => searchParams.get(prop),\n          });\n          let id = params.fcId;\n          app\n            .getTypeFromID(\"room\", id, false, {\n              platform: \"web\",\n              extend: \"editorialArtwork,uber,lockupStyle\",\n            })\n            .then(() => {\n              let kind = \"multiroom\";\n              window.location.hash = `${kind}/${id}`;\n              document.querySelector(\"#app-content\").scrollTop = 0;\n            });\n        }\n      }\n    },\n    navigateForward() {\n      this.setPagePos();\n      this.resumePagePos();\n      history.forward();\n    },\n    resetState() {\n      this.menuPanel.visible = false;\n      app.selectedMediaItems = [];\n      this.chrome.contentAreaScrolling = true;\n      for (let key in app.modals) {\n        app.modals[key] = false;\n      }\n    },\n    resumeTabs() {\n      if (app.cfg.general.resumeTabs.tab == \"dynamic\") {\n        this.appRoute(app.cfg.general.resumeTabs.dynamicData);\n      } else {\n        this.appRoute(app.cfg.general.resumeTabs.tab);\n      }\n    },\n    promptAddToPlaylist() {\n      app.modals.addToPlaylist = true;\n    },\n    async addSelectedToNewPlaylist() {\n      let self = this;\n      let pl_items = [];\n      for (let i = 0; i < self.selectedMediaItems.length; i++) {\n        if (self.selectedMediaItems[i].kind == \"song\" || self.selectedMediaItems[i].kind == \"songs\") {\n          self.selectedMediaItems[i].kind = \"songs\";\n          pl_items.push({\n            id: self.selectedMediaItems[i].id,\n            type: self.selectedMediaItems[i].kind,\n          });\n        } else if ((self.selectedMediaItems[i].kind == \"album\" || self.selectedMediaItems[i].kind == \"albums\") && self.selectedMediaItems[i].isLibrary != true) {\n          self.selectedMediaItems[i].kind = \"albums\";\n          let res = await self.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/albums/${self.selectedMediaItems[i].id}/tracks`);\n          let ids = res.data.data.map(function (i) {\n            return { id: i.id, type: i.type };\n          });\n          pl_items = pl_items.concat(ids);\n        } else if (self.selectedMediaItems[i].kind == \"library-song\" || self.selectedMediaItems[i].kind == \"library-songs\") {\n          self.selectedMediaItems[i].kind = \"library-songs\";\n          pl_items.push({\n            id: self.selectedMediaItems[i].id,\n            type: self.selectedMediaItems[i].kind,\n          });\n        } else if (self.selectedMediaItems[i].kind == \"library-album\" || self.selectedMediaItems[i].kind == \"library-albums\" || (self.selectedMediaItems[i].kind == \"album\" && self.selectedMediaItems[i].isLibrary == true)) {\n          self.selectedMediaItems[i].kind = \"library-albums\";\n          let res = await self.mk.api.v3.music(`/v1/me/library/albums/${self.selectedMediaItems[i].id}/tracks`);\n          let ids = res.data.data.map(function (i) {\n            return { id: i.id, type: i.type };\n          });\n          pl_items = pl_items.concat(ids);\n        } else {\n          pl_items.push({\n            id: self.selectedMediaItems[i].id,\n            type: self.selectedMediaItems[i].kind,\n          });\n        }\n      }\n      this.modals.addToPlaylist = false;\n      app.newPlaylist(app.getLz(\"term.newPlaylist\"), pl_items);\n    },\n    async isSongInPlaylist(song_ids, playlist_id) {\n      let isInPlaylist = false;\n      const playlistTracks = (\n        await app.mk.api.v3.music(`/v1/me/library/playlists/${playlist_id}/tracks`, {\n          platform: \"web\",\n          l: app.mklang,\n        })\n      ).data?.data;\n\n      playlistTracks.forEach((track) => {\n        if (song_ids.includes(track.id)) {\n          isInPlaylist = true;\n        }\n      });\n      return isInPlaylist;\n    },\n    addToPlaylist(pid, pitems) {\n      app.mk.api.v3\n        .music(\n          `/v1/me/library/playlists/${pid}/tracks`,\n          {},\n          {\n            fetchOptions: {\n              method: \"POST\",\n              body: JSON.stringify({\n                data: pitems,\n              }),\n            },\n          },\n        )\n        .then(() => {\n          if (app.page === \"playlist_\" + pid) {\n            app.getPlaylistFromID(app.showingPlaylist.id, true);\n          }\n        });\n    },\n    async addSelectedToPlaylist(playlist_id) {\n      let self = this;\n      let pl_items = [];\n      const song_ids = [];\n      for (let i = 0; i < self.selectedMediaItems.length; i++) {\n        if (self.selectedMediaItems[i].kind == \"song\" || self.selectedMediaItems[i].kind == \"songs\") {\n          self.selectedMediaItems[i].kind = \"songs\";\n          pl_items.push({\n            id: self.selectedMediaItems[i].id,\n            type: self.selectedMediaItems[i].kind,\n          });\n          song_ids.push(self.selectedMediaItems[i].id);\n        } else if ((self.selectedMediaItems[i].kind == \"album\" || self.selectedMediaItems[i].kind == \"albums\") && self.selectedMediaItems[i].isLibrary != true) {\n          self.selectedMediaItems[i].kind = \"albums\";\n          let res = await self.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/albums/${self.selectedMediaItems[i].id}/tracks`);\n          let ids = res.data.data.map(function (i) {\n            return { id: i.id, type: i.type };\n          });\n          pl_items = pl_items.concat(ids);\n          song_ids.push(...ids.map((id) => id.id));\n        } else if (self.selectedMediaItems[i].kind == \"library-song\" || self.selectedMediaItems[i].kind == \"library-songs\") {\n          self.selectedMediaItems[i].kind = \"library-songs\";\n          pl_items.push({\n            id: self.selectedMediaItems[i].id,\n            type: self.selectedMediaItems[i].kind,\n          });\n          song_ids.push(self.selectedMediaItems[i].id);\n        } else if (self.selectedMediaItems[i].kind == \"library-album\" || self.selectedMediaItems[i].kind == \"library-albums\" || (self.selectedMediaItems[i].kind == \"album\" && self.selectedMediaItems[i].isLibrary == true)) {\n          self.selectedMediaItems[i].kind = \"library-albums\";\n          let res = await self.mk.api.v3.music(`/v1/me/library/albums/${self.selectedMediaItems[i].id}/tracks`);\n          let ids = res.data.data.map(function (i) {\n            return { id: i.id, type: i.type };\n          });\n          pl_items = pl_items.concat(ids);\n          song_ids.push(...ids.map((id) => id.id));\n        } else {\n          pl_items.push({\n            id: self.selectedMediaItems[i].id,\n            type: self.selectedMediaItems[i].kind,\n          });\n          song_ids.push(self.selectedMediaItems[i].id);\n        }\n      }\n      this.modals.addToPlaylist = false;\n\n      if (await this.isSongInPlaylist(song_ids, playlist_id)) {\n        app.confirm(app.getLz(\"action.addToPlaylist.duplicate\"), (result) => {\n          if (result === true) {\n            app.addToPlaylist(playlist_id, pl_items);\n          }\n        });\n      } else {\n        app.addToPlaylist(playlist_id, pl_items);\n      }\n    },\n    async init() {\n      let self = this;\n      if (!localStorage.getItem(\"seenOOBE\")) {\n        localStorage.setItem(\"seenOOBE\", 1);\n      }\n      if (this.cfg.visual.styles.length != 0) {\n        await this.reloadStyles();\n      }\n\n      if (this.platform == \"darwin\") {\n        this.chrome.windowControlPosition = \"left\";\n      }\n\n      if (this.cfg.visual.nativeTitleBar) {\n        this.chrome.nativeControls = true;\n      }\n\n      this.setLz(this.cfg.general.language);\n      this.setLzManual();\n      clearTimeout(this.hangtimer);\n      this.mk = MusicKit.getInstance();\n      let needsReload = typeof localStorage[\"music.ampwebplay.media-user-token\"] == \"undefined\";\n      if (needsReload) {\n        ipcRenderer.send(\"auth-window\");\n        this.mkIsReady = true;\n      }\n      // this.mk.authorize().then(() => {\n      //   self.mkIsReady = true;\n      //   if (needsReload) {\n      //     document.location.reload();\n      //   }\n      // });\n      this.$forceUpdate();\n      if (this.isDev) {\n        this.mk.privateEnabled = true;\n        // Hide UserInfo if Dev mode\n      } else {\n        // Get Hide User from Settings\n        this.chrome.hideUserInfo = !this.cfg.visual.showuserinfo;\n        this.mk.privateEnabled = this.cfg.general.privateEnabled;\n      }\n      if (this.cfg.visual.hw_acceleration == \"disabled\") {\n        document.body.classList.add(\"no-gpu\");\n      }\n      this.mk._services.timing.mode = 0;\n      this.platform = this.cfg.main.PLATFORM;\n\n      this.mklang = await this.MKJSLang();\n      this.mk._playbackController._storekit.overrideRestrictEnabled(false);\n      try {\n        // Set profile name\n        this.chrome.userinfo = (await app.mk.api.v3.music(`/v1/me/social-profile`)).data.data[0];\n        // check if this.chrome.userinfo.attributes.artwork exists\n        if (this.chrome.userinfo.attributes.artwork && !this.chrome.hideUserInfo) {\n          document.documentElement.style.setProperty(\"--cvar-userprofileimg\", `url(\"${this.getMediaItemArtwork(this.chrome.userinfo.attributes.artwork.url)}\")`);\n        }\n      } catch (err) {}\n\n      // Used to get a scale factor for the window for CSS scaling\n      window.addEventListener(\"resize\", (e) => this.setWindowScaleFactor());\n      this.setWindowScaleFactor();\n      this.mk._bag.features[\"seamless-audio-transitions\"] = this.cfg.audio.seamless_audio;\n      this.mk._bag.features[\"broadcast-radio\"] = true;\n      this.mk._services.apiManager.store.storekit._restrictedEnabled = false;\n      // API Fallback\n      if (!this.chrome.userinfo) {\n        this.chrome.userinfo = {\n          id: \"\",\n          attributes: {\n            name: \"Cider User\",\n            handle: \"CiderUser\",\n            artwork: { url: \"./assets/logocut.png\" },\n          },\n        };\n      }\n      MusicKitInterop.init();\n      this.monitorMusickit();\n      // Set the volume\n\n      // Check the value of this.cfg.audio.muted\n      if (!this.cfg.audio.muted) {\n        // Set the mk.volume to the last stored volume data\n        this.mk.volume = this.cfg.audio.volume;\n      } else if (this.cfg.audio.muted) {\n        // Set mk.volume to -1 (setting to 0 wont work, so temp solution setting to -1)\n        this.mk.volume = -1;\n      }\n\n      // Restore mk\n\n      // load cached library\n      let librarySongs = await CiderCache.getCache(\"library-songs\");\n      let libraryAlbums = await CiderCache.getCache(\"library-albums\");\n      if (librarySongs) {\n        this.library.songs.listing = librarySongs;\n        this.library.songs.displayListing = this.library.songs.listing;\n      }\n      if (libraryAlbums) {\n        this.library.albums.listing = libraryAlbums;\n        this.library.albums.displayListing = this.library.albums.listing;\n      }\n\n      if (typeof MusicKit.PlaybackBitrate[app.cfg.audio.quality] !== \"string\") {\n        app.mk.bitrate = MusicKit.PlaybackBitrate[app.cfg.audio.quality];\n      } else {\n        app.mk.bitrate = 256;\n        app.cfg.audio.quality = \"HIGH\";\n      }\n\n      switch (this.cfg.general.resumeOnStartupBehavior) {\n        default:\n        case \"local\":\n          // load last played track\n          try {\n            let lastItem = window.localStorage.getItem(\"currentTrack\");\n            let time = window.localStorage.getItem(\"currentTime\");\n            let queue = window.localStorage.getItem(\"currentQueue\");\n            app.mk.queue.position = 0; // Reset queue position.\n            if (lastItem != null) {\n              lastItem = JSON.parse(lastItem);\n              let kind = lastItem.attributes.playParams.kind;\n              let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n              app.mk.setQueue({\n                [truekind]: [lastItem.attributes.playParams.id],\n                parameters: { l: app.mklang },\n              });\n              app.mk.mute();\n              setTimeout(() => {\n                app.mk.play().then(() => {\n                  app.mk.pause().then(() => {\n                    if (time != null) {\n                      app.mk.seekToTime(time);\n                    }\n                    app.mk.unmute();\n                    if (queue != null) {\n                      queue = JSON.parse(queue);\n                      if (queue && queue.length > 0) {\n                        let ids = queue.map((e) => (e.playParams ? e.playParams.id : e.item.attributes.playParams ? e.item.attributes.playParams.id : \"\"));\n                        let i = 0;\n                        if (ids.length > 0) {\n                          for (let id of ids) {\n                            if (!(i == 0 && ids[0] == lastItem.attributes.playParams.id)) {\n                              try {\n                                app.mk.playLater({ songs: [id] });\n                              } catch (err) {}\n                            }\n                            i++;\n                          }\n                        }\n                      }\n                    }\n                  });\n                });\n              }, 1500);\n            }\n          } catch (e) {\n            console.log(e);\n          }\n          break;\n        case \"history\":\n          let history = await app.mk.api.v3.music(`/v1/me/recent/played/tracks`, { l: app.mklang });\n          if (history.data.data.length > 0) {\n            let lastItem = history.data.data[0];\n            let kind = lastItem.attributes.playParams.kind;\n            let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n            app.mk.setQueue({\n              [truekind]: [lastItem.attributes.playParams.id],\n              parameters: { l: app.mklang },\n            });\n            app.mk.mute();\n            setTimeout(() => {\n              app.mk.play().then(() => {\n                app.mk.pause().then(() => {\n                  app.mk.unmute();\n                });\n              });\n            }, 1500);\n          }\n\n          break;\n        case \"disabled\":\n          break;\n      }\n\n      MusicKit.getInstance().videoContainerElement = document.getElementById(\"apple-music-video-player\");\n\n      ipcRenderer.on(\"setStoreValue\", (e, key, value) => {\n        app.cfg[key] = value;\n      });\n\n      ipcRenderer.on(\"theme-update\", async (event, arg) => {\n        await less.refresh(true, true, true);\n        self.setTheme(self.cfg.visual.theme, true);\n        if (app.cfg.visual.styles.length != 0) {\n          app.reloadStyles();\n        }\n      });\n\n      /**\n       * DiscordRPC Reload Return Event\n       * @author @coredev-uk\n       */\n      ipcRenderer.on(\"rpcReloaded\", (e, user) => {\n        if (user.username) {\n          app.notyf.success(\n            app.stringTemplateParser(app.getLz(\"settings.option.connectivity.discordRPC.reconnectedToUser\"), {\n              user: `${user.username}#${user.discriminator}`,\n              userid: user.id,\n            }),\n          );\n        }\n      });\n\n      ipcRenderer.on(\"getUpdatedLocalList\", (event, data) => {\n        // console.log(\"cider-local\", data);\n        this.library.localsongs = data;\n      });\n\n      ipcRenderer.on(\"window-state-changed\", (event, data) => {\n        this.chrome.windowState = data;\n      });\n\n      ipcRenderer.on(\"SoundCheckTag\", (event, tag) => {\n        // let replaygain = self.parseSCTagToRG(tag)\n        try {\n          if (app.mk.nowPlayingItem.type !== \"song\") {\n            CiderAudio.audioNodes.gainNode.gain.value = 0.70794578438;\n          } else {\n            let soundcheck = tag.split(\" \");\n            let numbers = [];\n            for (let item of soundcheck) {\n              numbers.push(parseInt(item, 16));\n            }\n            numbers.shift();\n            let peak = Math.max(numbers[6], numbers[7]) / 32768.0;\n            let gain = Math.pow(10, (-1.7 - Math.log10(peak) * 20) / 20); // EBU R 128 Compliant\n            console.debug(`[Cider][MaikiwiSoundCheck] Peak Gain: '${(Math.log10(peak) * 20).toFixed(2)}' dB | Adjusting '${(Math.log10(gain) * 20).toFixed(2)}' dB`);\n            try {\n              //CiderAudio.audioNodes.gainNode.gain.value = (Math.min(Math.pow(10, (replaygain.gain / 20)), (1 / replaygain.peak)))\n              CiderAudio.audioNodes.gainNode.gain.value = gain;\n              CiderAudio.hierarchical_loading();\n            } catch (e) {}\n          }\n        } catch (e) {\n          try {\n            ipcRenderer.send(\"SoundCheckTag\", event, tag);\n          } catch (e) {\n            try {\n              ipcRenderer.send(\"SoundCheckTag\", event, tag);\n            } catch (e) {\n              console.log(\"[Cider][MaikiwiSoundCheck] Error [Gave up after 3 consecutive attempts]: \" + e);\n            }\n          }\n        } // brute force until it works\n      });\n\n      ipcRenderer.on(\"play\", function (_event, mode, id) {\n        if (mode !== \"url\") {\n          self.mk.setQueue({ [mode]: id, parameters: { l: self.mklang } }).then(() => {\n            app.mk.play();\n          });\n        } else {\n          app.openAppleMusicURL(id);\n        }\n      });\n\n      this.mk.addEventListener(MusicKit.Events.playbackStateDidChange, (event) => {\n        ipcRenderer.send(\"wsapi-updatePlaybackState\", wsapi.getAttributes());\n        document.body.setAttribute(\"playback-state\", event.state == 2 ? \"playing\" : \"paused\");\n      });\n\n      this.mk.addEventListener(MusicKit.Events.playbackTimeDidChange, (a) => {\n        // self.lyriccurrenttime = self.mk.currentPlaybackTime - app.lyricOffset\n        this.currentSongInfo = a;\n        self.playerLCD.playbackDuration = self.mk.currentPlaybackTime;\n        // wsapi\n        ipcRenderer.send(\"wsapi-updatePlaybackState\", wsapi.getAttributes());\n      });\n\n      this.mk.addEventListener(MusicKit.Events.queueItemsDidChange, () => {\n        if (self.$refs.queue || self.$refs.fsView?.$refs?.queue) {\n          setTimeout(() => {\n            if (self.$refs.fsView?.$refs?.queue) {\n              self.$refs.fsView?.$refs?.queue.updateQueue();\n            }\n            if (self.$refs?.queue) {\n              self.$refs.queue.updateQueue();\n            }\n          }, 100);\n        }\n      });\n\n      // Used for Live Radio stations to set Metadata\n      this.mk.addEventListener(MusicKit.Events.timedMetadataDidChange, (e) => {\n        app.mk.nowPlayingItem.attributes.name = e.title;\n        app.mk.nowPlayingItem.attributes.artistName = e.performer;\n        app.mk.nowPlayingItem.attributes.albumName = e.album;\n        if (e.links[1]) {\n          app.currentArtUrl = e.links[1].url;\n          app.currentArtUrlRaw = e.links[1].url;\n        } else {\n          app.currentArtUrl = e.links[0].url;\n          app.currentArtUrlRaw = e.links[0].url;\n        }\n        app.mk.nowPlayingItem._songId = e._adamId ? e._adamId : -1;\n        app.mk.nowPlayingItem.id = e._adamId ? e._adamId : -1;\n      });\n\n      this.mk.addEventListener(MusicKit.Events.nowPlayingItemDidChange, (a) => {\n        if (self.$refs.fsView?.$refs?.queue) {\n          self.$refs.fsView?.$refs?.queue.updateQueue();\n        }\n        if (self.$refs?.queue) {\n          self.$refs.queue.updateQueue();\n        }\n        this.currentSongInfo = a;\n        if (this.currentSongInfo === null || this.currentSongInfo === undefined) {\n          return;\n        } // EVIL EMPTY OBJECTS BE GONE\n\n        try {\n          this.radiohls.destroy();\n          this.radiohls = null;\n        } catch (_) {}\n\n        try {\n          if ((MusicKit.getInstance().nowPlayingItem[\"type\"] ?? \"\").includes(\"ideo\")) {\n            setTimeout(() => {\n              this.MVsource = CiderAudio.context.createMediaElementSource(document.querySelector(\"div#apple-music-video-player > video\"));\n              this.MVsource.connect(CiderAudio.audioNodes.intelliGainComp);\n            }, 300);\n          } else {\n            this.MVsource.disconnect();\n            this.MVsource = null;\n          }\n        } catch (e) {\n          // console.log(e);\n        }\n\n        let localFiles = false;\n        try {\n          if (app.mk.nowPlayingItem.flavor.includes(\"64\") && app.mk.nowPlayingItem.flavor.includes(\":\")) {\n            localStorage.setItem(\"playingBitrate\", \"64\");\n          } else if (app.mk.nowPlayingItem.flavor.includes(\"256\") && app.mk.nowPlayingItem.flavor.includes(\":\")) {\n            localStorage.setItem(\"playingBitrate\", \"256\");\n          } else {\n            localFiles = true;\n            localStorage.setItem(\"playingBitrate\", app.mk.nowPlayingItem.flavor);\n          }\n        } catch (e) {\n          localFiles = true;\n          try {\n            localStorage.setItem(\"playingBitrate\", app.mk.nowPlayingItem.flavor);\n          } catch (e) {}\n        }\n\n        if (app.cfg.audio.normalization === false) {\n          CiderAudio.hierarchical_loading();\n        } // Just Reload for Adaptive CAP if norm is off\n        else {\n          // get unencrypted audio previews to get SoundCheck's normalization tag\n          try {\n            let previewURL = null;\n            try {\n              previewURL = app.mk.nowPlayingItem.previewURL;\n            } catch (e) {\n              if (e instanceof TypeError === false) {\n                console.debug(\"[Cider][MaikiwiSoundCheck] normalizer function err: \" + e);\n              } else {\n                if (localFiles === true) {\n                  CiderAudio.audioNodes.gainNode.gain.value = 0.822242649947;\n                }\n              }\n            }\n            if (previewURL == null && (app.mk.nowPlayingItem?._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? app.mk.nowPlayingItem.relationships.catalog.data[0].id) != -1) {\n              app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/songs/${app.mk.nowPlayingItem?._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? app.mk.nowPlayingItem.relationships.catalog.data[0].id}`).then((response) => {\n                try {\n                  previewURL = response.data.data[0].attributes.previews[0].url;\n                } catch (e) {\n                  if (e instanceof TypeError === false) {\n                    console.debug(\"[Cider][MaikiwiSoundCheck] normalizer function err: \" + e);\n                  } else {\n                    if (localFiles === true) {\n                      CiderAudio.audioNodes.gainNode.gain.value = 0.822242649947;\n                    }\n                  }\n                }\n                if (previewURL) {\n                  console.debug(\"[Cider][MaikiwiSoundCheck] previewURL response.data.data[0].attributes.previews[0].url: \" + previewURL);\n                  ipcRenderer.send(\"getPreviewURL\", previewURL);\n                } else {\n                  if (localFiles === true) {\n                    CiderAudio.audioNodes.gainNode.gain.value = 0.822242649947;\n                  }\n                }\n              });\n            } else {\n              if (previewURL) {\n                console.debug(\"[Cider][MaikiwiSoundCheck] previewURL in app.mk.nowPlayingItem.previewURL: \" + previewURL);\n                ipcRenderer.send(\"getPreviewURL\", previewURL);\n              }\n            }\n          } catch (e) {\n            if (e instanceof TypeError === false) {\n              console.debug(\"[Cider][MaikiwiSoundCheck] normalizer function err: \" + e);\n            } else {\n              if (localFiles === true) {\n                CiderAudio.audioNodes.gainNode.gain.value = 0.822242649947;\n              }\n            }\n          }\n        }\n\n        try {\n          a = a.item.attributes;\n        } catch (_) {}\n        let type = self.mk.nowPlayingItem != null ? self.mk.nowPlayingItem[\"type\"] ?? \"\" : \"\";\n\n        if (type.includes(\"musicVideo\") || type.includes(\"uploadedVideo\") || type.includes(\"music-movie\") || (self.mk.nowPlayingItem?.type == \"radioStation\") & (self.mk.nowPlayingItem?.attributes?.mediaKind == \"video\")) {\n          document.getElementById(\"apple-music-video-container\").style.display = \"block\";\n          document.body.setAttribute(\"video-playing\", \"true\");\n          // app.chrome.topChromeVisible = false\n        } else {\n          document.body.removeAttribute(\"video-playing\");\n          document.getElementById(\"apple-music-video-container\").style.display = \"none\";\n          // app.chrome.topChromeVisible = true\n        }\n        self.chrome.artworkReady = false;\n        self.lyrics = [];\n        self.richlyrics = [];\n        app.getCurrentArtURL().then((urls) => {\n          app.currentArtUrl = urls?.currentArtUrl ?? \"\";\n          app.currentArtUrlRaw = urls?.currentArtUrlRaw ?? \"\";\n          ipcRenderer.send(\"discordrpc:updateImage\", app.currentArtUrl);\n        });\n        // app.getNowPlayingArtwork(42);\n        app.getNowPlayingArtworkBG(32);\n        app.loadLyrics();\n\n        setTimeout(() => {\n          let i = document.querySelector(\"#apple-music-player\")?.src ?? \"\";\n          if (i.endsWith(\".m3u8\") || i.endsWith(\".m3u\")) {\n            this._playRadioStream(i);\n          }\n        }, 1500);\n      });\n\n      this.mk.addEventListener(MusicKit.Events.playbackVolumeDidChange, (_a) => {\n        this.cfg.audio.volume = this.mk.volume;\n        ipcRenderer.send(\"mpris:volumeChange\", this.mk.volume);\n      });\n\n      this.refreshPlaylists(this.isDev);\n      document.body.removeAttribute(\"loading\");\n      if (window.location.hash != \"\") {\n        this.appRoute(window.location.hash);\n      }\n\n      if (this.page != \"home\") {\n        this.resumeTabs();\n      }\n      this.mediaKeyFixes();\n\n      setTimeout(() => {\n        this.getSocialBadges();\n        this.getBrowsePage();\n        this.$forceUpdate();\n      }, 500);\n      document.querySelector(\"#apple-music-video-player-controls\").addEventListener(\"mousemove\", () => {\n        this.showFoo(\".music-player-info\", 2000);\n      });\n      ipcRenderer.invoke(\"renderer-ready\", true);\n      document.querySelector(\"#LOADER\").remove();\n      if (this.cfg.general.themeUpdateNotification && !this.isDev) {\n        this.checkForThemeUpdates();\n      }\n\n      if (!localStorage.getItem(\"noC2Startup\")) {\n        const c2UpgradeDate = 1688172351000;\n        if (Date.now() <= c2UpgradeDate) {\n          setTimeout(() => {\n            app.modals.c2Upgrade = true;\n          }, 2000);\n        }\n      }\n    },\n    setWindowScaleFactor() {\n      let scale = (((window.devicePixelRatio * window.innerWidth) / 1280) * window.innerHeight) / 720;\n      let desiredScale = clamp(parseFloat(app.cfg.visual.maxElementScale == -1 ? 1.5 : app.cfg.visual.maxElementScale), 1, 1.5);\n      app.$store.state.windowRelativeScale = scale;\n      if (scale <= 1) {\n        scale = 1;\n      } else if (scale >= desiredScale) {\n        scale = desiredScale;\n      }\n      document.documentElement.style.setProperty(\"--windowRelativeScale\", scale);\n    },\n    c2offer() {\n      app.modals.c2Upgrade = true;\n    },\n    showFoo(querySelector, time) {\n      clearTimeout(this.idleTimer);\n      if (this.idleState == true) {\n        document.querySelector(querySelector).classList.remove(\"inactive\");\n      }\n      this.idleState = false;\n      this.idleTimer = setTimeout(() => {\n        document.querySelector(querySelector).classList.add(\"inactive\");\n        this.idleState = true;\n      }, time);\n    },\n    setContentScrollPos(scroll) {\n      this.chrome.contentScrollPosY = scroll.target.scrollTop;\n    },\n    async checkForThemeUpdates() {\n      let self = this;\n      const themes = ipcRenderer.sendSync(\"get-themes\");\n      await asyncForEach(themes, async (theme) => {\n        if (theme.commit != \"\") {\n          if (theme.commit != \"\") {\n            app._fetch(`https://api.github.com/repos/${theme.github_repo}/commits`).then((res) => res.json());\n            if (res[0].sha != theme.commit) {\n              const notify = notyf.open({\n                className: \"notyf-info\",\n                type: \"info\",\n                message: app.stringTemplateParser(app.getLz(\"settings.notyf.visual.theme.updateAvailable\"), { theme: theme.name }),\n              });\n              notify.on(\"click\", () => {\n                app.openSettingsPage(\"github-themes\");\n                notyf.dismiss(notify);\n              });\n            }\n          }\n        }\n      });\n    },\n    async setTheme(theme = \"\", onlyPrefs = false) {\n      console.debug(theme);\n      if (this.cfg.visual.theme == \"\") {\n        this.cfg.visual.theme = \"default.less\";\n      }\n      if (theme == \"\") {\n        theme = this.cfg.visual.theme;\n      } else {\n        this.cfg.visual.theme = \"\";\n        this.cfg.visual.theme = theme;\n      }\n      const info = {};\n      try {\n        const infoResponse = await fetch(\"themes/\" + app.cfg.visual.theme.replace(\"index.less\", \"theme.json\"));\n        this.chrome.appliedTheme.info = await infoResponse.json();\n      } catch (e) {\n        e = null;\n        console.warn(\"failed to get theme.json\");\n        this.chrome.appliedTheme.info = {};\n      }\n\n      if (!onlyPrefs) {\n        document.querySelector(\"#userTheme\").href = `themes/${this.cfg.visual.theme}`;\n        document.querySelectorAll(`[id*='less']`).forEach((el) => {\n          el.remove();\n        });\n        await less.refresh();\n      }\n    },\n    async reloadStyles() {\n      const styles = this.cfg.visual.styles;\n      document.querySelectorAll(`[id*='less']`).forEach((el) => {\n        if (el.id != \"less:style\") {\n          el.remove();\n        }\n      });\n\n      this.chrome.appliedTheme.info = {};\n      await asyncForEach(styles, async (style) => {\n        let styleEl = document.createElement(\"link\");\n        styleEl.id = `less-${style.replace(\".less\", \"\")}`;\n        styleEl.rel = \"stylesheet/less\";\n        styleEl.href = `themes/${style}`;\n        styleEl.type = \"text/css\";\n        document.head.appendChild(styleEl);\n        try {\n          let infoResponse = await fetch(\"themes/\" + style.replace(\"index.less\", \"theme.json\"));\n          this.chrome.appliedTheme.info = Object.assign(this.chrome.appliedTheme.info, await infoResponse.json());\n        } catch (e) {\n          e = null;\n          console.warn(\"failed to get theme.json\");\n        }\n      });\n      less.registerStylesheetsImmediately();\n      await less.refresh(true, true, true);\n      this.$forceUpdate();\n      return;\n    },\n    macOSEmu() {\n      this.chrome.forceDirectives[\"macosemu\"] = {\n        value: true,\n      };\n      this.chrome.windowControlPosition = \"left\";\n    },\n    getThemeDirective(directive = \"\") {\n      let directives = {};\n      if (typeof this.chrome.appliedTheme.info.directives == \"object\") {\n        directives = this.chrome.appliedTheme.info.directives;\n      }\n      directives = Object.assign(directives, this.chrome.forceDirectives);\n      if (directives[directive]) {\n        return directives[directive].value;\n      } else if (this.cfg.visual.directives[directive]) {\n        return this.cfg.visual.directives[directive];\n      } else {\n        return false;\n      }\n    },\n    unauthorize() {\n      this.confirm(app.getLz(\"term.confirmLogout\"), function (result) {\n        if (result) {\n          app.mk.unauthorize();\n          document.location.reload();\n        }\n      });\n    },\n    getAppClasses() {\n      let classes = {};\n      switch (this.getThemeDirective(\"forceUI\") ?? \"none\") {\n        case \"compact\":\n          classes.compact = true;\n          break;\n        case \"standard\":\n          classes.compact = false;\n          break;\n        default:\n          if (this.cfg.advanced.experiments.includes(\"compactui\")) {\n            classes.compact = true;\n          }\n          break;\n      }\n\n      if (this.cfg.visual.window_background_style == \"none\") {\n        classes.simplebg = true;\n      }\n\n      if (this.platform !== \"darwin\") {\n        switch (parseInt(this.cfg.visual.windowControlPosition)) {\n          default:\n          case 0:\n            this.chrome.windowControlPosition = \"right\";\n            this.chrome.forceDirectives[\"macosemu\"] = {\n              value: false,\n            };\n            break;\n          case 1:\n            this.chrome.windowControlPosition = \"left\";\n            this.chrome.forceDirectives[\"macosemu\"] = {\n              value: true,\n            };\n            break;\n        }\n      }\n\n      if (this.getThemeDirective(\"windowLayout\") == \"twopanel\") {\n        classes.twopanel = true;\n      }\n      if (this.getThemeDirective(\"appNavigation\") == \"seperate\") {\n        classes.navbar = true;\n      }\n      if (this.getThemeDirective(\"macosemu\") == true) {\n        classes.macosemu = true;\n      }\n      return classes;\n    },\n    invokeDrawer(panel) {\n      if (this.drawer.panel == panel && this.drawer.open) {\n        if (panel == \"lyrics\") {\n          this.lyricon = false;\n        }\n        this.drawer.panel = \"\";\n        this.drawer.open = false;\n      } else {\n        if (panel == \"lyrics\") {\n          this.lyricon = true;\n        } else {\n          this.lyricon = false;\n        }\n        this.drawer.open = true;\n        this.drawer.panel = panel;\n      }\n    },\n    select_removeMediaItem(id) {\n      this.selectedMediaItems\n        .filter((item) => item.guid == id)\n        .forEach((item) => {\n          this.selectedMediaItems.splice(this.selectedMediaItems.indexOf(item), 1);\n        });\n    },\n    select_hasMediaItem(id) {\n      let found = this.selectedMediaItems.find((item) => item.guid == id);\n      if (found) {\n        return true;\n      } else {\n        return false;\n      }\n    },\n    select_selectMediaItem(id, kind, index, guid, library) {\n      if (!this.select_hasMediaItem(guid)) {\n        this.selectedMediaItems.push({\n          id: id,\n          kind: kind,\n          index: index,\n          guid: guid,\n          isLibrary: library,\n        });\n      }\n    },\n    getPlaylistFolderChildren(id) {\n      return this.playlists.listing.filter((playlist) => {\n        if (playlist.parent == id) {\n          return playlist;\n        }\n      });\n    },\n    async syncFavorites() {\n      const notify = notyf.open({\n        className: \"notyf-info\",\n        type: \"info\",\n        message: `[${app.getLz(\"home.syncFavorites\")}] ${app.getLz(\"home.syncFavorites.gettingArtists\")}`,\n      });\n      const results = await MusicKitTools.v3Continuous({\n        href: \"/v1/me/library/artists\",\n        options: {\n          include: [\"catalog\"],\n          \"fields[artists]\": [\"inFavorites\"],\n        },\n      });\n      let favs = [];\n      // for each result\n      results.forEach((result) => {\n        try {\n          if (result.relationships?.catalog?.data[0]?.attributes?.inFavorites) {\n            if (!favs.includes(result.relationships?.catalog?.data[0].id)) {\n              favs.push(result.relationships?.catalog?.data[0].id);\n            }\n          }\n        } catch (e) {\n          e = null;\n        }\n      });\n      notyf.success(`[${app.getLz(\"home.syncFavorites\")}] ${app.getLz(\"action.done\")}`);\n      app.cfg.home.followedArtists = favs;\n      return favs;\n    },\n    async setArtistFavorite(id, val = true) {\n      if (val) {\n        if (!app.cfg.home.followedArtists.includes(id)) {\n          app.cfg.home.followedArtists.push(id);\n        }\n        await app.mk.api.v3.music(\n          `/v1/me/favorites`,\n          {\n            \"art[url]\": \"f\",\n            \"ids[artists]\": app.artistPage.data.id,\n            l: app.mklang,\n            platform: \"web\",\n          },\n          {\n            fetchOptions: {\n              method: \"POST\",\n            },\n          },\n        );\n      } else {\n        if (app.cfg.home.followedArtists.includes(id)) {\n          app.cfg.home.followedArtists.splice(app.cfg.home.followedArtists.indexOf(id), 1);\n        }\n        await app.mk.api.v3.music(\n          `/v1/me/favorites`,\n          {\n            \"art[url]\": \"f\",\n            \"ids[artists]\": app.artistPage.data.id,\n            l: app.mklang,\n            platform: \"web\",\n          },\n          {\n            fetchOptions: {\n              method: \"DELETE\",\n            },\n          },\n        );\n      }\n    },\n    async refreshPlaylists(localOnly = false, useCachedPlaylists = true) {\n      let self = this;\n      let trackMap = this.cfg.advanced.playlistTrackMapping;\n      let newListing = [];\n      let trackMapping = {};\n\n      if (useCachedPlaylists) {\n        const cachedPlaylist = await CiderCache.getCache(\"library-playlists\");\n        const cachedTrackMapping = await CiderCache.getCache(\"library-playlists-tracks\");\n\n        if (cachedPlaylist) {\n          console.debug(\"[CiderCache] Using cached playlist\");\n          this.playlists.listing = cachedPlaylist;\n          self.sortPlaylists();\n        } else {\n          console.debug(\"[CiderCache] Playlist has no cache\");\n        }\n\n        if (cachedTrackMapping) {\n          console.debug(\"[CiderCache] Using cached track mapping\");\n          this.playlists.trackMapping = cachedTrackMapping;\n        }\n        if (localOnly) {\n          return;\n        }\n      }\n\n      this.library.backgroundNotification.message = app.getLz(\"notification.buildingPlaylistCache\");\n      this.library.backgroundNotification.show = true;\n\n      async function deepScan(parent = \"p.playlistsroot\") {\n        console.debug(`scanning ${parent}`);\n        // const playlistData = await app.mk.api.v3.music(`/v1/me/library/playlist-folders/${parent}/children/`)\n        const playlistData = await MusicKitTools.v3Continuous({\n          href: `/v1/me/library/playlist-folders/${parent}/children/`,\n        });\n        console.log(playlistData);\n        await asyncForEach(playlistData, async (playlist) => {\n          playlist.parent = parent;\n          if (playlist.type != \"library-playlist-folders\" && typeof playlist.attributes.playParams[\"versionHash\"] != \"undefined\") {\n            playlist.parent = \"p.applemusic\";\n          }\n          playlist.children = [];\n          playlist.tracks = [];\n          try {\n            if (trackMap) {\n              let tracks = await app.mk.api.v3.music(playlist.href + \"/tracks\").catch((e) => {\n                // no tracks\n                e = null;\n              });\n              tracks.data.data.forEach((track) => {\n                if (!trackMapping[track.id]) {\n                  trackMapping[track.id] = [];\n                }\n                trackMapping[track.id].push(playlist.id);\n\n                if (typeof track.attributes.playParams.catalogId == \"string\") {\n                  if (!trackMapping[track.attributes.playParams.catalogId]) {\n                    trackMapping[track.attributes.playParams.catalogId] = [];\n                  }\n                  trackMapping[track.attributes.playParams.catalogId].push(playlist.id);\n                }\n              });\n            }\n          } catch (e) {}\n          if (playlist.type == \"library-playlist-folders\") {\n            try {\n              await deepScan(playlist.id).catch((e) => {});\n            } catch (e) {}\n          }\n          newListing.push(playlist);\n        });\n      }\n\n      await deepScan();\n\n      this.library.backgroundNotification.show = false;\n      this.playlists.listing = newListing;\n      self.sortPlaylists();\n      if (trackMap) {\n        CiderCache.putCache(\"library-playlists-tracks\", trackMapping);\n        this.playlists.trackMapping = trackMapping;\n      }\n      CiderCache.putCache(\"library-playlists\", newListing);\n    },\n    sortPlaylists() {\n      this.playlists.listing.sort((a, b) => {\n        if (a.type === \"library-playlist-folders\" && b.type !== \"library-playlist-folders\") {\n          return -1;\n        } else if (a.type !== \"library-playlist-folders\" && b.type === \"library-playlist-folders\") {\n          return 1;\n        } else {\n          return 0;\n        }\n      });\n    },\n    playlistHeaderContextMenu(event) {\n      let menu = {\n        items: [\n          {\n            name: app.getLz(\"term.createNewPlaylist\"),\n            action: () => {\n              this.newPlaylist();\n            },\n          },\n          {\n            name: app.getLz(\"term.createNewPlaylistFolder\"),\n            action: () => {\n              this.newPlaylistFolder();\n            },\n          },\n          {\n            name: app.getLz(\"action.refresh\"),\n            action: () => {\n              this.refreshPlaylists();\n            },\n          },\n        ],\n      };\n      this.showMenuPanel(menu, event);\n    },\n    async editPlaylistFolder(id, name = app.getLz(\"term.newPlaylist\")) {\n      let self = this;\n      this.mk.api.v3\n        .music(\n          `/v1/me/library/playlist-folders/${id}`,\n          {},\n          {\n            fetchOptions: {\n              method: \"PATCH\",\n              body: JSON.stringify({\n                attributes: { name: name },\n              }),\n            },\n          },\n        )\n        .then((res) => {\n          self.refreshPlaylists(false, false);\n        });\n    },\n    async editPlaylist(id, name = app.getLz(\"term.newPlaylist\")) {\n      let self = this;\n      this.mk.api.v3\n        .music(\n          `/v1/me/library/playlists/${id}`,\n          {},\n          {\n            fetchOptions: {\n              method: \"PATCH\",\n              body: JSON.stringify({\n                attributes: { name: name },\n              }),\n            },\n          },\n        )\n        .then((res) => {\n          self.refreshPlaylists(false, false);\n        });\n    },\n    async editPlaylistDescription(id, name = app.getLz(\"term.newPlaylist\")) {\n      let self = this;\n      this.mk.api.v3\n        .music(\n          `/v1/me/library/playlists/${id}`,\n          {},\n          {\n            fetchOptions: {\n              method: \"PATCH\",\n              body: JSON.stringify({\n                attributes: { description: name },\n              }),\n            },\n          },\n        )\n        .then((res) => {\n          self.refreshPlaylists(false, false);\n        });\n    },\n    copyToClipboard(str) {\n      // if (navigator.userAgent.includes('Darwin') || navigator.appVersion.indexOf(\"Mac\") != -1) {\n      // this.darwinShare(str)\n      // } else {\n      notyf.success(app.getLz(\"term.share.success\"));\n      navigator.clipboard.writeText(str).then((r) => console.debug(\"Copied to clipboard.\"));\n      // }\n    },\n    newPlaylist(name = app.getLz(\"term.newPlaylist\"), tracks = []) {\n      let self = this;\n      let request = {\n        name: name,\n      };\n      if (tracks.length > 0) {\n        request.tracks = tracks;\n      }\n      app.mk.api.v3\n        .music(\n          `/v1/me/library/playlists`,\n          {},\n          {\n            fetchOptions: {\n              method: \"POST\",\n              body: JSON.stringify({\n                attributes: { name: name },\n                relationships: {\n                  tracks: { data: tracks },\n                },\n              }),\n            },\n          },\n        )\n        .then((res) => {\n          res = res.data.data[0];\n          console.debug(res);\n          self.appRoute(`playlist_` + res.id);\n          self.showingPlaylist = [];\n          self.getPlaylistFromID(app.page.substring(9), true);\n          self.playlists.listing.push({\n            id: res.id,\n            attributes: {\n              name: name,\n            },\n            parent: \"p.playlistsroot\",\n          });\n          self.sortPlaylists();\n          setTimeout(() => {\n            app.refreshPlaylists(false, false);\n          }, 8000);\n        });\n    },\n    deletePlaylist(id) {\n      let self = this;\n      this.confirm(app.getLz(\"term.deletePlaylist\"), (ok) => {\n        if (ok) {\n          app.mk.api.v3\n            .music(\n              `/v1/me/library/playlists/${id}`,\n              {},\n              {\n                fetchOptions: {\n                  method: \"DELETE\",\n                },\n              },\n            )\n            .then((res) => {\n              // remove this playlist from playlists.listing if it exists\n              let found = self.playlists.listing.find((item) => item.id == id);\n              if (found) {\n                self.playlists.listing.splice(self.playlists.listing.indexOf(found), 1);\n              }\n              setTimeout(() => {\n                app.refreshPlaylists(false, false);\n              }, 8000);\n            });\n        }\n      });\n    },\n    /**\n     * @param {string} url, href for the initial request\n     * @memberof app\n     */\n    async showRoom(url) {\n      let self = this;\n      const response = await this.mk.api.v3.music(url);\n      let room = response.data.data[0];\n      this.showCollection(room.relationships.contents, room.attributes.title);\n    },\n    async showCollection(response, title, type, requestBody = {}) {\n      let self = this;\n      console.debug(response);\n      this.collectionList.requestBody = {};\n      this.collectionList.response = response;\n      this.collectionList.title = title;\n      this.collectionList.type = type;\n      this.collectionList.requestBody = requestBody;\n      app.appRoute(\"collection-list\");\n    },\n    async showArtistView(artist, title, view) {\n      let response = (await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists/${artist}/view/${view}?l=${this.mklang}`, {}, { includeResponseMeta: !0 })).data;\n      console.debug(response);\n      await this.showCollection(response, title, \"artists\");\n    },\n    async showRecordLabelView(label, title, view) {\n      let response = (await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/record-labels/${label}/view/${view}?l=${this.mklang}`)).data;\n      await this.showCollection(response, title, \"record-labels\");\n    },\n    async showSearchView(term, group, title) {\n      let requestBody = {\n        platform: \"web\",\n        groups: group,\n        types: \"activities,albums,apple-curators,artists,curators,editorial-items,music-movies,music-videos,playlists,songs,stations,tv-episodes,uploaded-videos,record-labels\",\n        limit: 25,\n        relate: {\n          editorialItems: [\"contents\"],\n        },\n        include: {\n          albums: [\"artists\"],\n          songs: [\"artists\"],\n          \"music-videos\": [\"artists\"],\n        },\n        extend: \"artistUrl\",\n        fields: {\n          artists: \"url,name,artwork,hero\",\n          albums: \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url\",\n        },\n        with: \"serverBubbles,lyricHighlights\",\n        art: {\n          url: \"cf\",\n        },\n        omit: {\n          resource: [\"autos\"],\n        },\n        l: this.mklang,\n      };\n      let response = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/search?term=${term}`, requestBody, {\n        includeResponseMeta: !0,\n      });\n\n      console.debug(\"searchres\", response);\n      let responseFormat = {\n        data: response.data.results[group].data,\n        next: response.data.results[group].next,\n        groups: group,\n      };\n      await this.showCollection(responseFormat, title, \"search\", requestBody);\n    },\n    async getPlaylistContinuous(response, transient = false) {\n      response = response.data.data[0];\n      let self = this;\n      let playlistId = response.id;\n      this.playlists.loadingState = !transient ? 0 : 1;\n      this.showingPlaylist = response;\n      if (!response.relationships?.tracks?.next) {\n        this.playlists.loadingState = 1;\n        return;\n      }\n\n      function getPlaylistTracks(next) {\n        app.apiCall(app.musicBaseUrl + next, (res) => {\n          if (self.showingPlaylist.id != playlistId) {\n            return;\n          }\n          self.showingPlaylist.relationships.tracks.data = self.showingPlaylist.relationships.tracks.data.concat(res.data);\n          if (res.next) {\n            getPlaylistTracks(res.next);\n          } else {\n            self.playlists.loadingState = 1;\n          }\n        });\n      }\n\n      getPlaylistTracks(response.relationships.tracks.next);\n    },\n    async getPlaylistFromID(id, transient = false) {\n      let self = this;\n      const params = {\n        include: \"tracks\",\n        platform: \"web\",\n        \"include[library-playlists]\": \"catalog,tracks\",\n        \"fields[playlists]\": \"curatorName,playlistType,name,artwork,url,playParams\",\n        \"include[library-songs]\": \"catalog,artists,albums,playParams,name,artwork,url\",\n        \"fields[catalog]\": \"artistUrl,albumUrl,url\",\n        \"fields[songs]\": \"artistUrl,albumUrl,playParams,name,artwork,url,artistName,albumName,durationInMillis\",\n        l: this.mklang,\n      };\n      if (!transient) {\n        this.playlists.loadingState = 0;\n      }\n      app.mk.api.v3\n        .music(`/v1/me/library/playlists/${id}`, params)\n        .then((res) => {\n          self.getPlaylistContinuous(res, transient);\n        })\n        .catch((e) => {\n          console.debug(e);\n          try {\n            app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/playlists/${id}`, params).then((res) => {\n              self.getPlaylistContinuous(res, transient);\n            });\n          } catch (err) {\n            console.debug(err);\n          }\n        });\n    },\n    async getArtistFromID(id) {\n      this.page = \"\";\n      const artistData = await this.mkapi(\n        \"artists\",\n        false,\n        id,\n        {\n          views: \"featured-release,full-albums,appears-on-albums,featured-albums,featured-on-albums,singles,compilation-albums,live-albums,latest-release,top-music-videos,similar-artists,top-songs,playlists,more-to-hear,more-to-see\",\n          extend: \"centeredFullscreenBackground,artistBio,bornOrFormed,editorialArtwork,editorialVideo,isGroup,origin,hero\",\n          \"extend[playlists]\": \"trackCount\",\n          \"include[songs]\": \"albums\",\n          \"fields[albums]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url,trackCount\",\n          \"limit[artists:top-songs]\": 20,\n          \"art[url]\": \"f\",\n          l: this.mklang,\n        },\n        { includeResponseMeta: !0 },\n      );\n      console.debug(artistData.data.data[0]);\n      this.artistPage.data = artistData.data.data[0];\n      this.page = \"artist-page\";\n    },\n    progressBarStyle() {\n      let val = this.playerLCD.playbackDuration;\n      if (this.playerLCD.desiredDuration > 0) {\n        val = this.playerLCD.desiredDuration;\n      }\n      let min = 0;\n      let max = this.mk.currentPlaybackDuration;\n      let value = ((val - min) / (max - min)) * 100;\n      return {\n        background: \"linear-gradient(to right, var(--songProgressColor) 0%, var(--songProgressColor) \" + value + \"%, var(--songProgressBackground) \" + value + \"%, var(--songProgressBackground) 100%)\",\n      };\n    },\n    async getRecursive(response) {\n      // if response has a .next() property run it and keep running until .next is null or undefined\n      // and then return the response concatenated with the results of the next() call\n      function executeRequest() {\n        if (response.next) {\n          return response.next().then(executeRequest);\n        } else {\n          return response;\n        }\n      }\n\n      return executeRequest();\n    },\n    async getRecursive2(response, sendTo) {\n      let returnData = {\n        data: [],\n        meta: {},\n      };\n      if (response.next) {\n        console.debug(\"has next\");\n        returnData.data.concat(response.data);\n        returnData.meta = response.meta;\n        return await this.getRecursive(await response.next());\n      } else {\n        console.debug(\"no next\");\n        returnData.data.concat(response.data);\n        return returnData;\n      }\n    },\n    async getSearchHints() {\n      if (this.search.term == \"\") {\n        this.search.hints = [];\n        this.search.showHints = true;\n        this.search.showSearchView = false;\n        return;\n      }\n      let hints = await (\n        await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/search/suggestions?term=${encodeURIComponent(this.search.term)}`, {\n          \"fields[albums]\": \"artwork,name,playParams,url,artistName,id\",\n          \"fields[artists]\": \"url,name,artwork,id\",\n          \"fields[songs]\": \"artwork,name,playParams,url,artistName,id\",\n          kinds: \"terms,topResults\",\n          l: this.mklang,\n          \"limit[results:terms]\": 5,\n          \"limit[results:topResults]\": 5,\n          \"omit[resource]\": \"autos\",\n          platform: \"web\",\n          types: \"activities,albums,artists,editorial-items,music-movies,playlists,record-labels,songs,stations\",\n        })\n      ).data.results;\n      let shints = hints ? hints.suggestions : [];\n      for (let item in shints) {\n        if ((shints[item]?.displayTerm ?? \"\").includes(\"?fields[\")) {\n          shints[item].displayTerm = shints[item].searchTerm = shints[item].displayTerm.split(\"?fields[\")[0];\n        }\n      }\n      this.search.hints = shints;\n    },\n    getSongProgress() {\n      if (this.playerLCD.userInteraction) {\n        return this.playerLCD.desiredDuration;\n      } else {\n        return this.playerLCD.playbackDuration;\n      }\n    },\n    /**\n     * Converts seconds to dd:hh:mm:ss / Days:Hours:Minutes:Seconds\n     * @param {number} seconds\n     * @param {string} format (short, long)\n     * @returns {string}\n     * @author Core#1034\n     * @memberOf app\n     */\n    convertTime(seconds, format = \"short\") {\n      if (app.mk?.nowPlayingItem?.type === \"radioStation\") return;\n      if (isNaN(seconds) || seconds === Infinity) {\n        seconds = 0;\n      }\n\n      const datetime = new Date(seconds * 1000);\n\n      if (format === \"long\") {\n        const d = Math.floor(seconds / (3600 * 24));\n        const h = Math.floor((seconds % (3600 * 24)) / 3600);\n        const m = Math.floor((seconds % 3600) / 60);\n        const s = Math.floor(seconds % 60);\n\n        const dDisplay = d > 0 ? `${d} ${app.getLz(\"term.time.day\", { count: d })}` : \"\";\n        const hDisplay = h > 0 ? `${h} ${app.getLz(\"term.time.hour\", { count: h })}` : \"\";\n        const mDisplay = m > 0 ? `${m} ${app.getLz(\"term.time.minute\", { count: m })}` : \"\";\n\n        return dDisplay + (dDisplay && hDisplay ? \", \" : \"\") + hDisplay + (hDisplay && mDisplay ? \", \" : \"\") + mDisplay;\n      } else {\n        return MusicKit.formatMediaTime(seconds);\n      }\n    },\n    hashCode(str) {\n      let hash = 0,\n        i,\n        chr;\n      if (str.length === 0) return hash;\n      for (i = 0; i < str.length; i++) {\n        chr = str.charCodeAt(i);\n        hash = (hash << 5) - hash + chr;\n        hash |= 0; // Convert to 32bit integer\n      }\n      return hash;\n    },\n    getPagePos(href = \"\") {\n      let state = this.$store.state.pageState.scrollPos.pos.find((page) => {\n        return page.href === href;\n      });\n      return (\n        state ?? {\n          page: href,\n          position: 0,\n        }\n      );\n    },\n    appRoute(route) {\n      if (route == \"\" || route == \"#\" || route == \"/\") {\n        return;\n      }\n      route = route.replace(/#/g, \"\");\n      if (app.cfg.general.resumeTabs.tab == \"dynamic\") {\n        if (route == \"home\" || route == \"listen_now\" || route == \"browse\" || route == \"radio\" || route == \"library-songs\" || route == \"library-albums\" || route == \"library-artists\" || route == \"library-videos\" || route == \"podcasts\") {\n          app.cfg.general.resumeTabs.dynamicData = route;\n        } else {\n          app.cfg.general.resumeTabs.dynamicData = \"home\";\n        }\n      }\n\n      // if the route contains does not include a / then route to the page directly\n      if (route.indexOf(\"/\") == -1) {\n        this.page = route;\n        window.location.hash = this.page;\n        this.resumePagePos();\n        // if (this.page == \"settings\") {\n        //     this.version\n        // }\n        return;\n      }\n      let hash = route.split(\"/\");\n      let page = hash[0];\n      let id = hash[1];\n      let isLibrary = hash[2] ?? false;\n      if (page == \"plugin\") {\n        this.pluginPages.page = \"plugin.\" + id;\n        this.page = \"plugin-renderer\";\n        return;\n      }\n      this.routeView({\n        kind: page,\n        id: id,\n        attributes: {\n          playParams: { kind: page, id: id, isLibrary: isLibrary },\n        },\n      });\n    },\n    resumePagePos() {\n      setTimeout(() => {\n        $(\"#app-content\").scrollTop(app.getPagePos(window.location.hash).position);\n      }, 100);\n    },\n    setPagePos() {\n      try {\n        console.debug({\n          href: window.location.hash,\n          position: $(\"#app-content\").scrollTop(),\n        });\n        this.$store.commit(\"setPagePos\", {\n          href: window.location.hash,\n          position: $(\"#app-content\").scrollTop(),\n        });\n      } catch (e) {}\n    },\n    routeView(item) {\n      this.setPagePos();\n      let kind = item.attributes?.playParams ? item.attributes?.playParams?.kind ?? item.type ?? \"\" : item.type ?? \"\";\n      let id = item.attributes?.playParams ? item.attributes?.playParams?.id ?? item.id ?? \"\" : item.id ?? \"\";\n      let isLibrary = item.attributes?.playParams ? item.attributes?.playParams?.isLibrary ?? false : false;\n      if (kind.includes(\"playlist\") || kind.includes(\"album\")) {\n        app.showingPlaylist = [];\n      }\n      if (kind.toString().includes(\"apple-curator\")) {\n        kind = \"appleCurator\";\n        app\n          .getTypeFromID(\"appleCurator\", id, false, {\n            platform: \"web\",\n            include: \"grouping,playlists\",\n            extend: \"editorialArtwork\",\n            \"art[url]\": \"f\",\n          })\n          .then(() => {\n            kind = \"appleCurator\";\n            window.location.hash = `${kind}/${id}`;\n          });\n      } else if (kind == \"editorial-elements\" || kind == \"editorial-items\") {\n        console.debug(item);\n        if (item.relationships?.contents?.data != null && item.relationships?.contents?.data.length > 0) {\n          this.routeView(item.relationships.contents.data[0]);\n        } else if (item.attributes?.link?.url != null) {\n          if (item.attributes.link.url.includes(\"viewMultiRoom\") || item.attributes.link.url.includes(\"/collection/\")) {\n            const params = new Proxy(new URLSearchParams(new URL(item.attributes.link.url).search), {\n              get: (searchParams, prop) => searchParams.get(prop),\n            });\n            id = params.fcId;\n            kind = \"multiroom\";\n            if (item.attributes.link.url.includes(\"viewMultiRoom\")) {\n              kind = \"multiroom\";\n            } else {\n              kind = \"room\";\n            }\n            app\n              .getTypeFromID(kind, id, false, {\n                platform: \"web\",\n                extend: \"editorialArtwork,uber,lockupStyle\",\n              })\n              .then(() => {\n                kind = \"multiroom\";\n                window.location.hash = `${kind}/${id}`;\n              });\n\n            return;\n          } else if (item.attributes.link.url.includes(\"viewFeature\")) {\n            const params = new Proxy(new URLSearchParams(new URL(item.attributes.link.url).search), {\n              get: (searchParams, prop) => searchParams.get(prop),\n            });\n            id = params.id;\n            app.mk.api.v3.music(`/v1/editorial/${app.mk.storefrontId}/multiplex/${id}?art%5Burl%5D=f&format%5Bresources%5D=map&platform=web`).then((data) => {\n              let item = data.data.results?.target ?? [];\n              app.routeView(item);\n            });\n          } else {\n            window.open(item.attributes.link.url);\n          }\n        }\n      } else if (kind == \"multiplex\") {\n        app.mk.api.v3.music(`/v1/editorial/${app.mk.storefrontId}/multiplex/${id}?art%5Burl%5D=f&format%5Bresources%5D=map&platform=web`).then((data) => {\n          let item = data.data.results?.target ?? [];\n          app.routeView(item);\n        });\n      }\n      if (kind == \"multirooms\") {\n        app\n          .getTypeFromID(\"multiroom\", id, false, {\n            platform: \"web\",\n            extend: \"editorialArtwork,uber,lockupStyle\",\n          })\n          .then(() => {\n            kind = \"multiroom\";\n            window.location.hash = `${kind}/${id}`;\n            // document.querySelector(\"#app-content\").scrollTop = 0;\n          });\n        this.resumePagePos();\n      } else if (kind.toString().includes(\"artist\")) {\n        app.getArtistInfo(id, isLibrary);\n        window.location.hash = `${kind}/${id}${isLibrary ? \"/\" + isLibrary : \"\"}`;\n        // document.querySelector(\"#app-content\").scrollTop = 0;\n      } else if (kind.toString().includes(\"record-label\") || kind.toString().includes(\"curator\")) {\n        if (kind.toString().includes(\"record-label\")) {\n          kind = \"recordLabel\";\n        } else {\n          kind = \"curator\";\n        }\n        app.page = kind + \"_\" + id;\n        app.getTypeFromID(kind, id, isLibrary, {\n          extend: \"editorialVideo\",\n          include: \"grouping,playlists\",\n          views: \"top-releases,latest-releases,top-artists\",\n        });\n        window.location.hash = `${kind}/${id}`;\n        document.querySelector(\"#app-content\").scrollTop = 0;\n        this.resumePagePos();\n      } else if (kind.toString().includes(\"social-profiles\")) {\n        app.page = kind + \"_\" + id;\n        app.mk.api.v3\n          .music(`/v1/social/${app.mk.storefrontId}/social-profiles/${id}`, {\n            include: \"shared-playlists\",\n          })\n          .then((data) => {\n            console.log(data);\n            app.showingPlaylist = data.data?.data[0];\n            window.location.hash = `${kind}/${id}`;\n            document.querySelector(\"#app-content\").scrollTop = 0;\n          });\n        // app.getTypeFromID((kind), (id), (isLibrary), {\n        //     extend: \"editorialVideo\",\n        //     include: 'grouping,playlists',\n        //     views: 'top-releases,latest-releases,top-artists'\n        // });\n      } else if (!kind.toString().includes(\"radioStation\") && !kind.toString().includes(\"song\") && !kind.toString().includes(\"musicVideo\") && !kind.toString().includes(\"uploadedVideo\") && !kind.toString().includes(\"music-movie\")) {\n        let params = {\n          extend: \"offers,editorialVideo\",\n          views: \"appears-on,more-by-artist,related-videos,other-versions,you-might-also-like,video-extras,audio-extras\",\n        };\n        if (kind.includes(\"playlist\")) {\n          params[\"include\"] = \"tracks\";\n        }\n        if (kind.includes(\"album\")) {\n          params[\"include[albums]\"] = \"artists\";\n          params[\"fields[artists]\"] = \"name,url\";\n          params[\"omit[resource]\"] = \"autos\";\n          params[\"meta[albums:tracks]\"] = \"popularity\";\n          params[\"fields[albums]\"] = \"artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialNotes,editorialVideo,name,playParams,releaseDate,url,copyright,genreNames\";\n        }\n        if (kind.includes(\"playlist\") || kind.includes(\"album\")) {\n          app.page = kind + \"_\" + id;\n          window.location.hash = `${kind}/${id}${isLibrary ? \"/\" + isLibrary : \"\"}`;\n          app.getTypeFromID(kind, id, isLibrary, params);\n        } else {\n          app.page = kind;\n          window.location.hash = `${kind}/${id}${isLibrary ? \"/\" + isLibrary : \"\"}`;\n        }\n        this.resumePagePos();\n        // app.getTypeFromID((kind), (id), (isLibrary), params);\n      } else if (kind.toString().includes(\"song\")) {\n        const albumUrl = new Promise(async (resolve, reject) => {\n          resolve(await MusicKitInterop.fetchSongRelationships({ id: id, relationship: \"album\" }));\n        });\n        albumUrl.then((data) => {\n          if (data && data.type === \"albums\" && data.id) {\n            window.location.hash = `album/${data.id}${isLibrary ? \"/\" + isLibrary : \"\"}`;\n          } else {\n            app.playMediaItemById(id, kind, isLibrary, item.attributes.url ?? \"\");\n          }\n        });\n      } else {\n        app.playMediaItemById(id, kind, isLibrary, item.attributes.url ?? \"\");\n      }\n    },\n    prevButton() {\n      if (app.mk.nowPlayingItem && app.mk.currentPlaybackTime > 2) {\n        app.mk.seekToTime(0);\n      } else {\n        app.skipToPreviousItem();\n      }\n    },\n    isDisabled() {\n      return !app.mk.nowPlayingItem || app.mk.nowPlayingItem.attributes.playParams.kind === \"radioStation\";\n    },\n    isPrevDisabled() {\n      return this.isDisabled() || (app.mk.queue._position === 0 && app.mk.currentPlaybackTime <= 2);\n    },\n    isNextDisabled() {\n      return this.isDisabled() || app.mk.queue._position + 1 === app.mk.queue.length;\n    },\n\n    switchArtworkDisplayLayout() {\n      switch (app.cfg.visual.artworkDisplayLayout) {\n        case \"default\":\n          app.cfg.visual.artworkDisplayLayout = \"sidebar\";\n          break;\n        case \"sidebar\":\n          app.cfg.visual.artworkDisplayLayout = \"default\";\n          break;\n        default:\n          app.cfg.visual.artworkDisplayLayout = \"default\";\n          break;\n      }\n    },\n\n    async getNowPlayingItemDetailed(target) {\n      let nowPlayingItem = JSON.parse(JSON.stringify(this.mk.nowPlayingItem));\n      if (nowPlayingItem.type === \"radioStation\" && app.mk.nowPlayingItem.id !== -1) {\n        nowPlayingItem.playParams = { kind: \"songs\" };\n        nowPlayingItem.attributes.playParams.catalogId = app.mk.nowPlayingItem.id;\n        nowPlayingItem.attributes.playParams.id = app.mk.nowPlayingItem.id;\n        nowPlayingItem.id = app.mk.nowPlayingItem.id;\n      }\n      try {\n        let u = await app.mkapi(nowPlayingItem.playParams.kind, nowPlayingItem.songId == -1, nowPlayingItem.songId != -1 ? nowPlayingItem.songId : nowPlayingItem[\"id\"], { \"include[songs]\": \"albums,artists\", l: app.mklang });\n        app.searchAndNavigate(u.data.data[0], target);\n      } catch (e) {\n        app.searchAndNavigate(nowPlayingItem, target);\n      }\n    },\n    async searchAndNavigate(item, target) {\n      let self = this;\n      app.tmpVar = item;\n      switch (target) {\n        case \"artist\":\n          let artistId = \"\";\n          try {\n            if (item.relationships.artists && item.relationships.artists.data.length > 0 && !item.relationships.artists.data[0].type.includes(\"library\")) {\n              if (item.relationships.artists.data[0].type === \"artist\" || item.relationships.artists.data[0].type === \"artists\") {\n                artistId = item.relationships.artists.data[0].id;\n              }\n            }\n            if (item.relationships.albums && item.relationships.albums.data.length > 0) {\n              if (item.relationships.albums.data[0].attributes.artistUrl) {\n                artistId = item.relationships.albums.data[0].attributes.artistUrl.split(\"/\").pop();\n              }\n            }\n            if (artistId == \"\") {\n              const url = item.relationships.catalog.data[0].attributes.artistUrl;\n              artistId = url.substring(url.lastIndexOf(\"/\") + 1);\n              if (artistId.includes(\"viewCollaboration\")) {\n                artistId = artistId.substring(artistId.lastIndexOf(\"ids=\") + 4, artistId.lastIndexOf(\"-\"));\n              }\n            }\n          } catch (_) {}\n\n          if (artistId == \"\") {\n            let artistQuery = (\n              await app.mk.api.v3.music(`v1/catalog/${app.mk.storefrontId}/search?term=${item.attributes.artistName}`, {\n                limit: 1,\n                types: \"artists\",\n              })\n            ).data.results;\n            try {\n              if (artistQuery.artists.data.length > 0) {\n                artistId = artistQuery.artists.data[0].id;\n                console.debug(artistId);\n              }\n            } catch (e) {}\n          }\n          console.debug(artistId);\n          if (artistId != \"\") self.appRoute(`artist/${artistId}`);\n          break;\n        case \"album\":\n          let albumId = \"\";\n          try {\n            if ((item.type ?? item.playParams?.kind ?? \"\") == \"albums\") {\n              albumId = item.id ?? \"\";\n            } else if (item.relationships.albums && item.relationships.albums.data.length > 0 && !item.relationships.albums.data[0].type.includes(\"library\")) {\n              if (item.relationships.albums.data[0].type === \"album\" || item.relationships.albums.data[0].type === \"albums\") {\n                albumId = item.relationships.albums.data[0].id;\n              }\n            }\n            if (albumId == \"\") {\n              const url = item.relationships.catalog.data[0].attributes.url;\n              albumId = url.substring(url.lastIndexOf(\"/\") + 1);\n              if (albumId.includes(\"?i=\")) {\n                albumId = albumId.substring(0, albumId.indexOf(\"?i=\"));\n              }\n            }\n          } catch (_) {}\n\n          if (albumId == \"\") {\n            try {\n              let albumQuery = (\n                await app.mk.api.v3.music(`v1/catalog/${app.mk.storefrontId}/search?term=${(item.attributes.albumName ?? item.attributes.name ?? \"\") + \" \" + (item.attributes.artistName ?? \"\")}`, {\n                  limit: 1,\n                  types: \"albums\",\n                })\n              ).data.results;\n              if (albumQuery.albums.data.length > 0) {\n                albumId = albumQuery.albums.data[0].id;\n                console.debug(albumId);\n              }\n            } catch (e) {}\n          }\n          if (albumId != \"\") {\n            self.appRoute(`album/${albumId}`);\n          }\n          break;\n        case \"recordLabel\":\n          let labelId = \"\";\n          try {\n            labelId = item.relationships[\"record-labels\"].data[0].id;\n          } catch (_) {}\n\n          if (labelId == \"\") {\n            try {\n              let labelQuery = (\n                await app.mk.api.v3.music(`v1/catalog/${app.mk.storefrontId}/search?term=${item.attributes.recordLabel}`, {\n                  limit: 1,\n                  types: \"record-labels\",\n                })\n              ).data.results;\n              if (labelQuery[\"record-labels\"].data.length > 0) {\n                labelId = labelQuery[\"record-labels\"].data[0].id;\n                console.debug(labelId);\n              }\n            } catch (e) {}\n          }\n          if (labelId != \"\") {\n            app.showingPlaylist = [];\n            await app.getTypeFromID(\"recordLabel\", labelId, false, {\n              views: \"top-releases,latest-releases,top-artists\",\n            });\n            app.page = \"recordLabel_\" + labelId;\n          }\n\n          break;\n      }\n    },\n    exitMV() {\n      MusicKit.getInstance().stop();\n      document.getElementById(\"apple-music-video-container\").style.display = \"none\";\n    },\n    getArtistInfo(id, isLibrary) {\n      this.getArtistFromID(id);\n      //this.getTypeFromID(\"artist\",id,isLibrary,query)\n    },\n    followingArtist(id) {\n      console.debug(`check for ${id}`);\n      return this.cfg.home.followedArtists.includes(id);\n    },\n    playMediaItem(item) {\n      let kind = item.attributes.playParams ? item.attributes.playParams.kind ?? item.type ?? \"\" : item.type ?? \"\";\n      let id = item.attributes.playParams ? item.attributes.playParams.id ?? item.id ?? \"\" : item.id ?? \"\";\n      let isLibrary = item.attributes.playParams ? item.attributes.playParams.isLibrary ?? false : false;\n      let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n      // console.log(kind, id, isLibrary)\n      app.mk.stop().then(() => {\n        if (kind.includes(\"artist\")) {\n          app.mk.setStationQueue({ artist: \"a-\" + id }).then(() => {\n            app.mk.play();\n          });\n        } else {\n          app.playMediaItemById(id, kind, isLibrary, item.attributes.url ?? \"\");\n        }\n      });\n    },\n    async getTypeFromID(kind, id, isLibrary = false, params = {}, params2 = {}) {\n      let a;\n      if ((kind == \"album\") | (kind == \"albums\")) {\n        params[\"include\"] = \"tracks,artists,record-labels,catalog\";\n      }\n      params[\"l\"] = this.mklang;\n      try {\n        a = await this.mkapi(kind.toString(), isLibrary, id.toString(), params, params2);\n      } catch (e) {\n        console.debug(e);\n        try {\n          a = await this.mkapi(kind.toString(), !isLibrary, id.toString(), params, params2);\n        } catch (err) {\n          console.log(err);\n          a = [];\n        } finally {\n          if (kind == \"appleCurator\") {\n            app.appleCurator = a.data.data[0];\n          } else if (kind == \"multiroom\" || kind == \"room\") {\n            app.multiroom = a.data.data[0];\n          } else {\n            this.getPlaylistContinuous(a, true);\n          }\n        }\n      } finally {\n        if (kind == \"appleCurator\") {\n          app.appleCurator = a.data.data[0];\n        } else if (kind == \"multiroom\" || kind == \"room\") {\n          app.multiroom = a.data.data[0];\n        } else {\n          this.getPlaylistContinuous(a, true);\n        }\n      }\n    },\n    searchLibrarySongs() {\n      let self = this;\n      let prefs = this.cfg.libraryPrefs.songs;\n\n      function sortSongs() {\n        // sort this.library.songs.displayListing by song.attributes[self.library.songs.sorting] in descending or ascending order based on alphabetical order and numeric order\n        // check if song.attributes[self.library.songs.sorting] is a number and if so, sort by number if not, sort by alphabetical order ignoring case\n        self.library.songs.displayListing.sort((a, b) => {\n          let aa = a.attributes[prefs.sort];\n          let bb = b.attributes[prefs.sort];\n          if (prefs.sort === \"genre\") {\n            aa = a.attributes.genreNames[0];\n            bb = b.attributes.genreNames[0];\n          } else if (prefs.sort === \"dateAdded\") {\n            aa = a.relationships?.albums?.data[0]?.attributes?.dateAdded;\n            bb = b.relationships?.albums?.data[0]?.attributes?.dateAdded;\n            // if dateAdded is equal, an entire album was added at once, so sorting by track number (in reverse order because lower track number should be above in descending mode)\n            if (aa === bb) {\n              aa = b.attributes.trackNumber;\n              bb = a.attributes.trackNumber;\n            }\n          } else if (prefs.sort === \"artistName\") {\n            if (a.relationships?.artists?.data[0]?.id === b.relationships?.artists?.data[0]?.id) {\n              aa = a.attributes.albumName;\n              bb = b.attributes.albumName;\n            }\n            if (a.relationships?.albums?.data[0]?.id === b.relationships?.albums?.data[0]?.id) {\n              aa = a.attributes.trackNumber;\n              bb = b.attributes.trackNumber;\n            }\n          } else if (prefs.sort === \"albumName\") {\n            if (a.relationships?.albums?.data[0]?.id === b.relationships?.albums?.data[0]?.id) {\n              aa = a.attributes.trackNumber;\n              bb = b.attributes.trackNumber;\n            }\n          }\n          if (aa == null) {\n            aa = \"\";\n          }\n          if (bb == null) {\n            bb = \"\";\n          }\n          if (prefs.sortOrder === \"asc\") {\n            if (aa.toString().match(/^\\d+$/) && bb.toString().match(/^\\d+$/)) {\n              return aa - bb;\n            } else {\n              return aa.toString().toLowerCase().localeCompare(bb.toString().toLowerCase());\n            }\n          } else if (prefs.sortOrder === \"desc\") {\n            if (aa.toString().match(/^\\d+$/) && bb.toString().match(/^\\d+$/)) {\n              return bb - aa;\n            } else {\n              return bb.toString().toLowerCase().localeCompare(aa.toString().toLowerCase());\n            }\n          }\n        });\n      }\n\n      if (this.library.songs.search == \"\") {\n        this.library.songs.displayListing = this.library.songs.listing;\n        sortSongs();\n      } else {\n        this.library.songs.displayListing = this.library.songs.listing.filter((item) => {\n          let itemName = item.attributes.name.toLowerCase();\n          let searchTerm = this.library.songs.search.toLowerCase();\n          let artistName = \"\";\n          let albumName = \"\";\n          if (item.attributes.artistName != null) {\n            artistName = item.attributes.artistName.toLowerCase();\n          }\n          if (item.attributes.albumName != null) {\n            albumName = item.attributes.albumName.toLowerCase();\n          }\n\n          // remove any non-alphanumeric characters and spaces from search term and item name\n          searchTerm = searchTerm.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          itemName = itemName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          artistName = artistName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          albumName = albumName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n\n          if (itemName.includes(searchTerm) || artistName.includes(searchTerm) || albumName.includes(searchTerm)) {\n            return item;\n          }\n        });\n        sortSongs();\n      }\n    },\n    getAlbumSort() {\n      this.library.albums.sortOrder[1] = this.cfg.libraryPrefs.albums.sortOrder;\n      this.library.albums.sorting[1] = this.cfg.libraryPrefs.albums.sort;\n    },\n    // make a copy of searchLibrarySongs except use Albums instead of Songs\n    searchLibraryAlbums(index) {\n      let self = this;\n\n      function sortAlbums() {\n        // sort this.library.albums.displayListing by album.attributes[self.library.albums.sorting[index]] in descending or ascending order based on alphabetical order and numeric order\n        // check if album.attributes[self.library.albums.sorting[index]] is a number and if so, sort by number if not, sort by alphabetical order ignoring case\n        self.library.albums.displayListing.sort((a, b) => {\n          let aa = a.attributes[self.library.albums.sorting[index]];\n          let bb = b.attributes[self.library.albums.sorting[index]];\n          if (self.library.albums.sorting[index] == \"genre\") {\n            aa = a.attributes.genreNames[0];\n            bb = b.attributes.genreNames[0];\n          } else if (self.library.albums.sorting[index] === \"dateAdded\") {\n            aa = a.attributes?.dateAdded;\n            bb = b.attributes?.dateAdded;\n          }\n          if (aa == null) {\n            aa = \"\";\n          }\n          if (bb == null) {\n            bb = \"\";\n          }\n          if (self.library.albums.sortOrder[index] == \"asc\") {\n            if (aa.toString().match(/^\\d+$/) && bb.toString().match(/^\\d+$/)) {\n              return aa - bb;\n            } else {\n              return aa.toString().toLowerCase().localeCompare(bb.toString().toLowerCase());\n            }\n          } else if (self.library.albums.sortOrder[index] == \"desc\") {\n            if (aa.toString().match(/^\\d+$/) && bb.toString().match(/^\\d+$/)) {\n              return bb - aa;\n            } else {\n              return bb.toString().toLowerCase().localeCompare(aa.toString().toLowerCase());\n            }\n          }\n        });\n      }\n\n      if (this.library.albums.search == \"\") {\n        this.library.albums.displayListing = this.library.albums.listing;\n        sortAlbums();\n      } else {\n        this.library.albums.displayListing = this.library.albums.listing.filter((item) => {\n          let itemName = item.attributes.name.toLowerCase();\n          let searchTerm = this.library.albums.search.toLowerCase();\n          let artistName = \"\";\n          let albumName = \"\";\n          if (item.attributes.artistName != null) {\n            artistName = item.attributes.artistName.toLowerCase();\n          }\n          if (item.attributes.albumName != null) {\n            albumName = item.attributes.albumName.toLowerCase();\n          }\n\n          // remove any non-alphanumeric characters and spaces from search term and item name\n          searchTerm = searchTerm.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          itemName = itemName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          artistName = artistName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          albumName = albumName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n\n          if (itemName.includes(searchTerm) || artistName.includes(searchTerm) || albumName.includes(searchTerm)) {\n            return item;\n          }\n        });\n        sortAlbums();\n      }\n    },\n    // make a copy of searchLibrarySongs except use Albums instead of Songs\n    searchLibraryArtists(index) {\n      let self = this;\n\n      function sortArtists() {\n        // sort this.library.albums.displayListing by album.attributes[self.library.albums.sorting[index]] in descending or ascending order based on alphabetical order and numeric order\n        // check if album.attributes[self.library.albums.sorting[index]] is a number and if so, sort by number if not, sort by alphabetical order ignoring case\n        self.library.artists.displayListing.sort((a, b) => {\n          let aa = a.attributes[self.library.artists.sorting[index]];\n          let bb = b.attributes[self.library.artists.sorting[index]];\n          if (self.library.artists.sorting[index] == \"genre\") {\n            aa = a.attributes.genreNames[0];\n            bb = b.attributes.genreNames[0];\n          }\n          if (aa == null) {\n            aa = \"\";\n          }\n          if (bb == null) {\n            bb = \"\";\n          }\n          if (self.library.artists.sortOrder[index] == \"asc\") {\n            if (aa.toString().match(/^\\d+$/) && bb.toString().match(/^\\d+$/)) {\n              return aa - bb;\n            } else {\n              return aa.toString().toLowerCase().localeCompare(bb.toString().toLowerCase());\n            }\n          } else if (self.library.artists.sortOrder[index] == \"desc\") {\n            if (aa.toString().match(/^\\d+$/) && bb.toString().match(/^\\d+$/)) {\n              return bb - aa;\n            } else {\n              return bb.toString().toLowerCase().localeCompare(aa.toString().toLowerCase());\n            }\n          }\n        });\n      }\n\n      if (this.library.artists.search == \"\") {\n        this.library.artists.displayListing = this.library.artists.listing;\n        sortArtists();\n      } else {\n        this.library.artists.displayListing = this.library.artists.listing.filter((item) => {\n          let itemName = item.attributes.name.toLowerCase();\n          let searchTerm = this.library.artists.search.toLowerCase();\n          let artistName = \"\";\n          let albumName = \"\";\n          // if (item.attributes.artistName != null) {\n          //     artistName = item.attributes.artistName.toLowerCase()\n          // }\n          // if (item.attributes.albumName != null) {\n          //     albumName = item.attributes.albumName.toLowerCase()\n          // }\n\n          // remove any non-alphanumeric characters and spaces from search term and item name\n          searchTerm = searchTerm.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n          itemName = itemName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n\n          if (itemName.includes(searchTerm) || artistName.includes(searchTerm) || albumName.includes(searchTerm)) {\n            return item;\n          }\n        });\n        sortArtists();\n      }\n    },\n    focusSearch() {\n      app.appRoute(\"search\");\n      const search = document.getElementsByClassName(\"search-input\");\n      if (search.length > 0) {\n        search[0].focus();\n      }\n    },\n    getSidebarItemClass(page) {\n      if (this.page == page) {\n        return [\"active\"];\n      } else {\n        return [];\n      }\n    },\n    async mkapi(method, library = false, term, params = {}, params2 = {}, attempts = 0) {\n      if (method.includes(`recordLabel`)) {\n        method = `record-labels`;\n      }\n      if (method.includes(`appleCurator`)) {\n        method = `apple-curators`;\n      }\n      if (attempts > 3) {\n        return;\n      }\n      let truemethod = !method.endsWith(\"s\") ? method + \"s\" : method;\n      try {\n        if (method.includes(`room`)) {\n          return await this.mk.api.v3.music(`v1/editorial/${app.mk.storefrontId}/${truemethod}/${term.toString()}`, params, params2);\n        } else if (library) {\n          return await this.mk.api.v3.music(`v1/me/library/${truemethod}/${term.toString()}`, params, params2);\n        } else {\n          return await this.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/${truemethod}/${term.toString()}`, params, params2);\n        }\n      } catch (e) {\n        console.debug(e);\n        return await this.mkapi(method, library, term, params, params2, attempts + 1);\n      }\n    },\n    getLibraryGenres() {\n      let genres = [];\n      genres = [];\n      this.library.songs.listing.forEach((item) => {\n        item.attributes.genreNames.forEach((genre) => {\n          if (!genres.includes(genre)) {\n            genres.push(genre);\n          }\n        });\n      });\n      return genres;\n    },\n    async getLibrarySongsFull(force = false) {\n      let self = this;\n      let library = [];\n      let cacheId = \"library-songs\";\n      let downloaded = null;\n      this.$store.commit(\"resetRecentlyAdded\");\n      if (this.library.songs.downloadState == 2 && !force) {\n        return;\n      }\n      if (this.library.songs.downloadState == 1) {\n        return;\n      }\n      let librarySongs = await CiderCache.getCache(cacheId);\n      if (librarySongs) {\n        this.library.songs.listing.data = librarySongs;\n        this.searchLibrarySongs();\n      }\n      if (this.songstest) {\n        return;\n      }\n      this.library.songs.downloadState = 1;\n      this.library.backgroundNotification.show = true;\n      this.library.backgroundNotification.message = app.getLz(\"notification.updatingLibrarySongs\");\n\n      library = await MusicKitTools.v3Continuous({\n        href: `/v1/me/library/songs/`,\n        options: {\n          \"include[library-songs]\": \"catalog,artists,albums\",\n          \"fields[artists]\": \"name,url,id\",\n          \"fields[albums]\": \"name,url,id\",\n          platform: \"web\",\n          \"fields[catalog]\": \"artistUrl,albumUrl\",\n          \"fields[songs]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url\",\n          limit: 100,\n          l: app.mklang,\n        },\n        onProgress: (data) => {\n          console.debug(`${data.total}/${data.response.data.meta.total}`);\n          self.library.backgroundNotification.show = true;\n          self.library.backgroundNotification.message = app.getLz(\"notification.updatingLibrarySongs\");\n          self.library.backgroundNotification.total = data.response.data.meta.total;\n          self.library.backgroundNotification.progress = data.total;\n        },\n        onSuccess: () => {},\n      });\n\n      self.library.songs.listing = library;\n      self.library.songs.downloadState = 2;\n      self.library.backgroundNotification.show = false;\n      self.searchLibrarySongs();\n      CiderCache.putCache(cacheId, library);\n      console.debug(\"Done!\");\n\n      return;\n    },\n    // copy the getLibrarySongsFull function except change Songs to Albums\n    async getLibraryAlbumsFull(force = false, index) {\n      let self = this;\n      let library = [];\n      let cacheId = \"library-albums\";\n      let downloaded = null;\n      if ((this.library.albums.downloadState == 2 || this.library.albums.downloadState == 1) && !force) {\n        return;\n      }\n      let libraryAlbums = await CiderCache.getCache(cacheId);\n      if (libraryAlbums) {\n        this.library.albums.listing = libraryAlbums;\n        this.searchLibraryAlbums(index);\n      }\n      if (this.songstest) {\n        return;\n      }\n      this.library.albums.downloadState = 1;\n      this.library.backgroundNotification.show = true;\n      this.library.backgroundNotification.message = app.getLz(\"notification.updatingLibraryAlbums\");\n\n      function downloadChunk() {\n        self.library.albums.downloadState = 1;\n        const params = {\n          \"include[library-albums]\": \"catalog,artists,albums\",\n          \"fields[artists]\": \"name,url,id\",\n          // \"fields[albums]\": \"name,url,id\",\n          platform: \"web\",\n          \"fields[catalog]\": \"artistUrl,albumUrl\",\n          \"fields[albums]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url\",\n          limit: 100,\n          l: self.mklang,\n        };\n        const safeparams = {\n          platform: \"web\",\n          limit: \"60\",\n          \"include[library-albums]\": \"artists\",\n          \"include[library-artists]\": \"catalog\",\n          \"include[albums]\": \"artists\",\n          \"fields[artists]\": \"name,url\",\n          \"fields[albums]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url\",\n          includeOnly: \"catalog,artists\",\n        };\n        if (downloaded == null) {\n          app.mk.api.v3\n            .music(`/v1/me/library/albums/`, params)\n            .then((response) => {\n              processChunk(response.data);\n            })\n            .catch((error) => {\n              console.debug(\"safe loading\");\n              app.mk.api.v3\n                .music(`/v1/me/library/albums/`, safeparams)\n                .then((response) => {\n                  processChunk(response.data);\n                })\n                .catch((error) => {\n                  console.log(\"safe loading failed\", error);\n                  app.library.albums.downloadState = 2;\n                  app.library.backgroundNotification.show = false;\n                });\n            });\n        } else {\n          if (downloaded.next != null) {\n            app.mk.api.v3\n              .music(downloaded.next, params)\n              .then((response) => {\n                processChunk(response.data);\n              })\n              .catch((error) => {\n                console.debug(\"safe loading\");\n                app.mk.api.v3\n                  .music(downloaded.next, safeparams)\n                  .then((response) => {\n                    processChunk(response.data);\n                  })\n                  .catch((error) => {\n                    console.log(\"safe loading failed\", error);\n                    app.library.albums.downloadState = 2;\n                    app.library.backgroundNotification.show = false;\n                  });\n              });\n          } else {\n            console.debug(\"Download next\", downloaded.next);\n          }\n        }\n      }\n\n      function processChunk(response) {\n        downloaded = response;\n        library = library.concat(downloaded.data);\n        self.library.backgroundNotification.show = true;\n        self.library.backgroundNotification.message = app.getLz(\"notification.updatingLibraryAlbums\");\n        self.library.backgroundNotification.total = downloaded.meta.total;\n        self.library.backgroundNotification.progress = library.length;\n        if (downloaded.meta.total == 0) {\n          self.library.albums.downloadState = 3;\n          return;\n        }\n        if (typeof downloaded.next == \"undefined\") {\n          console.debug(\"downloaded.next is undefined\");\n          self.library.albums.listing = library;\n          self.library.albums.downloadState = 2;\n          self.library.backgroundNotification.show = false;\n          CiderCache.putCache(cacheId, library);\n          self.searchLibraryAlbums(index);\n        }\n        if (downloaded.meta.total > library.length || typeof downloaded.meta.next != \"undefined\") {\n          console.debug(`downloading next chunk - ${library.length} albums so far`);\n          downloadChunk();\n        } else {\n          self.library.albums.listing = library;\n          self.library.albums.downloadState = 2;\n          self.library.backgroundNotification.show = false;\n          CiderCache.putCache(cacheId, library);\n          self.searchLibraryAlbums(index);\n          // console.log(library)\n        }\n      }\n\n      downloadChunk();\n    },\n    // copy the getLibrarySongsFull function except change Songs to Albums\n    async getLibraryArtistsFull(force = false, index) {\n      let self = this;\n      let library = [];\n      let cacheId = \"library-artists\";\n      let downloaded = null;\n      if ((this.library.artists.downloadState == 2 || this.library.artists.downloadState == 1) && !force) {\n        return;\n      }\n      let libraryArtists = await CiderCache.getCache(cacheId);\n      if (libraryArtists) {\n        this.library.artists.listing = libraryArtists;\n        this.searchLibraryArtists(index);\n      }\n      if (this.songstest) {\n        return;\n      }\n      this.library.artists.downloadState = 1;\n      this.library.backgroundNotification.show = true;\n      this.library.backgroundNotification.message = app.getLz(\"notification.updatingLibraryArtists\");\n\n      function downloadChunk() {\n        self.library.artists.downloadState = 1;\n        const params = {\n          include: \"catalog\",\n          // \"include[library-artists]\": \"catalog,artists,albums\",\n          // \"fields[artists]\": \"name,url,id\",\n          // \"fields[albums]\": \"name,url,id\",\n          platform: \"web\",\n          // \"fields[catalog]\": \"artistUrl,albumUrl\",\n          // \"fields[artists]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url\",\n          limit: 100,\n          l: self.mklang,\n        };\n        const safeparams = {\n          include: \"catalog\",\n          platform: \"web\",\n          limit: 50,\n        };\n        if (downloaded == null) {\n          app.mk.api.v3\n            .music(`/v1/me/library/artists/`, params)\n            .then((response) => {\n              processChunk(response.data);\n            })\n            .catch((error) => {\n              console.debug(\"safe loading\");\n              app.mk.api.v3\n                .music(`/v1/me/library/artists/`, safeparams)\n                .then((response) => {\n                  processChunk(response.data);\n                })\n                .catch((error) => {\n                  console.log(\"safe loading failed\", error);\n                  app.library.artists.downloadState = 2;\n                  app.library.backgroundNotification.show = false;\n                });\n            });\n        } else {\n          if (downloaded.next != null) {\n            app.mk.api.v3\n              .music(downloaded.next, params)\n              .then((response) => {\n                processChunk(response.data);\n              })\n              .catch((error) => {\n                console.log(\"safe loading\");\n                app.mk.api.v3\n                  .music(downloaded.next, safeparams)\n                  .then((response) => {\n                    processChunk(response.data);\n                  })\n                  .catch((error) => {\n                    console.log(\"safe loading failed\", error);\n                    app.library.artists.downloadState = 2;\n                    app.library.backgroundNotification.show = false;\n                  });\n              });\n          } else {\n            console.log(\"Download next\", downloaded.next);\n          }\n        }\n      }\n\n      function processChunk(response) {\n        downloaded = response;\n        library = library.concat(downloaded.data);\n        self.library.backgroundNotification.show = true;\n        self.library.backgroundNotification.message = app.getLz(\"notification.updatingLibraryArtists\");\n        self.library.backgroundNotification.total = downloaded.meta.total;\n        self.library.backgroundNotification.progress = library.length;\n        if (downloaded.meta.total == 0) {\n          self.library.albums.downloadState = 3;\n          return;\n        }\n        if (typeof downloaded.next == \"undefined\") {\n          console.log(\"downloaded.next is undefined\");\n          self.library.artists.listing = library;\n          self.library.artists.downloadState = 2;\n          self.library.artists.show = false;\n          CiderCache.putCache(cacheId, library);\n          self.searchLibraryArtists(index);\n        }\n        if (downloaded.meta.total > library.length || typeof downloaded.meta.next != \"undefined\") {\n          console.log(`downloading next chunk - ${library.length} artists so far`);\n          downloadChunk();\n        } else {\n          self.library.artists.listing = library;\n          self.library.artists.downloadState = 2;\n          self.library.backgroundNotification.show = false;\n          CiderCache.putCache(cacheId, library);\n          self.searchLibraryArtists(index);\n          // console.log(library)\n        }\n      }\n\n      downloadChunk();\n    },\n    /**\n     * Gets the total duration in seconds of a playlist\n     * @returns {string} Total tracks, and duration\n     * @author Core#1034\n     * @memberOf app\n     */\n    getTotalTime() {\n      try {\n        if (app.showingPlaylist.relationships.tracks.data.length === 0) return \"\";\n        const timeInSeconds = Math.round([].concat(...app.showingPlaylist.relationships.tracks.data).reduce((a, { attributes: { durationInMillis } }) => a + durationInMillis, 0) / 1000);\n        return `${app.showingPlaylist.relationships.tracks.data.length} ${app.getLz(\"term.track\", {\n          count: app.showingPlaylist.relationships.tracks.data.length,\n        })}, ${app.convertTime(timeInSeconds, \"long\")}`;\n      } catch (err) {\n        return \"\";\n      }\n    },\n    async getLibrarySongs() {\n      let response = await this.mkapi(\"songs\", true, \"\", { limit: 100, l: this.mklang }, { includeResponseMeta: !0 });\n      this.library.songs.listing = response.data.data;\n      this.library.songs.meta = response.data.meta;\n    },\n    async getLibraryAlbums() {\n      let response = await this.mkapi(\"albums\", true, \"\", { limit: 100, l: this.mklang }, { includeResponseMeta: !0 });\n      this.library.albums.listing = response.data.data;\n      this.library.albums.meta = response.data.meta;\n    },\n    async getListenNow(attempt = 0) {\n      if (this.listennow.timestamp > Date.now() - 120000) {\n        return;\n      }\n\n      if (attempt > 3) {\n        return;\n      }\n      try {\n        this.listennow = (\n          await this.mk.api.v3.music(\n            `v1/me/recommendations?timezone=${encodeURIComponent(this.formatTimezoneOffset())}`,\n            {\n              name: \"listen-now\",\n              with: \"friendsMix,library,social\",\n              \"art[social-profiles:url]\": \"c\",\n              \"art[url]\": \"c,f\",\n              \"omit[resource]\": \"autos\",\n              \"relate[editorial-items]\": \"contents\",\n              extend: [\"editorialCard\", \"editorialVideo\"],\n              \"extend[albums]\": [\"artistUrl\"],\n              \"extend[library-albums]\": [\"artistUrl\", \"editorialVideo\"],\n              \"extend[playlists]\": [\"artistNames\", \"editorialArtwork\", \"editorialVideo\"],\n              \"extend[library-playlists]\": [\"artistNames\", \"editorialArtwork\", \"editorialVideo\"],\n              \"extend[social-profiles]\": \"topGenreNames\",\n              \"include[albums]\": \"artists\",\n              \"include[songs]\": \"artists\",\n              \"include[music-videos]\": \"artists\",\n              \"include[personal-recommendation]\": \"primary-content\",\n              \"fields[albums]\": [\"artistName\", \"artistUrl\", \"artwork\", \"contentRating\", \"editorialArtwork\", \"editorialVideo\", \"name\", \"playParams\", \"releaseDate\", \"url\"],\n              \"fields[artists]\": [\"name\", \"url\", \"artwork\"],\n              \"extend[stations]\": [\"airDate\", \"supportsAirTimeUpdates\"],\n              \"meta[stations]\": \"inflectionPoints\",\n              types: \"artists,albums,editorial-items,library-albums,library-playlists,music-movies,music-videos,playlists,stations,uploaded-audios,uploaded-videos,activities,apple-curators,curators,tv-shows,social-upsells\",\n              platform: \"web\",\n              l: this.mklang,\n            },\n            {\n              includeResponseMeta: !0,\n              reload: !0,\n            },\n          )\n        ).data;\n        this.listennow.timestamp = Date.now();\n        console.debug(this.listennow);\n      } catch (e) {\n        console.log(e);\n        this.getListenNow(attempt + 1);\n      }\n    },\n    async getRadioPage(attempt = 0) {\n      if (this.radio.timestamp > Date.now() - 120000) {\n        return;\n      }\n      if (attempt > 3) {\n        return;\n      }\n      try {\n        app.mk.api.v3\n          .music(`/v1/editorial/${app.mk.storefrontId}/groupings`, {\n            platform: \"web\",\n            name: \"radio\",\n            \"omit[resource:artists]\": \"relationships\",\n            \"include[albums]\": \"artists\",\n            \"include[songs]\": \"artists\",\n            \"include[music-videos]\": \"artists\",\n            extend: \"editorialArtwork,artistUrl\",\n            \"fields[artists]\": \"name,url,artwork,editorialArtwork,genreNames,editorialNotes\",\n            \"art[url]\": \"f\",\n            l: app.mklang,\n          })\n          .then((radio) => {\n            app.radio = radio.data.data[0];\n            console.debug(app.radio);\n          });\n\n        this.radio.timestamp = Date.now();\n      } catch (e) {\n        console.log(e);\n        this.getRadioPage(attempt + 1);\n      }\n    },\n    async getBrowsePage(attempt = 0) {\n      if (this.browsepage.timestamp > Date.now() - 120000) {\n        return;\n      }\n      if (attempt > 3) {\n        return;\n      }\n      try {\n        let browse = await app.mk.api.v3.music(`/v1/editorial/${app.mk.storefrontId}/groupings`, {\n          platform: \"web\",\n          name: \"music\",\n          \"omit[resource:artists]\": \"relationships\",\n          \"include[albums]\": \"artists\",\n          \"include[songs]\": \"artists\",\n          \"include[music-videos]\": \"artists\",\n          extend: \"editorialArtwork,artistUrl\",\n          \"fields[artists]\": \"name,url,artwork,editorialArtwork,genreNames,editorialNotes\",\n          \"art[url]\": \"f\",\n          l: app.mklang,\n        });\n        this.browsepage = browse.data.data[0];\n        this.browsepage.timestamp = Date.now();\n        console.debug(this.browsepage);\n      } catch (e) {\n        console.log(e);\n        this.getBrowsePage(attempt + 1);\n      }\n    },\n    async getMadeForYou(attempt = 0) {\n      if (attempt > 3) {\n        return;\n      }\n      try {\n        let mfu = await app.mk.api.v3.music(\"/v1/me/library/playlists?platform=web&extend=editorialVideo&fields%5Bplaylists%5D=lastModifiedDate&filter%5Bfeatured%5D=made-for-you&include%5Blibrary-playlists%5D=catalog&fields%5Blibrary-playlists%5D=artwork%2Cname%2CplayParams%2CdateAdded\");\n        this.madeforyou = mfu.data;\n      } catch (e) {\n        console.log(e);\n        this.getMadeForYou(attempt + 1);\n      }\n    },\n    newPlaylistFolder(name = app.getLz(\"term.newPlaylistFolder\")) {\n      let self = this;\n      this.mk.api.v3\n        .music(\n          \"/v1/me/library/playlist-folders/\",\n          {},\n          {\n            fetchOptions: {\n              method: \"POST\",\n              body: JSON.stringify({\n                attributes: { name: name },\n              }),\n            },\n          },\n        )\n        .then((res) => {\n          let playlist = res.data.data[0];\n          self.playlists.listing.push({\n            id: playlist.id,\n            attributes: {\n              name: playlist.attributes.name,\n            },\n            type: \"library-playlist-folders\",\n            parent: \"p.playlistsroot\",\n          });\n          self.sortPlaylists();\n          setTimeout(() => {\n            app.refreshPlaylists(false, false);\n          }, 13000);\n        });\n    },\n    showSearch() {\n      this.page = \"search\";\n    },\n    loadLyrics() {\n      const musicType = MusicKit.getInstance().nowPlayingItem != null ? MusicKit.getInstance().nowPlayingItem[\"type\"] ?? \"\" : \"\";\n      // console.log(\"mt\", musicType)\n      if (musicType === \"musicVideo\") {\n        this.loadYTLyrics();\n      } else {\n        // only load MXM lyrics if AM lyrics failed to load\n        if (app.cfg.lyrics.enable_mxm) {\n          this.loadMXM();\n        } else {\n          this.loadAMLyrics();\n        }\n      }\n    },\n    async loadAMLyrics() {\n      const songID = this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem[\"_songId\"] ?? this.mk.nowPlayingItem[\"songId\"] ?? -1 : -1;\n      // this.getMXM( trackName, artistName, 'en', duration);\n      if (songID != -1) {\n        try {\n          let response = await this.mk.api.v3.music(`v1/catalog/${this.mk.storefrontId}/songs/${songID}/lyrics`);\n          this.lyricsMediaItem = response.data?.data[0]?.attributes[\"ttml\"];\n          this.parseTTML();\n        } catch (_) {\n          if (app.cfg.lyrics.enable_mxm) {\n            this.loadQQLyrics();\n          } else {\n            this.loadMXM();\n          }\n        }\n      } else {\n        if (app.cfg.lyrics.enable_mxm) {\n          this.loadQQLyrics(); // since mxm is already prioritized, we can just load qq lyrics if am fails\n        } else {\n          this.loadMXM();\n        }\n      }\n    },\n    addToLibrary(id) {\n      let self = this;\n      this.mk.addToLibrary(id).then((data) => {\n        self.getLibrarySongsFull(true);\n      });\n      notyf.success(app.getLz(\"action.addToLibrary.success\"));\n    },\n    removeFromLibrary(kind, id) {\n      let self = this;\n      let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n      app.mk.api.v3\n        .music(\n          `v1/me/library/${truekind}/${id.toString()}`,\n          {},\n          {\n            fetchOptions: {\n              method: \"DELETE\",\n            },\n          },\n        )\n        .then((data) => {\n          self.getLibrarySongsFull(true);\n        });\n      notyf.success(app.getLz(\"action.removeFromLibrary.success\"));\n    },\n    async loadYTLyrics() {\n      const track = this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.title ?? \"\" : \"\";\n      const artist = this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.artistName ?? \"\" : \"\";\n      const time = this.mk.nowPlayingItem != null ? Math.round((this.mk.nowPlayingItem.attributes[\"durationInMillis\"] ?? -1000) / 1000) ?? -1 : -1;\n      ipcRenderer.invoke(\"getYTLyrics\", track, artist).then((result) => {\n        if (result.length > 0) {\n          let ytid = result[0][\"id\"][\"videoId\"];\n          if (app.cfg.lyrics.enable_yt) {\n            loadYT(ytid, app.cfg.lyrics.mxm_language ?? \"en\");\n          } else {\n            app.loadMXM();\n          }\n        } else {\n          app.loadMXM();\n        }\n\n        function loadYT(id, lang) {\n          let req = new XMLHttpRequest();\n          let url = `https://www.youtube.com/watch?&v=${id}`;\n          req.open(\"GET\", url, true);\n          req.onerror = function (e) {\n            this.loadMXM();\n          };\n          req.onload = function () {\n            // console.log(this.responseText);\n            let res = this.responseText;\n            let captionurl1 = res.substring(res.indexOf(`{\"playerCaptionsRenderer\":{\"baseUrl\":\"`) + `{\"playerCaptionsRenderer\":{\"baseUrl\":\"`.length);\n            let captionurl = captionurl1.substring(0, captionurl1.indexOf(`\"`));\n            if (captionurl.includes(\"timedtext\")) {\n              let json = JSON.parse(`{\"url\": \"${captionurl}\"}`);\n              let newurl = json.url + `&lang=${lang}&format=ttml`;\n\n              let req2 = new XMLHttpRequest();\n\n              req2.open(\"GET\", newurl, true);\n              req2.onerror = function (e) {\n                app.loadMXM();\n              };\n              req2.onload = function () {\n                try {\n                  const ttmlLyrics = this.responseText;\n                  if (ttmlLyrics) {\n                    this.lyricsMediaItem = ttmlLyrics;\n                    this.parseTTML();\n                  }\n                } catch (e) {\n                  app.loadMXM();\n                }\n              };\n              req2.send();\n            } else {\n              app.loadMXM();\n            }\n          };\n          req.send();\n        }\n      });\n    },\n    loadMXM() {\n      let attempt = 0;\n      const track = encodeURIComponent(this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.title ?? \"\" : \"\");\n      const artist = encodeURIComponent(this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.artistName ?? \"\" : \"\");\n      const time = encodeURIComponent(this.mk.nowPlayingItem != null ? Math.round((this.mk.nowPlayingItem.attributes[\"durationInMillis\"] ?? -1000) / 1000) ?? -1 : -1);\n      const id = encodeURIComponent(this.mk.nowPlayingItem != null ? app.mk.nowPlayingItem._songId ?? app.mk.nowPlayingItem[\"songId\"] ?? \"\" : \"\");\n      let lrcfile = \"\";\n      let richsync = [];\n      const lang = app.cfg.lyrics.mxm_language; //  translation language\n      function revisedRandId() {\n        return Math.random()\n          .toString(36)\n          .replace(/[^a-z]+/g, \"\")\n          .slice(2, 10);\n      }\n\n      /* get token */\n      function getToken(mode, track, artist, songid, lang, time, id) {\n        if (attempt > 2) {\n          app.loadNeteaseLyrics();\n          // app.loadAMLyrics();\n        } else {\n          attempt = attempt + 1;\n          let url = \"https://apic-desktop.musixmatch.com/ws/1.1/token.get?app_id=web-desktop-app-v1.0&t=\" + revisedRandId();\n          let req = new XMLHttpRequest();\n          req.overrideMimeType(\"application/json\");\n          req.open(\"GET\", url, true);\n          req.setRequestHeader(\"authority\", \"apic-desktop.musixmatch.com\");\n          req.onload = function () {\n            try {\n              let jsonResponse = JSON.parse(this.responseText);\n              let status2 = jsonResponse[\"message\"][\"header\"][\"status_code\"];\n              if (status2 == 200) {\n                let token = jsonResponse[\"message\"][\"body\"][\"user_token\"] ?? \"\";\n                if (token != \"\" && token != \"UpgradeOnlyUpgradeOnlyUpgradeOnlyUpgradeOnly\") {\n                  console.debug(\"200 token\", mode);\n                  // token good\n                  app.mxmtoken = token;\n\n                  if (mode == 1) {\n                    getMXMSubs(track, artist, app.mxmtoken, lang, time, id);\n                  } else {\n                    getMXMTrans(songid, lang, app.mxmtoken);\n                  }\n                } else {\n                  console.debug(\"fake 200 token\");\n                  getToken(mode, track, artist, songid, lang, time);\n                }\n              } else {\n                // console.log('token 4xx');\n                getToken(mode, track, artist, songid, lang, time);\n              }\n            } catch (e) {\n              console.log(\"error\");\n              app.loadQQLyrics();\n              //app.loadAMLyrics();\n            }\n          };\n          req.onerror = function () {\n            console.log(\"error\");\n            app.loadQQLyrics();\n            // app.loadAMLyrics();\n          };\n          req.send();\n        }\n      }\n\n      function getMXMSubs(track, artist, token, lang, time, id) {\n        let usertoken = encodeURIComponent(token);\n        let richsyncQuery = app.cfg.lyrics.mxm_karaoke ? \"&optional_calls=track.richsync\" : \"\";\n        let timecustom = !time || (time && time < 0) ? \"\" : `&f_subtitle_length=${time}&q_duration=${time}&f_subtitle_length_max_deviation=40`;\n        let itunesid = id && id != \"\" ? `&track_itunes_id=${id}` : \"\";\n        let url = \"https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get?format=json&namespace=lyrics_richsynched\" + richsyncQuery + \"&subtitle_format=lrc&q_artist=\" + artist + \"&q_track=\" + track + itunesid + \"&usertoken=\" + usertoken + timecustom + \"&app_id=web-desktop-app-v1.0&t=\" + revisedRandId();\n        let req = new XMLHttpRequest();\n        req.overrideMimeType(\"application/json\");\n        req.open(\"GET\", url, true);\n        req.setRequestHeader(\"authority\", \"apic-desktop.musixmatch.com\");\n        req.onload = function () {\n          try {\n            let jsonResponse = JSON.parse(this.responseText);\n            console.debug(jsonResponse);\n            let status1 = jsonResponse[\"message\"][\"header\"][\"status_code\"];\n\n            if (status1 == 200) {\n              let id = \"\";\n              try {\n                if (jsonResponse[\"message\"][\"body\"][\"macro_calls\"][\"matcher.track.get\"][\"message\"][\"header\"][\"status_code\"] == 200 && jsonResponse[\"message\"][\"body\"][\"macro_calls\"][\"track.subtitles.get\"][\"message\"][\"header\"][\"status_code\"] == 200) {\n                  id = jsonResponse[\"message\"][\"body\"][\"macro_calls\"][\"matcher.track.get\"][\"message\"][\"body\"][\"track\"][\"track_id\"] ?? \"\";\n                  lrcfile = jsonResponse[\"message\"][\"body\"][\"macro_calls\"][\"track.subtitles.get\"][\"message\"][\"body\"][\"subtitle_list\"][0][\"subtitle\"][\"subtitle_body\"];\n\n                  try {\n                    let lrcrich = jsonResponse[\"message\"][\"body\"][\"macro_calls\"][\"track.richsync.get\"][\"message\"][\"body\"][\"richsync\"][\"richsync_body\"];\n                    richsync = JSON.parse(lrcrich);\n                    app.richlyrics = richsync;\n                  } catch (_) {}\n                }\n\n                if (lrcfile == \"\") {\n                  app.loadQQLyrics();\n                  // app.loadAMLyrics()\n                } else {\n                  if (richsync == [] || richsync.length == 0) {\n                    console.log(\"ok\");\n                    // process lrcfile to json here\n                    app.lyricsMediaItem = lrcfile;\n                    let u = app.lyricsMediaItem.split(/[\\r\\n]/);\n                    let preLrc = [];\n                    for (var i = u.length - 1; i >= 0; i--) {\n                      let xline = /(\\[[0-9.:\\[\\]]*\\])+(.*)/.exec(u[i]);\n                      let end = preLrc.length > 0 ? preLrc[preLrc.length - 1].startTime ?? 99999 : 99999;\n                      preLrc.push({\n                        startTime: app.toMS(xline[1].substring(1, xline[1].length - 2)) ?? 0,\n                        endTime: end,\n                        line: xline[2],\n                        translation: \"\",\n                      });\n                    }\n                    if (preLrc.length > 0)\n                      preLrc.push({\n                        startTime: 0,\n                        endTime: preLrc[preLrc.length - 1].startTime,\n                        line: \"lrcInstrumental\",\n                        translation: \"\",\n                      });\n                    app.lyrics = preLrc.reverse();\n                  } else {\n                    let preLrc = richsync.map(function (item) {\n                      return {\n                        startTime: item.ts,\n                        endTime: item.te,\n                        line: item.x,\n                        translation: \"\",\n                      };\n                    });\n                    if (preLrc.length > 0)\n                      preLrc.unshift({\n                        startTime: 0,\n                        endTime: preLrc[0].startTime,\n                        line: \"lrcInstrumental\",\n                        translation: \"\",\n                      });\n                    app.lyrics = preLrc;\n                  }\n                  if (lrcfile != null && lrcfile != \"\") {\n                    // load translation\n                    getMXMTrans(id, lang, token);\n                  } else {\n                    // app.loadAMLyrics()\n                    app.loadQQLyrics();\n                  }\n                }\n              } catch (e) {\n                console.log(e);\n                app.loadQQLyrics();\n                //  app.loadAMLyrics()\n              }\n            } else {\n              //4xx rejected\n              getToken(1, track, artist, \"\", lang, time);\n            }\n          } catch (e) {\n            console.log(e);\n            app.loadQQLyrics();\n            //app.loadAMLyrics()\n          }\n        };\n        req.onerror = function () {\n          app.loadQQLyrics();\n          console.log(\"error\");\n          // app.loadAMLyrics();\n        };\n        req.send();\n      }\n\n      function getMXMTrans(id, lang, token) {\n        if (lang != \"disabled\" && id != \"\") {\n          let usertoken = encodeURIComponent(token);\n          let url2 = \"https://apic-desktop.musixmatch.com/ws/1.1/crowd.track.translations.get?translation_fields_set=minimal&selected_language=\" + lang + \"&track_id=\" + id + \"&comment_format=text&part=user&format=json&usertoken=\" + usertoken + \"&app_id=web-desktop-app-v1.0&t=\" + revisedRandId();\n          let req2 = new XMLHttpRequest();\n          req2.overrideMimeType(\"application/json\");\n          req2.open(\"GET\", url2, true);\n          req2.setRequestHeader(\"authority\", \"apic-desktop.musixmatch.com\");\n          req2.onload = function () {\n            try {\n              let jsonResponse2 = JSON.parse(this.responseText);\n              console.log(jsonResponse2);\n              let status2 = jsonResponse2[\"message\"][\"header\"][\"status_code\"];\n              if (status2 == 200) {\n                try {\n                  let preTrans = [];\n                  let u = app.lyrics;\n                  let translation_list = jsonResponse2[\"message\"][\"body\"][\"translations_list\"];\n                  if (translation_list.length > 0) {\n                    for (var i = 0; i < u.length - 1; i++) {\n                      preTrans[i] = \"\";\n                      for (var trans_line of translation_list) {\n                        if (u[i].line == \" \" + trans_line[\"translation\"][\"matched_line\"] || u[i].line == trans_line[\"translation\"][\"matched_line\"]) {\n                          u[i].translation = trans_line[\"translation\"][\"description\"];\n                          break;\n                        }\n                      }\n                    }\n                    app.lyrics = u;\n                  }\n                } catch (e) {\n                  /// not found trans -> ignore\n                }\n              } else {\n                //4xx rejected\n                getToken(2, \"\", \"\", id, lang, \"\");\n              }\n            } catch (e) {}\n          };\n          req2.send();\n        }\n      }\n\n      if ((track != \"\") & (track != \"No Title Found\")) {\n        if (app.mxmtoken != null && app.mxmtoken != \"\") {\n          getMXMSubs(track, artist, app.mxmtoken, lang, time, id);\n        } else {\n          getToken(1, track, artist, \"\", lang, time);\n        }\n      }\n    },\n    loadNeteaseLyrics() {\n      const track = encodeURIComponent(this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.title ?? \"\" : \"\");\n      const artist = encodeURIComponent(this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.artistName ?? \"\" : \"\");\n      const time = encodeURIComponent(this.mk.nowPlayingItem != null ? Math.round((this.mk.nowPlayingItem.attributes[\"durationInMillis\"] ?? -1000) / 1000) ?? -1 : -1);\n      var url = `http://music.163.com/api/search/get/?csrf_token=hlpretag=&hlposttag=&s=${track + \" \" + artist}&type=1&offset=0&total=true&limit=6`;\n      var req = new XMLHttpRequest();\n      req.overrideMimeType(\"application/json\");\n      req.open(\"GET\", url, true);\n      req.onload = function () {\n        try {\n          var jsonResponse = JSON.parse(req.responseText);\n          var id = jsonResponse[\"result\"][\"songs\"][0][\"id\"];\n          var url2 = \"https://music.163.com/api/song/lyric?os=pc&id=\" + id + \"&lv=-1&kv=-1&tv=-1\";\n          var req2 = new XMLHttpRequest();\n          req2.overrideMimeType(\"application/json\");\n          req2.open(\"GET\", url2, true);\n          req2.onload = function () {\n            try {\n              var jsonResponse2 = JSON.parse(req2.responseText);\n              var lrcfile = jsonResponse2[\"lrc\"][\"lyric\"];\n              app.lyricsMediaItem = lrcfile;\n              let u = app.lyricsMediaItem.split(/[\\n]/);\n              let preLrc = [];\n              for (var i = u.length - 1; i >= 0; i--) {\n                let xline = /(\\[[0-9.:\\[\\]]*\\])+(.*)/.exec(u[i]);\n                if (xline != null) {\n                  let end = preLrc.length > 0 ? preLrc[preLrc.length - 1].startTime ?? 99999 : 99999;\n                  preLrc.push({\n                    startTime: app.toMS(xline[1].substring(1, xline[1].length - 2)) ?? 0,\n                    endTime: end,\n                    line: xline[2],\n                    translation: \"\",\n                  });\n                }\n              }\n              if (preLrc.length > 0)\n                preLrc.push({\n                  startTime: 0,\n                  endTime: preLrc[preLrc.length - 1].startTime,\n                  line: \"lrcInstrumental\",\n                  translation: \"\",\n                });\n              app.lyrics = preLrc.reverse();\n            } catch (e) {\n              app.lyrics = \"\";\n            }\n          };\n          req2.onerror = function () {};\n          req2.send();\n        } catch (e) {\n          app.lyrics = \"\";\n        }\n      };\n      req.send();\n      req.onerror = function () {};\n    },\n    loadQQLyrics() {\n      if (!app.cfg.lyrics.enable_qq) return;\n      const track = encodeURIComponent(this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.title ?? \"\" : \"\");\n      const artist = encodeURIComponent(this.mk.nowPlayingItem != null ? this.mk.nowPlayingItem.artistName ?? \"\" : \"\");\n      const time = encodeURIComponent(this.mk.nowPlayingItem != null ? Math.round((this.mk.nowPlayingItem.attributes[\"durationInMillis\"] ?? -1000) / 1000) ?? -1 : -1);\n      var url = `https://c.y.qq.com/soso/fcgi-bin/client_search_cp?w=${track + \" \" + artist}&t=0&n=1&page=1&cr=1&new_json=1&format=json&platform=yqq.json`;\n\n      var req = new XMLHttpRequest();\n      req.overrideMimeType(\"application/json\");\n      req.open(\"GET\", url, true);\n      req.onload = function () {\n        try {\n          var jsonResponse = JSON.parse(req.responseText);\n          let id = jsonResponse?.data?.song?.list[0]?.mid;\n          console.log(jsonResponse);\n          let usz = new Date().getTime();\n          var url2 = `https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?-=MusicJsonCallback_lrc&songmid=${id}&pcachetime=${usz}&g_tk=5381&loginUin=3003436226&hostUin=0&inCharset=utf-8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0`;\n          var req2 = new XMLHttpRequest();\n          req2.overrideMimeType(\"application/json\");\n          req2.open(\"GET\", url2, true);\n          req2.onload = function () {\n            try {\n              function b64_to_utf8(str) {\n                return decodeURIComponent(escape(window.atob(str)));\n              }\n\n              const htmlDecode = (input) => {\n                const doc = new DOMParser().parseFromString(input, \"text/html\");\n                return doc.documentElement.textContent;\n              };\n              var jsonResponse2 = JSON.parse(req2.responseText.replace(\"MusicJsonCallback(\", \"\").replace(\"})\", \"}\"));\n              var lrcfile = htmlDecode(b64_to_utf8(jsonResponse2[\"lyric\"]));\n              app.lyricsMediaItem = lrcfile;\n              let u = app.lyricsMediaItem.split(/[\\n]/);\n\n              let preLrc = [];\n              for (var i = u.length - 1; i >= 0; i--) {\n                let xline = /(\\[[0-9.:\\[\\]]*\\])+(.*)/.exec(u[i]);\n                if (xline != null) {\n                  let end = preLrc.length > 0 ? preLrc[preLrc.length - 1].startTime ?? 99999 : 99999;\n                  preLrc.push({\n                    startTime: app.toMS(xline[1].substring(1, xline[1].length - 2)) ?? 0,\n                    endTime: end,\n                    line: xline[2],\n                    translation: \"\",\n                  });\n                }\n              }\n              if (preLrc.length > 0)\n                preLrc.push({\n                  startTime: 0,\n                  endTime: preLrc[preLrc.length - 1].startTime,\n                  line: \"lrcInstrumental\",\n                  translation: \"\",\n                });\n              app.lyrics = preLrc.reverse();\n              if (app.lyrics[5].line == \"\") {\n                app.loadNeteaseLyrics();\n              } // Detect incomplete QQ lyrics.\n            } catch (e) {\n              console.log(e);\n              app.loadNeteaseLyrics();\n              app.lyrics = \"\";\n            }\n          };\n          req2.onerror = function () {\n            app.loadNeteaseLyrics();\n          };\n          req2.send();\n        } catch (e) {\n          console.log(e);\n          app.loadNeteaseLyrics();\n          app.lyrics = \"\";\n        }\n      };\n      req.onerror = function () {\n        app.loadNeteaseLyrics();\n      };\n      req.send();\n    },\n    toMS(str) {\n      let rawTime = str.match(/(\\d+:)?(\\d+:)?(\\d+)(\\.\\d+)?/);\n      let hours = rawTime[2] != null ? rawTime[1].replace(\":\", \"\") : 0;\n      let minutes = rawTime[2] != null ? hours * 60 + rawTime[2].replace(\":\", \"\") * 1 : rawTime[1] != null ? rawTime[1].replace(\":\", \"\") : 0;\n      let seconds = rawTime[3] != null ? rawTime[3] : 0;\n      let milliseconds = rawTime[4] != null ? rawTime[4].replace(\".\", \"\") : 0;\n      return parseFloat(`${minutes * 60 + seconds * 1}.${milliseconds * 1}`);\n    },\n    parseTTML() {\n      this.lyrics = [];\n      let preLrc = [];\n      let xml = this.stringToXml(this.lyricsMediaItem);\n      let lyricsLines = xml.getElementsByTagName(\"p\");\n      let synced = true;\n      let endTimes = [];\n      if (xml.getElementsByTagName(\"tt\")[0].getAttribute(\"itunes:timing\") === \"None\") {\n        synced = false;\n      }\n      endTimes.push(0);\n      if (synced) {\n        for (let element of lyricsLines) {\n          let start = this.toMS(element.getAttribute(\"begin\"));\n          let end = this.toMS(element.getAttribute(\"end\"));\n          if (start - endTimes[endTimes.length - 1] > 5 && endTimes[endTimes.length - 1] != 0) {\n            preLrc.push({\n              startTime: endTimes[endTimes.length - 1],\n              endTime: start,\n              line: \"lrcInstrumental\",\n            });\n          }\n          preLrc.push({\n            startTime: start,\n            endTime: end,\n            line: element.textContent,\n          });\n          endTimes.push(end);\n        }\n        // first line dot\n        if (preLrc.length > 0)\n          preLrc.unshift({\n            startTime: 0,\n            endTime: preLrc[0].startTime,\n            line: \"lrcInstrumental\",\n          });\n      } else {\n        for (let element of lyricsLines) {\n          preLrc.push({\n            startTime: 9999999,\n            endTime: 9999999,\n            line: element.textContent,\n          });\n        }\n      }\n      this.lyrics = preLrc;\n    },\n    parseLyrics() {\n      let xml = this.stringToXml(this.lyricsMediaItem);\n      let json = xmlToJson(xml);\n      this.lyrics = json;\n    },\n    stringToXml(st) {\n      // string to xml\n      let xml = new DOMParser().parseFromString(st, \"text/xml\");\n      return xml;\n    },\n    getCurrentTime() {\n      return parseFloat(this.hmsToSecondsOnly(this.parseTime(this.mk.nowPlayingItem.attributes.durationInMillis - app.mk.currentPlaybackTimeRemaining * 1000)));\n    },\n    seekTo(time) {\n      this.mk.seekToTime(time);\n    },\n    parseTime(value) {\n      let minutes = Math.floor(value / 60000);\n      let seconds = ((value % 60000) / 1000).toFixed(0);\n      return minutes + \":\" + (seconds < 10 ? \"0\" : \"\") + seconds;\n    },\n    parseTimeDecimal(value) {\n      let minutes = Math.floor(value / 60000);\n      let seconds = ((value % 60000) / 1000).toFixed(0);\n      return minutes + \".\" + (seconds < 10 ? \"0\" : \"\") + seconds;\n    },\n    hmsToSecondsOnly(str) {\n      let p = str.split(\":\"),\n        s = 0,\n        m = 1;\n\n      while (p.length > 0) {\n        s += m * parseInt(p.pop(), 10);\n        m *= 60;\n      }\n\n      return s;\n    },\n    getLyricBGStyle(start, end) {\n      let currentTime = this.getCurrentTime();\n      // let duration = this.mk.nowPlayingItem.attributes.durationInMillis\n      let start2 = this.hmsToSecondsOnly(start);\n      let end2 = this.hmsToSecondsOnly(end);\n      // let currentProgress = ((100 * (currentTime)) / (end2))\n      // check if currenttime is between start and end\n      this.player.lyricsDebug.start = start2;\n      this.player.lyricsDebug.end = end2;\n      this.player.lyricsDebug.current = currentTime;\n      if (currentTime >= start2 && currentTime <= end2) {\n        return {\n          \"--bgSpeed\": `${end2 - start2}s`,\n        };\n      } else {\n        return {};\n      }\n    },\n    playMediaItemById(id, kind, isLibrary, raurl = \"\") {\n      let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n      console.debug(id, truekind, isLibrary);\n      try {\n        if (truekind.includes(\"artist\")) {\n          app.mk.setStationQueue({ artist: \"a-\" + id }).then(() => {\n            app.mk.play();\n          });\n        } else if (truekind == \"radioStations\") {\n          this.mk.setStationQueue({ url: raurl }).then(function (queue) {\n            MusicKit.getInstance().play();\n          });\n        } else {\n          this.mk\n            .setQueue({\n              [truekind]: [id],\n              parameters: { l: this.mklang },\n            })\n            .then(function (queue) {\n              MusicKit.getInstance().play();\n            });\n        }\n      } catch (err) {\n        console.log(err);\n        this.playMediaItemById(id, kind, isLibrary, raurl);\n      }\n    },\n    queueParentandplayChild(parent, childIndex, item) {\n      /* Randomize array in-place using Durstenfeld shuffle algorithm */\n      function shuffleArray(array) {\n        for (var i = array.length - 1; i > 0; i--) {\n          var j = Math.floor(Math.random() * (i + 1));\n          var temp = array[i];\n          array[i] = array[j];\n          array[j] = temp;\n        }\n      }\n\n      let kind = parent.substring(0, parent.indexOf(\":\"));\n      let id = parent.substring(parent.indexOf(\":\") + 1, parent.length);\n      let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n      console.log(truekind, id);\n\n      try {\n        if (parent == \"playlist:ciderlocal\") {\n          let u = app.library.localsongs.map((i) => {\n            return i.id;\n          });\n          app.mk.setQueue({ episodes: u }).then(() => {\n            let id = app.mk.queue._itemIDs.findIndex((element) => element == item.id);\n            app.mk.changeToMediaAtIndex(id);\n          });\n        } else if (app.library.songs.displayListing.length > childIndex && parent == \"librarysongs\") {\n          console.log(item);\n          if (item && app.library.songs.displayListing[childIndex].id != item.id) {\n            childIndex = app.library.songs.displayListing.indexOf(item);\n          }\n\n          let query = app.library.songs.displayListing.map((item) => new MusicKit.MediaItem(item));\n\n          app.mk.stop().then(() => {\n            if (item) {\n              app.mk\n                .setQueue({\n                  [item.attributes.playParams.kind ?? item.type]: item.attributes.playParams.id ?? item.id,\n                  parameters: { l: app.mklang },\n                })\n                .then(function () {\n                  app.mk.play().then(() => {\n                    if (app.mk.shuffleMode == 1) {\n                      shuffleArray(query);\n                    } else {\n                      for (let i = 0; i < query.length; i++) {\n                        if (query[i].id == item.id) {\n                          query.splice(0, i + 1);\n                          break;\n                        }\n                      }\n                    }\n                    app.mk.queue.append(query);\n                  });\n                });\n            } else {\n              app.mk.queue.splice(0, app.mk.queue._itemIDs.length);\n              if (app.mk.shuffleMode == 1) {\n                shuffleArray(query);\n              }\n              app.mk.queue.append(query);\n              if (childIndex != -1) {\n                app.mk.changeToMediaAtIndex(childIndex);\n              } else {\n                app.mk.play();\n              }\n            }\n          });\n        } else if (parent.startsWith(\"listitem-hr\")) {\n          app.mk.stop().then(() => {\n            if (app.mk.shuffleMode == 1) {\n              app.mk\n                .setQueue({\n                  [item.attributes.playParams.kind ?? item.type]: item.attributes.playParams.id ?? item.id,\n                })\n                .then(function () {\n                  app.mk.play().then(() => {\n                    let data = JSON.parse(parent.split(\"listitem-hr\")[1] ?? \"[]\");\n                    let itemsToPlay = {};\n                    let u = data.map((x) => x.id);\n                    try {\n                      data.splice(u.indexOf(item.attributes.playParams.id ?? item.id), 1);\n                    } catch (e) {}\n                    if (app.mk.shuffleMode == 1) {\n                      shuffleArray(data);\n                    }\n                    data.forEach((item) => {\n                      if (!itemsToPlay[item.kind]) {\n                        itemsToPlay[item.kind] = [];\n                      }\n                      itemsToPlay[item.kind].push(item.id);\n                    });\n                    // loop through itemsToPlay\n                    for (let kind in itemsToPlay) {\n                      let ids = itemsToPlay[kind];\n                      if (ids.length > 0) {\n                        app.mk.playLater({ [kind + \"s\"]: itemsToPlay[kind] });\n                      }\n                    }\n                  });\n                });\n            } else {\n              let data = JSON.parse(parent.split(\"listitem-hr\")[1] ?? \"[]\");\n              let itemsToPlay = {};\n              data.forEach((item) => {\n                if (!itemsToPlay[item.kind]) {\n                  itemsToPlay[item.kind] = [];\n                }\n                itemsToPlay[item.kind].push(item.id);\n              });\n              // loop through itemsToPlay\n              app.mk.queue.splice(0, app.mk.queue._itemIDs.length);\n              let ind = 0;\n              for (let kind in itemsToPlay) {\n                let ids = itemsToPlay[kind];\n                if (ids.length > 0) {\n                  if (app.mk.queue._itemIDs.length > 0) {\n                    app.mk.playLater({ [kind + \"s\"]: itemsToPlay[kind] }).then(function () {\n                      ind += 1;\n                      console.log(ind, Object.keys(itemsToPlay).length);\n                      if (ind >= Object.keys(itemsToPlay).length) {\n                        app.mk.changeToMediaAtIndex(app.mk.queue._itemIDs.indexOf(item.attributes.playParams.id ?? item.id));\n                      }\n                    });\n                  } else {\n                    app.mk.setQueue({ [kind + \"s\"]: itemsToPlay[kind] }).then(function () {\n                      ind += 1;\n                      console.log(ind, Object.keys(itemsToPlay).length);\n                      if (ind >= Object.keys(itemsToPlay).length) {\n                        app.mk.changeToMediaAtIndex(app.mk.queue._itemIDs.indexOf(item.attributes.playParams.id ?? item.id));\n                      }\n                    });\n                  }\n                }\n              }\n            }\n          });\n        } else {\n          app.mk.stop().then(() => {\n            if (truekind == \"playlists\" && (id.startsWith(\"p.\") || id.startsWith(\"pl.u\"))) {\n              app.mk\n                .setQueue({\n                  [item.attributes.playParams.kind ?? item.type]: item.attributes.playParams.id ?? item.id,\n                  parameters: { l: app.mklang },\n                })\n                .then(function () {\n                  app.mk.changeToMediaAtIndex(app.mk.queue._itemIDs.indexOf(item.id) ?? 1).then(function () {\n                    if (app.showingPlaylist && app.showingPlaylist.id == id) {\n                      let query = app.showingPlaylist.relationships.tracks.data.map((item) => new MusicKit.MediaItem(item));\n                      let u = query;\n                      if (app.mk.shuffleMode == 1) {\n                        shuffleArray(u);\n                      } else {\n                        for (let i = 0; i < app.showingPlaylist.relationships.tracks.data.length; i++) {\n                          if (app.showingPlaylist.relationships.tracks.data[i].id == item.id) {\n                            u.splice(0, i + 1);\n                            break;\n                          }\n                        }\n                      }\n                      app.mk.queue.append(u);\n                    } else {\n                      app.getPlaylistFromID(id, true).then(function () {\n                        let query = app.showingPlaylist.relationships.tracks.data.map((item) => new MusicKit.MediaItem(item));\n                        let u = query;\n                        if (app.mk.shuffleMode == 1) {\n                          shuffleArray(u);\n                        } else {\n                          for (let i = 0; i < app.showingPlaylist.relationships.tracks.data.length; i++) {\n                            if (app.showingPlaylist.relationships.tracks.data[i].id == item.id) {\n                              u.splice(0, i + 1);\n                              break;\n                            }\n                          }\n                        }\n                        app.mk.queue.append(u);\n                      });\n                    }\n                  });\n                });\n            } else {\n              this.mk\n                .setQueue({\n                  [truekind]: [id],\n                  parameters: { l: this.mklang },\n                })\n                .then(function (queue) {\n                  if (item && queue._itemIDs[childIndex] != item.id) {\n                    childIndex = queue._itemIDs.indexOf(item.id);\n                  }\n                  if (childIndex != -1) {\n                    app.mk.changeToMediaAtIndex(childIndex);\n                  } else if (item) {\n                    app.mk\n                      .playNext({\n                        [item.attributes.playParams.kind ?? item.type]: item.attributes.playParams.id ?? item.id,\n                      })\n                      .then(function () {\n                        app.mk.changeToMediaAtIndex(app.mk.queue._itemIDs.indexOf(item.id) ?? 1);\n                        app.mk.play();\n                      });\n                  } else {\n                    app.mk.play();\n                  }\n                });\n            }\n          });\n        }\n      } catch (err) {\n        console.log(err);\n        try {\n          app.mk.stop();\n        } catch (e) {}\n        this.playMediaItemById(item.attributes.playParams.id ?? item.id, item.attributes.playParams.kind ?? item.type, item.attributes.playParams.isLibrary ?? false, item.attributes.url);\n      }\n    },\n    friendlyTypes(type) {\n      // use switch statement to return friendly name for media types \"songs,artists,albums,playlists,music-videos,stations,apple-curators,curators\"\n      switch (type) {\n        case \"library-songs\":\n          return app.getLz(\"term.songs\");\n          break;\n        case \"library-artists\":\n          return app.getLz(\"term.artists\");\n          break;\n        case \"library-albums\":\n          return app.getLz(\"term.albums\");\n          break;\n        case \"library-playlists\":\n          return app.getLz(\"term.playlists\");\n          break;\n        case \"song\":\n          return app.getLz(\"term.songs\");\n          break;\n        case \"artist\":\n          return app.getLz(\"term.artists\");\n          break;\n        case \"album\":\n          return app.getLz(\"term.albums\");\n          break;\n        case \"playlist\":\n          return app.getLz(\"term.playlists\");\n          break;\n        case \"music_video\":\n          return app.getLz(\"term.musicVideos\");\n          break;\n        case \"station\":\n          return app.getLz(\"term.stations\");\n          break;\n        case \"apple-curator\":\n          return app.getLz(\"term.appleCurators\");\n          break;\n        case \"radio_show\":\n          return app.getLz(\"term.radioShows\");\n          break;\n        case \"record_label\":\n          return app.getLz(\"term.recordLabels\");\n          break;\n        case \"radio_episode\":\n          return app.getLz(\"podcast.episodes\");\n          break;\n        case \"video_extra\":\n          return app.getLz(\"term.videoExtras\");\n          break;\n        case \"curator\":\n          return app.getLz(\"term.curators\");\n          break;\n        case \"top\":\n          return app.getLz(\"term.top\");\n          break;\n        default:\n          return type;\n          break;\n      }\n    },\n    searchCursor(e) {\n      if (e.keyCode == \"40\") {\n        if (this.search.hints.length - 1 < this.search.cursor + 1) return;\n        this.search.cursor++;\n        let item = this.search.hints[this.search.cursor];\n        this.search.term = item.content ? item.content?.attributes?.name ?? \"\" : item.displayTerm;\n      } else if (e.keyCode == \"38\") {\n        if (this.search.cursor == 0) return;\n        this.search.cursor--;\n        let item = this.search.hints[this.search.cursor];\n        this.search.term = item.content ? item.content?.attributes?.name ?? \"\" : item.displayTerm;\n      }\n    },\n    async searchQuery(term = this.search.term) {\n      let self = this;\n      if (typeof term === \"object\") {\n        this.routeView(term);\n        this.search.term = \"\";\n        return;\n      }\n      if (term == \"\") {\n        return;\n      }\n      //this.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/search?term=${this.search.term}`\n      this.mk.api.v3\n        .music(`/v1/catalog/${app.mk.storefrontId}/search?term=${encodeURIComponent(this.search.term)}`, {\n          types: \"activities,albums,apple-curators,artists,curators,editorial-items,music-movies,music-videos,playlists,songs,stations,tv-episodes,uploaded-videos,record-labels\",\n          \"relate[editorial-items]\": \"contents\",\n          \"include[editorial-items]\": \"contents\",\n          \"include[albums]\": \"artists\",\n          \"include[artists]\": \"artists\",\n          \"include[songs]\": \"artists,albums\",\n          \"include[music-videos]\": \"artists\",\n          extend: \"artistUrl\",\n          \"fields[artists]\": \"url,name,artwork,hero\",\n          \"fields[albums]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url\",\n          with: \"serverBubbles,lyricHighlights\",\n          \"art[url]\": \"c,f\",\n          \"omit[resource]\": \"autos\",\n          platform: \"web\",\n          limit: 25,\n          l: this.mklang,\n        })\n        .then(function (results) {\n          results.data.results[\"meta\"] = results.data.meta;\n          self.search.results = results.data.results;\n        });\n\n      await app.mk.api.v3\n        .music(\n          `v1/social/${app.mk.storefrontId}/search?term=${app.search.term}`,\n          {\n            types: [\"playlists\", \"social-profiles\"],\n            limit: 25,\n            with: [\"serverBubbles\", \"lyricSnippet\"],\n            \"art[url]\": \"f\",\n            \"art[social-profiles:url]\": \"c\",\n          },\n          { includeResponseMeta: !0 },\n        )\n        .then(function (results) {\n          results.data.results[\"meta\"] = results.data.meta;\n          self.search.resultsSocial = results.data.results;\n        });\n\n      this.search.resultsLibrary = await app.mk.api.library.search(app.search.term, {\n        types: \"library-songs,library-albums,library-playlists,library-artists\",\n        limit: 25,\n        offset: 0,\n      });\n    },\n    async inLibrary(items = []) {\n      let types = [];\n\n      for (let item of items) {\n        let type = item.type;\n        if (type.slice(-1) != \"s\") {\n          type += \"s\";\n        }\n        type = type.replace(\"library-\", \"\");\n        let id = item.attributes.playParams?.catalogId ?? item.attributes.playParams.id ?? item.id;\n\n        let index = types.findIndex(function (type) {\n          return type.type == this;\n        }, type);\n        if (index == -1) {\n          types.push({ type: type, id: [id] });\n        } else {\n          types[index].id.push(id);\n        }\n      }\n      let types2 = types.map(function (item) {\n        return {\n          [`ids[${item.type}]`]: [item.id],\n        };\n      });\n      types2 = types2.reduce(function (result, item) {\n        var key = Object.keys(item)[0]; //first property: a, b, c\n        result[key] = item[key];\n        return result;\n      }, {});\n      return (\n        await this.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}`, {\n          ...{\n            \"omit[resource]\": \"autos\",\n            relate: \"library\",\n            fields: \"inLibrary\",\n          },\n          ...types2,\n        })\n      ).data.data;\n    },\n    isInLibrary(playParams) {\n      let self = this;\n      let id = \"\";\n      // ugly code to check if current playback item is in library\n      if (typeof playParams == \"undefined\") {\n        return true;\n      }\n      if (playParams[\"isLibrary\"]) {\n        return true;\n      } else if (playParams[\"catalogId\"]) {\n        id = playParams[\"catalogId\"];\n      } else if (playParams[\"id\"]) {\n        id = playParams[\"id\"];\n      }\n      let found = this.library.songs.listing.filter((item) => {\n        if (item[\"attributes\"]) {\n          if (item[\"attributes\"][\"playParams\"] && item[\"attributes\"][\"playParams\"][\"catalogId\"] == id) {\n            return item;\n          }\n        }\n      });\n      if (found.length != 0) {\n        return true;\n      } else {\n        return false;\n      }\n    },\n    mkReady() {\n      if (this.mk[\"nowPlayingItem\"]) {\n        return true;\n      } else {\n        return false;\n      }\n    },\n    getMediaItemArtwork(url, height = 64, width) {\n      try {\n        if (typeof url == \"undefined\" || url == \"\") {\n          return \"./assets/MissingArtwork.svg\";\n        }\n        height = parseInt(height * window.devicePixelRatio);\n        if (width) {\n          width = parseInt(width * window.devicePixelRatio);\n        }\n        let newurl = `${(url ?? \"\")\n          .replace(\"{w}\", width ?? height)\n          .replace(\"{h}\", height)\n          .replace(\"{f}\", \"webp\")\n          .replace(\"{c}\", width === 900 || width === 380 || width === 600 ? \"sr\" : \"cc\")}`;\n\n        if (newurl.includes(\"900x516\")) {\n          newurl = newurl.replace(\"900x516cc\", \"900x516sr\").replace(\"900x516bb\", \"900x516sr\");\n        }\n        return newurl;\n      } catch (e) {\n        console.log(url);\n        return \"./assets/MissingArtwork.svg\";\n      }\n    },\n    _rgbToRgb(rgb = [0, 0, 0]) {\n      // if rgb\n      return `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`;\n    },\n    getNowPlayingArtworkBG(size = 32, force = false) {\n      let self = this;\n      if (typeof this.mk.nowPlayingItem === \"undefined\") return;\n      let bginterval = setInterval(() => {\n        if (!this.mkReady()) {\n          return \"\";\n        }\n\n        try {\n          if ((this.mk.nowPlayingItem && this.mk.nowPlayingItem[\"id\"] != this.currentTrackID && document.querySelector(\".bg-artwork\")) || force) {\n            if (document.querySelector(\".bg-artwork\")) {\n              clearInterval(bginterval);\n            }\n            this.currentTrackID = this.mk.nowPlayingItem[\"id\"];\n            document.querySelector(\".bg-artwork\").src = \"\";\n            if (this.mk[\"nowPlayingItem\"][\"attributes\"][\"artwork\"][\"url\"]) {\n              getBase64FromUrl(this.mk[\"nowPlayingItem\"][\"attributes\"][\"artwork\"][\"url\"].replace(\"{w}\", size).replace(\"{h}\", size)).then((img) => {\n                document.querySelectorAll(\".bg-artwork\").forEach((artwork) => {\n                  artwork.src = img;\n                });\n                self.$store.commit(\"setLCDArtwork\", img);\n              });\n              try {\n                clearInterval(bginterval);\n              } catch (err) {}\n            } else {\n              this.setLibraryArtBG();\n            }\n          } else if (this.mk.nowPlayingItem[\"id\"] == this.currentTrackID) {\n            try {\n              clearInterval(bginterval);\n            } catch (err) {}\n          }\n        } catch (e) {\n          if (this.mk.nowPlayingItem && this.mk.nowPlayingItem[\"id\"] && document.querySelector(\".bg-artwork\")) {\n            this.setLibraryArtBG();\n            try {\n              clearInterval(bginterval);\n            } catch (err) {}\n          }\n        }\n      }, 200);\n    },\n    async getCurrentArtURL() {\n      let artworkSize = 50;\n      if (app.getThemeDirective(\"lcdArtworkSize\") !== \"\") {\n        artworkSize = app.getThemeDirective(\"lcdArtworkSize\");\n      } else if (this.cfg.visual.directives.windowLayout === \"twopanel\") {\n        artworkSize = 110;\n      }\n      const mediaItem = (app?.mk?.nowPlayingItem?.attributes?.artwork?.url ? app?.mk?.nowPlayingItem : null) ?? (await this.mk.api.v3.music(`/v1/me/library/songs/${this.mk?.nowPlayingItem?.id}`)?.data?.data?.data[0]) ?? {};\n      return { currentArtUrlRaw: mediaItem?.attributes?.artwork?.url ?? \"\", currentArtUrl: mediaItem?._assets[0]?.artworkURL ?? mediaItem?.attributes?.artwork?.url?.replace(\"{w}\", artworkSize).replace(\"{h}\", artworkSize) };\n    },\n    async setLibraryArt() {\n      if (typeof this.mk.nowPlayingItem === \"undefined\") return;\n      try {\n        let data = await this.mk.api.v3.music(`/v1/me/library/songs/${this.mk.nowPlayingItem.id}`);\n        data = data.data.data[0];\n\n        if (data != null && data !== \"\") {\n          document.querySelector(\".app-playback-controls .artwork\").style.setProperty(\"--artwork\", 'url(\"' + data[\"attributes\"][\"artwork\"][\"url\"].toString() + '\")');\n        } else {\n          document.querySelector(\".app-playback-controls .artwork\").style.setProperty(\"--artwork\", `url(\"\")`);\n        }\n      } catch (e) {}\n    },\n    async setLibraryArtBG() {\n      if (typeof this.mk.nowPlayingItem === \"undefined\") return;\n      try {\n        let data = await this.mk.api.v3.music(`/v1/me/library/songs/${this.mk.nowPlayingItem.id}`);\n        data = data.data.data[0];\n\n        if (data != null && data !== \"\") {\n          getBase64FromUrl(data[\"attributes\"][\"artwork\"][\"url\"].toString()).then((img) => {\n            document.querySelector(\".bg-artwork\").forEach((artwork) => {\n              artwork.src = img;\n            });\n            self.$store.commit(\"setLCDArtwork\", img);\n          });\n        }\n      } catch (e) {}\n    },\n    quickPlay(query) {\n      let self = this;\n      MusicKit.getInstance()\n        .api.search(query, { limit: 2, types: \"songs\" })\n        .then(function (data) {\n          MusicKit.getInstance()\n            .setQueue({\n              song: data[\"songs\"][\"data\"][0][\"id\"],\n              parameters: { l: app.mklang },\n            })\n            .then(function (queue) {\n              MusicKit.getInstance().play();\n              setTimeout(() => {\n                self.$forceUpdate();\n              }, 1000);\n            });\n        });\n    },\n    async getRating(item) {\n      let type = item.type.slice(-1) === \"s\" ? item.type : item.type + \"s\";\n      let id = item.attributes?.playParams?.catalogId ? item.attributes.playParams.catalogId : item.attributes?.playParams?.id ?? item.id;\n      if (item.id != null && item.id.toString().startsWith(\"i.\")) {\n        if (!type.startsWith(\"library-\")) {\n          type = \"library-\" + type;\n        }\n        id = item.id;\n      }\n      let response = await this.mk.api.v3.music(`/v1/me/ratings/${type}?platform=web&ids=${type.includes(\"library\") ? item.id : id}`);\n      if (response.data.data.length != 0) {\n        let value = response.data.data[0].attributes.value;\n        return value;\n      } else {\n        return 0;\n      }\n    },\n    love(item) {\n      let type = item.type.slice(-1) === \"s\" ? item.type : item.type + \"s\";\n      let id = item.attributes?.playParams?.catalogId ? item.attributes.playParams.catalogId : item.attributes?.playParams?.id ?? item.id;\n      if (item.id != null && item.id.toString().startsWith(\"i.\")) {\n        if (!type.startsWith(\"library-\")) {\n          type = \"library-\" + type;\n        }\n        id = item.id;\n      }\n      this.mk.api.v3.music(\n        `/v1/me/ratings/${type}/${id}`,\n        {},\n        {\n          fetchOptions: {\n            method: \"PUT\",\n            body: JSON.stringify({\n              type: \"rating\",\n              attributes: {\n                value: 1,\n              },\n            }),\n          },\n        },\n      );\n    },\n    dislike(item) {\n      let type = item.type.slice(-1) === \"s\" ? item.type : item.type + \"s\";\n      let id = item.attributes?.playParams?.catalogId ? item.attributes.playParams.catalogId : item.attributes?.playParams?.id ?? item.id;\n      if (item.id != null && item.id.toString().startsWith(\"i.\")) {\n        if (!type.startsWith(\"library-\")) {\n          type = \"library-\" + type;\n        }\n        id = item.id;\n      }\n      this.mk.api.v3.music(\n        `/v1/me/ratings/${type}/${id}`,\n        {},\n        {\n          fetchOptions: {\n            method: \"PUT\",\n            body: JSON.stringify({\n              type: \"rating\",\n              attributes: {\n                value: -1,\n              },\n            }),\n          },\n        },\n      );\n    },\n    unlove(item) {\n      let type = item.type.slice(-1) === \"s\" ? item.type : item.type + \"s\";\n      let id = item.attributes.playParams.catalogId ? item.attributes.playParams.catalogId : item.id;\n      if (item.id.startsWith(\"i.\")) {\n        if (!type.startsWith(\"library-\")) {\n          type = \"library-\" + type;\n        }\n        id = item.id;\n      }\n      this.mk.api.v3.music(\n        `/v1/me/ratings/${type}/${id}`,\n        {},\n        {\n          fetchOptions: {\n            method: \"DELETE\",\n          },\n        },\n      );\n    },\n    checkScrollDirectionIsUp(event) {\n      if (event.wheelDelta) {\n        return event.wheelDelta > 0;\n      }\n      return event.deltaY < 0;\n    },\n    volumeUp() {\n      if (app.mk.volume + app.cfg.audio.volumeStep > app.cfg.audio.maxVolume) {\n        app.mk.volume = app.cfg.audio.maxVolume;\n      } else {\n        app.mk.volume = (Math.floor(app.mk.volume * 100) + app.cfg.audio.volumeStep * 100) / 100;\n      }\n    },\n    volumeDown() {\n      if (app.mk.volume - app.cfg.audio.volumeStep < 0) {\n        app.mk.volume = 0;\n      } else {\n        app.mk.volume = (Math.floor(app.mk.volume * 100) - app.cfg.audio.volumeStep * 100) / 100;\n      }\n    },\n    volumeWheel(event) {\n      app.checkScrollDirectionIsUp(event) ? this.volumeUp() : this.volumeDown();\n    },\n    muteButtonPressed() {\n      if (this.cfg.audio.muted) {\n        this.mk.volume = this.cfg.audio.lastVolume;\n        this.cfg.audio.muted = false;\n      } else {\n        this.cfg.audio.lastVolume = this.cfg.audio.volume;\n        this.mk.volume = 0;\n        this.cfg.audio.muted = true;\n      }\n    },\n    checkMuteChange() {\n      if (this.cfg.audio.muted) {\n        this.cfg.audio.muted = false;\n      }\n    },\n    repeatIncrement() {\n      switch (app.mk.repeatMode) {\n        default:\n        case MusicKit.PlayerRepeatMode.none:\n          app.mk.repeatMode = MusicKit.PlayerRepeatMode.all;\n          break;\n\n        case MusicKit.PlayerRepeatMode.all:\n          app.mk.repeatMode = MusicKit.PlayerRepeatMode.one;\n          break;\n\n        case MusicKit.PlayerRepeatMode.one:\n          app.mk.repeatMode = MusicKit.PlayerRepeatMode.none;\n          break;\n      }\n    },\n    async apiCall(url, callback) {\n      const xmlHttp = new XMLHttpRequest();\n\n      xmlHttp.onreadystatechange = (e) => {\n        if (xmlHttp.readyState !== 4) {\n          return;\n        }\n\n        if (xmlHttp.status === 200) {\n          // console.log('SUCCESS', xmlHttp.responseText);\n          callback(JSON.parse(xmlHttp.responseText));\n        } else {\n          console.warn(\"request_error\");\n        }\n      };\n\n      xmlHttp.open(\"GET\", url);\n      xmlHttp.setRequestHeader(\"Authorization\", \"Bearer \" + MusicKit.getInstance().developerToken);\n      xmlHttp.setRequestHeader(\"Music-User-Token\", \"\" + MusicKit.getInstance().musicUserToken);\n      xmlHttp.setRequestHeader(\"Accept\", \"application/json\");\n      xmlHttp.setRequestHeader(\"Content-Type\", \"application/json\");\n      xmlHttp.responseType = \"text\";\n      xmlHttp.send();\n    },\n    fetchPlaylist(id, callback) {\n      // id can be found in playlist.attributes.playParams.globalId\n      // this.mk.api.\n      this.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/playlists/${id}`).then((res) => {\n        callback(res.data.data[0]);\n      });\n\n      // tracks are found in relationship.data\n    },\n    setAirPlayCodeUI(identifier) {\n      this.modals.airplayPW = true;\n      this.currentAirPlayCodeID = identifier;\n    },\n    sendAirPlaySuccess(silent = false, identifier = \"\") {\n      if (!silent) {\n        notyf.success(\"Device paired successfully!\");\n      }\n      console.log(\"delete idx-pre\", identifier);\n      let idx = this.airplayTrys.findIndex((a) => {\n        return a.id == identifier;\n      });\n      console.log(\"delete idx\", idx);\n      if (idx != -1) delete this.airplayTrys[idx];\n      this.airplayTrys = this.airplayTrys.filter((n) => n);\n    },\n    sendAirPlayFailed() {\n      notyf.success(\"Device paring failed!\");\n    },\n    airplayDisconnect(dropped, array = [], identifier = \"\") {\n      console.log(\"airplay dropped\", dropped, array, identifier);\n      if (dropped) {\n        let [ipv4, ipport, sepassword, title, artist, album, artworkURL, txt, airplay2dv] = array;\n        console.log(ipv4, ipport, sepassword, title, artist, album, artworkURL, txt, airplay2dv);\n        let idx = this.airplayTrys.findIndex((a) => {\n          return a.id == ipv4 + \":\" + ipport + \"ap\";\n        });\n        if (idx == -1) {\n          this.airplayTrys.push({\n            id: ipv4 + \":\" + ipport + \"ap\",\n            attempts: 1,\n          });\n        }\n        idx = this.airplayTrys.findIndex((a) => {\n          return a.id == ipv4 + \":\" + ipport + \"ap\";\n        });\n        if (this.airplayTrys[idx].attempts > 3) {\n          delete this.airplayTrys[idx];\n          this.airplayTrys = this.airplayTrys.filter((n) => n);\n          console.log(\"delete idx\", idx);\n          return;\n        } else {\n          this.airplayTrys[idx].attempts = this.airplayTrys[idx].attempts + 1;\n          setTimeout(() => {\n            ipcRenderer.send(\"performAirplayPCM\", ipv4, ipport, sepassword, title, artist, album, artworkURL, txt, airplay2dv, true);\n          }, 1000);\n        }\n      } else {\n        if (identifier == \"\") {\n          app.activeCasts = [];\n          notyf.error(\"Devices disconnected!\");\n        } else {\n          app.activeCasts;\n          notyf.error(\"Device disconnected!\");\n        }\n      }\n    },\n    windowFocus(val) {\n      if (val) {\n        document.querySelectorAll(\".animated-artwork-video\").forEach((el) => {\n          el.play();\n        });\n        document.querySelector(\"body\").classList.remove(\"stopanimation\");\n        document.body.setAttribute(\"focus-state\", \"focused\");\n        this.animateBackground = true;\n      } else {\n        document.querySelectorAll(\".animated-artwork-video\").forEach((el) => {\n          el.pause();\n        });\n        document.querySelector(\"body\").classList.add(\"stopanimation\");\n        document.body.setAttribute(\"focus-state\", \"blurred\");\n        this.animateBackground = false;\n      }\n    },\n    async nowPlayingContextMenu(event) {\n      let self = this;\n      let data_type = this.mk.nowPlayingItem.playParams.kind;\n      let item_id = this.mk.nowPlayingItem.attributes.playParams.id ?? this.mk.nowPlayingItem.id;\n      let isLibrary = this.mk.nowPlayingItem.attributes.playParams.isLibrary ?? false;\n      let params = {\n        \"fields[songs]\": \"inLibrary\",\n        \"fields[albums]\": \"inLibrary\",\n        relate: \"library\",\n        t: \"1\",\n      };\n      app.selectedMediaItems = [];\n      app.select_selectMediaItem(item_id, data_type, 0, \"12344\", isLibrary);\n      let useMenu = \"normal\";\n      let menus = {\n        multiple: {\n          items: [],\n        },\n        normal: {\n          headerItems: [\n            {\n              icon: \"./assets/feather/heart.svg\",\n              id: \"love\",\n              name: app.getLz(\"action.love\"),\n              hidden: false,\n              disabled: true,\n              action: function () {\n                app.love(app.mk.nowPlayingItem);\n              },\n            },\n            {\n              icon: \"./assets/feather/heart.svg\",\n              id: \"unlove\",\n              active: true,\n              name: app.getLz(\"action.unlove\"),\n              hidden: true,\n              action: function () {\n                app.unlove(app.mk.nowPlayingItem);\n              },\n            },\n            {\n              icon: \"./assets/feather/thumbs-down.svg\",\n              id: \"dislike\",\n              name: app.getLz(\"action.dislike\"),\n              hidden: false,\n              disabled: true,\n              action: function () {\n                app.dislike(app.mk.nowPlayingItem);\n              },\n            },\n            {\n              icon: \"./assets/feather/thumbs-down.svg\",\n              id: \"undo_dislike\",\n              name: app.getLz(\"action.undoDislike\"),\n              active: true,\n              hidden: true,\n              action: function () {\n                app.unlove(app.mk.nowPlayingItem);\n              },\n            },\n          ],\n          items: [\n            {\n              icon: \"./assets/feather/plus.svg\",\n              id: \"addToLibrary\",\n              name: app.getLz(\"action.addToLibrary\") + \" ...\",\n              disabled: true,\n              action: function () {\n                app.addToLibrary(app.mk.nowPlayingItem.id);\n              },\n            },\n            {\n              id: \"removeFromLibrary\",\n              icon: \"./assets/feather/x-circle.svg\",\n              name: app.getLz(\"action.removeFromLibrary\"),\n              hidden: true,\n              action: function () {\n                self.removeFromLibrary(app.mk.nowPlayingItem.type, MusicKitInterop.getAttributes().songId);\n              },\n            },\n            {\n              icon: \"./assets/feather/list.svg\",\n              name: app.getLz(\"action.addToPlaylist\") + \" ...\",\n              action: function () {\n                app.promptAddToPlaylist();\n              },\n            },\n            {\n              icon: \"./assets/feather/radio.svg\",\n              name: app.getLz(\"action.startRadio\"),\n              action: function () {\n                app.mk.setStationQueue({ song: app.mk.nowPlayingItem.id }).then(() => {\n                  app.mk.play();\n                  app.selectedMediaItems = [];\n                });\n              },\n            },\n            {\n              icon: \"./assets/feather/user.svg\",\n              name: app.getLz(\"action.goToArtist\"),\n              action: async function () {\n                if (app.mk.nowPlayingItem.relationships.artists.data[0].id) {\n                  app.appRoute(`artist/${app.mk.nowPlayingItem.relationships.artists.data[0].id}`);\n                } else {\n                  const primaryArtist = await MusicKitInterop.fetchSongRelationships({ relationship: \"primaryArtist\" });\n                  app.appRoute(`artist/${primaryArtist.id}`);\n                }\n              },\n            },\n            {\n              icon: \"./assets/feather/disc.svg\",\n              name: app.getLz(\"action.goToAlbum\"),\n              action: function () {\n                app.appRoute(`album/${app.mk.nowPlayingItem.relationships.albums.data[0].id}`);\n              },\n            },\n            {\n              id: \"showInMusic\",\n              icon: \"./assets/music.svg\",\n              hidden: true,\n              name: app.getLz(\"action.showInAppleMusic\"),\n              action: function () {\n                app.routeView(app.mk.nowPlayingItem._container);\n              },\n            },\n            {\n              icon: \"./assets/feather/share.svg\",\n              name: app.getLz(\"action.share\"),\n              action: function () {\n                app.mkapi(app.mk.nowPlayingItem.attributes?.playParams?.kind ?? app.mk.nowPlayingItem.type ?? \"songs\", false, app.mk.nowPlayingItem._songId ?? app.mk.nowPlayingItem.songId ?? app.mk.nowPlayingItem.id ?? \"\").then((u) => {\n                  app.copyToClipboard(u.data.data.length && u.data.data.length > 0 ? u.data.data[0].attributes.url : u.data.data.attributes.url);\n                });\n              },\n            },\n            {\n              icon: \"./assets/feather/share.svg\",\n              name: `${app.getLz(\"action.share\")} (song.link)`,\n              action: function () {\n                app.mkapi(app.mk.nowPlayingItem.attributes?.playParams?.kind ?? app.mk.nowPlayingItem.type ?? \"songs\", false, app.mk.nowPlayingItem._songId ?? app.mk.nowPlayingItem.songId ?? app.mk.nowPlayingItem.id ?? \"\").then((u) => {\n                  app.songLinkShare(u.data.data.length && u.data.data.length > 0 ? u.data.data[0].attributes.url : u.data.data.attributes.url);\n                });\n              },\n            },\n            {\n              id: \"equalizer\",\n              icon: \"../views/svg/speaker.svg\",\n              name: app.getLz(\"term.equalizer\"),\n              hidden: false,\n              action: function () {\n                app.modals.equalizer = true;\n                app.modals.audioSettings = false;\n              },\n            },\n            {\n              id: \"audioLab\",\n              icon: \"../views/svg/speaker.svg\",\n              name: app.getLz(\"settings.option.audio.audioLab\"),\n              hidden: false,\n              action: function () {\n                app.openSettingsPage(\"audiolabs\");\n              },\n            },\n          ],\n        },\n      };\n      /*\n            if (this.cfg.advanced.AudioContext) {\n                menus.normal.items.find(i => i.id === 'audioLab').hidden = false\n                menus.normal.items.find(i => i.id === 'equalizer').hidden = false\n            }\n            */\n      if (this.contextExt) {\n        if (this.contextExt.normal) {\n          menus.normal.items = menus.normal.items.concat(this.contextExt.normal);\n        }\n      }\n\n      const nowPlayingContainer = app.mk.nowPlayingItem._container;\n      if (nowPlayingContainer && nowPlayingContainer[\"attributes\"] && nowPlayingContainer.name != \"station\") {\n        menus.normal.items.find((x) => x.id == \"showInMusic\").hidden = false;\n      }\n\n      this.showMenuPanel(menus[useMenu], event);\n\n      try {\n        // if its a radio station, then change the attributes to match a song\n        const nowPlayingItem = JSON.parse(JSON.stringify(this.mk.nowPlayingItem));\n        if (nowPlayingItem.type == \"radioStation\" && app.mk.nowPlayingItem.id != -1) {\n          nowPlayingItem.type = \"song\";\n          nowPlayingItem.attributes.playParams.catalogId = app.mk.nowPlayingItem.id;\n          nowPlayingItem.attributes.playParams.id = app.mk.nowPlayingItem.id;\n          nowPlayingItem.id = app.mk.nowPlayingItem.id;\n        }\n        let result = await this.inLibrary([nowPlayingItem]);\n        if (result[0].attributes.inLibrary) {\n          menus.normal.items.find((x) => x.id == \"addToLibrary\").hidden = true;\n          menus.normal.items.find((x) => x.id == \"removeFromLibrary\").hidden = false;\n        } else {\n          menus.normal.items.find((x) => x.id == \"addToLibrary\").disabled = false;\n        }\n      } catch (e) {\n        e = null;\n      }\n\n      try {\n        let rating = await app.getRating(app.mk.nowPlayingItem);\n        if (rating == 0) {\n          menus.normal.headerItems.find((x) => x.id == \"love\").disabled = false;\n          menus.normal.headerItems.find((x) => x.id == \"dislike\").disabled = false;\n        } else if (rating == 1) {\n          menus.normal.headerItems.find((x) => x.id == \"unlove\").hidden = false;\n          menus.normal.headerItems.find((x) => x.id == \"love\").hidden = true;\n        } else if (rating == -1) {\n          menus.normal.headerItems.find((x) => x.id == \"undo_dislike\").hidden = false;\n          menus.normal.headerItems.find((x) => x.id == \"dislike\").hidden = true;\n        }\n      } catch (err) {}\n    },\n    openSettingsPage(page) {\n      switch (page) {\n        case \"general\":\n          this.$store.state.pageState.settings.currentTabIndex = 0;\n          break;\n        case \"audio\":\n          this.$store.state.pageState.settings.currentTabIndex = 1;\n          break;\n        case \"audiolabs\":\n          this.$store.state.pageState.settings.currentTabIndex = 2;\n          break;\n        case \"styles\":\n          this.$store.state.pageState.settings.currentTabIndex = 3;\n          break;\n        case \"visual\":\n          this.$store.state.pageState.settings.currentTabIndex = 4;\n          break;\n        case \"github-plugins\":\n          this.$store.state.pageState.settings.currentTabIndex = 5;\n          break;\n        case \"lyrics\":\n          this.$store.state.pageState.settings.currentTabIndex = 6;\n          break;\n        case \"connectivity\":\n          this.$store.state.pageState.settings.currentTabIndex = 7;\n          break;\n        case \"advanced\":\n          this.$store.state.pageState.settings.currentTabIndex = 8;\n          break;\n        case \"keybindings\":\n          this.$store.state.pageState.settings.currentTabIndex = 9;\n          break;\n        case \"github-themes\":\n          this.$store.state.pageState.settings.currentTabIndex = 10;\n          break;\n      }\n      app.modals.settings = true;\n    },\n    fullscreen(flag, mv = false) {\n      this.fullscreenState = flag;\n      if (flag) {\n        ipcRenderer.send(\"setFullScreen\", true);\n        if (!mv) {\n          app.appMode = \"fullscreen\";\n        } else {\n          app.mvViewMode = \"full\";\n        }\n\n        document.addEventListener(\"keydown\", (event) => {\n          if (event.key === \"Escape\" && app.appMode === \"fullscreen\") {\n            this.fullscreen(false);\n          }\n        });\n      } else {\n        ipcRenderer.send(\"setFullScreen\", false);\n        app.appMode = \"player\";\n      }\n    },\n    pip() {\n      // document.querySelector(\"video#apple-music-video-player\").requestPictureInPicture();\n      // // .then(pictureInPictureWindow => {\n      // //     pictureInPictureWindow.addEventListener(\"resize\", () => {\n      // //         console.log(\"[PIP] Resized\")\n      // //     }, false);\n      // //   })\n      this.mvViewMode = this.mvViewMode == \"mini\" ? \"full\" : \"mini\";\n    },\n    miniPlayer(flag) {\n      if (flag) {\n        this.tmpWidth = window.innerWidth;\n        this.tmpHeight = window.innerHeight;\n        this.tmpX = window.screenX;\n        this.tmpY = window.screenY;\n        ipcRenderer.send(\"unmaximize\");\n        ipcRenderer.send(\"windowmin\", 250, 250);\n        if (this.miniTmpX !== \"\" && this.miniTmpY !== \"\") ipcRenderer.send(\"windowmove\", this.miniTmpX, this.miniTmpY);\n        ipcRenderer.send(\"windowresize\", 300, 300, false);\n        app.appMode = \"mini\";\n      } else {\n        this.miniTmpX = window.screenX;\n        this.miniTmpY = window.screenY;\n        ipcRenderer.send(\"windowmin\", 844, 410);\n        ipcRenderer.send(\"windowresize\", this.tmpWidth, this.tmpHeight, false);\n        ipcRenderer.send(\"windowmove\", this.tmpX, this.tmpY);\n        ipcRenderer.send(\"windowontop\", false);\n        //this.cfg.visual.miniplayer_top_toggle = true;\n        app.appMode = \"player\";\n      }\n    },\n    pinMiniPlayer(status = false) {\n      if (!status) {\n        if (!this.cfg.visual.miniplayer_top_toggle) {\n          ipcRenderer.send(\"windowontop\", true);\n          this.cfg.visual.miniplayer_top_toggle = true;\n        } else {\n          ipcRenderer.send(\"windowontop\", false);\n          this.cfg.visual.miniplayer_top_toggle = false;\n        }\n      } else {\n        ipcRenderer.send(\"windowontop\", this.cfg.visual.miniplayer_top_toggle ?? false);\n      }\n    },\n    formatTimezoneOffset: (e = new Date()) => {\n      let leadingZeros = (e, s = 2) => {\n        let n = \"\" + e;\n        for (; n.length < s; ) n = \"0\" + n;\n        return n;\n      };\n\n      const s = e.getTimezoneOffset(),\n        n = Math.floor(Math.abs(s) / 60),\n        d = Math.round(Math.abs(s) % 60);\n      let h = \"+\";\n      return 0 !== s && (h = s > 0 ? \"-\" : \"+\"), `${h}${leadingZeros(n, 2)}:${leadingZeros(d, 2)}`;\n    },\n    toggleHideUserInfo() {\n      if (this.chrome.hideUserInfo) {\n        this.cfg.visual.showuserinfo = true;\n        this.chrome.hideUserInfo = false;\n      } else {\n        this.cfg.visual.showuserinfo = false;\n        this.chrome.hideUserInfo = true;\n      }\n    },\n    isElementOverflowing(selector) {\n      try {\n        let element = document.querySelector(selector);\n        var overflowX = element.offsetWidth < element.scrollWidth,\n          overflowY = element.offsetHeight < element.scrollHeight;\n        element.setAttribute(\"data-value\", \"\\xa0\\xa0\\xa0\\xa0\" + element.textContent);\n\n        return overflowX || overflowY;\n      } catch (e) {\n        return false;\n      }\n    },\n    async showWebRemoteQR() {\n      //this.webremoteqr = await ipcRenderer.invoke('setRemoteQR','')\n      this.webremoteurl = await ipcRenderer.invoke(\"showQR\", \"\");\n      //this.modals.qrcode = true;\n    },\n    checkMarquee() {\n      if (isElementOverflowing(\"#app-main > div.app-chrome > div.app-chrome--center > div > div > div.playback-info > div.song-artist\") == true) {\n        document.getElementsByClassName(\"song-artist\")[0].classList.add(\"marquee\");\n        document.getElementsByClassName(\"song-artist\")[1].classList.add(\"marquee-after\");\n      }\n      if (isElementOverflowing(\"#app-main > div.app-chrome > div.app-chrome--center > div > div > div.playback-info > div.song-name\") == true) {\n        document.getElementsByClassName(\"song-name\")[0].classList.add(\"marquee\");\n        document.getElementsByClassName(\"song-name\")[1].classList.add(\"marquee-after\");\n      }\n    },\n    closeWindow() {\n      ipcRenderer.send(\"close\");\n    },\n    darwinShare(url) {\n      ipcRenderer.send(\"share-menu\", url);\n    },\n    arrayToChunk(arr, chunkSize) {\n      let R = [];\n      for (let i = 0, len = arr.length; i < len; i += chunkSize) {\n        R.push(arr.slice(i, i + chunkSize));\n      }\n      return R;\n    },\n    SpacePause() {\n      const elems = document.querySelectorAll(\"input\");\n      for (let elem of elems) {\n        if (elem === document.activeElement) {\n          return;\n        }\n      }\n      if (!this.isDev) {\n        // disable in dev mode to keep my sanity\n        MusicKitInterop.playPause();\n      }\n    },\n    async MKJSLang() {\n      let u = this.cfg.general.language;\n      // use MusicKit.getInstance or crash\n      try {\n        let item = await MusicKit.getInstance().api.v3.music(`v1/storefronts/${app.mk.storefrontId}`);\n        let langcodes = item.data.data[0].attributes.supportedLanguageTags;\n        if (langcodes)\n          langcodes = langcodes.map(function (u) {\n            return u.replace(/-Han[s|t]/i, \"\").toLowerCase();\n          });\n        console.log(langcodes);\n        let sellang = \"\";\n        if (u && langcodes.includes(u.toLowerCase().replace(\"_\", \"-\"))) {\n          sellang = u.toLowerCase().replace(\"_\", \"-\");\n        } else if (u && u.includes(\"_\") && langcodes.includes(u.toLowerCase().replace(\"_\", \"-\").split(\"-\")[0])) {\n          sellang = u.toLowerCase().replace(\"_\", \"-\").split(\"-\")[0];\n        }\n        if (sellang == \"\") sellang = item.data.data[0].attributes.defaultLanguageTag.toLowerCase();\n\n        // Fix weird locales:\n        if (sellang == \"iw\") sellang = \"iw-il\";\n        sellang = sellang.replace(/-Han[s|t]/i, \"\").toLowerCase();\n\n        console.log(sellang);\n        return await sellang;\n      } catch (err) {\n        console.log(\"locale err\", err);\n        let langcodes = [\n          \"af\",\n          \"sq\",\n          \"ar\",\n          \"eu\",\n          \"bg\",\n          \"be\",\n          \"ca\",\n          \"zh\",\n          \"zh-tw\",\n          \"zh-cn\",\n          \"zh-hk\",\n          \"zh-sg\",\n          \"hr\",\n          \"cs\",\n          \"da\",\n          \"nl\",\n          \"nl-be\",\n          \"en\",\n          \"en-us\",\n          \"en-eg\",\n          \"en-au\",\n          \"en-gb\",\n          \"en-ca\",\n          \"en-nz\",\n          \"en-ie\",\n          \"en-za\",\n          \"en-jm\",\n          \"en-bz\",\n          \"en-tt\",\n          \"en-001\",\n          \"et\",\n          \"fo\",\n          \"fa\",\n          \"fi\",\n          \"fr\",\n          \"fr-ca\",\n          \"gd\",\n          \"de\",\n          \"de-ch\",\n          \"el\",\n          \"he\",\n          \"hi\",\n          \"hu\",\n          \"is\",\n          \"id\",\n          \"it\",\n          \"ja\",\n          \"ko\",\n          \"lv\",\n          \"lt\",\n          \"mk\",\n          \"mt\",\n          \"no\",\n          \"nb\",\n          \"nn\",\n          \"pl\",\n          \"pt-br\",\n          \"pt\",\n          \"rm\",\n          \"ro\",\n          \"ru\",\n          \"sr\",\n          \"sk\",\n          \"sl\",\n          \"es\",\n          \"es-mx\",\n          \"es-419\",\n          \"sv\",\n          \"th\",\n          \"ts\",\n          \"tn\",\n          \"tr\",\n          \"uk\",\n          \"ur\",\n          \"ve\",\n          \"vi\",\n          \"xh\",\n          \"yi\",\n          \"zu\",\n          \"ms\",\n          \"iw\",\n          \"lo\",\n          \"tl\",\n          \"kk\",\n          \"ta\",\n          \"te\",\n          \"bn\",\n          \"ga\",\n          \"ht\",\n          \"la\",\n          \"pa\",\n          \"sa\",\n        ];\n        let sellang = \"en\";\n        if (u && langcodes.includes(u.toLowerCase().replace(\"_\", \"-\"))) {\n          sellang = u.toLowerCase().replace(\"_\", \"-\");\n        } else if (u && u.includes(\"_\") && langcodes.includes(u.toLowerCase().replace(\"_\", \"-\").split(\"-\")[0])) {\n          sellang = u.toLowerCase().replace(\"_\", \"-\").split(\"-\")[0];\n        }\n        if (sellang.startsWith(\"en\") && this.mk.storefrontId != \"us\") sellang = \"en-gb\";\n        return await sellang;\n      }\n    },\n    skipToNextItem() {\n      if (this.mk.queue.nextPlayableItemIndex !== -1 && this.mk.queue.nextPlayableItemIndex != null) this.mk.changeToMediaAtIndex(this.mk.queue.nextPlayableItemIndex);\n    },\n    skipToPreviousItem() {\n      if (this.mk.queue.previousPlayableItemIndex !== -1 && this.mk.queue.previousPlayableItemIndex != null) this.mk.changeToMediaAtIndex(this.mk.queue.previousPlayableItemIndex);\n    },\n    mediaKeyFixes() {\n      MusicKitInterop.initMediaSession();\n      // navigator.mediaSession.setActionHandler(\"previoustrack\", function () {\n      //   app.skipToPreviousItem();\n      // });\n      // navigator.mediaSession.setActionHandler(\"nexttrack\", function () {\n      //   app.skipToNextItem();\n      // });\n    },\n    authCC() {\n      ipcRenderer.send(\"cc-auth\");\n    },\n    _playRadioStream(e) {\n      var xhr = new XMLHttpRequest();\n      xhr.onreadystatechange = process;\n      xhr.open(\"GET\", e, true);\n      xhr.send();\n      let self = this;\n\n      function process() {\n        if (xhr.readyState == 4) {\n          let sources = xhr.responseText.match(/^(?!#)(?!\\s).*$/gm).filter(function (element) {\n            return element;\n          });\n          // Load first source\n          let src = sources[0];\n          if (src.includes(\"http\")) {\n            app.mk._services.mediaItemPlayback._currentPlayer._playAssetURL(src, false);\n          } else {\n            if (Hls.isSupported()) {\n              let d = \"WIDEVINE_SOFTWARE\";\n              let h = {\n                initDataTypes: [\"cenc\", \"keyids\"],\n                distinctiveIdentifier: \"optional\",\n                persistentState: \"required\",\n              };\n              let p = {\n                platformInfo: { requiresCDMAttachOnStart: !0, maxSecurityLevel: d, keySystemConfig: h },\n                appData: { serviceName: \"Apple Music\" },\n              };\n              if (app.radiohls != null && app.radiohls.destroy != null) {\n                app.radiohls.destroy();\n                app.radiohls = null;\n                app.radiohls = new CiderHls();\n                app.radiohls.loadSource(e);\n                app.radiohls.attachMedia(app.mk._services.mediaItemPlayback._currentPlayer._targetElement);\n                app.mk._services.mediaItemPlayback._currentPlayer._targetElement.play();\n              } else {\n                app.radiohls = null;\n                app.radiohls = new CiderHls();\n                app.radiohls.loadSource(e);\n                app.radiohls.attachMedia(app.mk._services.mediaItemPlayback._currentPlayer._targetElement);\n                app.mk._services.mediaItemPlayback._currentPlayer._targetElement.play();\n              }\n            }\n          }\n        }\n      }\n    },\n    confirm(message, callback) {\n      bootbox.confirm(this.getBootboxParams(null, message, callback));\n    },\n    prompt(title, callback) {\n      bootbox.prompt(this.getBootboxParams(title, null, callback));\n    },\n    getBootboxParams(title, message, callback) {\n      return {\n        title: title,\n        message: message,\n        buttons: {\n          confirm: {\n            label: app.getLz(\"dialog.ok\"),\n          },\n          cancel: {\n            label: app.getLz(\"dialog.cancel\"),\n          },\n        },\n        callback: function (result) {\n          if (callback) callback(result);\n        },\n      };\n    },\n  },\n});\n\nexport { app };\n"
  },
  {
    "path": "src/renderer/main/vuex-store.js",
    "content": "const store = new Vuex.Store({\n  state: {\n    windowRelativeScale: 1,\n    library: {\n      // songs: ipcRenderer.sendSync(\"get-library-songs\"),\n      // albums: ipcRenderer.sendSync(\"get-library-albums\"),\n      // recentlyAdded: ipcRenderer.sendSync(\"get-library-recentlyAdded\"),\n      // playlists: ipcRenderer.sendSync(\"get-library-playlists\")\n    },\n    pageState: {\n      recentlyAdded: {\n        loaded: false,\n        nextUrl: null,\n        items: [],\n        size: \"normal\",\n      },\n      settings: {\n        currentTabIndex: 0,\n        fullscreen: false,\n      },\n      scrollPos: {\n        limit: 10,\n        pos: [],\n      },\n    },\n    artwork: {\n      playerLCD: \"\",\n    },\n  },\n  mutations: {\n    resetRecentlyAdded(state) {\n      state.pageState.recentlyAdded.loaded = false;\n      state.pageState.recentlyAdded.nextUrl = null;\n      state.pageState.recentlyAdded.items = [];\n    },\n    setLCDArtwork(state, artwork) {\n      state.artwork.playerLCD = artwork;\n    },\n    setPagePos(state, pageState = {}) {\n      let cached = state.pageState.scrollPos.pos.find((page) => {\n        return page.href === pageState.href;\n      });\n      if (cached) {\n        state.pageState.scrollPos.pos.find((page) => {\n          if (page.href === pageState.href) {\n            page.position = pageState.position;\n          }\n        });\n        return;\n      }\n      state.pageState.scrollPos.pos.push({\n        href: pageState.href,\n        position: pageState.position,\n      });\n      if (state.pageState.scrollPos.pos.length > state.pageState.scrollPos.limit) {\n        pages.value.shift();\n      }\n      return;\n    },\n  },\n});\n\nexport { store };\n"
  },
  {
    "path": "src/renderer/main/wsapi_interop.js",
    "content": "const wsapi = {\n  cache: { playParams: { id: 0 }, status: null, remainingTime: 0 },\n  playbackCache: { status: null, time: Date.now() },\n  async v3(encoded = \"\") {\n    let decoded = atob(encoded);\n    let json = JSON.parse(decoded);\n    console.log(json);\n    let response = await await MusicKit.getInstance().api.v3.music(json.route, json.body, json.options);\n    let ret = response.data;\n    return JSON.stringify(ret);\n  },\n  search(term, limit) {\n    MusicKit.getInstance()\n      .api.search(term, {\n        limit: limit,\n        types: \"songs,artists,albums,playlists\",\n      })\n      .then((results) => {\n        ipcRenderer.send(\"wsapi-returnSearch\", JSON.stringify(results));\n      });\n  },\n  searchLibrary(term, limit) {\n    MusicKit.getInstance()\n      .api.library.search(term, {\n        limit: limit,\n        types: \"library-songs,library-artists,library-albums,library-playlists\",\n      })\n      .then((results) => {\n        ipcRenderer.send(\"wsapi-returnSearchLibrary\", JSON.stringify(results));\n      });\n  },\n  getAttributes: function () {\n    const mk = MusicKit.getInstance();\n    const nowPlayingItem = mk.nowPlayingItem;\n    const isPlayingExport = mk.isPlaying;\n    const remainingTimeExport = mk.currentPlaybackTimeRemaining;\n    const attributes = nowPlayingItem != null ? nowPlayingItem.attributes : {};\n\n    attributes.status = isPlayingExport ? isPlayingExport : false;\n    attributes.name = attributes.name ? attributes.name : \"No Title Found\";\n    attributes.artwork = attributes.artwork ? attributes.artwork : { url: \"\" };\n    attributes.artwork.url = attributes.artwork.url ? attributes.artwork.url : \"\";\n    attributes.playParams = attributes.playParams ? attributes.playParams : { id: \"no-id-found\" };\n    attributes.playParams.id = attributes.playParams.id ? attributes.playParams.id : \"no-id-found\";\n    attributes.albumName = attributes.albumName ? attributes.albumName : \"\";\n    attributes.artistName = attributes.artistName ? attributes.artistName : \"\";\n    attributes.genreNames = attributes.genreNames ? attributes.genreNames : [];\n    attributes.remainingTime = remainingTimeExport ? remainingTimeExport * 1000 : 0;\n    attributes.durationInMillis = attributes.durationInMillis ? attributes.durationInMillis : 0;\n    attributes.startTime = Date.now();\n    attributes.endTime = attributes.endTime ? attributes.endTime : Date.now();\n    attributes.volume = mk.volume;\n    attributes.shuffleMode = mk.shuffleMode;\n    attributes.repeatMode = mk.repeatMode;\n    attributes.autoplayEnabled = mk.autoplayEnabled;\n    return attributes;\n  },\n  moveQueueItem(oldPosition, newPosition) {\n    MusicKit.getInstance().queue._queueItems.splice(newPosition, 0, MusicKit.getInstance().queue._queueItems.splice(oldPosition, 1)[0]);\n    MusicKit.getInstance().queue._reindex();\n  },\n  setAutoplay(value) {\n    MusicKit.getInstance().autoplayEnabled = value;\n  },\n  returnDynamic(data, type) {\n    ipcRenderer.send(\"wsapi-returnDynamic\", JSON.stringify(data), type);\n  },\n  musickitApi(method, id, params, library = false) {\n    if (library) {\n      MusicKit.getInstance()\n        .api.library[method](id, params)\n        .then((results) => {\n          ipcRenderer.send(\"wsapi-returnMusicKitApi\", JSON.stringify(results), method);\n        });\n    } else {\n      MusicKit.getInstance()\n        .api[method](id, params)\n        .then((results) => {\n          ipcRenderer.send(\"wsapi-returnMusicKitApi\", JSON.stringify(results), method);\n        });\n    }\n  },\n  getPlaybackState() {\n    ipcRenderer.send(\"wsapi-updatePlaybackState\", MusicKitInterop.getAttributes());\n  },\n  getLyrics() {\n    ipcRenderer.send(\"wsapi-returnLyrics\", JSON.stringify(app.lyrics));\n  },\n  getQueue() {\n    ipcRenderer.send(\"wsapi-returnQueue\", JSON.stringify(MusicKit.getInstance().queue));\n  },\n  playNext(type, id) {\n    var request = {};\n    request[type] = id;\n    MusicKit.getInstance().playNext(request);\n  },\n  playLater(type, id) {\n    var request = {};\n    request[type] = id;\n    MusicKit.getInstance().playLater(request);\n  },\n  love() {},\n  playTrackById(id, kind = \"song\") {\n    MusicKit.getInstance()\n      .setQueue({ [kind]: id, parameters: { l: app.mklang } })\n      .then(function (queue) {\n        MusicKit.getInstance().play();\n      });\n  },\n  quickPlay(term) {\n    // Quick play by song name\n    MusicKit.getInstance()\n      .api.search(term, { limit: 2, types: \"songs\" })\n      .then(function (data) {\n        MusicKit.getInstance()\n          .setQueue({\n            song: data[\"songs\"][0][\"id\"],\n            parameters: { l: app.mklang },\n          })\n          .then(function (queue) {\n            MusicKit.getInstance().play();\n          });\n      });\n  },\n  toggleShuffle() {\n    MusicKit.getInstance().shuffleMode = MusicKit.getInstance().shuffleMode === 0 ? 1 : 0;\n  },\n  togglePlayPause() {\n    app.mk.isPlaying ? app.mk.pause() : app.mk.play();\n  },\n  toggleRepeat() {\n    app.repeatIncrement();\n  },\n  getmaxVolume() {\n    ipcRenderer.send(\"wsapi-returnvolumeMax\", JSON.stringify(app.cfg.audio.maxVolume));\n  },\n  getLibraryStatus(kind, id) {\n    if (kind === undefined || id === \"no-id-found\") return;\n\n    let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n    app.mk.api.v3\n      .music(`/v1/catalog/${app.mk.storefrontId}/?ids[${truekind}]=${id}`, {\n        relate: \"library\",\n        fields: \"inLibrary\",\n      })\n      .then((data) => {\n        const res = data.data.data[0];\n        const inLibrary = res && res.attributes && res.attributes.inLibrary;\n\n        app.getRating({ type: truekind, id: id }).then((rating) => {\n          ipcRenderer.send(\"wsapi-libraryStatus\", inLibrary, rating);\n        });\n      });\n  },\n  rate(kind, id, rating) {\n    if (kind === undefined || id === \"no-id-found\") return;\n\n    let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n\n    if (rating === 0) {\n      app.mk.api.v3\n        .music(\n          `/v1/me/ratings/${truekind}/${id}`,\n          {},\n          {\n            fetchOptions: {\n              method: \"DELETE\",\n            },\n          },\n        )\n        .then(function () {\n          ipcRenderer.send(\"wsapi-rate\", kind, id, rating);\n        });\n    } else if (rating === undefined) {\n      app.getRating({ type: truekind, id: id }).then((rating) => {\n        ipcRenderer.send(\"wsapi-rate\", kind, id, rating);\n      });\n    } else {\n      app.mk.api.v3\n        .music(\n          `/v1/me/ratings/${truekind}/${id}`,\n          {},\n          {\n            fetchOptions: {\n              method: \"PUT\",\n              body: JSON.stringify({\n                type: \"rating\",\n                attributes: {\n                  value: rating,\n                },\n              }),\n            },\n          },\n        )\n        .then(function () {\n          ipcRenderer.send(\"wsapi-rate\", kind, id, rating);\n        });\n    }\n  },\n  changeLibrary(kind, id, shouldAdd) {\n    if (shouldAdd) {\n      app.addToLibrary(id);\n      ipcRenderer.send(\"wsapi-change-library\", kind, id, shouldAdd);\n    } else {\n      let truekind = !kind.endsWith(\"s\") ? kind + \"s\" : kind;\n\n      app.mk.api.v3\n        .music(`/v1/catalog/${app.mk.storefrontId}/?ids[${truekind}]=${id}`, {\n          relate: \"library\",\n          fields: \"inLibrary\",\n        })\n        .then((res) => {\n          res = res.data.data[0];\n          if (res && res.relationships && res.relationships.library && res.relationships.library.data) {\n            const item = res.relationships.library.data[0];\n\n            if (item) {\n              app.removeFromLibrary(kind, item.id);\n            }\n\n            ipcRenderer.send(\"wsapi-change-library\", kind, id, shouldAdd);\n          }\n        });\n    }\n  },\n};\n\nexport { wsapi };\n"
  },
  {
    "path": "src/renderer/style.less",
    "content": "@import url(\"assets/fonts/Pretendard/pretendardvariable.css\");\n@import url(\"https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;700;900&display=swap\");\n@import url(\"https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap\");\n@import url(\"https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@100;300;400;500;700;900&display=swap\");\n@import url(\"https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@100;300;400;500;700;900&display=swap\");\n// @import url(\"lib/quasar/quasar.min.css\");\n@import url(\"less/appvars.less\");\n@import url(\"less/bootstrap-vue.min.less\");\n@import url(\"less/ameframework.less\");\n@import url(\"less/codicon.css\");\n@import url(\"less/bootstrap.less\");\n@import url(\"less/notyf.less\");\n@import url(\"less/elements.less\");\n@import url(\"less/helpers.less\");\n@import url(\"less/pages.less\");\n\n:root {\n  --windowRelativeScale: 1;\n  --appleEase: cubic-bezier(0.42, 0, 0.58, 1);\n  --borderColor: rgb(200 200 200 / 16%);\n  --mediaItemShadow: inset 0px 0px 0px 1px rgb(200 200 200 / 16%);\n  --mediaItemShadow-Shadow: 0 8px 40px rgb(0 0 0 / 0.55);\n  --mediaItemShadow-ShadowSubtle: 0 4px 14px rgb(0 0 0 / 10%);\n  --ciderShadow-Generic: var(--mediaItemShadow), 0 8px 40px rgb(0 0 0 / 0.55);\n  --mediaItemRadius: 8px;\n  --mediaItemRadiusSmall: 6px;\n  --mediaItemRadiusMedium: 8px;\n  --mediaItemRadiusRound: 100%;\n  --panelRadius: 10px;\n  --contentInnerPadding: 16px;\n  --navbarHeight1: 48px;\n  --navbarHeight2: 0px;\n  --navbarHeight: calc(var(--navbarHeight1) + var(--navbarHeight2));\n  --selected: rgb(130 130 130 / 30%);\n  --selected-click: rgb(80 80 80 / 30%);\n  --hover: rgb(200 200 200 / 10%);\n  // --keyColor: #fa586a;\n  --keyColorDefault: @keyColor;\n  --keyColor: @keyColor;\n  --keyColor-rgb: 250, 88, 106;\n  --keyColor-rollover: #ff8a9c;\n  --keyColor-rollover-rgb: 255, 138, 156;\n  --keyColor-pressed: #ff7183;\n  --keyColor-pressed-rgb: 255, 113, 131;\n  --keyColor-deepPressed: #ff8a9c;\n  --keyColor-deepPressed-rgb: 255, 138, 156;\n  --keyColor-disabled: rgba(250, 88, 106, 0.35);\n  --keyColor-primary: #ff2b52a6;\n  --navigationBarHeight: 0px;\n  --modalBackground: #262626;\n  --songProgressColor: var(--keyColor);\n  --songProgressBackground: #333;\n  --textColor: #eee;\n  --replayGradient: linear-gradient(45deg, hsl(248deg 58% 29%), hsl(13deg 41% 42%));\n  --glassFilter: blur(16px) saturate(180%);\n  --glassFilterHeavy: blur(64px) saturate(280%);\n  --sidebarWidth: 260px;\n}\n\n*:focus-visible {\n  outline: 2px solid var(--keyColor);\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  overflow: hidden;\n  width: 100%;\n  height: 100%;\n  box-sizing: border-box;\n  background-size: cover;\n  background-position: center;\n  background: #0000;\n  font-family:\n    \"Pretendard Variable\",\n    \"Noto Sans JP\",\n    \"Noto Sans KR\",\n    \"Noto Sans TC\",\n    \"Noto Sans SC\",\n    -apple-system,\n    BlinkMacSystemFont,\n    \"Segoe UI\",\n    Roboto,\n    Oxygen,\n    Ubuntu,\n    Cantarell,\n    \"Open Sans\",\n    \"Helvetica Neue\",\n    sans-serif;\n  transition: opacity 0.1s var(--appleEase);\n}\n\na:-webkit-any-link {\n  color: var(--keyColor);\n}\n\nhr {\n  appearance: none;\n  border: none;\n  height: 1px;\n  background-color: rgb(255 255 255 / 20%);\n}\n\nbody[loading] {\n  .app-navigation {\n    pointer-events: none;\n  }\n}\n\nbody.stopanimation * {\n  animation: unset !important;\n\n  .loadbar-sound {\n    display: none;\n  }\n}\n\nbody.notransparency::before {\n  content: \"\";\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  opacity: 0.5;\n  display: none;\n  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAAUVBMVEWFhYWDg4N3d3dtbW17e3t1dXWBgYGHh4d5eXlzc3OLi4ubm5uVlZWPj4+NjY19fX2JiYl/f39ra2uRkZGZmZlpaWmXl5dvb29xcXGTk5NnZ2c8TV1mAAAAG3RSTlNAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAvEOwtAAAFVklEQVR4XpWWB67c2BUFb3g557T/hRo9/WUMZHlgr4Bg8Z4qQgQJlHI4A8SzFVrapvmTF9O7dmYRFZ60YiBhJRCgh1FYhiLAmdvX0CzTOpNE77ME0Zty/nWWzchDtiqrmQDeuv3powQ5ta2eN0FY0InkqDD73lT9c9lEzwUNqgFHs9VQce3TVClFCQrSTfOiYkVJQBmpbq2L6iZavPnAPcoU0dSw0SUTqz/GtrGuXfbyyBniKykOWQWGqwwMA7QiYAxi+IlPdqo+hYHnUt5ZPfnsHJyNiDtnpJyayNBkF6cWoYGAMY92U2hXHF/C1M8uP/ZtYdiuj26UdAdQQSXQErwSOMzt/XWRWAz5GuSBIkwG1H3FabJ2OsUOUhGC6tK4EMtJO0ttC6IBD3kM0ve0tJwMdSfjZo+EEISaeTr9P3wYrGjXqyC1krcKdhMpxEnt5JetoulscpyzhXN5FRpuPHvbeQaKxFAEB6EN+cYN6xD7RYGpXpNndMmZgM5Dcs3YSNFDHUo2LGfZuukSWyUYirJAdYbF3MfqEKmjM+I2EfhA94iG3L7uKrR+GdWD73ydlIB+6hgref1QTlmgmbM3/LeX5GI1Ux1RWpgxpLuZ2+I+IjzZ8wqE4nilvQdkUdfhzI5QDWy+kw5Wgg2pGpeEVeCCA7b85BO3F9DzxB3cdqvBzWcmzbyMiqhzuYqtHRVG2y4x+KOlnyqla8AoWWpuBoYRxzXrfKuILl6SfiWCbjxoZJUaCBj1CjH7GIaDbc9kqBY3W/Rgjda1iqQcOJu2WW+76pZC9QG7M00dffe9hNnseupFL53r8F7YHSwJWUKP2q+k7RdsxyOB11n0xtOvnW4irMMFNV4H0uqwS5ExsmP9AxbDTc9JwgneAT5vTiUSm1E7BSflSt3bfa1tv8Di3R8n3Af7MNWzs49hmauE2wP+ttrq+AsWpFG2awvsuOqbipWHgtuvuaAE+A1Z/7gC9hesnr+7wqCwG8c5yAg3AL1fm8T9AZtp/bbJGwl1pNrE7RuOX7PeMRUERVaPpEs+yqeoSmuOlokqw49pgomjLeh7icHNlG19yjs6XXOMedYm5xH2YxpV2tc0Ro2jJfxC50ApuxGob7lMsxfTbeUv07TyYxpeLucEH1gNd4IKH2LAg5TdVhlCafZvpskfncCfx8pOhJzd76bJWeYFnFciwcYfubRc12Ip/ppIhA1/mSZ/RxjFDrJC5xifFjJpY2Xl5zXdguFqYyTR1zSp1Y9p+tktDYYSNflcxI0iyO4TPBdlRcpeqjK/piF5bklq77VSEaA+z8qmJTFzIWiitbnzR794USKBUaT0NTEsVjZqLaFVqJoPN9ODG70IPbfBHKK+/q/AWR0tJzYHRULOa4MP+W/HfGadZUbfw177G7j/OGbIs8TahLyynl4X4RinF793Oz+BU0saXtUHrVBFT/DnA3ctNPoGbs4hRIjTok8i+algT1lTHi4SxFvONKNrgQFAq2/gFnWMXgwffgYMJpiKYkmW3tTg3ZQ9Jq+f8XN+A5eeUKHWvJWJ2sgJ1Sop+wwhqFVijqWaJhwtD8MNlSBeWNNWTa5Z5kPZw5+LbVT99wqTdx29lMUH4OIG/D86ruKEauBjvH5xy6um/Sfj7ei6UUVk4AIl3MyD4MSSTOFgSwsH/QJWaQ5as7ZcmgBZkzjjU1UrQ74ci1gWBCSGHtuV1H2mhSnO3Wp/3fEV5a+4wz//6qy8JxjZsmxxy5+4w9CDNJY09T072iKG0EnOS0arEYgXqYnXcYHwjTtUNAcMelOd4xpkoqiTYICWFq0JSiPfPDQdnt+4/wuqcXY47QILbgAAAABJRU5ErkJggg==);\n}\n\n*,\n*:before,\n*:after {\n  box-sizing: inherit;\n}\n\n/* Modern style overlay scrollbars */\n::-webkit-scrollbar {\n  width: 16px;\n  height: 24px;\n}\n\n::-webkit-scrollbar-button {\n  display: none;\n}\n\n::-webkit-scrollbar-track-piece {\n  background: transparent;\n}\n\n::-webkit-scrollbar-thumb {\n  background: transparent;\n  border: 6px solid transparent;\n  box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n  border-radius: 16px;\n  min-height: 64px;\n  transition: border 1s;\n}\n\n::-webkit-scrollbar-thumb:hover {\n  border: 5px solid transparent;\n  box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 80%);\n}\n\n[disabled] {\n  pointer-events: none;\n  opacity: 0.5;\n}\n\n#app {\n  @panelBrightness: 0%;\n  @panelTransparency: 50%;\n  @msColor1: #202020;\n  @msColor2: #272727;\n  @msColor3: #2b2b2b;\n  --panelColor1: darken(mix(@msColor1, transparent, @panelTransparency), @panelBrightness);\n  --panelColor2: darken(mix(@msColor2, transparent, @panelTransparency), @panelBrightness);\n  --color1: var(--panelColor2);\n  --color2: var(--panelColor1);\n  --color3: rgb(0 0 0 / 20%);\n  --bgColor: transparent;\n  --bgWidth: 0px;\n  --bgHeight: 0px;\n  --chromeHeight1: 55px;\n  --chromeHeight2: 0px;\n  --chromeHeight: calc(var(--chromeHeight1) + var(--chromeHeight2));\n  width: 100%;\n  height: 100%;\n  background: transparent;\n  color: var(--textColor);\n  user-select: none;\n  margin: 0 auto;\n  position: relative;\n  overflow: hidden;\n  background-size: 400% 400%;\n\n  &.simplebg {\n    background: #0e0e0e;\n  }\n}\n\n.bgGradientMaterial-base {\n  position: relative;\n}\n\n.bgGradientMaterial-base::before {\n  position: absolute;\n  top: -50%;\n  left: -50%;\n  width: 200%;\n  height: 250%;\n  background-image: var(--bgColor);\n  content: \"\";\n  z-index: -1;\n  transform: rotateZ(0deg);\n  transform-origin: center;\n  animation: bgRotate 10s linear infinite;\n  filter: brightness(100%) saturate(200%) contrast(1.5);\n}\n\n@keyframes bgRotate {\n  0% {\n    transform: rotateZ(0deg);\n  }\n\n  100% {\n    transform: rotateZ(360deg);\n  }\n}\n\n[hidden] {\n  display: none !important;\n}\n\ninput[type=\"text\"],\ninput[type=\"number\"] {\n  background: #1c1c1c;\n  border-radius: 3px;\n  border: 1px solid rgb(200 200 200 / 25%);\n  color: #eee;\n  padding: 6px;\n  font-size: 1em;\n  font-family: inherit;\n}\n\n.bg-artwork--placeholder {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: #222;\n  z-index: -1;\n  background-size: cover;\n  background-position: center;\n  opacity: 0.7;\n}\n\na.dropdown-item {\n  color: var(--textColor);\n\n  &:hover {\n    background-color: var(--selected);\n    color: var(--textColor);\n  }\n\n  &:active {\n    background-color: var(--selected-click);\n  }\n}\n\n.bg-artwork {\n  position: absolute;\n  width: 200%;\n  background: var(--artwork);\n  filter: brightness(200%) blur(180px) saturate(280%) contrast(2);\n  opacity: 1;\n  transition: opacity 0.25s var(--appleEase);\n  pointer-events: none;\n  transform: translateZ(0px);\n  animation: rotateBg 35s linear infinite;\n  backface-visibility: hidden;\n}\n\n@keyframes rotateBg {\n  0% {\n    transform: rotate(0deg);\n  }\n\n  100% {\n    transform: rotate(360deg);\n  }\n}\n\n.bg-artwork-container {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  pointer-events: none;\n  transform: translateZ(0px);\n  z-index: -1;\n\n  .bg-artwork.a {\n    top: 0;\n    left: 0;\n    //mix-blend-mode: luminosity;\n  }\n\n  .bg-artwork.b {\n    bottom: 0;\n    right: 0;\n    animation-direction: reverse;\n    animation-delay: 10s;\n  }\n\n  &.noanimation {\n    .bg-artwork {\n      animation: none;\n    }\n  }\n}\n\n.artworkMaterial {\n  position: relative;\n  height: 100%;\n  width: 100%;\n  overflow: hidden;\n  pointer-events: none;\n\n  img {\n    position: absolute;\n    width: 200%;\n    opacity: 0.5;\n    filter: brightness(200%) blur(180px) saturate(280%) contrast(2);\n  }\n\n  img:first-child {\n    top: 0;\n    left: 0;\n  }\n\n  img:last-child {\n    bottom: 0;\n    right: 0;\n    transform: rotate(180deg);\n  }\n}\n\n[artwork-hidden] {\n  transition: opacity 0.25s var(--appleEase);\n  opacity: 0;\n}\n\ninput[type=\"range\"].web-slider {\n  -webkit-appearance: none;\n  height: 4px;\n  background: rgba(255, 255, 255, 0.6);\n  border-radius: 5px;\n  background-size: 70% 100%;\n  background-repeat: no-repeat;\n}\n\ninput[type=\"range\"].web-slider::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  height: 20px;\n  width: 20px;\n  border-radius: 50%;\n  background: rgb(255 255 255);\n  cursor: ew-resize;\n  box-shadow: 0 0 2px 0 #555;\n}\n\ninput[type=\"range\"].web-slider::-webkit-slider-runnable-track {\n  -webkit-appearance: none;\n  box-shadow: none;\n  border: none;\n  background: transparent;\n}\n\n.nopadding {\n  padding: 0px;\n}\n\n#app-main {\n  display: flex;\n  width: 100%;\n  height: 100%;\n  flex-direction: column;\n  opacity: 1;\n  overflow: hidden;\n  background-color: rgba(20 20 20 / 0.7);\n}\n\n#app-sidebar {\n  height: 100%;\n  width: var(--sidebarWidth);\n  display: flex;\n  flex-direction: column;\n  flex: 0 0 auto;\n  position: relative;\n  background: linear-gradient(180deg, var(--baseColorMix) calc(var(--chromeHeight1) + 1px), var(--sidebarColorMix) calc(var(--chromeHeight1) + 1px));\n  max-width: var(--sidebarWidth);\n  padding-top: var(--chromeHeight1);\n}\n\n#app-navbar {\n  height: 40px;\n  width: 100%;\n  background: rgb(30 30 30 / 85%);\n  position: sticky;\n  top: 0px;\n  left: 0;\n  z-index: 2;\n  backdrop-filter: blur(16px) saturate(180%);\n}\n\n#app-content {\n  --navigationBarHeight: var(--chromeHeight1);\n  background-color: var(--baseColorMix);\n  height: 100%;\n  width: 100%;\n  overflow-y: scroll;\n  overflow-y: overlay;\n  overflow-x: hidden;\n  border-radius: 0;\n  border-left: 1px solid var(--baseColorMix);\n  // border-top: 1px solid rgb(0 0 0 / 25%);\n  position: relative;\n\n  &::-webkit-scrollbar-track-piece {\n    margin-top: var(--chromeHeight1);\n  }\n}\n\n.app-drawer {\n  width: 300px;\n  flex: 0 0 auto;\n  position: absolute;\n  right: 16px;\n  background: var(--color2);\n  border-radius: 12px;\n  z-index: 10;\n  backdrop-filter: blur(40px) saturate(180%);\n  box-shadow: var(--ciderShadow-Generic);\n  overflow: hidden;\n  height: calc(calc(100% - 6%) - var(--chromeHeight1));\n  top: calc(var(--chromeHeight1) + 3%);\n\n  .bgArtworkMaterial {\n    display: none;\n    position: absolute;\n    width: 100%;\n    height: 100%;\n\n    .bg-artwork-container .bg-artwork {\n      filter: brightness(80%) blur(180px) saturate(180%) contrast(1);\n    }\n  }\n\n  transition: 0.3s var(--appleEase);\n}\n\n.search-input-container {\n  position: relative;\n}\n\n.search-input {\n  width: 100%;\n  padding: 6px;\n  border-radius: 6px;\n  border: 1px solid rgba(100, 100, 100, 0.35);\n  border-top: 1px solid rgba(100, 100, 100, 0.5);\n  border-bottom: 1px solid rgb(60 60 60 / 62%);\n  font-family: inherit;\n  font-size: 14px;\n  background: #1e1e1e99;\n  color: #c8c8c8;\n  font-weight: 500;\n  padding-left: 32px;\n  position: relative;\n}\n\n.search-input:focus {\n  outline: none;\n  border-bottom: 1px solid var(--keyColor);\n}\n\n.search-input--icon {\n  content: \"\";\n  width: 100%;\n  height: 100%;\n  display: block;\n  position: absolute;\n  top: 0px;\n  left: 0px;\n  background-image: url(\"assets/search.svg\");\n  background-position: 10px;\n  background-repeat: no-repeat;\n  background-size: 12px;\n  pointer-events: none;\n  opacity: 0.55;\n}\n\n.app-sidebar-header {\n  font-size: 14px;\n  padding: 11px;\n  font-weight: 600;\n}\n\n.app-sidebar-header-text {\n  font-size: 11px;\n  padding: 6px 6px;\n  font-weight: 600;\n  opacity: 0.5;\n  background-image: url(\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDYiIGhlaWdodD0iNDYiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZmZmZiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2Utd2lkdGg9IjIiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cGF0aCBkPSJtNiA5IDYgNiA2LTYiPjwvcGF0aD4KPC9zdmc+\");\n  background-size: 16px;\n  background-repeat: no-repeat;\n  background-position: 98%;\n  border-radius: 3px;\n\n  &.collapsed {\n    background-image: url(\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDYiIGhlaWdodD0iNDYiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZmZmZiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2Utd2lkdGg9IjIiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cGF0aCBkPSJtOSAxOCA2LTYtNi02Ij48L3BhdGg+Cjwvc3ZnPg==\");\n  }\n\n  &:hover {\n    background-color: var(--selected);\n  }\n\n  &:active {\n    background-color: var(--selected-click);\n  }\n}\n\n.app-sidebar-footer {\n  border-top: 1px solid rgba(200, 200, 200, 0.15);\n  padding: 11px;\n\n  .app-playback-controls {\n    margin: 0 auto;\n\n    .control-buttons {\n      display: flex;\n      justify-content: center;\n      align-content: center;\n    }\n\n    .volume {\n      display: flex;\n    }\n  }\n\n  &.collapseTab {\n    display: flex;\n    padding: 6px;\n    border: 0;\n\n    > button {\n      appearance: none;\n      width: 100%;\n      position: relative;\n      padding-left: 40px;\n      text-align: left;\n      font-family: inherit;\n\n      &:hover {\n        background-color: var(--selected);\n      }\n\n      &:active {\n        background-color: var(--selected-click);\n      }\n\n      &:after {\n        content: \"\";\n        display: flex;\n        justify-content: center;\n        align-items: center;\n        width: 46px;\n        height: 100%;\n        position: absolute;\n        top: 0;\n        left: 0;\n        font-weight: bold;\n        font-size: 1em;\n        font-family: \"codicon\";\n      }\n    }\n  }\n}\n\n.app-sidebar-button {\n  width: 100%;\n  padding: 0px;\n  font-family: inherit;\n  display: flex;\n  border-radius: 6px;\n  border: 1px solid rgb(200 200 200 / 5%);\n  background: rgb(100 100 100 / 25%);\n  color: #eee;\n  font-weight: 500;\n  align-items: center;\n\n  &.active {\n    background: rgb(200 200 200 / 15%);\n    animation: usermenuBtnClick 0.3s cubic-bezier(0.36, 0, 0.66, -0.56);\n  }\n}\n\n@keyframes usermenuBtnClick {\n  0% {\n    transform: translateY(0px);\n  }\n\n  50% {\n    transform: translateY(-6px);\n  }\n\n  100% {\n    transform: translateY(0px);\n  }\n}\n\n.app-sidebar-button > .sidebar-user-icon {\n  width: 32px;\n  height: 32px;\n  border-radius: 100%;\n  background-image: var(--artwork);\n  margin: 10px;\n  flex: 0 0 auto;\n  box-shadow: var(--mediaItemShadow);\n  background-size: contain;\n}\n\n.app-sidebar-button > .sidebar-user-text {\n  width: 100%;\n  display: flex;\n  font-size: 14px;\n  flex-direction: column;\n  text-align: center;\n  margin-right: 35px;\n}\n\n.app-sidebar-button > .sidebar-user-text .fullname {\n  text-align: left;\n}\n\n.app-sidebar-button > .sidebar-user-text .handle-text {\n  font-size: 12px;\n  opacity: 0.7;\n  text-align: left;\n}\n\n.app-sidebar-notification {\n  text-align: center;\n  font-size: 12px;\n  min-height: 36px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  border-top: 1px solid rgb(200 200 200 / 15%);\n  background: rgb(0 0 0 / 15%);\n  flex-direction: column;\n  padding: 10px 0px;\n\n  &.libraryNotification {\n    flex-direction: row;\n    padding: 0px;\n\n    .message {\n      flex-grow: 1;\n    }\n\n    .spinner {\n      width: 46px;\n      height: 30px;\n      margin-left: 1em;\n    }\n  }\n}\n\n.app-sidebar-content {\n  padding: 8px;\n  overflow-y: scroll;\n  overflow-y: overlay;\n  height: 100%;\n}\n\n#cmenu() {\n  .container {\n    position: absolute;\n    left: 0px;\n    width: var(--sidebarWidth);\n    max-width: var(--sidebarWidth);\n    padding: 10px;\n    z-index: 1;\n  }\n\n  .body {\n    background: rgb(30 30 30 / 45%);\n    padding: 6px;\n    border-radius: var(--panelRadius);\n    width: 100%;\n    box-shadow: var(--ciderShadow-Generic);\n    backdrop-filter: var(--glassFilter);\n    animation: cmenuBodyIn 0.5s var(--appleEase);\n\n    @keyframes cmenuBodyIn {\n      0% {\n        background: rgb(30 30 30);\n      }\n\n      100% {\n        background: rgb(30 30 30 / 45%);\n      }\n    }\n  }\n\n  .item {\n    background: transparent;\n    display: block;\n    width: 100%;\n    text-align: left;\n    color: #eee;\n    font-family: inherit;\n    font-size: 15px;\n    padding: 8px 12px;\n    border: 0px;\n    appearance: none;\n    border-radius: 6px;\n    margin: 2px 0px;\n\n    &:hover {\n      background: var(--selected);\n    }\n  }\n}\n\n.search-hints-container {\n  top: 44px;\n  #cmenu.container();\n\n  .search-hints {\n    background: rgb(30 30 30) !important;\n    #cmenu.body();\n\n    .search-hint {\n      #cmenu.item();\n\n      &.active {\n        background: var(--keyColor);\n      }\n    }\n  }\n}\n\n.usermenu-container {\n  top: var(--chromeHeight1);\n  z-index: 200001 !important;\n  #cmenu.container();\n\n  .usermenu-body {\n    #cmenu.body();\n\n    .usermenu-item {\n      #cmenu.item();\n\n      .usermenu-item-icon {\n        position: relative;\n        top: 1.5px;\n        right: 3px;\n        display: table-cell;\n      }\n\n      .usermenu-item-name {\n        position: relative;\n        bottom: 2px;\n        padding-left: 5px;\n        display: table-cell;\n      }\n    }\n  }\n}\n\n.context-menu {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: rgba(0, 0, 0, 0);\n  z-index: 100;\n\n  .context-menu-item {\n    background: transparent;\n    display: flex;\n    width: 100%;\n    text-align: left;\n    color: #eee;\n    font-family: inherit;\n    font-size: 14px;\n    padding: 6px 12px;\n    border: 0px;\n    appearance: none;\n    border-radius: 6px;\n    margin: 2px 0px;\n\n    &:hover {\n      background: var(--selected);\n      cursor: pointer;\n    }\n\n    &:active {\n      background: var(--selected-click);\n    }\n  }\n\n  .context-menu-body {\n    background: #242424;\n    padding: 6px;\n    border-radius: 6px;\n    box-shadow: var(--ciderShadow-Generic);\n\n    &.context-menu-open {\n      animation-duration: 0.1s;\n      animation-name: contextMenuIn;\n      animation-iteration-count: 1;\n      animation-easings: var(--appleEase);\n    }\n\n    &.context-menu-close {\n      animation-duration: 0.1s;\n      animation-name: contextMenuOut;\n      animation-iteration-count: 1;\n      animation-easings: var(--appleEase);\n    }\n  }\n}\n\n@keyframes contextMenuIn {\n  0% {\n    transform: scale(0.9);\n    opacity: 0;\n  }\n\n  100% {\n    transform: scale(1);\n    opacity: 1;\n  }\n}\n\n@keyframes contextMenuOut {\n  0% {\n    transform: scale(1);\n    opacity: 1;\n  }\n\n  100% {\n    transform: scale(0.9);\n    opacity: 0;\n  }\n}\n\n.hidden-opacity {\n  opacity: 0;\n  height: 0px;\n  width: 0px;\n  margin: 0px;\n}\n\n.spinner {\n  background-image: url(\"assets/spinner.svg\");\n  background-position: center;\n  background-repeat: no-repeat;\n  background-size: contain;\n  width: 50px;\n  height: 50px;\n  display: inline-block;\n}\n\n.app-sidebar-content::-webkit-scrollbar {\n  display: none;\n}\n\n.app-sidebar-content:hover::-webkit-scrollbar {\n  display: initial;\n}\n\n.app-sidebar-item {\n  --iconSize: 18px;\n  display: flex;\n  width: 100%;\n  padding: 8px 12px;\n  font-weight: 400;\n  font-family: inherit;\n  font-size: 14px;\n  margin: 3px 0px;\n  border: 1px solid transparent;\n  border-radius: 6px;\n  background: transparent;\n  color: #eee;\n  transition: transform 0.1s;\n  text-align: left;\n  align-items: center;\n  gap: 12px;\n  position: relative;\n\n  &.app-sidebar-item-playlist {\n    -webkit-user-drag: element;\n    overflow: hidden;\n    text-overflow: ellipsis;\n\n    .presentNotice {\n      align-self: center;\n      margin-left: 8px;\n      text-transform: uppercase;\n      font-size: 0.7em;\n      opacity: 0.6;\n    }\n  }\n\n  > ._svg-icon {\n    --size: var(--iconSize);\n    flex-shrink: 0;\n  }\n}\n\n.app-sidebar-item:hover {\n  border: 1px solid rgb(200 200 200 / 0%);\n  background: rgb(180 180 180 / 15%);\n  // cursor: pointer;\n}\n\n.app-sidebar-item:active {\n  border: 1px solid rgb(200 200 200 / 0%);\n  background: rgb(150 150 150 / 15%);\n  // transform: scale(0.98);\n  transition: transform 0s;\n}\n\n.app-sidebar-item.active {\n  border: 1px solid rgb(200 200 200 / 0%);\n  background: rgb(200 200 200 / 15%);\n  transform: scale(1);\n  transition: transform 0s;\n  cursor: default;\n}\n\n.app-chrome {\n  background-color: var(--baseColorMix);\n  box-shadow:\n    0px 3px 6px rgb(20 20 20 / 12%),\n    0px 1px 0px 0px rgb(200 200 200 / 12%);\n  width: 100%;\n  height: var(--chromeHeight1);\n  display: flex;\n  flex-direction: row;\n  -webkit-app-region: drag;\n  z-index: 4;\n\n  &:not(.chrome-bottom) {\n    // box-shadow: 0px 0px\n    z-index: 16;\n    position: fixed;\n    backdrop-filter: var(--glassFilter);\n\n    .app-chrome--center {\n      flex: 1;\n    }\n  }\n\n  .top-nav-group {\n    background: var(--baseColor);\n    border: 1px solid lighten(@baseColor, 8);\n    border-radius: 10px;\n    display: flex;\n    height: 32px;\n\n    .app-sidebar-item {\n      background-color: var(--baseColor);\n      border-radius: 10px !important;\n      border: 0px;\n      min-width: 120px;\n      padding: 6px;\n      justify-content: center;\n      align-items: center;\n      margin: 0px;\n      height: 100%;\n\n      &:hover {\n        background-color: lighten(@baseColor, @colorMixRate * 5);\n      }\n\n      &.active {\n        background-color: lighten(@baseColor, @colorMixRate * 5);\n      }\n\n      &.md-btn-primary {\n        box-shadow: 0px 0px 0px 1px lighten(@baseColor, @colorMixRate * 8);\n        background-color: lighten(@baseColor, @colorMixRate * 5);\n        z-index: 1;\n      }\n    }\n  }\n\n  .vdiv {\n    width: 1px;\n    background: white;\n    opacity: 0.25;\n    height: 50%;\n    margin: 6px;\n  }\n}\n\n.mv-chrome {\n  position: absolute;\n  top: 0;\n  right: 0;\n  width: 90%;\n  height: 55px;\n  -webkit-app-region: drag;\n}\n\n.app-chrome .app-chrome--left,\n.app-chrome .app-chrome--center,\n.app-chrome .app-chrome--right {\n  height: 100%;\n  width: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.app-chrome .app-chrome--left {\n  width: 30%;\n  justify-content: left;\n  -webkit-app-region: drag;\n}\n\n.app-chrome .app-chrome--center {\n  //width: 40%;\n  .app-title-text {\n    font-size: 0.8em;\n  }\n}\n\n.app-chrome .app-chrome--right {\n  width: 30%;\n  justify-content: right;\n}\n\n.app-chrome .app-chrome-item {\n  height: 100%;\n  width: auto;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  -webkit-app-region: no-drag;\n  height: auto;\n\n  &.generic {\n    width: 50px;\n    opacity: 0.7;\n  }\n\n  &.volume {\n    width: 100px;\n    margin-right: 6px;\n  }\n\n  &.search {\n    margin-right: 6px;\n  }\n}\n\n.volume-button {\n  background-image: url(\"./assets/feather/volume-2.svg\");\n  height: 15px;\n  width: 30px;\n  padding: 0px;\n  background: transparent;\n  border: 0px;\n  border-radius: 0px;\n  box-shadow: unset;\n  background-size: 12px;\n  background-position: center;\n  background-repeat: no-repeat;\n  opacity: 0.7;\n  border-radius: 6px;\n}\n\n.volume-button:active,\n.volume-button--small:active {\n  transform: scale(0.9);\n}\n\n.volume-button.active,\n.volume-button--small.active {\n  background-image: url(\"./assets/feather/volume.svg\");\n}\n\n.volume-button--small {\n  border-radius: 6px;\n  color: inherit;\n  background-size: 16px;\n  background-repeat: no-repeat;\n  background-position: center;\n  background-color: transparent;\n  height: 15px;\n  width: 30px;\n  border: 0px;\n  box-shadow: unset;\n  opacity: 0.7;\n  background-image: url(\"./assets/feather/volume-2.svg\");\n}\n\n.app-chrome .app-chrome-item.volume > input[type=\"range\"]::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  height: 14px;\n  width: 14px;\n  border-radius: 50%;\n  background: #a5a8ba;\n  box-shadow: 0px 0px 0px 1px rgba(0 0 0 / 10%);\n  cursor: default;\n  transition: all var(--appleTransition);\n}\n\n.app-chrome .app-chrome-item.volume > input[type=\"range\"] {\n  -webkit-appearance: none;\n  height: 4px;\n  background: rgba(255, 255, 255, 0.4);\n  border-radius: 5px;\n  background-size: 70% 100%;\n  background-repeat: no-repeat;\n  width: 100%;\n}\n\n.app-chrome .app-chrome-item.volume > input[type=\"range\"]::-webkit-slider-runnable-track {\n  -webkit-appearance: none;\n  box-shadow: none;\n  border: none;\n  background: transparent;\n}\n\n.app-chrome .back-button {\n  height: 100%;\n  width: 60px;\n}\n\n.app-chrome .app-chrome-item.full-height {\n  height: 100%;\n}\n\n.app-chrome .app-chrome-item > .app-mainmenu {\n  width: 34px;\n  font-size: 13px;\n  background: url(\"./assets/CiderMenu.svg\");\n  background-size: auto;\n  background-repeat: no-repeat;\n  background-position: center;\n  height: 34px;\n  margin-right: 16px;\n  margin-left: 16px;\n  margin-top: 1.5px;\n  border: 0px;\n  border-radius: 6px;\n  transition: transform 0.1s var(--appleEase);\n  position: relative;\n\n  // &:after {\n  //   content: \"\";\n  //   background-image: var(--cvar-userprofileimg);\n  //   height:100%;\n  //   width:100%;\n  //   top:0;\n  //   left: 0;\n  //   display:block;\n  //   position: absolute;\n  //   background-size: cover;\n  //   border-radius: 100%;\n  //   border: 0px solid rgb(50 50 50);\n  //   box-shadow: 0px 0px 0px 1px rgb(80 80 80);\n  // }\n\n  &:hover {\n    transform: scale(1.1);\n  }\n\n  &:active,\n  &.active {\n    border-radius: 100%;\n    transform: scale(1.1);\n    outline: 2px solid var(--keyColor);\n  }\n}\n\n.app-chrome .app-chrome-item > .window-controls {\n  width: 138px;\n  font-size: 13px;\n  height: 100%;\n  display: flex;\n\n  &-macos {\n    width: 100px;\n  }\n\n  > div {\n    height: 100%;\n    width: 32px;\n\n    &:hover {\n      background: rgb(200 200 200 / 10%);\n    }\n\n    &.close {\n      width: 100%;\n      height: 100%;\n      background-image: var(--gfx-closeBtn);\n      background-position: center;\n      background-repeat: no-repeat;\n      -webkit-app-region: no-drag;\n\n      &:hover {\n        background-color: rgb(196, 43, 28);\n      }\n    }\n\n    &.minmax {\n      background-image: var(--gfx-maxBtn);\n      background-position: center;\n      background-repeat: no-repeat;\n      -webkit-app-region: no-drag;\n      width: 100%;\n      height: 100%;\n    }\n\n    &.minmax.restore {\n      background-image: var(--gfx-restoreBtn);\n    }\n\n    &.minimize {\n      background-image: var(--gfx-minBtn);\n      background-position: center;\n      background-repeat: no-repeat;\n      -webkit-app-region: no-drag;\n      width: 100%;\n      height: 100%;\n    }\n  }\n}\n\nbody[platform=\"darwin\"] .app-chrome .app-chrome-item > .window-controls > div.minimize {\n  display: none;\n}\n\n//body[platform=\"darwin\"] .app-chrome .app-chrome-item > .window-controls {\n//  display: none;\n//}\n\nbody[platform=\"darwin\"] .app-chrome .app-chrome-item > .window-controls > div.minmax {\n  display: none;\n}\n\nbody[platform=\"darwin\"] .app-chrome .app-chrome-item > .window-controls > div.close {\n  display: none;\n}\n\n.app-chrome .app-chrome-item.playback-controls {\n  width: 80%;\n  height: 90%;\n  display: flex;\n  max-width: 500px;\n  border-left: 1px solid rgb(200 200 200 / 8%);\n  border-right: 1px solid rgb(200 200 200 / 8%);\n  -webkit-app-region: drag;\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls {\n  display: flex;\n  justify-content: center;\n  align-content: center;\n  width: 100%;\n  -webkit-app-region: no-drag;\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls {\n  .info-rect {\n    mask-image: linear-gradient(-90deg, transparent 0%, black 10%, black 90%, transparent 100%);\n    -webkit-mask-image: linear-gradient(-90deg, transparent 3%, black 10%, black 90%, transparent 100%);\n    display: flex;\n    flex-direction: column;\n    justify-content: center;\n    align-items: center;\n    width: 100%;\n  }\n\n  .song-name {\n    font-weight: 600;\n    text-align: center;\n    font-size: 13px;\n    height: 1.3em;\n    line-height: 1.3em;\n    white-space: nowrap;\n    max-width: 360px;\n\n    .song-name-normal {\n      height: inherit;\n    }\n\n    &.song-artist-marquee {\n      > marquee {\n        //margin-bottom: -3px;\n      }\n    }\n\n    .explicit-icon {\n      background-image: url(\"./assets/explicit.svg\");\n      height: 9px;\n      width: 13px;\n      filter: contrast(0);\n      background-repeat: no-repeat;\n      margin-left: 3px;\n    }\n\n    .heart-icon {\n      height: 9px;\n      width: 13px;\n      filter: contrast(0);\n      background-repeat: no-repeat;\n      margin-left: 3px;\n    }\n  }\n\n  .lossless-icon {\n    background-image: url(\"./assets/lossless.svg\") !important;\n    margin-left: 0.5em !important;\n    flex: 1;\n  }\n\n  .ppe-icon {\n    background-image: url(\"./assets/ppe.svg\") !important;\n    margin-left: 0.5em !important;\n    flex: 1;\n  }\n\n  .spatial-icon {\n    background-image: url(\"./assets/spatialization.svg\") !important;\n    margin-left: 0.5em !important;\n    flex: 1;\n  }\n\n  .private-icon {\n    background-image: url(\"./assets/private.svg\") !important;\n    margin-left: 0.5em !important;\n    flex: 1;\n  }\n\n  .live-icon {\n    filter: none !important;\n    margin-left: 0.5em !important;\n    flex: 1;\n  }\n\n  .chrome-icon-container {\n    display: flex;\n    position: absolute;\n    right: 0px;\n  }\n\n  .audio-type {\n    filter: contrast(0);\n    background-repeat: no-repeat;\n    background-size: contain;\n    height: 15px;\n    width: 15px;\n    margin-bottom: 15px;\n    z-index: 1;\n  }\n}\n\n// Add Music Video Icons to Songs that are Music Videos\ndiv[data-type=\"library-music-videos\"] .info-rect .title::before,\ndiv[data-type=\"musicVideo\"] .info-rect .title::before {\n  content: \"\";\n  background-image: url(./assets/feather/video.svg);\n  background-size: contain;\n  filter: invert(0.6);\n  display: inline-block;\n  width: 20px;\n  height: 20px;\n  margin-bottom: -4px;\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .song-duration p {\n  font-weight: 400;\n  font-size: 10px;\n  height: 1.2em;\n  line-height: 1.3em;\n  overflow: hidden;\n  margin: 0 0 0 0.25em;\n}\n\n.app-playback-controls:hover .marquee {\n  animation: unset;\n\n  &.song-artist {\n    overflow: hidden;\n  }\n\n  .song-artist {\n    overflow: hidden;\n  }\n\n  &.song-name {\n    overflow: hidden;\n  }\n\n  &::after {\n    content: none !important;\n    display: none;\n  }\n}\n\n.marquee {\n  animation: marquee 15s linear 2s infinite;\n\n  &.song-artist {\n    overflow: unset;\n  }\n\n  .song-artist {\n    overflow: unset;\n  }\n\n  &.song-name {\n    overflow: unset;\n  }\n\n  &::after {\n    content: attr(data-value);\n  }\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .song-progress {\n  @bgColor: transparent;\n  //height: 16px;\n  position: absolute;\n  bottom: 0px;\n  left: 0px;\n  background: @bgColor;\n\n  &:hover {\n    > input[type=\"range\"] {\n      &::-webkit-slider-thumb {\n        opacity: 1;\n        transform: scale(1);\n        z-index: 1;\n      }\n    }\n  }\n\n  > input[type=\"range\"] {\n    appearance: none;\n    width: 100%;\n    height: 4px;\n    background-color: rgb(200 200 200 / 10%);\n    border-radius: 2px;\n    margin: 0;\n\n    &::-webkit-slider-thumb {\n      opacity: 0;\n      transform: scale(0.5);\n      -webkit-appearance: none;\n      appearance: none;\n      width: 12px;\n      height: 12px;\n      border-radius: 100%;\n      background: var(--songProgressColor);\n      cursor: default;\n      transition:\n        opacity 0.1s var(--appleEase),\n        transform 0.1s var(--appleEase);\n    }\n\n    &::-moz-range-thumb {\n      width: 8px;\n      height: 8px;\n      border-radius: 100%;\n      background: var(--songProgressColor);\n      cursor: default;\n    }\n  }\n}\n\n@keyframes marquee {\n  from {\n    transform: translateX(0);\n  }\n\n  to {\n    transform: translateX(-140%);\n  }\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .artwork {\n  width: 42px;\n  height: 42px;\n  background-image: var(--artwork);\n  background-position: center;\n  background-size: contain;\n  background-repeat: no-repeat;\n  border-radius: var(--mediaItemRadiusSmall);\n  flex: 0 0 auto;\n  margin: 6px;\n  image-rendering: -webkit-optimize-contrast;\n\n  .mediaitem-artwork {\n    border-radius: var(--mediaItemRadiusSmall);\n  }\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .actions {\n  width: 42px;\n  height: 42px;\n  border-radius: 2px;\n  flex: 0 0 auto;\n  margin: 6px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  filter: contrast(0.8);\n\n  .lcdMenu {\n    height: 100%;\n    width: 100%;\n    padding: 0px;\n    margin: 0px;\n    background: transparent;\n    border: 0px;\n    appearance: none;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    border-radius: 6px;\n\n    &:focus {\n      outline: none;\n    }\n\n    &:hover {\n      background: var(--hover);\n    }\n\n    &:active {\n      background: var(--selected-click);\n      transform: scale(0.95);\n    }\n\n    .svg-icon {\n      --url: url(\"views/svg/more.svg\") !important;\n    }\n  }\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .playback-info {\n  width: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  flex-direction: column;\n  position: relative;\n  overflow: hidden;\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .playback-info > .song-progress {\n  width: 100%;\n}\n\n.app-navigation {\n  background: transparent;\n  align-items: center;\n  justify-content: center;\n  background: var(--color1);\n  height: calc(100% - var(--chromeHeight2));\n  width: 100%;\n  display: flex;\n  position: relative;\n}\n\n.app-chrome .app-chrome-item > .app-playback-controls .song-artist-album {\n  font-weight: 400;\n  font-size: 12px;\n  text-align: center;\n  /*height       : 1.2em;\n  line-height    : 1.2em;*/\n  z-index: 1;\n  align-items: center;\n  justify-content: center;\n  width: 80%;\n  max-width: 340px;\n  overflow: hidden;\n\n  .song-artist-album-content {\n    font-weight: 400;\n    font-size: 12px;\n    text-align: center;\n    width: 100%;\n\n    &.song-artist-normal {\n      height: inherit;\n    }\n  }\n\n  &.song-artist-marquee {\n    > marquee {\n      margin-bottom: -3px;\n    }\n  }\n}\n\n.display--small {\n  display: none !important;\n}\n\n.web-slider.display--small {\n  margin: 10px;\n}\n\ninput[type=\"range\"].web-slider.display--small::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  height: 14px;\n  width: 14px;\n  border-radius: 50%;\n  background: rgb(50 50 50);\n  cursor: default;\n  box-shadow: inset 0px 0px 0px 1px rgba(255, 255, 255, 0.4);\n}\n\n/* Window is smaller <= 1023px width */\n@media only screen and (max-width: 1120px) {\n  .display--small {\n    display: inherit !important;\n\n    .slider {\n      width: 100%;\n      z-index: 1;\n    }\n\n    .input-container {\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      width: 100%;\n      padding-bottom: 10px;\n    }\n\n    input[type=\"range\"] {\n      -webkit-appearance: none;\n      height: 4px;\n      background: rgba(255, 255, 255, 0.4);\n      border-radius: 5px;\n      background-size: 70% 100%;\n      background-repeat: no-repeat;\n\n      &::-webkit-slider-thumb {\n        -webkit-appearance: none;\n        height: 14px;\n        width: 14px;\n        border-radius: 50%;\n        background: rgb(50 50 50);\n        cursor: default;\n        box-shadow: inset 0px 0px 0px 1px rgba(255, 255, 255, 0.4);\n        transition: all var(--appleTransition);\n      }\n\n      &::-webkit-slider-thumb:hover {\n        background-image: radial-gradient(var(--songProgressColor) 2px, transparent 3px, transparent 10px);\n        transform: scale(1.2);\n      }\n\n      &::-webkit-slider-thumb:active {\n        background-image: radial-gradient(var(--songProgressColor) 3px, transparent 4px, transparent 10px);\n        transform: scale(1);\n      }\n\n      &::-webkit-slider-runnable-track {\n        -webkit-appearance: none;\n        box-shadow: none;\n        border: none;\n        background: transparent;\n      }\n    }\n  }\n\n  .display--large {\n    display: none !important;\n  }\n}\n\n.cider-flex-center {\n  display: flex;\n  align-items: center;\n  flex-wrap: wrap;\n}\n\n.md-container {\n  width: 100%;\n  position: relative;\n}\n\n.lyric-body {\n  -webkit-mask-image: -webkit-gradient(linear, left 95%, left bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0)));\n  overflow-y: scroll;\n  overflow-x: hidden;\n  display: flex;\n  flex-flow: column;\n  font-family:\n    \"Pretendard Variable\",\n    \"Noto Sans JP\",\n    \"Noto Sans KR\",\n    \"Noto Sans TC\",\n    \"Noto Sans SC\",\n    -apple-system,\n    BlinkMacSystemFont,\n    \"Segoe UI\",\n    Roboto,\n    Oxygen,\n    Ubuntu,\n    Cantarell,\n    \"Open Sans\",\n    \"Helvetica Neue\",\n    sans-serif;\n}\n\n.lyric-body .no-lyrics {\n  width: 100%;\n  justify-content: center;\n  align-items: center;\n  font-weight: bold;\n  font-size: 26px;\n}\n\n.lyric-line {\n  --bgSpeed: 1s;\n  appearance: none;\n  color: white;\n  font-size: 26px;\n  transform: scale(0.8);\n  transform-origin: left center;\n  transition: transform 0.5s var(--appleEase);\n  opacity: 0.75;\n  width: auto;\n  display: inline-block;\n  margin: 10px;\n  margin-left: 5%;\n  margin-right: 0px;\n  overflow-wrap: break-word;\n}\n\n.lyric-line.active .verse {\n  opacity: 0.6;\n}\n\n.lyric-line.active .verse.verse-active {\n  opacity: 1;\n  transition: opacity 0.35s var(--appleEase);\n}\n\n.lyric-line:hover {\n  cursor: pointer;\n}\n\n.lyric-line:hover::after {\n  content: \" \";\n  width: 100%;\n  height: 100%;\n  position: absolute;\n  top: 0;\n  left: 0;\n  transform: scale(1.06);\n  background: rgba(200, 200, 200, 0.1);\n  pointer-events: none;\n  border-radius: 10px;\n  -webkit-backface-visibility: hidden;\n}\n\n.lyric-line.active {\n  --bgSpeed: 1s;\n  opacity: 1;\n  transform: scale(1);\n  /*background: var(--keyColor);*/\n  transition:\n    transform 0.2s var(--appleEase),\n    opacity 0.35s var(--appleEase);\n}\n\n.lyric-line:not(.active) {\n  filter: blur(1px);\n}\n\n.lyric-line:not(.active).unsynced {\n  filter: none !important;\n}\n\n.lyric-line.unsynced {\n  filter: none !important;\n}\n\n.lyric-body:hover > .lyric-line:not(.active) {\n  filter: none !important;\n}\n\n.lyric-body > .lyric-line:not(.active) {\n  // transition: filter var(--appleEase) 0.5s ease;\n}\n\n.lyricWaiting {\n  margin-bottom: 10px;\n  display: none;\n}\n\n.lyric-line.active .lyricWaiting {\n  display: inline-flex;\n  animation: lyricWaitingLine 6s cubic-bezier(0.42, 0, 0.58, 1) infinite;\n}\n\n.lyric-line.active .lyricWaiting > div {\n  width: 10px;\n  height: 10px;\n  background: white;\n  border-radius: 50%;\n  margin: 3px;\n}\n\n.lyrics-translation {\n  font-size: 1.6rem;\n  font-weight: 450;\n  font-family:\n    \"Pretendard Variable\",\n    \"Noto Sans JP\",\n    \"Noto Sans KR\",\n    \"Noto Sans TC\",\n    \"Noto Sans SC\",\n    -apple-system,\n    BlinkMacSystemFont,\n    \"Segoe UI\",\n    Roboto,\n    Oxygen,\n    Ubuntu,\n    Cantarell,\n    \"Open Sans\",\n    \"Helvetica Neue\",\n    sans-serif;\n  filter: contrast(0.5);\n}\n\n.lyric-footer {\n  bottom: 0;\n  height: 50px;\n  width: 100%;\n  position: absolute;\n  z-index: 1000;\n  opacity: 1;\n  background-image: linear-gradient(180deg, transparent, rgba(30, 30, 30, 0.8));\n  justify-content: center;\n  align-items: center;\n  display: none;\n  transition: opacity 0.1s var(--appleEase);\n}\n\n.lyric-body:hover + .lyric-footer,\n.lyric-footer:hover {\n  display: flex;\n}\n\n.modular-fs .app-drawer .lyric-footer {\n  background: unset;\n  display: flex;\n  opacity: 0.3;\n}\n\n.modular-fs .app-drawer .lyric-footer:hover {\n  opacity: 1;\n}\n\n.modular-fs .app-drawer .lyric-body .no-lyrics {\n  height: 100%;\n  display: flex;\n}\n\n@keyframes lyricWaitingLine {\n  0% {\n    opacity: 0.25;\n    transform: scale(0.85);\n  }\n\n  50% {\n    opacity: 1;\n    transform: scale(1);\n  }\n\n  100% {\n    opacity: 0.25;\n    transform: scale(0.85);\n  }\n}\n\n@keyframes dotOpacity {\n  0% {\n    opacity: 0.25;\n  }\n\n  100% {\n    opacity: 1;\n  }\n}\n\n.lyric-line2:before {\n  background: var(--keyColor);\n  content: \"\";\n  width: 0%;\n  height: 6px;\n  position: absolute;\n  bottom: -8px;\n  left: 0;\n  border-radius: 10px;\n  z-index: -1;\n  transition: width var(--bgSpeed);\n}\n\n.lyric-line2.active:before {\n  width: 100%;\n  transition: width var(--bgSpeed);\n}\n\n.player_top {\n  height: 100%;\n}\n\n/* Cider */\n\n.more-btn-round {\n  border-radius: 100%;\n  background: rgba(100, 100, 100, 0.5);\n  box-shadow: var(--ciderShadow-Generic);\n  width: 32px;\n  height: 32px;\n  border: 0px;\n  cursor: pointer;\n  z-index: 5;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n\n  &:hover {\n    filter: brightness(125%);\n  }\n\n  &:active {\n    filter: brightness(75%);\n    transform: scale(0.98);\n    transition:\n      transform 0s var(--appleEase),\n      box-shadow 0.2s var(--appleEase);\n  }\n\n  .svg-icon {\n    width: 100%;\n    background: #eee;\n    --url: url(\"./views/svg/more.svg\");\n  }\n}\n\n.social-btn {\n  border-radius: 100%;\n  background: transparent;\n  height: 17px;\n  border: 0px;\n  cursor: pointer;\n  z-index: 69;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  float: right;\n}\n\n@media only screen and (min-width: 1133px) and (max-width: 1277px) {\n  .about-page {\n    .social-btn {\n      display: none !important;\n    }\n  }\n}\n\n.about-page {\n  .teamBtn {\n    display: flex;\n    align-items: center;\n    width: 100%;\n    font-size: 14px;\n    padding: 6px 16px;\n    margin: 4px;\n\n    > img {\n      width: 30px;\n      margin: 0px 16px 0px 0px;\n      pointer-events: none;\n      border-radius: 100%;\n      box-shadow: var(--mediaItemShadow);\n      image-rendering: -webkit-optimize-contrast;\n    }\n  }\n\n  .sponsorBtn {\n    display: inline-flex;\n    justify-content: center;\n    align-items: center;\n\n    > img {\n      width: 26px;\n      margin: 0px 16px 0px 0px;\n      pointer-events: none;\n    }\n\n    &.githubBtn {\n      background-color: #211f1f;\n    }\n\n    &.kofiBtn {\n      background-color: #fbaa19;\n    }\n\n    &.opencollectiveBtn {\n      background-color: #7fadf2;\n    }\n\n    &.discordBtn {\n      background-color: #5865f2;\n    }\n\n    &.twitterBtn {\n      background-color: #1d9bf0;\n    }\n\n    &.qqBtn {\n      background-color: #d32f2f;\n    }\n  }\n}\n\n.sidebar-playlist {\n  .folder-button-active {\n    background: rgb(255 255 255 / 12%);\n  }\n\n  .folder-body {\n    background: #ffffff0a;\n    border-radius: 10px;\n    padding: 1px 6px;\n\n    .spinner {\n      display: block;\n      width: 100%;\n      height: 32px;\n      background-size: 16px;\n    }\n  }\n}\n\n#navigation-bar {\n  width: 100%;\n  background: rgba(0, 0, 0, 0.25);\n  height: var(--navigationBarHeight);\n  display: flex;\n  align-items: center;\n  padding: 0px 6px;\n  z-index: 7;\n  position: sticky;\n  top: 0;\n  left: 0;\n  backdrop-filter: blur(32px);\n  //box-shadow: 0px 1px 0px rgba(185, 185, 185, 0.08);\n  mix-blend-mode: hard-light;\n\n  .nav-item {\n    appearance: none;\n    border: 0px;\n    height: 32px;\n    width: 40px;\n    background: transparent;\n    padding: 6px;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    color: rgba(200, 200, 200, 0.8);\n    margin: 2px;\n    border-radius: 6px;\n    transition: transform 0.1s var(--appleEase);\n\n    &:active {\n      background: var(--selected-click);\n      transform: scale(0.96);\n      transition: transform 0s var(--appleEase);\n    }\n\n    > svg {\n      width: 8px;\n      pointer-events: none;\n    }\n\n    &:hover {\n      background: var(--selected);\n\n      > svg {\n        color: rgba(200, 200, 200, 1);\n      }\n    }\n  }\n}\n\n.well {\n  background: rgba(200, 200, 200, 0.05);\n  border-radius: 10px;\n  padding: var(--contentInnerPadding);\n  margin-top: 16px;\n\n  &.itemContainer {\n    display: flex;\n    flex-flow: wrap;\n    justify-content: center;\n\n    .cd-mediaitem-square-container {\n      align-items: center;\n    }\n\n    .cd-mediaitem-square {\n      width: 220px;\n      height: 260px;\n      display: inline-flex;\n      flex: 0 0 auto;\n      flex-direction: column;\n      font-size: 14px;\n      justify-content: center;\n      align-items: center;\n      border-radius: 6px;\n      max-width: 240px;\n      flex-grow: 1;\n    }\n\n    &.collection-list-square {\n      display: grid;\n      grid-template-columns: repeat(4, minmax(200px, 1fr));\n\n      // screen size > 1200px\n      @media screen and (min-width: 1500px) {\n        grid-template-columns: repeat(5, minmax(200px, 1fr));\n      }\n\n      // less than 1100px\n      @media screen and (max-width: 1150px) {\n        grid-template-columns: repeat(3, minmax(200px, 1fr));\n      }\n    }\n  }\n}\n\n.cd-mediaitem-square-container {\n  display: inline-flex;\n  flex-direction: column;\n  justify-content: center;\n}\n\n.reasonSP {\n  // margin-left: 15px;\n  color: rgb(167 163 163);\n  font-weight: 500;\n  margin-left: 15px;\n}\n\n.text-overflow-elipsis {\n  display: -webkit-box;\n  min-width: 0px;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  -webkit-line-clamp: 1;\n  -webkit-box-orient: vertical;\n}\n\n.no-animation {\n  animation: unset !important;\n}\n\n@import url(\"less/fullscreen.less\");\n@import url(\"less/miniplayer.less\");\n\n// Cider App\n\n#micaEffect {\n  opacity: 1;\n  // animation: micaEnter 1s ease-in-out forwards;\n  filter: brightness(1) saturate(320%);\n\n  @keyframes micaEnter {\n    0% {\n      opacity: 0;\n      transform: translateY(10px);\n    }\n\n    100% {\n      opacity: 1;\n      transform: translateY(0px);\n    }\n  }\n}\n\n@keyframes rotate {\n  from {\n    transform: rotate(0deg);\n  }\n\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n// Modular\n.modular-fs {\n  .app-chrome.chrome-bottom {\n    position: fixed;\n    bottom: 0;\n    left: 0;\n    z-index: 14 !important;\n    backdrop-filter: var(--glassFilter);\n  }\n\n  .app-navigation {\n    height: 100%;\n  }\n\n  .app-drawer {\n    width: 100%;\n    right: 0px;\n    top: 0px;\n    height: 100%;\n    border-radius: 0px;\n    box-shadow: unset;\n    background: black;\n\n    .bgArtworkMaterial {\n      display: block;\n\n      &::before {\n        top: -50%;\n        left: -20%;\n        width: 200vh;\n        height: 200vh;\n      }\n\n      .bg-artwork-container {\n        display: block !important;\n      }\n    }\n\n    .lyric-body {\n      justify-content: center;\n      align-items: center;\n      padding: 0px;\n      margin: 0px;\n      overflow: hidden;\n      filter: drop-shadow(0px 4px 6px rgb(0 0 0 / 70%));\n\n      .lyric-line {\n        pointer-events: none;\n        font-weight: 600;\n        font-size: 2em;\n        transform-origin: center;\n        animation: fsLyricIn var(--appleEase) 0.2s;\n        opacity: 0.9;\n\n        &:not(.active) {\n          display: none;\n          margin: 0;\n          transform: scale(1);\n        }\n\n        &.active {\n          margin: 0;\n          transform: scale(1);\n        }\n      }\n    }\n  }\n}\n\n@keyframes fsLyricIn {\n  0% {\n    opacity: 0;\n    transform: scale(0.98);\n  }\n\n  100% {\n    opacity: 1;\n    transform: scale(1);\n  }\n}\n\n// Modular\n\n/* Transitions */\n\n.replaycard-enter-active,\n.replaycard-leave-active {\n  transition:\n    opacity 0.5s var(--appleEase),\n    transform 0.5s var(--appleEase);\n}\n\n.replaycard-enter,\n.replaycard-leave-to {\n  opacity: 0;\n  transform: translateY(20px);\n}\n\n.fade-enter-active,\n.fade-leave-active {\n  transition: opacity 0.15s var(--appleEase);\n}\n\n.fade-enter,\n.fade-leave-to {\n  opacity: 0;\n}\n\n.modal-enter-active,\n.modal-leave-active {\n  transition:\n    opacity 0.1s var(--appleEase),\n    transform 0.1s var(--appleEase);\n}\n\n.modal-enter,\n.modal-leave-to {\n  opacity: 0;\n  transform: scale(1.1);\n}\n\n.wpfade-enter-active,\n.wpfade-leave-active {\n  transition: opacity 0.1s var(--appleEase);\n}\n\n.wpfade-enter,\n.wpfade-leave-to {\n  opacity: 0;\n}\n\n.wpfade_transform-enter-active,\n.wpfade_transform-leave-active {\n  --transitionTime: 0.2s;\n  transition: opacity var(--transitionTime) var(--appleEase);\n  will-change: opacity, transform;\n}\n\n.wpfade_transform-enter {\n  opacity: 0;\n  transform: unset;\n  will-change: opacity;\n}\n\n.wpfade_transform-leave-to {\n  opacity: 0;\n  transform: unset;\n  will-change: opacity;\n}\n\n.wpfade_transform_backwards-enter-active,\n.wpfade_transform_backwards-leave-active {\n  --transitionTime: 0.2s;\n  transition: opacity var(--transitionTime) var(--appleEase);\n}\n\n.wpfade_transform_backwards-enter {\n  opacity: 0;\n  transform: unset;\n  will-change: opacity;\n}\n\n.wpfade_transform_backwards-leave-to {\n  opacity: 0;\n  transform: unset;\n  will-change: opacity;\n}\n\n.fabfade-enter-active,\n.fabfade-leave-active {\n  transition:\n    transform 0.1s var(--appleEase),\n    opacity 0.1s var(--appleEase);\n}\n\n.fabfade-enter,\n.fabfade-leave-to {\n  opacity: 0;\n  transform: scale(0.5);\n}\n\n.fsModeSwitch-enter-active,\n.fsModeSwitch-leave-active {\n  transition:\n    transform 1s var(--appleEase),\n    opacity 1s var(--appleEase);\n}\n\n.fsModeSwitch-enter,\n.fsModeSwitch-leave-to {\n  transform: scale(1.1);\n  opacity: 0;\n}\n\n.sidebartransition-enter-active,\n.sidebartransition-leave-active {\n  transition: margin-left 0.35s var(--appleEase);\n}\n\n.sidebartransition-enter,\n.sidebartransition-leave-to {\n  margin-left: calc(var(--sidebarWidth) * -1);\n}\n\n.drawertransition-enter-active,\n.drawertransition-leave-active {\n  transition: transform 0.25s var(--appleEase);\n}\n\n.drawertransition-enter,\n.drawertransition-leave-to {\n  transform: translateX(400px);\n}\n\n@media (prefers-color-scheme: dark) {\n}\n\n:root {\n  --gfx-closeBtn: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAIn2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS41LjAiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiCiAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyIKICAgZGM6Zm9ybWF0PSJpbWFnZS9wbmciCiAgIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiCiAgIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIKICAgdGlmZjpJbWFnZUxlbmd0aD0iMTAiCiAgIHRpZmY6SW1hZ2VXaWR0aD0iMTAiCiAgIHRpZmY6UmVzb2x1dGlvblVuaXQ9IjIiCiAgIHRpZmY6WFJlc29sdXRpb249IjcyLjAiCiAgIHRpZmY6WVJlc29sdXRpb249IjcyLjAiCiAgIHhtcDpDcmVhdGVEYXRlPSIyMDIwLTAyLTE3VDEyOjU1OjM3WiIKICAgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiCiAgIHhtcDpNZXRhZGF0YURhdGU9IjIwMjEtMTAtMDVUMTQ6Mjc6MzYtMDc6MDAiCiAgIHhtcDpNb2RpZnlEYXRlPSIyMDIxLTEwLTA1VDE0OjI3OjM2LTA3OjAwIgogICB4bXBNTTpEb2N1bWVudElEPSJhZG9iZTpkb2NpZDpwaG90b3Nob3A6ZTk5OWM2NWYtNDhhOS0wNjQyLWI2MTktZmJlYTExMmUxOGZiIgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5MzMyOWNhLWNkNjctMzY0Zi04MzU1LTY5N2ZmYzI0ZDdlZCIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjgyZjQwYmU3LTE0YzItZjc0Ni1hZmE1LWQxYmIxNzAyMjM4OCIKICAgZXhpZjpQaXhlbFhEaW1lbnNpb249IjEwIgogICBleGlmOlBpeGVsWURpbWVuc2lvbj0iMTAiCiAgIGV4aWY6Q29sb3JTcGFjZT0iMSI+CiAgIDxwaG90b3Nob3A6VGV4dExheWVycz4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgcGhvdG9zaG9wOkxheWVyTmFtZT0i7qSiIgogICAgICBwaG90b3Nob3A6TGF5ZXJUZXh0PSLupKIiLz4KICAgIDwvcmRmOlNlcT4KICAgPC9waG90b3Nob3A6VGV4dExheWVycz4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHhtcE1NOmFjdGlvbj0iY3JlYXRlZCIKICAgICAgeG1wTU06aW5zdGFuY2VJRD0ieG1wLmlpZDo4MmY0MGJlNy0xNGMyLWY3NDYtYWZhNS1kMWJiMTcwMjIzODgiCiAgICAgIHhtcE1NOnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE5IChXaW5kb3dzKSIKICAgICAgeG1wTU06d2hlbj0iMjAyMC0wMi0xN1QxMjo1NTozN1oiLz4KICAgICA8cmRmOmxpCiAgICAgIHhtcE1NOmFjdGlvbj0ic2F2ZWQiCiAgICAgIHhtcE1NOmNoYW5nZWQ9Ii8iCiAgICAgIHhtcE1NOmluc3RhbmNlSUQ9InhtcC5paWQ6NjkzMzI5Y2EtY2Q2Ny0zNjRmLTgzNTUtNjk3ZmZjMjRkN2VkIgogICAgICB4bXBNTTpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiCiAgICAgIHhtcE1NOndoZW49IjIwMjAtMDItMTdUMTI6NTU6MzdaIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InByb2R1Y2VkIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZmZpbml0eSBQaG90byAxLjEwLjEiCiAgICAgIHN0RXZ0OndoZW49IjIwMjEtMTAtMDVUMTQ6Mjc6MzYtMDc6MDAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KPD94cGFja2V0IGVuZD0iciI/PmN2D9EAAAGCaUNDUHNSR0IgSUVDNjE5NjYtMi4xAAAokXWRv0tCURTHP2lhmGFRQUODhDVZlELU0qD0C6pBDbJa9OWPQO3xnhHRGrQKBVFLv4b6C2oNmoOgKIJoC5qLWkpe56mgRJ7Luedzv/eew73ngiWcVjJ6/QBksjktOOF3zUcWXLZX7DTQQSu+qKKrM6HxMDXt64E6M971mbVqn/vXmpbjugJ1jcKjiqrlhCeFp9dzqsm7wu1KKrosfC7s0eSCwvemHivxm8nJEv+YrIWDAbC0CLuSVRyrYiWlZYTl5bgz6TWlfB/zJY54di4ksVu8C50gE/hxMcUYAYYYZETmIfrw0i8rauQPFPNnWZVcRWaVDTRWSJIih0fUNakel5gQPS4jzYbZ/7991RM+b6m6ww8NL4bx0QO2HSjkDeP72DAKJ2B9hqtsJX/1CIY/Rc9XNPchOLfg4rqixfbgchs6n9SoFi1KVnFLIgHvZ9AcgbZbsC+Welbe5/QRwpvyVTewfwC9ct659At2bGftHD0UJwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAEtJREFUGJWNkMENwDAIA1FGY/8hkn8HOAqPfBsFKvz1yZYtbqwAlUIB6saUAH2NJ4MvL4PLgK/x13LAGTSqEaVa1a0x7XvcmI3D1wbntaRbB2haYwAAAABJRU5ErkJggg==\");\n  --gfx-maxBtn: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAIn2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS41LjAiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiCiAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyIKICAgZGM6Zm9ybWF0PSJpbWFnZS9wbmciCiAgIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiCiAgIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIKICAgdGlmZjpJbWFnZUxlbmd0aD0iMTAiCiAgIHRpZmY6SW1hZ2VXaWR0aD0iMTAiCiAgIHRpZmY6UmVzb2x1dGlvblVuaXQ9IjIiCiAgIHRpZmY6WFJlc29sdXRpb249IjcyLjAiCiAgIHRpZmY6WVJlc29sdXRpb249IjcyLjAiCiAgIHhtcDpDcmVhdGVEYXRlPSIyMDIwLTAyLTE3VDEyOjU1OjM3WiIKICAgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiCiAgIHhtcDpNZXRhZGF0YURhdGU9IjIwMjEtMTAtMDVUMTQ6Mjc6NTgtMDc6MDAiCiAgIHhtcDpNb2RpZnlEYXRlPSIyMDIxLTEwLTA1VDE0OjI3OjU4LTA3OjAwIgogICB4bXBNTTpEb2N1bWVudElEPSJhZG9iZTpkb2NpZDpwaG90b3Nob3A6ZTk5OWM2NWYtNDhhOS0wNjQyLWI2MTktZmJlYTExMmUxOGZiIgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5MzMyOWNhLWNkNjctMzY0Zi04MzU1LTY5N2ZmYzI0ZDdlZCIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjgyZjQwYmU3LTE0YzItZjc0Ni1hZmE1LWQxYmIxNzAyMjM4OCIKICAgZXhpZjpQaXhlbFhEaW1lbnNpb249IjEwIgogICBleGlmOlBpeGVsWURpbWVuc2lvbj0iMTAiCiAgIGV4aWY6Q29sb3JTcGFjZT0iMSI+CiAgIDxwaG90b3Nob3A6VGV4dExheWVycz4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgcGhvdG9zaG9wOkxheWVyTmFtZT0i7qSiIgogICAgICBwaG90b3Nob3A6TGF5ZXJUZXh0PSLupKIiLz4KICAgIDwvcmRmOlNlcT4KICAgPC9waG90b3Nob3A6VGV4dExheWVycz4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHhtcE1NOmFjdGlvbj0iY3JlYXRlZCIKICAgICAgeG1wTU06aW5zdGFuY2VJRD0ieG1wLmlpZDo4MmY0MGJlNy0xNGMyLWY3NDYtYWZhNS1kMWJiMTcwMjIzODgiCiAgICAgIHhtcE1NOnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE5IChXaW5kb3dzKSIKICAgICAgeG1wTU06d2hlbj0iMjAyMC0wMi0xN1QxMjo1NTozN1oiLz4KICAgICA8cmRmOmxpCiAgICAgIHhtcE1NOmFjdGlvbj0ic2F2ZWQiCiAgICAgIHhtcE1NOmNoYW5nZWQ9Ii8iCiAgICAgIHhtcE1NOmluc3RhbmNlSUQ9InhtcC5paWQ6NjkzMzI5Y2EtY2Q2Ny0zNjRmLTgzNTUtNjk3ZmZjMjRkN2VkIgogICAgICB4bXBNTTpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiCiAgICAgIHhtcE1NOndoZW49IjIwMjAtMDItMTdUMTI6NTU6MzdaIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InByb2R1Y2VkIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZmZpbml0eSBQaG90byAxLjEwLjEiCiAgICAgIHN0RXZ0OndoZW49IjIwMjEtMTAtMDVUMTQ6Mjc6NTgtMDc6MDAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KPD94cGFja2V0IGVuZD0iciI/PlwQMBUAAAGCaUNDUHNSR0IgSUVDNjE5NjYtMi4xAAAokXWRv0tCURTHP2lhmGFRQUODhDVZlELU0qD0C6pBDbJa9OWPQO3xnhHRGrQKBVFLv4b6C2oNmoOgKIJoC5qLWkpe56mgRJ7Luedzv/eew73ngiWcVjJ6/QBksjktOOF3zUcWXLZX7DTQQSu+qKKrM6HxMDXt64E6M971mbVqn/vXmpbjugJ1jcKjiqrlhCeFp9dzqsm7wu1KKrosfC7s0eSCwvemHivxm8nJEv+YrIWDAbC0CLuSVRyrYiWlZYTl5bgz6TWlfB/zJY54di4ksVu8C50gE/hxMcUYAYYYZETmIfrw0i8rauQPFPNnWZVcRWaVDTRWSJIih0fUNakel5gQPS4jzYbZ/7991RM+b6m6ww8NL4bx0QO2HSjkDeP72DAKJ2B9hqtsJX/1CIY/Rc9XNPchOLfg4rqixfbgchs6n9SoFi1KVnFLIgHvZ9AcgbZbsC+Welbe5/QRwpvyVTewfwC9ct659At2bGftHD0UJwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAFBJREFUGJXV0LERgCAUBNHVsQADM3uwWWbojQIs47MEGhgAuS/eSw41qeFYqGlRA7iAm74DKLyrfRABoLrOgq+/hJXngi71BOoGZKBMHqhAbtMvQzel9pREAAAAAElFTkSuQmCC\");\n  --gfx-restoreBtn: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAIn2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS41LjAiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiCiAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyIKICAgZGM6Zm9ybWF0PSJpbWFnZS9wbmciCiAgIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiCiAgIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIKICAgdGlmZjpJbWFnZUxlbmd0aD0iMTAiCiAgIHRpZmY6SW1hZ2VXaWR0aD0iMTAiCiAgIHRpZmY6UmVzb2x1dGlvblVuaXQ9IjIiCiAgIHRpZmY6WFJlc29sdXRpb249IjcyLjAiCiAgIHRpZmY6WVJlc29sdXRpb249IjcyLjAiCiAgIHhtcDpDcmVhdGVEYXRlPSIyMDIwLTAyLTE3VDEyOjU1OjM3WiIKICAgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiCiAgIHhtcDpNZXRhZGF0YURhdGU9IjIwMjEtMTAtMDVUMTQ6Mjc6MjQtMDc6MDAiCiAgIHhtcDpNb2RpZnlEYXRlPSIyMDIxLTEwLTA1VDE0OjI3OjI0LTA3OjAwIgogICB4bXBNTTpEb2N1bWVudElEPSJhZG9iZTpkb2NpZDpwaG90b3Nob3A6ZTk5OWM2NWYtNDhhOS0wNjQyLWI2MTktZmJlYTExMmUxOGZiIgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5MzMyOWNhLWNkNjctMzY0Zi04MzU1LTY5N2ZmYzI0ZDdlZCIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjgyZjQwYmU3LTE0YzItZjc0Ni1hZmE1LWQxYmIxNzAyMjM4OCIKICAgZXhpZjpQaXhlbFhEaW1lbnNpb249IjEwIgogICBleGlmOlBpeGVsWURpbWVuc2lvbj0iMTAiCiAgIGV4aWY6Q29sb3JTcGFjZT0iMSI+CiAgIDxwaG90b3Nob3A6VGV4dExheWVycz4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgcGhvdG9zaG9wOkxheWVyTmFtZT0i7qSiIgogICAgICBwaG90b3Nob3A6TGF5ZXJUZXh0PSLupKIiLz4KICAgIDwvcmRmOlNlcT4KICAgPC9waG90b3Nob3A6VGV4dExheWVycz4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHhtcE1NOmFjdGlvbj0iY3JlYXRlZCIKICAgICAgeG1wTU06aW5zdGFuY2VJRD0ieG1wLmlpZDo4MmY0MGJlNy0xNGMyLWY3NDYtYWZhNS1kMWJiMTcwMjIzODgiCiAgICAgIHhtcE1NOnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE5IChXaW5kb3dzKSIKICAgICAgeG1wTU06d2hlbj0iMjAyMC0wMi0xN1QxMjo1NTozN1oiLz4KICAgICA8cmRmOmxpCiAgICAgIHhtcE1NOmFjdGlvbj0ic2F2ZWQiCiAgICAgIHhtcE1NOmNoYW5nZWQ9Ii8iCiAgICAgIHhtcE1NOmluc3RhbmNlSUQ9InhtcC5paWQ6NjkzMzI5Y2EtY2Q2Ny0zNjRmLTgzNTUtNjk3ZmZjMjRkN2VkIgogICAgICB4bXBNTTpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiCiAgICAgIHhtcE1NOndoZW49IjIwMjAtMDItMTdUMTI6NTU6MzdaIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InByb2R1Y2VkIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZmZpbml0eSBQaG90byAxLjEwLjEiCiAgICAgIHN0RXZ0OndoZW49IjIwMjEtMTAtMDVUMTQ6Mjc6MjQtMDc6MDAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KPD94cGFja2V0IGVuZD0iciI/PqiFCFwAAAGCaUNDUHNSR0IgSUVDNjE5NjYtMi4xAAAokXWRv0tCURTHP2lhmGFRQUODhDVZlELU0qD0C6pBDbJa9OWPQO3xnhHRGrQKBVFLv4b6C2oNmoOgKIJoC5qLWkpe56mgRJ7Luedzv/eew73ngiWcVjJ6/QBksjktOOF3zUcWXLZX7DTQQSu+qKKrM6HxMDXt64E6M971mbVqn/vXmpbjugJ1jcKjiqrlhCeFp9dzqsm7wu1KKrosfC7s0eSCwvemHivxm8nJEv+YrIWDAbC0CLuSVRyrYiWlZYTl5bgz6TWlfB/zJY54di4ksVu8C50gE/hxMcUYAYYYZETmIfrw0i8rauQPFPNnWZVcRWaVDTRWSJIih0fUNakel5gQPS4jzYbZ/7991RM+b6m6ww8NL4bx0QO2HSjkDeP72DAKJ2B9hqtsJX/1CIY/Rc9XNPchOLfg4rqixfbgchs6n9SoFi1KVnFLIgHvZ9AcgbZbsC+Welbe5/QRwpvyVTewfwC9ct659At2bGftHD0UJwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAHNJREFUGJWtkKEOwlAMRc+QM5AwQYJFoPjZCWb2YRPIaeRTLwfTLQs0UxzX3tumtxCog78UdVTbZmM8AmsdXIABeKH2ak221dDuamnUCjyA+WtbB0zAGXgT0ycSFk31kBky/moUeBLpbsl91wi6Nnbfs/g+7XOQq6ifjfkAAAAASUVORK5CYII=\");\n  --gfx-minBtn: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAGOmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDUgNzkuMTYzNDk5LCAyMDE4LzA4LzEzLTE2OjQwOjIyICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIiB4bWxuczpwaG90b3Nob3A9Imh0dHA6Ly9ucy5hZG9iZS5jb20vcGhvdG9zaG9wLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDIwLTAyLTE3VDEzOjAwOjMyWiIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAyMC0wMi0xN1QxMzowMDozMloiIHhtcDpNb2RpZnlEYXRlPSIyMDIwLTAyLTE3VDEzOjAwOjMyWiIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDo4NWQwZWRiMC1mZDAwLWI2NGYtOWVmYi1hMmI0NTg3MDVhOGEiIHhtcE1NOkRvY3VtZW50SUQ9ImFkb2JlOmRvY2lkOnBob3Rvc2hvcDphMzAwMWUxYS0yOTE5LWU0NDktYjk0Yy1jMjEyMjQ4YTlmOGEiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3ODdmNzk5Yy00YjExLWU1NGEtYjIwZC02ODYxN2VkOWM1ZTIiIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo3ODdmNzk5Yy00YjExLWU1NGEtYjIwZC02ODYxN2VkOWM1ZTIiIHN0RXZ0OndoZW49IjIwMjAtMDItMTdUMTM6MDA6MzJaIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjg1ZDBlZGIwLWZkMDAtYjY0Zi05ZWZiLWEyYjQ1ODcwNWE4YSIgc3RFdnQ6d2hlbj0iMjAyMC0wMi0xN1QxMzowMDozMloiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE5IChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPHBob3Rvc2hvcDpUZXh0TGF5ZXJzPiA8cmRmOkJhZz4gPHJkZjpsaSBwaG90b3Nob3A6TGF5ZXJOYW1lPSLupKEiIHBob3Rvc2hvcDpMYXllclRleHQ9Iu6koSIvPiA8L3JkZjpCYWc+IDwvcGhvdG9zaG9wOlRleHRMYXllcnM+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+FwvRXAAAABdJREFUGNNj/P//PwMxgHGIKPw/XDwDAOr1HuzlELLnAAAAAElFTkSuQmCC\");\n}\n\n#apple-music-video-container {\n  background: black;\n  position: absolute;\n  float: left;\n  display: none;\n  width: 100%;\n  height: 100%;\n  bottom: 0;\n  z-index: 100000;\n  &.mini {\n    width: 20%;\n    height: 20%;\n    right: 2vw;\n    bottom: 5vh;\n  }\n}\n\n#apple-music-video-container {\n  // AM Web Style Fullscreen Button\n  #player-fullscreen {\n    background-size: 50%;\n    background-position: center;\n    background-repeat: no-repeat;\n    filter: opacity(0.6);\n    // filter: drop-shadow(0px 0px 4px rgb(0 0 0 / 80%));\n    background-color: transparent;\n    border-radius: 10px;\n    transition: 0.2s ease-in-out filter;\n    bottom: 0;\n\n    &:hover {\n      filter: opacity(1);\n      transition: 0.2s ease-in-out filter;\n    }\n  }\n\n  // AM Web Style PiP Button\n  #player-pip {\n    background-color: transparent;\n    border-radius: 10px;\n    bottom: 0;\n    filter: opacity(0.6);\n    transition: 0.2s ease-in-out filter;\n\n    &.mini {\n      right: 0px;\n    }\n\n    &:hover {\n      filter: opacity(1);\n      transition: 0.2s ease-in-out filter;\n    }\n  }\n\n  .playback-info {\n    position: absolute;\n    width: 100%;\n    bottom: 0;\n    padding: 20px 40px;\n    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.5) 50%);\n\n    .song-artist {\n      font-size: 1.7rem;\n      font-weight: bold;\n    }\n\n    .song-name {\n      font-size: 1.2rem;\n      font-weight: bold;\n      color: rgb(255, 255, 255, 0.8);\n    }\n  }\n\n  input[type=\"range\"] {\n    align-self: center;\n    height: 4px;\n    border-radius: 0.5rem;\n    margin-inline: 10px;\n  }\n\n  .song-progress input[type=\"range\"] {\n    appearance: initial;\n\n    &::-webkit-slider-thumb {\n      box-shadow: 0px 0px 0px #000000;\n      border: 1px solid #39404d;\n      background: #fff;\n      height: 0.7rem;\n      width: 0.7rem;\n      border-radius: 50%;\n      cursor: pointer;\n      -webkit-appearance: none;\n    }\n  }\n}\n\n#apple-music-video-player {\n  position: absolute;\n  top: 50%;\n  width: 100%;\n  transform: translate(0, -50%);\n  height: 100%;\n}\n\n#app.twopanel #apple-music-video-container {\n  top: 0;\n  bottom: unset;\n}\n\n.inactive {\n  opacity: 0;\n}\n\n#apple-music-video-player-controls {\n  position: absolute;\n  z-index: 100001;\n  float: left;\n  width: 100%;\n  height: 100%;\n\n  .playback-info {\n    .song-progress {\n      display: flex;\n    }\n\n    .app-chrome-item.display--large {\n      position: relative;\n      display: flex;\n      flex-direction: row;\n      flex-wrap: nowrap;\n      align-items: center;\n\n      .playback-button {\n        position: absolute;\n        top: 50%;\n        left: 50%;\n        transform: translate(-50%, -50%);\n        padding: 3px;\n      }\n    }\n\n    .song-artist-album {\n      font-weight: 400;\n      font-size: 12px;\n      text-align: center;\n      /*height       : 1.2em;\n      line-height    : 1.2em;*/\n      z-index: 1;\n      align-items: center;\n      justify-content: center;\n      width: 80%;\n      max-width: 340px;\n      overflow: hidden;\n\n      .song-artist-album-content {\n        font-weight: 400;\n        font-size: 12px;\n        text-align: center;\n        width: 100%;\n\n        &.song-artist-normal {\n          height: inherit;\n        }\n      }\n\n      &.song-artist-marquee {\n        > marquee {\n          margin-bottom: -3px;\n        }\n      }\n    }\n  }\n}\n\n#apple-music-video-player-controls #player-exit {\n  position: absolute;\n  z-index: 100001;\n  float: left;\n  width: 100%;\n  margin-left: 10px;\n  margin-right: 10px;\n  margin-top: 10px;\n  margin-bottom: 10px;\n  cursor: pointer;\n}\n\n#apple-music-video-player-controls #player-pip {\n  position: absolute;\n  z-index: 100001;\n  width: 32px;\n  height: 32px;\n  margin: 10px;\n  right: 50px;\n  border-radius: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  cursor: pointer;\n}\n\n#apple-music-video-player-controls #player-pip > svg {\n  width: 50%;\n}\n\n#apple-music-video-player-controls #player-fullscreen {\n  position: absolute;\n  z-index: 100001;\n  width: 32px;\n  height: 32px;\n  margin: 10px;\n  right: 0px;\n  border-radius: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  cursor: pointer;\n}\n\n#apple-music-video-player-controls #player-fullscreen > svg {\n  width: 70%;\n}\n\n#apple-music-video-player-controls:hover {\n  opacity: 1;\n}\n\nimg[src=\"\"] {\n  text-indent: -10000px;\n}\n\ndiv#captions {\n  font-size: 1.2rem;\n  position: absolute;\n  top: 85%;\n  text-align: center;\n  width: auto;\n  align-self: center;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  background: rgba(0, 0, 0, 0.6);\n  color: yellow;\n  white-space: pre-line;\n  font-family: \"Inter\", \"Noto Sans JP\", \"Source Han Sans SC\", \"Source Han Sans HK\", \"Source Han Sans SC\", \"Source Han Sans HK\", \"Noto Sans SC\", \"Noto Sans TC\", \"Noto Sans HK\", \"Noto Sans KR\", sans-serif;\n}\n\n[v-cloak] {\n  display: none !important;\n}\n\n.item-navigate:hover {\n  text-decoration: underline;\n  cursor: pointer;\n}\n\n.title-browse-sp {\n  width: 100%;\n  text-align: left;\n  margin-bottom: 2px;\n}\n\n.bold {\n  font-weight: bold;\n}\n\n.semibold {\n  font-weight: 500;\n}\n\n.madeforyou-body {\n  margin-top: 15px;\n}\n\n.albums-square-container {\n  text-align: center;\n}\n\nbody.no-gpu {\n  --ciderShadow-Generic: var(--mediaItemShadow);\n  --mediaItemShadow-Shadow: var(--mediaItemShadow);\n  --mediaItemShadow-ShadowSubtle: var(--mediaItemShadow);\n\n  .bg-artwork-container {\n    display: none;\n    animation: none !important;\n\n    .bg-artwork {\n      animation: none !important;\n    }\n  }\n\n  .floating-header {\n    background: black;\n    backdrop-filter: unset;\n  }\n\n  .artworkContainer {\n    animation: unset !important;\n    opacity: 0.7;\n  }\n\n  .info-rect-card {\n    &:before {\n      display: none;\n    }\n  }\n\n  .menu-panel .menu-panel-body {\n    background: rgb(30 30 30);\n    backdrop-filter: unset;\n  }\n\n  #navigation-bar {\n    backdrop-filter: unset;\n    mix-blend-mode: unset;\n    background: rgb(0 0 0);\n  }\n\n  .addtoplaylist-panel {\n    .modal-window {\n      background: rgb(18 18 18);\n      backdrop-filter: unset;\n    }\n  }\n\n  .app-drawer {\n    backdrop-filter: unset;\n    mix-blend-mode: unset;\n    background: #1c1c1c;\n    transition: unset;\n  }\n\n  .wpfade-enter-active,\n  .wpfade-leave-active {\n    transition: opacity 0s var(--appleEase);\n  }\n\n  .wpfade-enter,\n  .wpfade-leave-to {\n    opacity: 0;\n  }\n\n  .drawertransition-enter-active,\n  .drawertransition-leave-active {\n    transition: right 0s var(--appleEase);\n  }\n\n  .drawertransition-enter,\n  .drawertransition-leave-to {\n    right: -300px;\n  }\n\n  .lyric-line:hover::after {\n    display: none;\n  }\n}\n\n.qrimg {\n  width: -webkit-fill-available;\n  max-block-size: -webkit-fill-available;\n  object-fit: contain;\n  overflow-x: hidden;\n  overflow-y: hidden;\n}\n\n.moreinfo-modal {\n  .modal-window {\n    height: max-content !important;\n\n    .modal-content {\n      height: max-content !important;\n      padding-block: 25px;\n    }\n  }\n}\n\n.equalizer-panel {\n  .modal-window {\n    height: 330px;\n    max-height: 330px;\n    width: 740px;\n    max-width: 800px;\n    overflow: hidden;\n\n    .info-header {\n      padding-left: 12px;\n    }\n\n    .visual-container {\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      overflow: hidden;\n    }\n\n    .modal-header {\n      padding: 16px;\n      position: relative;\n      overflow: hidden;\n\n      .modal-title {\n        text-align: center;\n      }\n\n      .close-btn {\n        .menu-panel.menu-header-text.close-btn;\n      }\n    }\n\n    .modal-content {\n      display: block;\n\n      .inputs-container {\n        margin-left: 8px;\n      }\n\n      .input-container {\n        display: inline-grid;\n        width: 54px;\n        justify-items: center;\n        font-size: 0.7em;\n      }\n\n      .input-container.mini {\n        display: inline-grid;\n        width: 43px;\n        justify-items: center;\n        font-size: 0.7em;\n      }\n\n      .freq-header {\n        margin-bottom: 2px;\n      }\n\n      .reset-button {\n        width: 50%;\n        margin-left: 25%;\n        text-align: center;\n      }\n\n      input.eq-slider {\n        -webkit-appearance: slider-vertical;\n        width: 5%;\n      }\n\n      input[type=\"number\"] {\n        padding: unset;\n        width: 55px;\n      }\n\n      .header input.eq-slider {\n        -webkit-appearance: slider-vertical;\n        width: 5%;\n        opacity: 0;\n      }\n    }\n\n    .modal-lowercontent {\n      padding: 16px;\n      background-color: var(--modalBackground);\n    }\n  }\n}\n\nbody[platform=\"darwin\"] {\n  #window-controls-container {\n    display: none;\n  }\n\n  .app-chrome .app-chrome-item > .app-mainmenu {\n    opacity: 0;\n    width: 52px;\n    pointer-events: none;\n    -webkit-app-region: drag;\n  }\n}\n\n.percent {\n  display: inline-block;\n  position: relative;\n}\n\n.percent::after {\n  position: relative;\n  right: 2em;\n  transition: all 0.05s ease-in-out;\n}\n\n.percent:hover::after,\n.percent:focus-within::after {\n  right: 3.5em;\n}\n\n.percent::after {\n  content: \"%\";\n}\n\n.playbackrate-text {\n  align-items: end;\n  margin-right: 5px;\n}\n\n.modal .close {\n  color: transparent;\n}\n\n.spatialproperties-panel.modal-fullscreen {\n  flex-direction: column;\n}\n\n.cursor {\n  background: rgb(255 255 255 / 50%);\n  width: 16px;\n  height: 16px;\n  position: fixed;\n  z-index: 9999999999;\n  pointer-events: none;\n  border-radius: 100%;\n  box-shadow: 0px 0px 0px 2px rgb(200 200 200 / 100%);\n  top: 0;\n  left: 0;\n  display: none;\n}\n\n.keybinds-page {\n  .md-option-header {\n    padding: 10px 0px;\n    border-bottom: unset;\n    border-top: unset;\n    font-weight: 600;\n    background: rgba(255, 255, 255, 0);\n    font-size: 2em;\n  }\n\n  .md-option-header-sub {\n    padding: 15px 10px;\n    border-bottom: unset;\n    border-top: unset;\n    background: rgba(255, 255, 255, 0);\n    font-weight: 600;\n    font-size: 1.7em;\n  }\n\n  .md-option-line {\n    padding: 15px 20px;\n    font-size: 0.9em;\n  }\n}\n\n.content-inner.keybinds-page {\n  top: var(--navigationBarHeight);\n  padding: 15px;\n}\n\n@import url(\"less/macos.less\");\n@import url(\"less/linux.less\");\n@import url(\"less/compact.less\");\n@import url(\"less/directives.less\");\n@import url(\"less/macosemu.less\");\n"
  },
  {
    "path": "src/renderer/sw.js",
    "content": "if (!self.define) {\n  let e,\n    i = {};\n  const s = (s, r) => (\n    (s = new URL(s + \".js\", r).href),\n    i[s] ||\n      new Promise((i) => {\n        if (\"document\" in self) {\n          const e = document.createElement(\"script\");\n          (e.src = s), (e.onload = i), document.head.appendChild(e);\n        } else (e = s), importScripts(s), i();\n      }).then(() => {\n        let e = i[s];\n        if (!e) throw new Error(`Module ${s} didn’t register its module`);\n        return e;\n      })\n  );\n  self.define = (r, c) => {\n    const n = e || (\"document\" in self ? document.currentScript.src : \"\") || location.href;\n    if (i[n]) return;\n    let o = {};\n    const t = (e) => s(e, n),\n      a = { module: { uri: n }, exports: o, require: t };\n    i[n] = Promise.all(r.map((e) => a[e] || t(e))).then((e) => (c(...e), o));\n  };\n}\ndefine([\"./workbox-962786f2\"], function (e) {\n  \"use strict\";\n  self.addEventListener(\"message\", (e) => {\n    e.data && \"SKIP_WAITING\" === e.data.type && self.skipWaiting();\n  }),\n    e.precacheAndRoute(\n      [\n        {\n          url: \"ameframework.css\",\n          revision: \"4bcc8646bb5742638fad52b94e231601\",\n        },\n        { url: \"apple-hls.js\", revision: \"2b74055662676b0fcc2d4a4bf994a9dc\" },\n        { url: \"hlscider.js\", revision: \"cf7f512e83e32694f2c94f904714fe4c\" },\n        { url: \"index_old.html\", revision: \"c21f3e9c5b015599d3ab07639f64a7a8\" },\n        { url: \"index.js\", revision: \"8591a69fc9c975a063eb264b7447f173\" },\n        { url: \"less.js\", revision: \"b6e574e4d680686786a28e7e71a17bbc\" },\n        { url: \"musickit.js\", revision: \"211d80891c3336c1795cb83df58d4b63\" },\n        {\n          url: \"sortable.min.js\",\n          revision: \"5cbc31ebec32adf60e27b76418e79d93\",\n        },\n        { url: \"style-old.css\", revision: \"aea9ea49df13f2deee42b68654aeea06\" },\n        { url: \"todo.js\", revision: \"18d49fabcb96de8bd11455877d8eacb6\" },\n        {\n          url: \"vue-observe-visibility.min.js\",\n          revision: \"5a52e761f6aa71b4f65a7b458f698b95\",\n        },\n        { url: \"vue.js\", revision: \"0a9a4681294d8c5f476687eea6e74842\" },\n        {\n          url: \"vuedraggable.umd.min.js\",\n          revision: \"9a84fec5263bb510cee88e1c3b9583cc\",\n        },\n      ],\n      {\n        ignoreURLParametersMatching: [/^utm_/, /^fbclid$/, /^X-Amz-Algorithm/, /^X-Amz-Date/, /^X-Amz-SignedHeaders/, /^X-Amz-Expires/, /^X-Amz-Credential/, /^X-Amz-Signature/],\n      },\n    ),\n    e.registerRoute(/\\.(?:png|jpg|jpeg|svg|webp)$/, new e.CacheFirst({ cacheName: \"imageinternet\", plugins: [] }), \"GET\"),\n    e.registerRoute(/https:\\/\\/is[0-9]-ssl\\.mzstatic\\.com\\/image+/, new e.CacheFirst(), \"GET\"),\n    e.registerRoute(/^https:\\/\\/store-\\d{3}\\.blobstore\\.apple\\.com\\/.{65}\\/image+/, new e.CacheFirst(), \"GET\");\n});\n//# sourceMappingURL=sw.js.map\n"
  },
  {
    "path": "src/renderer/themes/WIP.md",
    "content": "# Themes (WIP)\n\n## Making a theme\n* If one does not already exist, create a new theme directory in the user data folder.\n  * **Windows:** `%appdata%/Cider/themes`\n  * **Mac:** `~/Library/Application Support/Cider/themes`\n  * **Linux:** `~/.config/Cider/themes`\n* Create a `theme.less` file with the name of the theme.\n* In Cider, select the theme in the settings.\n* To enable hot reloading for the theme, open the DevTools and enter `less.watch()` in the console.\n\n## Resources\n* The default styles.less can be found in: [src/renderer/style.less](https://github.com/ciderapp/Cider/tree/main/src/renderer/style.less)\n* [Less.js documentation](https://lesscss.org/)"
  },
  {
    "path": "src/renderer/themes/compactui.less",
    "content": ""
  },
  {
    "path": "src/renderer/themes/dark.less",
    "content": "#app {\n  --color1: #111;\n}\n"
  },
  {
    "path": "src/renderer/themes/default.less",
    "content": "// Default theme\n"
  },
  {
    "path": "src/renderer/themes/grain.less",
    "content": "body.notransparency::before {\n  display: block;\n}\n"
  },
  {
    "path": "src/renderer/themes/inline_drawer.less",
    "content": "&:not(.modular-fs) {\n  .app-drawer {\n    border-radius: 0px;\n    top: 0;\n    right: 0;\n    height: 100%;\n    box-shadow: unset;\n    border-left: 1px solid var(--color2);\n    background: var(--color1);\n    margin-right: 0px;\n    position: relative;\n  }\n\n  .drawertransition-enter-active,\n  .drawertransition-leave-active {\n    transition:\n      margin 0.25s var(--appleEase),\n      opacity 0.25s var(--appleEase);\n  }\n\n  .drawertransition-enter,\n  .drawertransition-leave-to {\n    margin-right: -300px;\n  }\n\n  @media screen and (max-width: 1120px) {\n    .app-drawer {\n      margin-right: 0px;\n      position: absolute;\n    }\n\n    .drawertransition-enter-active,\n    .drawertransition-leave-active {\n      transition:\n        right 0.25s var(--appleEase),\n        opacity 0.25s var(--appleEase);\n    }\n\n    .drawertransition-enter,\n    .drawertransition-leave-to {\n      right: -300px;\n    }\n  }\n}\n"
  },
  {
    "path": "src/renderer/themes/reduce_visuals.less",
    "content": "body {\n  --ciderShadow-Generic: var(--mediaItemShadow);\n  --mediaItemShadow-Shadow: var(--mediaItemShadow);\n  --mediaItemShadow-ShadowSubtle: var(--mediaItemShadow);\n}\n\n.bg-artwork-container {\n  display: none;\n  animation: none !important;\n\n  .bg-artwork {\n    animation: none !important;\n  }\n}\n\n.app-chrome:not(.chrome-bottom) {\n  backdrop-filter: unset;\n  background-color: var(--baseColor);\n}\n\n.menu-panel .menu-panel-body {\n  background: rgb(30 30 30);\n}\n.menu-panel .menu-panel-body .menu-option::before {\n  transition: unset !important;\n}\n\n#app.twopanel .app-chrome:not(.chrome-bottom) .app-chrome--center .top-nav-group .app-sidebar-item:before {\n  transition: unset !important;\n}\n\n.playback-button:before,\n.playback-button--small:before {\n  transition: unset !important;\n}\n\n.floating-header {\n  backdrop-filter: unset !important;\n  background: rgb(0 0 0 / 80%) !important;\n}\n\n.replaycard-enter-active,\n.replaycard-leave-active {\n  transition: unset;\n}\n\n.replaycard-enter,\n.replaycard-leave-to {\n  opacity: 0;\n  transform: translateY(20px);\n}\n\n.modal-enter-active,\n.modal-leave-active {\n  transition: unset;\n}\n\n.modal-enter,\n.modal-leave-to {\n  opacity: 0;\n  transform: scale(1.1);\n}\n\n.wpfade-enter-active,\n.wpfade-leave-active {\n  transition: opacity 0.1s var(--appleEase);\n}\n\n.wpfade-enter,\n.wpfade-leave-to {\n  opacity: 0;\n}\n\n.wpfade_transform-enter-active,\n.wpfade_transform-leave-active {\n  transition: unset;\n  will-change: unset;\n}\n\n.wpfade_transform-enter {\n  opacity: 0;\n  transform: unset;\n  will-change: unset;\n}\n\n.wpfade_transform-leave-to {\n  opacity: 0;\n  transform: unset;\n  will-change: unset;\n}\n\n.wpfade_transform_backwards-enter-active,\n.wpfade_transform_backwards-leave-active {\n  transition: unset;\n}\n\n.wpfade_transform_backwards-enter {\n  opacity: 0;\n  transform: unset;\n  will-change: unset;\n}\n\n.wpfade_transform_backwards-leave-to {\n  opacity: 0;\n  transform: unset;\n  will-change: unset;\n}\n\n.fabfade-enter-active,\n.fabfade-leave-active {\n  transition: unset;\n}\n\n.fabfade-enter,\n.fabfade-leave-to {\n  opacity: 0;\n  transform: scale(0.5);\n}\n\n.fsModeSwitch-enter-active,\n.fsModeSwitch-leave-active {\n  transition: unset;\n}\n\n.fsModeSwitch-enter,\n.fsModeSwitch-leave-to {\n  transform: scale(1.1);\n  opacity: 0;\n}\n\n.drawertransition-enter-active,\n.drawertransition-leave-active {\n  transition: unset;\n}\n\n.drawertransition-enter,\n.drawertransition-leave-to {\n  right: -300px;\n}\n"
  },
  {
    "path": "src/renderer/themes/sweetener.less",
    "content": "@panelColorsFallback: rgb(30 30 30);\n@panelColors: rgb(30 30 30 / 45%);\n\n.menu-panel {\n  .menu-panel-body {\n    background-color: @panelColors;\n    backdrop-filter: blur(32px) saturate(180%);\n\n    &.menu-panel-body-down {\n      animation: menuInDown 0.1s var(--appleEase);\n    }\n\n    &.menu-panel-body-up {\n      animation: menuInUp 0.1s var(--appleEase);\n    }\n  }\n\n  @keyframes menuInUp {\n    0% {\n      opacity: 0;\n      transform: translateY(-10px) translate3d(0, 0, 0);\n      background: @panelColorsFallback;\n    }\n\n    100% {\n      opacity: 1;\n      transform: translateY(0);\n      background: @panelColors;\n    }\n  }\n\n  @keyframes menuInDown {\n    0% {\n      opacity: 0;\n      transform: translateY(10px) translate3d(0, 0, 0);\n      background: @panelColorsFallback;\n    }\n\n    100% {\n      opacity: 1;\n      transform: translateY(0);\n      background: @panelColors;\n    }\n  }\n}\n\n.cd-mediaitem-square {\n  --transition: width 1s, height 1s;\n  transition: var(--transition);\n  .artwork {\n    transition: var(--transition);\n  }\n}\n\n.cd-mediaitem-square:not(.mediaitem-card) {\n  transition: transform 0.2s var(--appleEase);\n  transition-delay: 0.1s;\n\n  .artwork-container {\n  }\n\n  .info-rect {\n  }\n\n  .artwork-container,\n  .info-rect {\n    transition: transform 0.22s var(--appleEase);\n    transition-delay: 0.05s;\n  }\n\n  .artwork-container {\n    transform: scale(0.962) translateZ(0);\n    transition: transform 0.1s var(--appleEase);\n    transition-delay: 0s;\n    transform-origin: center;\n  }\n\n  &:hover {\n    .artwork-container {\n      transform: scale(1);\n      transition: transform 0.1s var(--appleEase);\n      transition-delay: 0s;\n      transform-origin: center;\n    }\n\n    .info-rect {\n      z-index: 1;\n      transition: transform 0.1s var(--appleEase);\n      transition-delay: 0s;\n      transform: translateY(8px) translate3d(0, 0, 0);\n    }\n  }\n\n  &:active {\n  }\n}\n\n.wpfade_transform-enter-active,\n.wpfade_transform-leave-active {\n  --transitionTime: 0.2s;\n  transition:\n    opacity var(--transitionTime) var(--appleEase),\n    transform var(--transitionTime) var(--appleEase);\n  will-change: opacity, transform;\n}\n\n.wpfade_transform-enter {\n  opacity: 0;\n  transform: translateX(50%) translate3d(0, 0, 0);\n  will-change: opacity, transform;\n}\n.wpfade_transform-leave-to {\n  opacity: 0;\n  transform: translateX(-50%) translate3d(0, 0, 0);\n  will-change: opacity, transform;\n}\n\n.wpfade_transform_backwards-enter-active,\n.wpfade_transform_backwards-leave-active {\n  --transitionTime: 0.2s;\n  transition:\n    opacity var(--transitionTime) var(--appleEase),\n    transform var(--transitionTime) var(--appleEase);\n}\n\n.wpfade_transform_backwards-enter {\n  opacity: 0;\n  transform: translateX(-50%) translate3d(0, 0, 0);\n  will-change: opacity, transform;\n}\n.wpfade_transform_backwards-leave-to {\n  opacity: 0;\n  transform: translateX(50%) translate3d(0, 0, 0);\n  will-change: opacity, transform;\n}\n"
  },
  {
    "path": "src/renderer/todo.js",
    "content": "// Apple Music Listen Now Page\n// URL : https://amp-api.music.apple.com/v1/me/recommendations?timezone=+00:00\n//  &with=friendsMix,library,social&art[social-profiles:url]=c\n//  &name=listen-now&art[url]=c,f&omit[resource]=autos\n//  &relate[editorial-items]=contents\n//  &extend=editorialCard,editorialVideo\n//  &extend[albums]=artistUrl\n//  &extend[library-albums]=artistUrl\n//  &extend[playlists]=artistNames,editorialArtwork\n//  &extend[library-playlists]=artistNames,editorialArtwork\n//  &extend[social-profiles]=topGenreNames&include[albums]=artists\n//  &include[songs]=artists&include[music-videos]=artists\n//  &fields[albums]=artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url\n//  &fields[artists]=name,url&extend[stations]=airDate,supportsAirTimeUpdates&meta[stations]=inflectionPoints\n//  &types=artists,albums,editorial-items,library-albums,library-playlists,music-movies,music-videos,playlists,stations,uploaded-audios,uploaded-videos,activities,apple-curators,curators,tv-shows,social-profiles,social-upsells\n//  &l=en-gb&platform=web\n\nawait app.mk.api.personalRecommendations(\n  \"\",\n  {\n    name: \"listen-now\",\n    with: \"friendsMix,library,social\",\n    \"art[social-profiles:url]\": \"c\",\n    \"art[url]\": \"c,f\",\n    \"omit[resource]\": \"autos\",\n    \"relate[editorial-items]\": \"contents\",\n    extend: [\"editorialCard\", \"editorialVideo\"],\n    \"extend[albums]\": [\"artistUrl\"],\n    \"extend[library-albums]\": [\"artistUrl\"],\n    \"extend[playlists]\": [\"artistNames\", \"editorialArtwork\"],\n    \"extend[library-playlists]\": [\"artistNames\", \"editorialArtwork\"],\n    \"extend[social-profiles]\": \"topGenreNames\",\n    \"include[albums]\": \"artists\",\n    \"include[songs]\": \"artists\",\n    \"include[music-videos]\": \"artists\",\n    \"fields[albums]\": [\"artistName\", \"artistUrl\", \"artwork\", \"contentRating\", \"editorialArtwork\", \"editorialVideo\", \"name\", \"playParams\", \"releaseDate\", \"url\"],\n    \"fields[artists]\": [\"name\", \"url\"],\n    \"extend[stations]\": [\"airDate\", \"supportsAirTimeUpdates\"],\n    \"meta[stations]\": \"inflectionPoints\",\n    types: \"artists,albums,editorial-items,library-albums,library-playlists,music-movies,music-videos,playlists,stations,uploaded-audios,uploaded-videos,activities,apple-curators,curators,tv-shows,social-profiles,social-upsells\",\n    l: \"en-gb\",\n    platform: \"web\",\n  },\n  {\n    includeResponseMeta: !0,\n    reload: !0,\n  },\n);\n\n// Browse page\nawait app.mk.api.groupings(\"\", {\n  platform: \"web\",\n  name: \"music\",\n  l: \"en-gb\",\n  \"omit[resource:artists]\": \"relationships\",\n  \"include[albums]\": \"artists\",\n  \"include[songs]\": \"artists\",\n  \"include[music-videos]\": \"artists\",\n  extend: \"editorialArtwork,artistUrl\",\n  \"fields[artists]\": \"name,url,artwork,editorialArtwork,genreNames,editorialNotes\",\n  \"art[url]\": \"f\",\n});\n\n// Radio page\nawait app.mk.api.recentRadioStations(\"\", {\n  l: \"en-gb\",\n  platform: \"web\",\n  \"art[url]\": \"f\",\n});\n\n// Recently Added\nawait app.mk.api.library.recentlyAdded(\n  {\n    platform: \"web\",\n    include: {\n      \"library-albums\": [\"artists\"],\n      \"library-artists\": [\"catalog\"],\n    },\n    fields: {\n      artists: [\"url\"],\n      albums: \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url\",\n    },\n    includeOnly: [\"catalog\", \"artists\"],\n    limit: 25,\n  },\n  {\n    reload: !0,\n    includePagination: !0,\n  },\n);\n\n// Songs\nawait app.mk.api.library.songs({ limit: 100 }).then((data) => {\n  console.log(data);\n});\n\n// Artists\nawait app.mk.api.library.artists({ limit: 100 }).then((data) => {\n  console.log(data);\n});\n\n// Artists\nawait app.mk.api.library.albums({ limit: 100 }).then((data) => {\n  console.log(data);\n});\n\n// Albums\n// does not like limit = 100 for some reason\nawait app.mk.api.library.albums({ limit: 50 }).then((data) => {\n  console.log(data);\n});\n\n// Made For You\napp.mk.api.recommendations(\"\", { extend: \"editorialArtwork,artistUrl\" });\n\n// Library with library length\nawait app.mk.api.library.songs(\"\", { limit: 100 }, { includeResponseMeta: !0 }).then((data) => {\n  console.log(data);\n});\n\n// Artist View Top Songs\napp.mk.api.artistView(\"325096253\", \"top-songs\", {}, { view: \"top-songs\", includeResponseMeta: !0 });\n\n// Artist Page Data\napp\n  .mkapi(\n    \"artists\",\n    false,\n    \"412778295\",\n    {\n      views: \"featured-release,full-albums,appears-on-albums,featured-albums,featured-on-albums,singles,compilation-albums,live-albums,latest-release,top-music-videos,similar-artists,top-songs,playlists,more-to-hear,more-to-see\",\n      extend: \"artistBio,bornOrFormed,editorialArtwork,editorialVideo,isGroup,origin,hero\",\n      \"extend[playlists]\": \"trackCount\",\n      \"omit[resource:songs]\": \"relationships\",\n      \"fields[albums]\": \"artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url,trackCount\",\n      \"limit[artists:top-songs]\": 20,\n      \"art[url]\": \"f\",\n    },\n    { includeResponseMeta: !0 },\n  )\n  .then((data) => {\n    console.log(data);\n  });\n\n// download entire library\nvar library = [];\nvar downloaded = null;\nfunction downloadChunk() {\n  if (downloaded == null) {\n    app.mk.api.library.songs(\"\", { limit: 100 }, { includeResponseMeta: !0 }).then((response) => {\n      processChunk(response);\n    });\n  } else {\n    downloaded.next(\"\", { limit: 100 }, { includeResponseMeta: !0 }).then((response) => {\n      processChunk(response);\n    });\n  }\n}\nfunction processChunk(response) {\n  downloaded = response;\n  library = library.concat(downloaded.data);\n  if (downloaded.meta.total > library.length) {\n    console.log(`downloading next chunk - ${library.length} songs so far`);\n    downloadChunk();\n  } else {\n    console.log(library);\n  }\n}\n\n//Some Available Functions from MusicKit\n// recentPlayed() -> recently played songs ?\n\n// create Artist / Song/ Album stations:\napp.mk.setStationQueue({ artist: \"1258279972\" });\napp.mk.setStationQueue({ song: \"1437308307\" }); // yes the song id here can be the albumId, but just keep using the song:\n\n// Sorting Playlists, send an array of tracks in the format below\n// playlist must be fully recursively downloaded first before sorting\n\napp.mk.api.library.putPlaylistTracklisting(app.showingPlaylist.attributes.playParams.id, [\n  {\n    id: relationships.tracks.data[X].id,\n    type: relationships.tracks.data[X].type,\n  },\n  {\n    id: relationships.tracks.data[X].id,\n    type: relationships.tracks.data[X].type,\n  },\n  {\n    id: relationships.tracks.data[X].id,\n    type: relationships.tracks.data[X].type,\n  },\n]);\n"
  },
  {
    "path": "src/renderer/views/app/app-navigation.ejs",
    "content": "<div\n  class=\"app-navigation\"\n  v-cloak>\n  <transition name=\"wpfade\">\n    <div\n      class=\"usermenu-container\"\n      v-if=\"chrome.menuOpened\">\n      <div class=\"usermenu-body\">\n        <button\n          class=\"app-sidebar-button\"\n          style=\"width: 100%\"\n          @click=\"appRoute('apple-account-settings')\">\n          <img\n            class=\"sidebar-user-icon\"\n            loading=\"lazy\"\n            :src=\"getMediaItemArtwork(chrome.hideUserInfo ? './assets/logocut.png' : (chrome.userinfo.attributes['artwork'] ? chrome.userinfo.attributes['artwork']['url'] : ''), 26)\" />\n\n          <div\n            class=\"sidebar-user-text\"\n            v-if=\"!chrome.hideUserInfo\">\n            <template v-if=\"chrome.userinfo.id || mk.isAuthorized\">\n              <div class=\"fullname text-overflow-elipsis\">\n                {{ chrome.userinfo != null && chrome.userinfo.attributes != null ? chrome.userinfo.attributes.name ?? \"\" : \"\" }}\n              </div>\n              <div class=\"handle-text text-overflow-elipsis\">\n                {{ chrome.userinfo != null && chrome.userinfo.attributes != null ? chrome.userinfo.attributes.handle ?? \"\" : \"\" }}\n              </div>\n            </template>\n            <template v-else>\n              <div @click=\"mk.authorize()\">\n                {{ $root.getLz(\"term.login\") }}\n              </div>\n            </template>\n          </div>\n          <div\n            class=\"sidebar-user-text\"\n            v-else>\n            {{ $root.getLz(\"app.name\") }}\n          </div>\n        </button>\n        <!-- Use 20px SVG for usermenu icon -->\n        <button\n          class=\"usermenu-item\"\n          v-if=\"cfg.general.privateEnabled\"\n          @click=\"cfg.general.privateEnabled = false\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/x.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.disablePrivateSession\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"appRoute('remote-pair')\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/smartphone.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"action.showWebRemoteQR\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"modals.castMenu = true\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/cast.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.cast\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"modals.audioSettings = true\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/headphones.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.audioSettings\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          v-if=\"pluginInstalled\"\n          @click=\"modals.pluginMenu = true\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/grid.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.plugin\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"appRoute('about')\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/info.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.about\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"modals.settings = true\">\n          <span class=\"usermenu-item-icon\"> <%- include(\"../svg/settings.svg\") %> </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.settings\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          v-for=\"entry in $root.pluginMenuTopEntries\"\n          @click=\"entry.onClick()\">\n          <span\n            class=\"usermenu-item-icon\"\n            style=\"right: 2.5px\">\n            <%- include(\"../svg/grid.svg\") %>\n          </span>\n          <span class=\"usermenu-item-name\">{{ entry.name }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"unauthorize()\">\n          <span\n            class=\"usermenu-item-icon\"\n            style=\"right: 2.5px\">\n            <%- include(\"../svg/log-out.svg\") %>\n          </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.logout\") }}</span>\n        </button>\n        <button\n          class=\"usermenu-item\"\n          @click=\"quit()\">\n          <span\n            class=\"usermenu-item-icon\"\n            style=\"right: 2.5px\">\n            <%- include(\"../svg/x.svg\") %>\n          </span>\n          <span class=\"usermenu-item-name\">{{ $root.getLz(\"term.quit\") }}</span>\n        </button>\n        <button\n          v-if=\"!chrome.noC2Upgrade\"\n          class=\"usermenu-item\"\n          @click=\"c2offer()\">\n          <span\n            class=\"usermenu-item-icon\"\n            style=\"right: 1.5px\">\n            <img\n              class=\"sidebar-user-icon\"\n              loading=\"lazy\"\n              style=\"height: 16px; width: 16px\"\n              src=\"./assets/logocut.png\" />\n          </span>\n          <span class=\"usermenu-item-name\">Cider 2 Upgrade</span>\n        </button>\n      </div>\n    </div>\n  </transition>\n  <transition name=\"sidebartransition\">\n    <cider-app-sidebar v-if=\"!chrome.sidebarCollapsed\"></cider-app-sidebar>\n  </transition>\n  <app-content-area></app-content-area>\n  <transition name=\"drawertransition\">\n    <div\n      class=\"app-drawer\"\n      v-if=\"drawer.open && drawer.panel == 'lyrics' && lyrics && lyrics != [] && lyrics.length > 0\">\n      <div class=\"bgArtworkMaterial\">\n        <div class=\"bg-artwork-container\">\n          <img\n            v-if=\"(cfg.visual.bg_artwork_rotation && animateBackground)\"\n            class=\"bg-artwork a\"\n            :src=\"$store.state.artwork.playerLCD\" />\n          <img\n            v-if=\"(cfg.visual.bg_artwork_rotation && animateBackground)\"\n            class=\"bg-artwork b\"\n            :src=\"$store.state.artwork.playerLCD\" />\n          <img\n            v-if=\"!(cfg.visual.bg_artwork_rotation && animateBackground)\"\n            class=\"bg-artwork no-animation\"\n            :src=\"$store.state.artwork.playerLCD\" />\n        </div>\n      </div>\n      <lyrics-view\n        v-if=\"drawer.panel == 'lyrics'\"\n        :time=\"mk.currentPlaybackTime - lyricOffset\"\n        :lyrics=\"lyrics\"\n        :richlyrics=\"richlyrics\"></lyrics-view>\n      <div\n        v-if=\"drawer.panel == 'lyrics'\"\n        class=\"lyric-footer\">\n        <button\n          class=\"md-btn\"\n          @click=\"modularUITest(!fullscreenLyrics)\">\n          {{ fullscreenLyrics ? $root.getLz(\"term.defaultView\") : $root.getLz(\"term.fullscreenView\") }}\n        </button>\n      </div>\n    </div>\n  </transition>\n  <transition name=\"drawertransition\">\n    <div\n      class=\"app-drawer\"\n      v-if=\"drawer.open && drawer.panel == 'queue'\">\n      <cider-queue\n        ref=\"queue\"\n        v-if=\"drawer.panel == 'queue'\"></cider-queue>\n    </div>\n  </transition>\n</div>\n"
  },
  {
    "path": "src/renderer/views/app/chrome-bottom.ejs",
    "content": "<div class=\"app-chrome chrome-bottom\" v-if=\"getThemeDirective('windowLayout') == 'twopanel'\"\n     :style=\"{'display': chrome.topChromeVisible ? '' : 'none'}\">\n    <div class=\"app-chrome--left\">\n        <div class=\"app-chrome-item playback-controls\">\n            <template v-if=\"mkReady()\">\n                <div class=\"app-playback-controls\" @mouseover=\"chrome.progresshover = true\"\n                     @mouseleave=\"chrome.progresshover = false\" @contextmenu=\"nowPlayingContextMenu\">\n                    <div v-if=\"cfg.visual.artworkDisplayLayout == 'default'\" @click.stop=\"switchArtworkDisplayLayout()\" class=\"artwork\" id=\"artworkLCD\">\n                        <mediaitem-artwork :url=\"$root.currentArtUrl\"></mediaitem-artwork>\n                        <b-popover custom-class=\"mediainfo-popover\" target=\"artworkLCD\" triggers=\"hover\" placement=\"right\">\n                          <div class=\"content\">\n                              <div class=\"shadow-artwork\">\n                                  <mediaitem-artwork :url=\"currentArtUrl\"></mediaitem-artwork>\n                              </div>\n                              <div class=\"popover-artwork\">\n                                  <mediaitem-artwork :url=\"currentArtUrl\"></mediaitem-artwork>\n                              </div>\n                              <div class=\"song-name\">{{ mk.nowPlayingItem[\"attributes\"][\"name\"] }}</div>\n                              <div class=\"song-artist\" @click=\"getNowPlayingItemDetailed(`artist`)\">{{\n                                  mk.nowPlayingItem[\"attributes\"][\"artistName\"] }}\n                              </div>\n                              <div class=\"song-album\" @click=\"getNowPlayingItemDetailed(`album`)\">\n                                  {{(mk.nowPlayingItem[\"attributes\"][\"albumName\"]) ?\n                                  (mk.nowPlayingItem[\"attributes\"][\"albumName\"]) : \"\" }}\n                              </div>\n                              <hr>\n                              <div class=\"btn-group\" style=\"width:100%;\">\n                                  <button class=\"md-btn md-btn-small\" style=\"width: 100%;\"\n                                          @click=\"drawer.open = false; miniPlayer(true)\">{{ $root.getLz(\"term.miniplayer\")\n                                      }}\n                                  </button>\n                                  <button class=\"md-btn md-btn-small\" style=\"width: 100%;\"\n                                          @click=\"drawer.open = false; fullscreen(true)\">{{\n                                      $root.getLz(\"term.fullscreenView\") }}\n                                  </button>\n                              </div>\n                          </div>\n                      </b-popover>\n                    </div>\n                    <div class=\"playback-info\">\n                        <div class=\"song-name\"\n                             :class=\"[isElementOverflowing('#app-main > div.app-chrome > div.app-chrome--center > div > div > div.playback-info > div.song-name') ? 'marquee' : '']\">\n                            {{ mk.nowPlayingItem[\"attributes\"][\"name\"] }}\n                            <div class=\"explicit-icon\"\n                                 v-if=\"mk.nowPlayingItem['attributes']['contentRating'] == 'explicit'\"\n                                 style=\"display: inline-block\"></div>\n                        </div>\n                        <div class=\"song-artist\" @click=\"getNowPlayingItemDetailed(`artist`)\">\n                            {{ mk.nowPlayingItem[\"attributes\"][\"artistName\"] }}\n                        </div>\n                        <div class=\"song-album\" @click=\"getNowPlayingItemDetailed('album')\"\n                             v-if='mk.nowPlayingItem[\"attributes\"][\"albumName\"]'>\n                            {{(mk.nowPlayingItem[\"attributes\"][\"albumName\"]) ?\n                            (mk.nowPlayingItem[\"attributes\"][\"albumName\"]) : \"\" }}\n                        </div>\n                        <div class=\"chrome-icon-container\">\n                            <div class=\"audio-type private-icon\" v-if=\"cfg.general.privateEnabled === true\"></div>\n                            <div class=\"audio-type spatial-icon\" v-if=\"cfg.audio.maikiwiAudio.spatial === true\"\n                                 :title=\"$root.getLz('settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization') + ' (' + getProfileLz('CTS', cfg.audio.maikiwiAudio.spatialProfile) + ')'\"\n                                 v-b-tooltip.hover\n                            ></div>\n                            <div class=\"audio-type lossless-icon\"\n                                 v-if=\"(mk.nowPlayingItem?.localFilesMetadata?.lossless ?? false) === true\"\n                                 :title=\"mk.nowPlayingItem?.localFilesMetadata?.bitDepth +'-bit / '+ mk.nowPlayingItem?.localFilesMetadata?.sampleRate/1000 + ' kHz ' + mk.nowPlayingItem.localFilesMetadata.container\"\n                                 v-b-tooltip.hover\n                            ></div>\n                            <div class=\"audio-type ppe-icon\"\n                                 v-if=\"mk.nowPlayingItem.localFilesMetadata == null && cfg.audio.maikiwiAudio.ciderPPE === true\"\n                                 :title=\"$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPE')\"\n                                 v-b-tooltip.hover\n                            ></div>\n                            <svg class=\"audio-type live-icon\" v-if=\"mk.nowPlayingItem?.attributes?.isLive === true\" :title=\"$root.getLz('term.live')\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--keyColor)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" v-b-tooltip.hover><path d=\"M5 12.55a11 11 0 0 1 14.08 0\"></path><path d=\"M1.42 9a16 16 0 0 1 21.16 0\"></path><path d=\"M8.53 16.11a6 6 0 0 1 6.95 0\"></path><line x1=\"12\" y1=\"20\" x2=\"12.01\" y2=\"20\"></line></svg>\n                        </div>\n                    </div>\n                    <template v-if=\"mk.nowPlayingItem['attributes']['playParams']\">\n                        <div class=\"actions\">\n                            <button class=\"lcdMenu\" @click=\"nowPlayingContextMenu\"\n                                    :title=\"$root.getLz('term.more')\" v-b-tooltip.hover>\n                                <div class=\"svg-icon\"></div>\n                            </button>\n                        </div>\n                    </template>\n\n                </div>\n            </template>\n\n            <template v-else>\n                <div class=\"app-playback-controls\">\n                    <div v-if=\"cfg.visual.artworkDisplayLayout == 'default'\" class=\"artwork\" id=\"artworkLCD\" style=\"pointer-events: none;\">\n                        <mediaitem-artwork :url=\"currentArtUrl\"></mediaitem-artwork>\n                    </div>\n                    <div class=\"playback-info\">\n                        <div class=\"song-name\">\n\n                        </div>\n                    </div>\n\n                </div>\n            </template>\n        </div>\n\n    </div>\n    <div class=\"app-chrome--center\">\n        <div class=\"app-chrome-playback-duration-bottom\">\n            <b-row v-if=\"mkReady() && mk.nowPlayingItem?.attributes?.isLive !== true\">\n                <b-col sm=\"auto\">{{ convertTime(getSongProgress()) }}</b-col>\n                <b-col>\n                    <input type=\"range\" step=\"0.01\" min=\"0\" :style=\"progressBarStyle()\"\n                           @input=\"playerLCD.desiredDuration = $event.target.value;playerLCD.userInteraction = true\"\n                           @mouseup=\"mk.seekToTime($event.target.value);setTimeout(()=>{playerLCD.desiredDuration = 0;playerLCD.userInteraction = false}, 1000);\"\n                           @touchend=\"mk.seekToTime($event.target.value);setTimeout(()=>{playerLCD.desiredDuration = 0;playerLCD.userInteraction = false}, 1000);\"\n                           :max=\"mk.currentPlaybackDuration\" :value=\"getSongProgress()\">\n                </b-col>\n                <b-col sm=\"auto\" v-if=\"!mk.nowPlayingItem?.isLiveRadioStation\">{{\n                    convertTime(mk.currentPlaybackDuration) }}\n                </b-col>\n                <b-col sm=\"auto\" v-else>{{ getLz(\"term.live\") }}</b-col>\n            </b-row>\n        </div>\n        <div class=\"app-chrome-playback-controls\">\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button--small shuffle\" v-if=\"mk.shuffleMode == 0\"\n                        :class=\"isDisabled() && 'disabled'\"\n                        @click=\"mk.shuffleMode = 1\" :title=\"$root.getLz('term.enableShuffle')\"\n                        v-b-tooltip.hover></button>\n                <button class=\"playback-button--small shuffle active\" v-else :class=\"isDisabled() && 'disabled'\"\n                        @click=\"mk.shuffleMode = 0\" :title=\"$root.getLz('term.disableShuffle')\"\n                        v-b-tooltip.hover></button>\n            </div>\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button previous\" @click=\"prevButton()\" :class=\"isPrevDisabled() && 'disabled'\"\n                        :title=\"$root.getLz('term.previous')\" v-b-tooltip.hover></button>\n            </div>\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button stop\" @click=\"mk.stop()\"\n                        v-if=\"mk.isPlaying && mk.nowPlayingItem.attributes.playParams.kind == 'radioStation'\"\n                        :title=\"$root.getLz('term.stop')\" v-b-tooltip.hover></button>\n                <button class=\"playback-button pause\" @click=\"mk.pause()\" v-else-if=\"mk.isPlaying\"\n                        :title=\"$root.getLz('term.pause')\" v-b-tooltip.hover></button>\n                <button class=\"playback-button play\" @click=\"mk.play()\" v-else\n                        :title=\"$root.getLz('term.play')\" v-b-tooltip.hover></button>\n            </div>\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button next\" @click=\"skipToNextItem()\" :class=\"isNextDisabled() && 'disabled'\"\n                        :title=\"$root.getLz('term.next')\" v-b-tooltip.hover></button>\n            </div>\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button--small repeat\" :class=\"mk.repeatMode == 1 ? 'repeatOne' : mk.repeatMode == 2 ? 'active' : ''\"\n                        :class=\"isDisabled() && 'disabled'\"\n                        @click=\"repeatIncrement()\" :title=\"$root.lz.repeat[mk.repeatMode]\"\n                        v-b-tooltip.hover></button>\n            </div>\n        </div>\n    </div>\n    <div class=\"app-chrome--right\">\n        <div class=\"app-chrome-item volume\">\n            <button class=\"volume-button--small volume\" @click=\"muteButtonPressed()\"\n                    :class=\"{'active': this.cfg.audio.volume == 0}\"\n                    :title=\"cfg.audio.muted ? $root.getLz('term.unmute') : $root.getLz('term.mute')\"\n                    v-b-tooltip.hover></button>\n            <input type=\"range\" @wheel=\"volumeWheel\" :step=\"cfg.audio.volumeStep\" min=\"0\" :max=\"cfg.audio.maxVolume\"\n                   v-model=\"mk.volume\" v-if=\"typeof mk.volume != 'undefined'\" @change=\"checkMuteChange()\"\n                   v-b-tooltip.hover :title=\"formatVolumeTooltip()\">\n        </div>\n        <div class=\"app-chrome-item generic\">\n            <button class=\"playback-button--small cast\"\n                    :title=\"$root.getLz('term.cast')\"\n                    v-b-tooltip.hover\n                    @click=\"modals.castMenu = true\"></button>\n        </div>\n        <div class=\"app-chrome-item generic\">\n            <button class=\"playback-button--small queue\" :class=\"{'active': drawer.panel == 'queue'}\"\n                    :title=\"$root.getLz('term.queue')\"\n                    v-b-tooltip.hover\n                    @click=\"invokeDrawer('queue')\"></button>\n        </div>\n        <div class=\"app-chrome-item generic\">\n            <template v-if=\"lyrics && lyrics != [] && lyrics.length > 0\">\n                <button class=\"playback-button--small lyrics\"\n                        :title=\"$root.getLz('term.lyrics')\"\n                        v-b-tooltip.hover\n                        :class=\"{'active': drawer.panel == 'lyrics'}\"\n                        @click=\"invokeDrawer('lyrics')\"></button>\n            </template>\n            <template v-else>\n                <button class=\"playback-button--small lyrics\"\n                        :style=\"{'opacity': 0.3, 'pointer-events': 'none'}\"></button>\n            </template>\n\n        </div>\n    </div>\n</div>\n"
  },
  {
    "path": "src/renderer/views/app/chrome-top.ejs",
    "content": "<div class=\"app-chrome\" :style=\"{'display': chrome.topChromeVisible ? '' : 'none'}\">\n    <div class=\"app-chrome--left\">\n        <div class=\"app-chrome-item full-height\"\n             v-if=\"chrome.windowControlPosition == 'left' && !chrome.nativeControls\">\n            <div class=\"window-controls-macos\">\n                <div class=\"close\" @click=\"ipcRenderer.send('close')\"></div>\n                <div class=\"minimize\" @click=\"ipcRenderer.send('minimize')\"></div>\n                <div class=\"minmax restore\" v-if=\"chrome.maximized\" @click=\"ipcRenderer.send('maximize')\"></div>\n                <div class=\"minmax\" v-else @click=\"ipcRenderer.send('maximize')\"></div>\n            </div>\n        </div>\n        <div class=\"app-chrome-item full-height\" v-else>\n            <button class=\"app-mainmenu\" @blur=\"mainMenuVisibility(false)\" @click=\"mainMenuVisibility(true)\"\n                    @contextmenu=\"mainMenuVisibility(true)\" :class=\"{active: chrome.menuOpened}\"\n                    :aria-label=\"$root.getLz('term.quickNav')\"></button>\n        </div>\n        <template v-if=\"getThemeDirective('appNavigation') != 'seperate'\">\n            <div class=\"vdiv\" v-if=\"getThemeDirective('windowLayout') == 'twopanel'\"></div>\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button navigation\" @click=\"navigateBack()\"\n                        :title=\"$root.getLz('term.navigateBack')\"\n                        v-b-tooltip.hover>\n                    <svg-icon url=\"./views/svg/chevron-left.svg\"></svg-icon>\n                </button>\n            </div>\n            <div class=\"app-chrome-item\">\n                <button class=\"playback-button navigation\" @click=\"navigateForward()\"\n                        :title=\"$root.getLz('term.navigateForward')\" v-b-tooltip.hover>\n                    <svg-icon url=\"./views/svg/chevron-right.svg\"></svg-icon>\n                </button>\n            </div>\n            <div class=\"app-chrome-item\" v-if=\"getThemeDirective('windowLayout') == 'twopanel'\">\n                <button class=\"playback-button collapseLibrary\" v-b-tooltip.hover\n                        :title=\"chrome.sidebarCollapsed ? getLz('action.showLibrary') : getLz('action.hideLibrary')\"\n                        @click=\"chrome.sidebarCollapsed = !chrome.sidebarCollapsed\">\n                    <transition name=\"fade\">\n                        <span v-if=\"chrome.sidebarCollapsed\"></span>\n                    </transition>\n                    <transition name=\"fade\">\n                        <span v-if=\"!chrome.sidebarCollapsed\"></span>\n                    </transition>\n\n                </button>\n            </div>\n            <div class=\"vdiv display--large\" v-if=\"getThemeDirective('windowLayout') != 'twopanel'\"></div>\n        </template>\n        <template v-if=\"getThemeDirective('windowLayout') != 'twopanel'\">\n            <div class=\"app-chrome-item playback-control-buttons\">\n                <div class=\"app-chrome-item display--large\">\n                    <button class=\"playback-button--small shuffle\" v-if=\"mk.shuffleMode == 0\"\n                            :class=\"isDisabled() && 'disabled'\"\n                            @click=\"mk.shuffleMode = 1\" :title=\"$root.getLz('term.enableShuffle')\"\n                            v-b-tooltip.hover></button>\n                    <button class=\"playback-button--small shuffle active\" v-else :class=\"isDisabled() && 'disabled'\"\n                            @click=\"mk.shuffleMode = 0\" :title=\"$root.getLz('term.disableShuffle')\"\n                            v-b-tooltip.hover></button>\n                </div>\n                <div class=\"app-chrome-item display--large\">\n                    <button class=\"playback-button previous\" @click=\"prevButton()\"\n                            :class=\"isPrevDisabled() && 'disabled'\"\n                            :title=\"$root.getLz('term.previous')\" v-b-tooltip.hover></button>\n                </div>\n                <div class=\"app-chrome-item display--large\">\n                    <button class=\"playback-button stop\" @click=\"mk.stop()\"\n                            v-if=\"mk.isPlaying && mk.nowPlayingItem.attributes.playParams.kind == 'radioStation'\"\n                            :title=\"$root.getLz('term.stop')\" v-b-tooltip.hover></button>\n                    <button class=\"playback-button pause\" @click=\"mk.pause()\" v-else-if=\"mk.isPlaying\"\n                            :title=\"$root.getLz('term.pause')\" v-b-tooltip.hover></button>\n                    <button class=\"playback-button play\" @click=\"mk.play()\" v-else :title=\"$root.getLz('term.play')\"\n                            v-b-tooltip.hover></button>\n                </div>\n                <div class=\"app-chrome-item display--large\">\n                    <button class=\"playback-button next\" @click=\"skipToNextItem()\"\n                            :class=\"isNextDisabled() && 'disabled'\"\n                            :title=\"$root.getLz('term.next')\" v-b-tooltip.hover></button>\n                </div>\n                <div class=\"app-chrome-item display--large\">\n                    <button class=\"playback-button--small repeat\" :class=\"mk.repeatMode == 1 ? 'repeatOne' : mk.repeatMode == 2 ? 'active' : ''\"\n                            :class=\"isDisabled() && 'disabled'\"\n                            @click=\"repeatIncrement()\" :title=\"$root.lz.repeat[mk.repeatMode]\"\n                            v-b-tooltip.hover></button>\n                </div>\n            </div>\n        </template>\n    </div>\n    <div class=\"app-chrome--center\">\n        <div class=\"app-chrome-item playback-controls\" v-if=\"getThemeDirective('windowLayout') != 'twopanel'\">\n            <template v-if=\"mkReady()\">\n                <div class=\"app-playback-controls\" @mouseover=\"chrome.progresshover = true\"\n                     @mouseleave=\"chrome.progresshover = false\" @contextmenu=\"nowPlayingContextMenu\">\n                    <div class=\"artwork\" id=\"artworkLCD\">\n                        <mediaitem-artwork :url=\"currentArtUrl\"></mediaitem-artwork>\n                    </div>\n                    <b-popover custom-class=\"mediainfo-popover\" target=\"artworkLCD\" triggers=\"hover\" placement=\"bottom\">\n                        <div class=\"content\">\n                            <div class=\"shadow-artwork\">\n                                <mediaitem-artwork :url=\"currentArtUrl\"></mediaitem-artwork>\n                            </div>\n                            <div class=\"popover-artwork\">\n                                <mediaitem-artwork :size=\"210\" :url=\"currentArtUrl\"></mediaitem-artwork>\n                            </div>\n                            <div class=\"song-name\">\n                                {{ mk.nowPlayingItem[\"attributes\"][\"name\"] }}\n                            </div>\n                            <div class=\"song-artist\" @click=\"getNowPlayingItemDetailed(`artist`)\">\n                                {{ mk.nowPlayingItem[\"attributes\"][\"artistName\"] }}\n                            </div>\n                            <div class=\"song-album\" @click=\"getNowPlayingItemDetailed(`album`)\">\n                                {{\n                                mk.nowPlayingItem[\"attributes\"][\"albumName\"]\n                                ? mk.nowPlayingItem[\"attributes\"][\"albumName\"]\n                                : \"\"\n                                }}\n                            </div>\n                            <hr />\n                            <div class=\"btn-group\" style=\"width: 100%\">\n                                <button class=\"md-btn md-btn-small\" style=\"width: 100%\"\n                                        @click=\"drawer.open = false; miniPlayer(true)\">\n                                    {{ $root.getLz(\"term.miniplayer\") }}\n                                </button>\n                                <button class=\"md-btn md-btn-small\" style=\"width: 100%\"\n                                        @click=\"drawer.open = false; fullscreen(true)\">\n                                    {{ $root.getLz(\"term.fullscreenView\") }}\n                                </button>\n                            </div>\n                        </div>\n                    </b-popover>\n                    <div class=\"playback-info\">\n                        <div class=\"chrome-icon-container\">\n                            <div class=\"audio-type private-icon\" v-if=\"cfg.general.privateEnabled === true\" :title=\"$root.getLz('term.privateSession')\" v-b-tooltip.hover></div>\n                            <div class=\"audio-type spatial-icon\" v-if=\"cfg.audio.maikiwiAudio.spatial === true\"\n                                 :title=\"$root.getLz('settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization') + ' (' + getProfileLz('CTS', cfg.audio.maikiwiAudio.spatialProfile) + ')'\"\n                                 v-b-tooltip.hover\n                            ></div>\n                            <div class=\"audio-type lossless-icon\"\n                                 v-if=\"(mk.nowPlayingItem?.localFilesMetadata?.lossless ?? false) === true\"\n                                 :title=\"mk.nowPlayingItem?.localFilesMetadata?.bitDepth +'-bit / '+ mk.nowPlayingItem?.localFilesMetadata?.sampleRate/1000 + ' kHz ' + mk.nowPlayingItem.localFilesMetadata.container\"\n                                 v-b-tooltip.hover\n                            ></div>\n                            <div class=\"audio-type ppe-icon\"\n                                 v-if=\"mk.nowPlayingItem.localFilesMetadata == null && cfg.audio.maikiwiAudio.ciderPPE === true\"\n                                 :title=\"$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPE')\"\n                                 v-b-tooltip.hover\n                            ></div>\n                            <svg class=\"audio-type live-icon\" v-if=\"mk.nowPlayingItem?.attributes?.isLive === true\" :title=\"$root.getLz('term.live')\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--keyColor)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" v-b-tooltip.hover><path d=\"M5 12.55a11 11 0 0 1 14.08 0\"></path><path d=\"M1.42 9a16 16 0 0 1 21.16 0\"></path><path d=\"M8.53 16.11a6 6 0 0 1 6.95 0\"></path><line x1=\"12\" y1=\"20\" x2=\"12.01\" y2=\"20\"></line></svg>\n                        </div>\n                        <div class=\"info-rect\">\n                            <div class=\"song-name\"\n                                 :class=\"[isElementOverflowing('#app-main > div.app-chrome > div.app-chrome--center > div > div > div.playback-info > div.song-name') ? 'marquee' : '']\">\n                                {{ mk.nowPlayingItem[\"attributes\"][\"name\"] }}\n                                <div class=\"explicit-icon\"\n                                     v-if=\"mk.nowPlayingItem['attributes']['contentRating'] == 'explicit'\"\n                                     style=\"display: inline-block\"></div>\n                            </div>\n                            <div class=\"song-artist-album\">\n                                <div class=\"song-artist-album-content\"\n                                     :class=\"[isElementOverflowing('#app-main > .app-chrome .app-chrome-item > .app-playback-controls > div >.song-artist-album > .song-artist-album-content') ? 'marquee' : '']\"\n                                     style=\"\n                  display: inline-block;\n                  -webkit-box-orient: horizontal;\n                  white-space: nowrap;\n                \">\n                                    <div class=\"item-navigate song-artist\" style=\"display: inline-block\"\n                                         @click=\"getNowPlayingItemDetailed(`artist`)\">\n                                        {{ mk.nowPlayingItem[\"attributes\"][\"artistName\"] }}\n                                    </div>\n                                    <div class=\"song-artist item-navigate\" style=\"display: inline-block\"\n                                         @click=\"getNowPlayingItemDetailed('album')\"\n                                         v-if=\"mk.nowPlayingItem['attributes']['albumName'] != ''\">\n                                        <div class=\"separator\" style=\"display: inline-block\">\n                                            {{ \"—\" }}\n                                        </div>\n                                        {{\n                                        mk.nowPlayingItem[\"attributes\"][\"albumName\"]\n                                        ? mk.nowPlayingItem[\"attributes\"][\"albumName\"]\n                                        : \"\"\n                                        }}\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                        <div class=\"song-progress\" v-if=\"mk.nowPlayingItem?.attributes?.isLive !== true\">\n                            <div class=\"song-duration\" style=\"justify-content: space-between; height: 1px\"\n                                 :style=\"[chrome.progresshover ? {'display': 'flex'} : {'display' : 'none'} ]\">\n                                <p style=\"width: auto\">{{ convertTime(getSongProgress()) }}</p>\n                                <p style=\"width: auto\">\n                                    {{ convertTime(mk.currentPlaybackDuration) }}\n                                </p>\n                            </div>\n\n                            <input type=\"range\" step=\"0.01\" min=\"0\" :style=\"progressBarStyle()\"\n                                   @input=\"playerLCD.desiredDuration = $event.target.value;playerLCD.userInteraction = true\"\n                                   @mouseup=\"mk.seekToTime($event.target.value);setTimeout(()=>{playerLCD.desiredDuration = 0;playerLCD.userInteraction = false}, 1000);\"\n                                   @touchend=\"mk.seekToTime($event.target.value);setTimeout(()=>{playerLCD.desiredDuration = 0;playerLCD.userInteraction = false}, 1000);\"\n                                   :max=\"mk.currentPlaybackDuration\" :value=\"getSongProgress()\" />\n                        </div>\n                    </div>\n                    <template v-if=\"mk.nowPlayingItem['attributes']['playParams']\">\n                        <div class=\"actions\">\n                            <button class=\"lcdMenu\" @click=\"nowPlayingContextMenu\" :title=\"$root.getLz('term.more')\"\n                                    v-b-tooltip.hover>\n                                <div class=\"svg-icon\"></div>\n                            </button>\n                        </div>\n                    </template>\n                </div>\n            </template>\n            <template v-else>\n                <div class=\"app-playback-controls\">\n                    <div class=\"artwork\" id=\"artworkLCD\" style=\"pointer-events: none;\">\n                        <mediaitem-artwork :url=\"currentArtUrl\"></mediaitem-artwork>\n                    </div>\n                    <div class=\"playback-info\">\n                        <div class=\"info-rect\">\n\n                        </div>\n                    </div>\n                </div>\n            </template>\n        </div>\n        <div class=\"app-chrome-item\" v-else>\n            <div class=\"top-nav-group\">\n                <sidebar-library-item :name=\"$root.getLz('home.title')\" svg-icon=\"./assets/feather/home.svg\"\n                                      svg-icon-name=\"home\" page=\"home\">\n                </sidebar-library-item>\n                <sidebar-library-item :name=\"$root.getLz('term.listenNow')\" svg-icon=\"./assets/feather/play-circle.svg\"\n                                      svg-icon-name=\"listenNow\"\n                                      page=\"listen_now\"></sidebar-library-item>\n                <sidebar-library-item :name=\"$root.getLz('term.browse')\" svg-icon=\"./assets/feather/globe.svg\"\n                                      svg-icon-name=\"browse\" page=\"browse\">\n                </sidebar-library-item>\n                <sidebar-library-item :name=\"$root.getLz('term.radio')\" svg-icon=\"./assets/feather/radio.svg\"\n                                      svg-icon-name=\"radio\" page=\"radio\">\n                </sidebar-library-item>\n            </div>\n        </div>\n    </div>\n    <div class=\"app-chrome--right\">\n        <template v-if=\"getThemeDirective('windowLayout') != 'twopanel'\">\n            <div class=\"app-chrome-item volume display--large\">\n                <button class=\"volume-button--small volume\" @click=\"muteButtonPressed()\"\n                        :class=\"{'active': this.cfg.audio.volume == 0}\"\n                        :title=\"cfg.audio.muted ? $root.getLz('term.unmute') : $root.getLz('term.mute')\"\n                        v-b-tooltip.hover></button>\n                <input type=\"range\" @wheel=\"volumeWheel\" :step=\"cfg.audio.volumeStep\" min=\"0\" :max=\"cfg.audio.maxVolume\"\n                       v-model=\"mk.volume\" v-if=\"typeof mk.volume != 'undefined'\" @change=\"checkMuteChange()\"\n                       v-b-tooltip.hover\n                       :title=\"formatVolumeTooltip()\" />\n            </div>\n            <div class=\"app-chrome-item generic\">\n                <button class=\"playback-button--small cast\" :title=\"$root.getLz('term.cast')\"\n                        @click=\"modals.castMenu = true\"\n                        v-b-tooltip.hover></button>\n            </div>\n            <div class=\"app-chrome-item generic\">\n                <button class=\"playback-button--small queue\" :title=\"$root.getLz('term.queue')\" v-b-tooltip.hover\n                        :class=\"{'active': drawer.panel == 'queue'}\" @click=\"invokeDrawer('queue')\"></button>\n            </div>\n            <div class=\"app-chrome-item generic\">\n                <template v-if=\"lyrics && lyrics != [] && lyrics.length > 0\">\n                    <button class=\"playback-button--small lyrics\" :title=\"$root.getLz('term.lyrics')\" v-b-tooltip.hover\n                            :class=\"{'active': drawer.panel == 'lyrics'}\" @click=\"invokeDrawer('lyrics')\"></button>\n                </template>\n                <template v-else>\n                    <button class=\"playback-button--small lyrics\"\n                            :style=\"{'opacity': 0.3, 'pointer-events': 'none'}\"></button>\n                </template>\n            </div>\n        </template>\n        <template v-else>\n            <div class=\"app-chrome-item search\">\n                <div class=\"search-input-container\">\n                    <div class=\"search-input--icon\"></div>\n                    <input type=\"search\" spellcheck=\"false\" @click=\"$root.appRoute('search');search.showHints = true\"\n                           @focus=\"search.showHints = true\"\n                           @blur=\"setTimeout(()=>{if(hintscontext != true){search.showHints = false} }, 300)\"\n                           v-on:keyup.enter=\"searchQuery(search.hints[search.cursor]?.content ?? search.hints[search.cursor]?.searchTerm ?? search.term);search.showHints = false;search.showSearchView = true;search.cursor = -1\" @change=\"$root.appRoute('search');\"\n                           v-on:keyup=\"searchCursor\"\n                           @input=\"getSearchHints()\"\n                           :placeholder=\"$root.getLz('term.search') + '...'\" v-model=\"search.term\" ref=\"searchInput\"\n                           class=\"search-input\" />\n\n                    <div class=\"search-hints-container\" v-if=\"search.showHints && search.hints.length != 0\" style=\"right:-13px;left:unset;padding-top:0;\">\n                        <div class=\"search-hints\">\n                            <button class=\"search-hint text-overflow-elipsis\" :class=\"{active: (search.cursor == index)}\" v-for=\"(hint, index) in search.hints.filter((a) => {return a.content == null})\"\n                                    @click=\"search.term = hint.searchTerm;search.showHints = false;searchQuery(hint.searchTerm);search.cursor = -1\">\n                                {{ hint.displayTerm }}\n                            </button>\n                            <template v-for=\"(item, position) in search.hints.filter((a) => {return a.content != null})\">\n                                <mediaitem-smarthints :item=\"item.content\" :position=\"position\"> </mediaitem-smarthints>\n                            </template>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </template>\n        <div class=\"app-chrome-item full-height\" id=\"window-controls-container\"\n             v-if=\"chrome.windowControlPosition == 'right' && !chrome.nativeControls\">\n            <div class=\"window-controls\">\n                <div class=\"minimize\" @click=\"ipcRenderer.send('minimize')\"></div>\n                <div class=\"minmax restore\" v-if=\"chrome.maximized\" @click=\"ipcRenderer.send('maximize')\"></div>\n                <div class=\"minmax\" v-else @click=\"ipcRenderer.send('maximize')\"></div>\n                <div class=\"close\" @click=\"ipcRenderer.send('close')\"></div>\n            </div>\n        </div>\n        <div class=\"app-chrome-item full-height\" v-else-if=\"platform != 'darwin' && !chrome.nativeControls\">\n            <button class=\"app-mainmenu\" @blur=\"mainMenuVisibility(false)\" @click=\"mainMenuVisibility(true)\"\n                    @contextmenu=\"mainMenuVisibility(true)\" :class=\"{active: chrome.menuOpened}\"></button>\n        </div>\n    </div>\n</div>\n"
  },
  {
    "path": "src/renderer/views/app/panels.ejs",
    "content": "<cider-menu-panel v-if=\"menuPanel.visible\"> </cider-menu-panel>\n<transition name=\"wpfade\">\n  <div\n    class=\"bg-artwork-container\"\n    v-if=\"cfg.visual.window_background_style == 'artwork'\"\n    :class=\"{noanimation: (!cfg.visual.bg_artwork_rotation || !animateBackground)}\">\n    <img\n      @load=\"chrome.artworkReady = true\"\n      class=\"bg-artwork a\" />\n    <img class=\"bg-artwork b\" />\n  </div>\n</transition>\n<transition name=\"wpfade\">\n  <div class=\"bg-artwork--placeholder\"></div>\n</transition>\n<transition name=\"modal\">\n  <c2-upgrade\n    v-if=\"modals.c2Upgrade\"></c2-upgrade>\n</transition>\n<transition name=\"modal\">\n  <add-to-playlist\n    :playlists=\"playlists.listing\"\n    v-if=\"modals.addToPlaylist\"></add-to-playlist>\n</transition>\n<transition name=\"modal\">\n  <audio-controls v-if=\"modals.audioControls\"></audio-controls>\n</transition>\n<transition name=\"modal\">\n  <audio-playbackrate v-if=\"modals.audioPlaybackRate\"></audio-playbackrate>\n</transition>\n<transition name=\"modal\">\n  <audio-settings v-if=\"modals.audioSettings\"></audio-settings>\n</transition>\n<transition name=\"modal\">\n  <castmenu v-if=\"modals.castMenu\"></castmenu>\n</transition>\n<transition name=\"modal\">\n  <pathmenu v-if=\"modals.pathMenu\"></pathmenu>\n</transition>\n<transition name=\"modal\">\n  <airplay-modal v-if=\"modals.airplayPW\"></airplay-modal>\n</transition>\n<transition name=\"modal\">\n  <plugin-menu v-if=\"modals.pluginMenu\"></plugin-menu>\n</transition>\n<transition name=\"modal\">\n  <settings-window v-if=\"modals.settings\"></settings-window>\n</transition>\n<transition name=\"modal\">\n  <eq-view v-if=\"modals.equalizer\"></eq-view>\n</transition>\n<transition name=\"modal\">\n  <qrcode-modal\n    v-if=\"modals.qrcode\"\n    :src=\"webremoteqr\"\n    :url=\"webremoteurl\"></qrcode-modal>\n</transition>\n<transition name=\"modal\">\n  <moreinfo-modal\n    v-if=\"modals.moreInfo\"\n    :data=\"moreinfodata\"></moreinfo-modal>\n</transition>\n<div\n  id=\"apple-music-video-container\"\n  :class=\"{'mini': mvViewMode == 'mini'}\">\n  <div id=\"apple-music-video-player-controls\">\n    <div\n      id=\"player-exit\"\n      title=\"Close\"\n      @click=\"exitMV();fullscreen(false);\">\n      <svg\n        fill=\"white\"\n        xmlns=\"http://www.w3.org/2000/svg\"\n        width=\"21\"\n        height=\"21\"\n        viewBox=\"0 0 21 21\"\n        aria-role=\"presentation\"\n        focusable=\"false\"\n        @click=\"exitMV();fullscreen(false);\">\n        <path\n          d=\"M10.5 21C4.724 21 0 16.275 0 10.5S4.724 0 10.5 0 21 4.725 21 10.5 16.276 21 10.5 21zm-3.543-5.967a.96.96 0 00.693-.295l2.837-2.842 2.85 2.842c.167.167.41.295.693.295.552 0 1.001-.461 1.001-1.012 0-.281-.115-.512-.295-.704L11.899 10.5l2.85-2.855a.875.875 0 00.295-.68c0-.55-.45-.998-1.001-.998a.871.871 0 00-.668.295l-2.888 2.855-2.862-2.843a.891.891 0 00-.668-.281.99.99 0 00-1.001.986c0 .269.116.512.295.678L9.088 10.5l-2.837 2.843a.926.926 0 00-.295.678c0 .551.45 1.012 1.001 1.012z\"\n          fill-rule=\"nonzero\" />\n      </svg>\n    </div>\n    <div\n      id=\"captions\"\n      v-if=\"lyricon && mvViewMode == 'full'\">\n      {{ (lyricon ? (lyrics.length > 0 && lyrics[currentLyricsLine] && lyrics[currentLyricsLine].line ? lyrics[currentLyricsLine].line.replace(\"lrcInstrumental\", \"\") : \"\") : \"\") + (lyricon ? (lyrics.length > 0 && lyrics[currentLyricsLine] && lyrics[currentLyricsLine].line ? (lyrics[currentLyricsLine].translation ? \"\\n\\r\" + lyrics[currentLyricsLine].translation : \"\") : \"\") : \"\") }}\n    </div>\n    <div class=\"playback-info music-player-info\">\n      <div\n        class=\"song-artist-album-content\"\n        v-if=\"mvViewMode == 'full'\"\n        style=\"display: inline-block; -webkit-box-orient: horizontal; white-space: nowrap\">\n        <div\n          class=\"song-artist\"\n          style=\"display: inline-block\">\n          {{ mk.nowPlayingItem?.attributes?.artistName ?? \"\" }}\n        </div>\n      </div>\n      <div\n        class=\"song-name\"\n        v-if=\"mvViewMode == 'full'\">\n        {{ mk.nowPlayingItem?.attributes?.name ?? \"\" }}\n        <div\n          class=\"explicit-icon\"\n          v-if=\"mk.nowPlayingItem?.attributes?.contentRating == 'explicit'\"\n          style=\"display: inline-block\"></div>\n      </div>\n      <div\n        class=\"song-progress\"\n        v-if=\"mvViewMode == 'full'\">\n        <p style=\"width: auto\">{{ convertTime(getSongProgress()) }}</p>\n        <input\n          type=\"range\"\n          step=\"0.01\"\n          min=\"0\"\n          :style=\"progressBarStyle()\"\n          style=\"width: 95%\"\n          @input=\"playerLCD.desiredDuration = $event.target.value;playerLCD.userInteraction = true\"\n          @mouseup=\"mk.seekToTime($event.target.value);setTimeout(()=>{playerLCD.desiredDuration = 0;playerLCD.userInteraction = false}, 1000);\"\n          @touchend=\"mk.seekToTime($event.target.value);setTimeout(()=>{playerLCD.desiredDuration = 0;playerLCD.userInteraction = false}, 1000);\"\n          :max=\"mk.currentPlaybackDuration\"\n          :value=\"getSongProgress()\" />\n        <p style=\"width: auto\">{{ convertTime(mk.currentPlaybackDuration) }}</p>\n      </div>\n\n      <div class=\"app-chrome-item display--large\">\n        <div\n          class=\"app-chrome-item volume display--large\"\n          v-if=\"mvViewMode == 'full'\">\n          <button\n            class=\"volume-button--small volume\"\n            @click=\"muteButtonPressed()\"\n            :class=\"{'active': this.cfg.audio.volume == 0}\"\n            :title=\"cfg.audio.muted ? $root.getLz('term.unmute') : $root.getLz('term.mute')\"\n            v-b-tooltip.hover></button>\n          <input\n            type=\"range\"\n            @wheel=\"volumeWheel\"\n            :step=\"cfg.audio.volumeStep\"\n            min=\"0\"\n            :max=\"cfg.audio.maxVolume\"\n            v-model=\"mk.volume\"\n            v-if=\"typeof mk.volume != 'undefined'\"\n            @change=\"checkMuteChange()\"\n            v-b-tooltip.hover\n            :title=\"formatVolumeTooltip()\" />\n        </div>\n        <template v-if=\"mvViewMode == 'full'\">\n          <button\n            class=\"playback-button pause\"\n            @click=\"mk.pause()\"\n            v-if=\"mk.isPlaying\"\n            :title=\"$root.getLz('term.pause')\"\n            v-b-tooltip.hover></button>\n          <button\n            class=\"playback-button play\"\n            @click=\"mk.play()\"\n            v-else\n            :title=\"$root.getLz('term.play')\"\n            v-b-tooltip.hover></button>\n        </template>\n        <div\n          class=\"app-chrome-item generic\"\n          v-if=\"mvViewMode == 'full'\">\n          <template v-if=\"lyrics && lyrics != [] && lyrics.length > 0\">\n            <button\n              class=\"playback-button--small lyrics\"\n              :title=\"$root.getLz('term.lyrics')\"\n              v-b-tooltip.hover\n              :class=\"{'active': drawer.panel == 'lyrics'}\"\n              @click=\"invokeDrawer('lyrics')\"></button>\n          </template>\n          <template v-else>\n            <button\n              class=\"playback-button--small lyrics\"\n              :style=\"{'opacity': 0.3, 'pointer-events': 'none'}\"></button>\n          </template>\n        </div>\n        <div\n          id=\"player-pip\"\n          :class=\"{'mini': mvViewMode == 'mini'}\"\n          @click=\"pip()\"\n          title=\"Picture-in-Picture\"\n          v-b-tooltip.hover>\n          <%- include(\"../svg/pip.svg\") %>\n        </div>\n        <div\n          id=\"player-fullscreen\"\n          v-if=\"mvViewMode == 'full'\"\n          @click=\"fullscreen(!fullscreenState, true)\"\n          title=\"Fullscreen\"\n          v-b-tooltip.hover>\n          <%- include(\"../svg/fullscreen.svg\") %>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div id=\"apple-music-video-player\"></div>\n</div>\n"
  },
  {
    "path": "src/renderer/views/components/add-to-playlist.ejs",
    "content": "<script type=\"text/x-template\" id=\"add-to-playlist\">\n    <div class=\"modal-fullscreen addtoplaylist-panel\" @click.self=\"app.resetState()\"\n         @contextmenu.self=\"app.resetState()\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{app.getLz('action.addToPlaylist')}}</div>\n                <button class=\"close-btn\" @click=\"app.resetState()\" :aria-label=\"app.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n                <button class=\"playlist-item\"\n                        @click=\"app.addSelectedToNewPlaylist()\" style=\"width:100%;\">\n                    <div class=\"icon\"><%- include(\"../svg/plus.svg\") %></div>\n                    <div class=\"name\">{{app.getLz('action.createPlaylist')}}</div>\n                </button>\n                <sidebar-playlist :playlist-select=\"playlistSelect\" :relate-media-items=\"relateItems\"\n                                  v-for=\"item in $root.getPlaylistFolderChildren('p.playlistsroot')\" v-bind:key=\"item.id\" :item=\"item\">\n                </sidebar-playlist>\n            </div>\n            <div class=\"modal-search\">\n                <div class=\"search-input-container\" style=\"width:100%;margin: 16px 0;\">\n                    <div class=\"search-input--icon\"></div>\n                    <input type=\"search\"\n                           ref=\"searchInput\"\n                           style=\"width:100%;\"\n                           spellcheck=\"false\"\n                           :placeholder=\"app.getLz('term.search') + '...'\"\n                           v-model=\"searchQuery\"\n                           @input=\"search()\"\n                           class=\"search-input\">\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('add-to-playlist', {\n    template: '#add-to-playlist',\n    data: function() {\n      return {\n        playlistSorted: [],\n        searchQuery: \"\",\n        focused: \"\",\n        app: this.$root,\n        relateItems: []\n      }\n    },\n    props: {\n      playlists: {\n        type: Array,\n        required: true\n      }\n    },\n    mounted() {\n      this.relateItems = [this.$root.selectedMediaItems[0].id]\n      this.search()\n      this.$refs.searchInput.focus()\n      this.$refs.searchInput.addEventListener('keydown', (e) => {\n        if (e.keyCode == 13) {\n          if (this.focused != \"\") {\n            this.addToPlaylist(this.focused)\n          }\n        }\n      })\n    },\n    methods: {\n      playlistSelect(playlist) {\n        if (playlist.type != \"library-playlist-folders\") {\n          this.addToPlaylist(playlist.id)\n        }\n      },\n      addToPlaylist(id) {\n        app.addSelectedToPlaylist(id)\n      },\n      search() {\n        this.focused = \"\"\n        if (this.searchQuery == \"\") {\n          this.playlistSorted = this.playlists\n        } else {\n          this.playlistSorted = this.playlists.filter(playlist => {\n            return playlist.attributes.name.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1\n          })\n          if (this.playlistSorted.length == 1) {\n            this.focused = this.playlistSorted[0].id\n          }\n        }\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/airplay-modal.ejs",
    "content": "<script type=\"text/x-template\" id=\"airplay-modal\">\n    <div class=\"spatialproperties-panel castmenu modal-fullscreen airplay-modal\" @click.self=\"close()\"\n         @contextmenu.self=\"close()\">\n        <div class=\"modal-window airplay-modal\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{'Enter password'}}</div>\n                <button class=\"close-btn\" @click=\"close()\" :aria-label=\"this.$root.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\" style=\"overflow-y: overlay; padding: 3%\">\n                <input type=\"text\" v-model=\"passcode\" />\n            </div>\n            <div class=\"md-footer\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <button style=\"width:100%\" @click=\"enterPassword()\" class=\"md-btn md-btn-block md-btn-primary\">\n                            {{'OK'}}\n                        </button>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('airplay-modal', {\n    template: '#airplay-modal',\n    data: function() {\n      return {\n        passcode: '',\n      }\n    },\n    mounted() {\n    },\n    methods: {\n      close() {\n        this.$root.modals.airplayPW = false\n      },\n      enterPassword() {\n        console.log('Entered passCode: ', this.passcode)\n        ipcRenderer.send(\"setAirPlayPasscode\", this.passcode, this.$root.currentAirPlayCodeID)\n        this.close()\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/animatedartwork-view.ejs",
    "content": "<script type=\"text/x-template\" id=\"animatedartwork-view\">\n    <div class=\"animated\" v-bind:vid=\"app.hashCode(video).toString()\" v-if=\"video\">\n        <video ref=\"video\" class=\"animated-artwork-video\" loop id=\"animated-artwork\"></video>\n    </div>\n</script>\n\n<script>\n  Vue.component('animatedartwork-view', {\n    template: '#animatedartwork-view',\n    data: function() {\n      return {\n        app: this.$root,\n        hls: null,\n      }\n    },\n    props: {\n      video: {\n        type: String,\n        required: true\n      },\n      priority: {\n        type: Boolean,\n        default: false\n      }\n    },\n    async mounted() {\n      if (!this.priority && app.cfg.visual.animated_artwork == \"limited\") {\n        return\n      } else if (app.cfg.visual.animated_artwork == \"disabled\") {\n        return\n      }\n      if (this.video) {\n        this.$nextTick(function() {\n          var config = {\n            backBufferLength: 0,\n            enableWebVTT: false,\n            enableCEA708Captions: false,\n            emeEnabled: false,\n            abrEwmaDefaultEstimate: 10000,\n            testBandwidth: false,\n          };\n          if (this.hls) {\n            this.hls.detachMedia();\n          } else {\n\n            this.hls = new CiderHls(config);\n          }\n          // bind them together\n          if (this.$refs.video) {\n            let d = \"WIDEVINE_SOFTWARE\"\n            let h = {\n              initDataTypes: [\"cenc\", \"keyids\"],\n              distinctiveIdentifier: \"optional\",\n              persistentState: \"required\"\n            }\n            let p = {\n              platformInfo: { requiresCDMAttachOnStart: !0, maxSecurityLevel: d, keySystemConfig: h },\n              appData: { serviceName: \"Apple Music\" }\n            }\n\n            this.hls.attachMedia(this.$refs.video);\n            this.hls.loadSource(this.video, p);\n            let u = this.hls;\n            var quality = app.cfg.visual.animated_artwork_qualityLevel;\n            setTimeout(() => {\n              let levelsnum = u.levels.map((level) => {\n                return level.width\n              })\n              if (levelsnum.length > 0) {\n                let qualities = []\n                let qualities2 = []\n                for (let i = 0; i < levelsnum.length; i++) {\n                  if (qualities2.indexOf(levelsnum[i]) == -1) {\n                    qualities.push({ level: i, quality: levelsnum[i] })\n                    qualities2.push(levelsnum[i])\n                  }\n                }\n                let actualnum = Math.floor(qualities[qualities.length - 1].level * (quality / 4))\n                if (quality != 0) {\n                  quality = qualities[Math.min(actualnum, qualities.length - 1)].level\n                }\n                if (quality == 4) {\n                  quality = qualities[qualities.length - 1].level\n                }\n              }\n              try {\n                this.hls.loadLevel = parseInt(quality || 1);\n              } catch (e) {\n              }\n            }, 200)\n          }\n        })\n      }\n    },\n    async beforeDestroy() {\n      if (this.hls) {\n        await this.hls.destroy();\n        this.hls = null\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/app-content.ejs",
    "content": "<script type=\"text/x-template\" id=\"app-content-area\">\n    <div id=\"app-content\" :scrollpos=\"$root.chrome.contentScrollPosY\" scrollaxis=\"y\"\n         :style=\"{'overflow': ($root.chrome.contentAreaScrolling ? '' : 'hidden')}\">\n        <div id=\"navigation-bar\" v-if=\"$root.getThemeDirective('appNavigation') == 'seperate'\">\n            <button class=\"nav-item\" @click=\"$root.navigateBack()\">\n                <%- include('../svg/chevron-left.svg') %>\n            </button>\n            <button class=\"nav-item\" @click=\"$root.navigateForward()\">\n                <%- include('../svg/chevron-right.svg') %>\n            </button>\n        </div>\n\n        <!-- Include App Routes -->\n        <% for(var i = 0; i < Object.keys(env.appRoutes).length ; i++) { %>\n            <transition\n            <% if(env.appRoutes[i].onEnter) {\n            %>\n                v-on:enter=\"<%- env.appRoutes[i].onEnter; %>\"\n                    <%\n                    }\n                    %>\n                :name=\"$root.chrome.desiredPageTransition\">\n                <template\n                        v-if=\"<%- env.appRoutes[i].condition; %>\">\n                    <%- env.appRoutes[i].component; %>\n                </template>\n            </transition>\n        <% } %>\n        <!-- Library - Made For You -->\n        <transition :name=\"$root.chrome.desiredPageTransition\" v-on:enter=\"$root.getMadeForYou()\">\n            <template v-if=\"$root.page == 'library-madeforyou'\">\n                <%- include('../pages/madeforyou') %>');\n                %>\n            </template>\n        </transition>\n        <!-- Library - Artists-->\n    </div>\n</script>\n\n<script>\n  Vue.component('app-content-area', {\n    template: '#app-content-area',\n    data: function() {\n      return {\n        scrollPos: 0\n      }\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/artist-chip.ejs",
    "content": "<script type=\"text/x-template\" id=\"artist-chip\">\n    <div class=\"artist-chip\" @click.self=\"route\" tabindex=\"0\">\n        <div class=\"artist-chip__image\" v-if=\"image\"\n             :style=\"{backgroundColor: '#' + (artist.attributes.artwork?.bgColor ?? '000')}\">\n            <mediaitem-artwork v-if=\"artist.id != null\" :url=\"artist.attributes.artwork.url\"\n                               :size=\"80\"></mediaitem-artwork>\n        </div>\n        <div class=\"artist-chip__image\" v-else>\n        </div>\n        <div class=\"artist-chip__name\">\n            <span>{{ item.attributes.name }}</span>\n        </div>\n        <button @click=\"$root.setArtistFavorite(artist.id, true)\" title=\"Follow\"\n                v-if=\"!$root.followingArtist(artist.id)\" class=\"artist-chip__follow codicon codicon-add\"></button>\n        <button @click=\"$root.setArtistFavorite(artist.id, false)\" title=\"Following\" v-else\n                class=\"artist-chip__follow codicon codicon-check\"></button>\n    </div>\n</script>\n\n<script>\n  Vue.component('artist-chip', {\n    props: {\n      item: {\n        type: Object,\n        required: true\n      }\n    },\n    data: function() {\n      return {\n        image: false,\n        artist: {\n          id: null\n        }\n      }\n    },\n    template: '#artist-chip',\n    async mounted() {\n      let artistId = this.item.id\n      if (typeof this.item.relationships == \"object\") {\n        artistId = this.item.relationships.catalog.data[0].id\n      }\n      app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists/${artistId}`).then(response => {\n        this.artist = response.data.data[0];\n        this.image = true;\n      });\n    },\n    methods: {\n      route() {\n        app.appRoute(`artist/${this.artist.id}`);\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/artwork-material.ejs",
    "content": "<script type=\"text/x-template\" id=\"artwork-material\">\n    <div class=\"artworkMaterial\">\n        <mediaitem-artwork :url=\"src\" :size=\"500\" v-for=\"image in images\" />\n    </div>\n</script>\n\n<script>\n  Vue.component('artwork-material', {\n    template: '#artwork-material',\n    data: function() {\n      return {\n        src: \"\"\n      }\n    },\n    mounted() {\n      this.src = app.getMediaItemArtwork(this.url, this.size)\n    },\n    props: {\n      url: {\n        type: String,\n        required: true\n      },\n      size: {\n        type: [String, Number],\n        required: false,\n        default: '32'\n      },\n      images: {\n        type: [String, Number],\n        required: false,\n        default: '2'\n      }\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/audio-controls.ejs",
    "content": "<script type=\"text/x-template\" id=\"audio-controls\">\n    <div class=\"modal-fullscreen addtoplaylist-panel\" @click.self=\"app.modals.audioControls = false\"\n         @contextmenu.self=\"app.modals.audioControls = false\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{app.getLz('term.audioControls')}}</div>\n                <button class=\"close-btn\" @click=\"app.modals.audioControls = false\"\n                        :aria-label=\"app.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{app.getLz('term.volume')}}\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto percent\">\n                        <input type=\"number\"\n                               style=\"width: 100%; text-align: center; margin-right: 5px;\" min=\"0\"\n                               step=\"2\" v-model=\"volume\" />\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{app.getLz('settings.option.audio.volumeStep')}}\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto percent\">\n                        <input type=\"number\" style=\"width: 100%; text-align: center; margin-right: 5px;\" min=\"0\"\n                               v-model=\"volumeStep\" />\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{app.getLz('settings.option.audio.maxVolume')}}\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto percent\">\n                        <input type=\"number\" style=\"width: 100%; text-align: center; margin-right: 5px;\" min=\"0\"\n                               v-model=\"maxVolume\" />\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.advanced')}}\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <label>\n                            <input type=\"checkbox\" v-model=\"app.cfg.audio.advanced\" switch />\n                        </label>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('audio-controls', {\n    template: '#audio-controls',\n    data: function() {\n      return {\n        app: this.$root,\n        maxVolume: this.$root.cfg.audio.maxVolume * 100,\n        volumeStep: this.$root.cfg.audio.volumeStep * 100,\n        volume: this.$root.cfg.audio.volume * 100\n      }\n    },\n    watch: {\n      maxVolume: function(newValue, _oldValue) {\n        if (newValue > 100) {\n          newValue = 100\n        } else {\n          newValue = Math.round(newValue)\n        }\n        this.$root.cfg.audio.maxVolume = newValue / 100\n        this.maxVolume = newValue\n        console.log(newValue, _oldValue)\n      },\n      volume: function(newValue, _oldValue) {\n        if (newValue > this.maxVolume) {\n          newValue = 100\n        } else {\n          newValue = Math.round(newValue)\n        }\n        this.$root.mk.volume = newValue / 100\n        this.volume = newValue\n        console.log(newValue, _oldValue)\n      },\n      volumeStep: function(newValue, _oldValue) {\n        if (newValue > this.maxVolume) {\n          newValue = 100\n        } else {\n          newValue = Math.round(newValue)\n        }\n        this.$root.cfg.audio.volumeStep = newValue / 100\n        this.volumeStep = newValue\n        console.log(newValue, _oldValue)\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/audio-playbackrate.ejs",
    "content": "<script type=\"text/x-template\" id=\"audio-playbackrate\">\n    <div class=\"modal-fullscreen addtoplaylist-panel\" @click.self=\"app.modals.audioPlaybackRate = false\"\n         @contextmenu.self=\"app.modals.audioPlaybackRate = false\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{app.getLz('settings.option.audio.changePlaybackRate')}}</div>\n                <button class=\"close-btn\" @click=\"app.modals.audioPlaybackRate = false\"\n                        :aria-label=\"app.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{app.getLz('settings.option.audio.playbackRate')}}\n                    </div>\n                    <div class=\"md-option-segment playbackrate-text\" v-if=\"this.playbackRate\">\n                        {{playbackRate}} ×\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <input type=\"range\" :step=\"0.05\" min=\"0.25\" :max=\"2\" @wheel=\"playbackRateWheel\"\n                               v-model=\"playbackRate\">\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('audio-playbackrate', {\n    template: '#audio-playbackrate',\n    data: function() {\n      return {\n        app: this.$root,\n        playbackRate: this.$root.cfg.audio.playbackRate\n      }\n    },\n    watch: {\n      playbackRate: function(newValue, _oldValue) {\n        this.saveValue(newValue);\n      }\n    },\n    methods: {\n      playbackRateWheel(event) {\n        if (app.checkScrollDirectionIsUp(event)) {\n          this.saveValue(this.$root.cfg.audio.playbackRate + 0.05);\n        } else {\n          this.saveValue(this.$root.cfg.audio.playbackRate - 0.05);\n        }\n      },\n      saveValue(newValue) {\n        newValue = Number(newValue);\n        if (newValue >= 0.25 && newValue <= 2) {\n          newValue = String(newValue).length > 4 ? newValue.toFixed(2) : newValue;\n          this.$root.mk.playbackRate = newValue;\n          this.$root.cfg.audio.playbackRate = newValue;\n          this.playbackRate = newValue;\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/audio-settings.ejs",
    "content": "<script type=\"text/x-template\" id=\"audio-settings\">\n    <template>\n        <div class=\"modal-fullscreen addtoplaylist-panel\" @click.self=\"app.modals.audioSettings = false\"\n             @contextmenu.self=\"app.modals.audioSettings = false\">\n            <div class=\"modal-window\">\n                <div class=\"modal-header\">\n                    <div class=\"modal-title\">{{app.getLz('term.audioSettings')}}</div>\n                    <button class=\"close-btn\" @click=\"app.modals.audioSettings = false\"\n                            :aria-label=\"app.getLz('action.close')\"></button>\n                </div>\n                <div class=\"modal-content\">\n                    <button class=\"playlist-item\"\n                            @click=\"openEqualizer()\" style=\"width:100%;\">\n                        <div class=\"icon\"><%- include(\"../svg/speaker.svg\") %></div>\n                        <div class=\"name\">{{app.getLz('term.equalizer')}}</div>\n                    </button>\n                    <button class=\"playlist-item\"\n                            @click=\"openAudioControls()\" style=\"width:100%;\">\n                        <div class=\"icon\"><%- include(\"../svg/speaker.svg\") %></div>\n                        <div class=\"name\">{{app.getLz('term.audioControls')}}</div>\n                    </button>\n                    <button class=\"playlist-item\"\n                            @click=\"openAudioPlaybackRate()\" style=\"width:100%;\">\n                        <div class=\"icon\"><%- include(\"../svg/speaker.svg\") %></div>\n                        <div class=\"name\">{{app.getLz('settings.option.audio.changePlaybackRate')}}</div>\n                    </button>\n                    <button class=\"playlist-item\"\n                            @click=\"$root.openSettingsPage('audiolabs')\" style=\"width:100%;\">\n                        <div class=\"icon\"><%- include(\"../svg/speaker.svg\") %></div>\n                        <div class=\"name\">{{app.getLz('settings.option.audio.audioLab')}}</div>\n                    </button>\n                </div>\n            </div>\n        </div>\n    </template>\n</script>\n\n<script>\n  Vue.component('audio-settings', {\n      template: '#audio-settings',\n      data: function() {\n        return {\n          app: this.$root,\n        }\n      },\n      props: {},\n      mounted() {\n      },\n      methods: {\n        openEqualizer() {\n          app.modals.equalizer = true\n          app.modals.audioSettings = false\n        },\n        openAudioControls() {\n          app.modals.audioControls = true\n          app.modals.audioSettings = false\n        },\n        openAudioPlaybackRate() {\n          app.modals.audioPlaybackRate = true\n          app.modals.audioSettings = false\n        },\n      },\n    }\n  );\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/c2-upgrade.ejs",
    "content": "<template\n  type=\"text/x-template\"\n  id=\"c2-upgrade\">\n  <div\n    class=\"modal-fullscreen addtoplaylist-panel\"\n    @click.self=\"closePromo\"\n    @contextmenu.self=\"closePromo\">\n    <div class=\"modal-window\">\n      <div class=\"modal-header\">\n        <div class=\"modal-title\">Cider 2 Free Upgrade — Last Call!</div>\n        <button\n          class=\"close-btn\"\n          @click=\"closePromo\"\n          :aria-label=\"app.getLz('action.close')\"></button>\n      </div>\n      <div\n        class=\"modal-content\"\n        style=\"text-align: center\">\n        <img\n          src=\"./assets/c1-c2.png\"\n          style=\"margin: 12px 22px 0; pointer-events: none\" />\n        <p\n          class=\"p-3\"\n          style=\"font-size: 14px\">\n          Earlier this year, we released Cider 2, a complete rewrite of Cider.\n          <br />Cider 2 is a paid upgrade, but we're offering it <b>for free</b> to Cider users who have purchased Cider 1.\n          <br />\n          <br />\n          Download Cider 2 from the Microsoft Store today!\n          <br />\n\n          <br />\n          <b>This limited offer is valid until June 4th, 2023.</b>\n          <br />\n          <br />\n          <i>Upon opening the website, please click \"Get in Store app\" to continue.</i>\n          <br />\n          <br />\n          <label>\n            <input\n              type=\"checkbox\"\n              style=\"accent-color: var(--keyColor)\"\n              v-model=\"showOnStartup\" />\n            Show this reminder again on next startup\n          </label>\n          <template v-if=\"hasSeen\">\n            <br />\n            <label>\n              <input\n                type=\"checkbox\"\n                style=\"accent-color: var(--keyColor)\"\n                v-model=\"removeItemFromMainMenu\" />\n              Remove upgrade button from Quick Navigation/Main Menu\n            </label>\n          </template>\n        </p>\n      </div>\n      <div\n        class=\"modal-search\"\n        style=\"padding: 12px\">\n        <button\n          class=\"btn btn-primary\"\n          @click=\"openStore\"\n          style=\"width: 100%\">\n          Open in Microsoft Store\n        </button>\n        <button\n          class=\"btn btn-secondary\"\n          @click=\"closePromo\"\n          style=\"width: 100%; margin-top: 1em\">\n          Close\n        </button>\n      </div>\n    </div>\n  </div>\n</template>\n\n<script>\n  Vue.component(\"c2-upgrade\", {\n    template: \"#c2-upgrade\",\n    data: function () {\n      return {\n        app: this.$root,\n        showOnStartup: true,\n        hasSeen: localStorage.getItem(\"seenC2Upgrade\"),\n        removeItemFromMainMenu: false,\n      };\n    },\n    methods: {\n      closePromo() {\n        this.app.modals.c2Upgrade = false;\n        if (!this.showOnStartup) {\n          localStorage.setItem(\"noC2Startup\", true);\n        }\n        if (this.removeItemFromMainMenu) {\n          localStorage.setItem(\"noC2Upgrade\", true);\n          app.chrome.noC2Upgrade = true;\n        }\n        localStorage.setItem(\"seenC2Upgrade\", true);\n      },\n      openStore() {\n        window.open(\"https://www.microsoft.com/store/productId/9PL8WPH0QK9M\");\n      },\n    },\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/castmenu.ejs",
    "content": "<script type=\"text/x-template\" id=\"castmenu\">\n    <div class=\"spatialproperties-panel castmenu modal-fullscreen\" @click.self=\"close()\" @contextmenu.self=\"close()\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{$root.getLz('action.cast.todevices')}}</div>\n                <button class=\"close-btn\" @click=\"close()\" :aria-label=\"$root.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\" style=\"overflow-y: overlay; padding: 3%\">\n                <div class=\"md-labeltext\">{{$root.getLz('action.cast.chromecast')}}</div>\n                <div class=\"md-option-container\" style=\"margin-top: 12px;margin-bottom: 12px;overflow-y: scroll;\">\n                    <template v-if=\"!scanning\">\n                        <template v-for=\"(device) in devices.cast\">\n                            <div class=\"md-option-line\" style=\"cursor: pointer\" @click=\"setCast(device)\">\n                                <div class=\"md-option-segment\">\n                                    {{ device.name }}\n                                    <br>\n                                    <small>{{ device.host }}</small>\n                                </div>\n                                <div class=\"md-option-segment_auto\"\n                                     style=\"display: flex;justify-content: center;align-items: center\"\n                                     v-if=\"activeCasts.includes(device)\">\n                                    Connected\n                                </div>\n                                <div class=\"md-option-segment_auto\" v-else\n                                     style=\"display: flex;justify-content: center;align-items: center\">\n                                    <svg width=\"20\" height=\"20\" viewBox=\"0 0 34 34\" fill=\"#fff\" version=\"1.1\"\n                                         xmlns=\"http://www.w3.org/2000/svg\"\n                                         xml:space=\"preserve\" class=\"castPlayIndicator\"><path\n                                                d=\"M28.228,18.327l-16.023,8.983c-0.99,0.555 -2.205,-0.17 -2.205,-1.318l0,-17.984c0,-1.146 1.215,-1.873 2.205,-1.317l16.023,8.982c1.029,0.577 1.029,2.077 0,2.654Z\"\n                                                style=\"fill-rule:nonzero\"></path></svg>\n                                </div>\n                            </div>\n                        </template>\n                    </template>\n                    <template v-else>\n                        <div class=\"md-option-line\" style=\"cursor: pointer\">\n                            <div class=\"md-option-segment\">\n                                {{$root.getLz('action.cast.scanning')}}\n                            </div>\n                        </div>\n                    </template>\n                </div>\n                <div class=\"md-labeltext\">{{$root.getLz('action.cast.airplay')}}</div>\n                <div class=\"md-option-container\" style=\"margin-top: 12px;margin-bottom: 12px;overflow-y: scroll;\">\n                    <div class=\"md-option-line\">\n                        <div class=\"md-option-segment\">\n                            Supports AirPlay 1 & AirPlay 2. Please set your device access in the Home app to \"Everyone\" or \"Anyone on the same network\".\n                            <!-- {{$root.getLz('action.cast.airplay.underdevelopment')}} -->\n                            <template v-if=\"true\" v-for=\"(device) in devices.airplay\">\n                                <div class=\"md-option-line\" style=\"cursor: pointer\" @click=\"setAirPlayCast(device)\">\n                                    <div class=\"md-option-segment\">\n                                        {{ device.name }}\n                                        <br>\n                                        <small>{{ device.host }}</small>\n                                    </div>\n                                    <div class=\"md-option-segment_auto\"\n                                         style=\"display: flex;justify-content: center;align-items: center\" @click=\"disconnectAirPlayCast(device)\"\n                                         v-if=\"activeCasts.some(item => { return item.host == device.host && item.name == device.name && item.port == device.port})\">\n                                         <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"20px\" height=\"20px\" viewBox=\"0 0 20 20\" version=\"1.1\">\n                                          <g id=\"surface1\">\n                                          <path style=\"stroke:none;fill-rule:evenodd;fill:#fff;fill-opacity:1;\" d=\"M 10 0 C 15.523438 0 20 4.476562 20 10 C 20 15.523438 15.523438 20 10 20 C 4.476562 20 0 15.523438 0 10 C 0 4.476562 4.476562 0 10 0 Z M 12.136719 5.988281 C 12.421875 5.703125 12.597656 5.472656 12.953125 5.828125 L 14.089844 6.988281 C 14.464844 7.355469 14.445312 7.570312 14.089844 7.914062 L 11.933594 10.0625 L 14.011719 12.136719 C 14.296875 12.421875 14.527344 12.597656 14.171875 12.953125 L 13.011719 14.089844 C 12.644531 14.464844 12.429688 14.445312 12.089844 14.089844 L 10 12 L 7.914062 14.082031 C 7.574219 14.433594 7.359375 14.453125 6.992188 14.082031 L 5.828125 12.945312 C 5.472656 12.59375 5.703125 12.417969 5.992188 12.128906 L 8.066406 10.0625 L 5.917969 7.917969 C 5.566406 7.574219 5.546875 7.359375 5.917969 6.992188 L 7.054688 5.828125 C 7.40625 5.472656 7.582031 5.703125 7.871094 5.992188 L 10 8.128906 Z M 12.136719 5.988281 \"/>\n                                          </g>\n                                          </svg>\n                                    </div>\n                                    <div class=\"md-option-segment_auto\" v-else\n                                         style=\"display: flex;justify-content: center;align-items: center\">\n                                        <svg width=\"20\" height=\"20\" viewBox=\"0 0 34 34\" fill=\"#fff\" version=\"1.1\"\n                                             xmlns=\"http://www.w3.org/2000/svg\"\n                                             xml:space=\"preserve\"\n                                             class=\"castPlayIndicator\"><path\n                                                    d=\"M28.228,18.327l-16.023,8.983c-0.99,0.555 -2.205,-0.17 -2.205,-1.318l0,-17.984c0,-1.146 1.215,-1.873 2.205,-1.317l16.023,8.982c1.029,0.577 1.029,2.077 0,2.654Z\"\n                                                    style=\"fill-rule:nonzero\"></path></svg>\n                                    </div>\n                                </div>\n                            </template>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            <div class=\"md-footer\">\n                <div class=\"row\">\n                    <div class=\"col\" v-if=\"activeCasts.length != 0\">\n                        <button style=\"width:100%\" @click=\"stopCasting()\" class=\"md-btn md-btn-block md-btn-primary\">\n                            {{$root.getLz('action.cast.stop')}}\n                        </button>\n                    </div>\n                    <div class=\"col\">\n                        <button style=\"width:100%\" class=\"md-btn md-btn-block\" @click=\"scan()\">\n                            {{$root.getLz('action.cast.scan')}}\n                        </button>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('castmenu', {\n    template: '#castmenu',\n    data: function() {\n      return {\n        devices: {\n          cast: [],\n          airplay: []\n        },\n        scanning: false,\n        activeCasts: this.$root.activeCasts,\n\n      }\n    },\n    mounted() {\n      this.scan();\n    },\n    watch: {\n      activeCasts: function(newVal, oldVal) {\n        this.$root.activeCasts = this.activeCasts;\n      }\n    },\n    methods: {\n      close() {\n        this.$root.modals.castMenu = false\n      },\n      scan() {\n        let self = this;\n        this.scanning = true;\n        ipcRenderer.send('getChromeCastDevices', '');\n        ipcRenderer.send(\"getAirplayDevice\", \"\")\n        setTimeout(() => {\n          self.devices.cast = ipcRenderer.sendSync(\"getKnownCastDevices\");\n          self.devices.airplay = ipcRenderer.sendSync(\"getKnownAirplayDevices\");\n          self.scanning = false;\n        }, 2000);\n        console.log(this.devices);\n        // vm.$forceUpdate();\n      },\n      setCast(device) {\n        CiderAudio.sendAudio();\n        this.activeCasts.push(device);\n        ipcRenderer.send('performGCCast', device, \"Cider\", \"Playing ...\", \"Test build\", '');\n      },\n      setAirPlayCast(device) {\n        if (!this.activeCasts.some(item => { return item.host == device.host && item.name == device.name && item.port == device.port})) {\n        this.activeCasts.push(device);\n        ipcRenderer.send(\"performAirplayPCM\", device.host, device.port, null, \"\", \"\", \"\", \"\", device.txt, device.airplay2, false)}\n      },\n      disconnectAirPlayCast(device) {\n        app.confirm(\"Do you want to disconnect this device?\",(res) => {\n          if (res){\n            ipcRenderer.send('disconnectAirplay', device.host +\":\"+ device.port+\"ap\");\n            console.log('disconnectAirplay', device.host +\":\"+ device.port+\"ap\")\n            let idx = this.activeCasts.findIndex(((a) => {return a.host == device.host &&  a.port == device.port}))\n            console.log(idx)\n            if (idx != -1) {\n              delete this.activeCasts[idx]\n              delete this.$root.activeCasts[idx]\n              this.activeCasts = this.activeCasts.filter(a => {return !(a.host == device.host &&  a.port == device.port)})\n              console.log(this.activeCasts)\n              if (this.activeCasts.length == 0){\n                this.stopCasting()\n              }\n          }}\n        })\n      },\n      stopCasting() {\n        CiderAudio.stopAudio();\n        ipcRenderer.send('disconnectAirplay', '');\n        ipcRenderer.send('stopGCast', '');\n        this.activeCasts = [];\n        // vm.$forceUpdate();\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/cider-modal.ejs",
    "content": "<script type=\"text/x-template\" id=\"add-to-playlist\">\n    <template>\n        <div class=\"modal-fullscreen modal-generic\" @click.self=\"app.resetState()\" @contextmenu.self=\"app.resetState()\">\n            <div class=\"modal-window\">\n                <div class=\"modal-header\">\n                    <div class=\"modal-title\">{{app.getLz('action.addToLibrary')}}</div>\n                    <button class=\"close-btn\" @click=\"app.resetState()\"\n                            :aria-label=\"app.getLz('action.close')\"></button>\n                </div>\n                <div class=\"modal-content\">\n                    <button class=\"playlist-item\"\n                            :class=\"{ focused: playlist.id == focused }\"\n                            @click=\"addToPlaylist(playlist.id)\" style=\"width:100%;\" v-for=\"playlist in playlistSorted\"\n                            v-if=\"playlist.attributes.canEdit && playlist.type != 'library-playlist-folders'\">\n                        <div class=\"icon\"><%- include(\"../svg/playlist.svg\") %></div>\n                        <div class=\"name\">{{ playlist.attributes.name }}</div>\n                    </button>\n                </div>\n                <div class=\"modal-search\">\n                    <div class=\"search-input-container\" style=\"width:100%;margin: 16px 0;\">\n                        <div class=\"search-input--icon\"></div>\n                        <input type=\"search\"\n                               ref=\"searchInput\"\n                               style=\"width:100%;\"\n                               spellcheck=\"false\"\n                               :placeholder=\"app.getLz('term.search') + '...'\"\n                               v-model=\"searchQuery\"\n                               @input=\"search()\"\n                               class=\"search-input\">\n                    </div>\n                </div>\n            </div>\n        </div>\n    </template>\n</script>\n\n<script>\n  Vue.component('add-to-playlist', {\n    template: '#add-to-playlist',\n    data: function() {\n      return {\n        playlistSorted: [],\n        searchQuery: \"\",\n        focused: \"\",\n        app: this.$root,\n      }\n    },\n    props: {\n      playlists: {\n        type: Array,\n        required: true\n      }\n    },\n    mounted() {\n      this.search()\n      this.$refs.searchInput.focus()\n      this.$refs.searchInput.addEventListener('keydown', (e) => {\n        if (e.keyCode == 13) {\n          if (this.focused != \"\") {\n            this.addToPlaylist(this.focused)\n          }\n        }\n      })\n    },\n    methods: {\n      addToPlaylist(id) {\n        app.addSelectedToPlaylist(id)\n      },\n      search() {\n        this.focused = \"\"\n        if (this.searchQuery == \"\") {\n          this.playlistSorted = this.playlists\n        } else {\n          this.playlistSorted = this.playlists.filter(playlist => {\n            return playlist.attributes.name.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1\n          })\n          if (this.playlistSorted.length == 1) {\n            this.focused = this.playlistSorted[0].id\n          }\n        }\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/editorialNotes.ejs",
    "content": "<div class=\"modal-backdrop\">\n    <div class=\"modal-dialog\">\n        <div class=\"modal-header\">\n            <button type=\"button\" class=\"close\">&times;</button>\n            <h4 class=\"modal-title\" v-html=\"title\"></h4>\n        </div>\n        <div class=\"modal-content\" v-html=\"content\">\n\n        </div>\n        <div class=\"modal-footer\">\n\n        </div>\n    </div>\n</div>"
  },
  {
    "path": "src/renderer/views/components/equalizer.ejs",
    "content": "<script type=\"text/x-template\" id=\"eq-view\">\n    <div class=\"modal-fullscreen equalizer-panel\" @click.self=\"close()\" @contextmenu.self=\"close()\">\n        <div class=\"modal-window\" >\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{$root.getLz('term.equalizer')}}</div>\n                <button class=\"close-btn\" @click=\"close()\" :aria-label=\"$root.getLz('action.close')\"></button>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <select class=\"md-select\" style=\"width:220px;text-align:center;margin-right:245px\" v-model=\"$root.cfg.audio.equalizer.preset\" v-on:change=\"changePreset($root.cfg.audio.equalizer.preset)\">\n                        <optgroup :label=\"$root.getLz('term.userPresets')\">\n                            <option v-for=\"preset in $root.cfg.audio.equalizer.presets\" :value=\"preset.preset\">{{preset.name}}</option>\n                        </optgroup>\n                        <optgroup :label=\"$root.getLz('term.defaultPresets')\">\n                            <option v-for=\"preset in defaultPresets\" :value=\"preset.preset\">{{preset.name}}</option>\n                        </optgroup>\n                    </select>\n                </div>\n            </div>\n            <div class=\"modal-content\">\n                <!-- BANDS = [60, 170, 310, 600, 1000, 3000, 6000, 12000, 14000, 16000]; -->\n                <div class=\"inputs-container\">\n                    <div class=\"input-container mini\">\n                        {{$root.cfg.audio.equalizer.vibrantBass}}\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider mini\" orient=\"vertical\" min=\"-15\" max=\"15\" step=\"1\" v-model=\"$root.cfg.audio.equalizer.vibrantBass\" @change=\"changeVibrantBass()\">\n                        Vibrant Bass\n                    </div>\n                    <div class=\"input-container mini\">\n                        {{$root.cfg.audio.equalizer.mix}}\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider mini\" orient=\"vertical\" min=\"0\" max=\"2\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.mix\" @change=\"changeMix()\">\n                        Mix\n                    </div>\n                    <div class=\"input-container header mini\">\n                        Gain\n                        <input type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" >\n                        <div class=\"freq-header\">Freq</div>\n                        <div>Q</div>\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[0]\" @change=\"changeGain(0)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[0]\" @change=\"changeGain(0)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"22\" max=\"44\" step=\"2\" v-model=\"$root.cfg.audio.equalizer.frequencies[0]\" @change=\"changeFreq(0)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[0]\" @change=\"changeQ(0)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[1]\" @change=\"changeGain(1)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[1]\" @change=\"changeGain(1)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"44\" max=\"88\" step=\"4\" v-model=\"$root.cfg.audio.equalizer.frequencies[1]\" @change=\"changeFreq(1)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[1]\" @change=\"changeQ(1)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[2]\" @change=\"changeGain(2)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[2]\" @change=\"changeGain(2)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"88\" max=\"177\" step=\"8\" v-model=\"$root.cfg.audio.equalizer.frequencies[2]\" @change=\"changeFreq(2)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[2]\" @change=\"changeQ(2)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[3]\" @change=\"changeGain(3)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[3]\" @change=\"changeGain(3)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"177\" max=\"355\" step=\"16\" v-model=\"$root.cfg.audio.equalizer.frequencies[3]\" @change=\"changeFreq(3)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[3]\" @change=\"changeQ(3)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[4]\" @change=\"changeGain(4)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[4]\" @change=\"changeGain(4)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"355\" max=\"710\" step=\"32\" v-model=\"$root.cfg.audio.equalizer.frequencies[4]\" @change=\"changeFreq(4)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[4]\" @change=\"changeQ(4)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[5]\" @change=\"changeGain(5)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[5]\" @change=\"changeGain(5)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"710\" max=\"1420\" step=\"64\" v-model=\"$root.cfg.audio.equalizer.frequencies[5]\" @change=\"changeFreq(5)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[5]\" @change=\"changeQ(5)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[6]\" @change=\"changeGain(6)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[6]\" @change=\"changeGain(6)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"1420\" max=\"2840\" step=\"128\" v-model=\"$root.cfg.audio.equalizer.frequencies[6]\" @change=\"changeFreq(6)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[6]\" @change=\"changeQ(6)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[7]\" @change=\"changeGain(7)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[7]\" @change=\"changeGain(7)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"2840\" max=\"5680\" step=\"256\" v-model=\"$root.cfg.audio.equalizer.frequencies[7]\" @change=\"changeFreq(7)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[7]\" @change=\"changeQ(7)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[8]\" @change=\"changeGain(8)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[8]\" @change=\"changeGain(8)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"5680\" max=\"11360\" step=\"512\" v-model=\"$root.cfg.audio.equalizer.frequencies[8]\" @change=\"changeFreq(8)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[8]\" @change=\"changeQ(8)\">\n                    </div>\n                    <div class=\"input-container\">\n                        <input tabindex=\"0\" type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[9]\" @change=\"changeGain(9)\">\n                        <input tabindex=\"0\" type=\"range\" class=\"eq-slider\" orient=\"vertical\" min=\"-12\" max=\"12\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.gain[9]\" @change=\"changeGain(9)\">\n                        <input type=\"number\" class=\"eq-freq\" orient=\"vertical\" min=\"11360\" max=\"22720\" step=\"1024\" v-model=\"$root.cfg.audio.equalizer.frequencies[9]\" @change=\"changeFreq(9)\">\n                        <input type=\"number\" class=\"eq-q\" orient=\"vertical\" min=\"0\" max=\"5\" step=\"0.1\" v-model=\"$root.cfg.audio.equalizer.Q[9]\" @change=\"changeQ(9)\">\n                    </div>\n                </div>\n            </div>\n            <div class=\"modal-lowercontent\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <button class=\"md-btn\" style=\"width:100%\" @click=\"resetGain()\">{{$root.getLz('term.reset')}}</button>\n                    </div>\n                    <div class=\"col\">\n                        <button class=\"md-btn\" style=\"width:100%\" @click=\"presetOptions($event)\">{{$root.getLz('term.menu')}}</button>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n    Vue.component('eq-view', {\n        template: '#eq-view',\n        data: function () {\n            return {\n                // app: this.$root,\n                eqPreset: function () {\n                    this.preset = uuidv4()\n                    this.name = \"\"\n                    this.frequencies = []\n                    this.gain = []\n                    this.Q = []\n                    this.mix = 1\n                    this.vibrantBass = 0\n                    this.userGenerated = true\n                },\n                defaultPresets: [\n                    {\n                        'preset': 'default',\n                        'name': 'Default',\n                        'frequencies': [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000],\n                        'gain': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n                        'Q': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'boostAiriness',\n                        'name': 'Boost Airiness',\n                        'frequencies': [1169, 1733, 5962, 8688, 14125, 18628, 18628, 19000, 19500, 20000],\n                        'gain': [-1.41, 0.25, 3.33, 0.22, -0.53, 0.2, 3.64, 0, 0, 0],\n                        'Q': [0.405, 2.102, 0.025, 2.5, 7.071, 1.768, 1.146, 1, 1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'acoustic',\n                        'name': 'Acoustic',\n                        'frequencies': [32, 75, 125, 220, 700, 1000, 2000, 4000, 10000, 16000],\n                        'gain': [0, -8, 0, -0.1, -3, 0, 0, 0, 4, 0],\n                        'Q': [1, 0.2, 1, 2.0, 1.4, 1, 1, 1, 0.1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'clearVocal',\n                        'name': 'Clear Vocal',\n                        'frequencies': [20, 63, 125, 250, 400, 1000, 2000, 4000, 8000, 20000],\n                        'gain': [-22, 0, 0, 0, -3, 0, 1.8, 0, 0, 3.5],\n                        'Q': [0.3, 1, 1, 1, 2.0, 1, 0.7, 1, 1, 0.8],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'instrumentClarity',\n                        'name': 'Instrument Clarity',\n                        'frequencies': [20, 63, 155, 250, 500, 1000, 2000, 5000, 11000, 16000],\n                        'gain': [-15, 0, -3, 0, 0, 0, 0, 3.1, 0, 0],\n                        'Q': [0.5, 1, 2, 1, 1, 1, 1, 1.5, 0.1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'reduceHarshness',\n                        'name': 'Reduce Harshness',\n                        'frequencies': [32, 63, 125, 250, 500, 1128, 2000, 4057, 8000, 16000],\n                        'gain': [0, 0, 0, 0, 0, 2, 0, -6.4, 0, 0],\n                        'Q': [1, 1, 1, 1, 1, 2, 1, 1, 1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'smileyFace',\n                        'name': 'Smiley Face',\n                        'frequencies': [35, 63, 125, 250, 500, 800, 2000, 4000, 8000, 20000],\n                        'gain': [5, 0, 0, 0, 0, -5, 0, 0, 0, 5],\n                        'Q': [0.1, 1, 1, 1, 1, 0.6, 1, 1, 1, 0.2],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    },\n                    {\n                        'preset': 'bassBoostSurgical',\n                        'name': 'Surgical Bass Boost',\n                        'frequencies': [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000],\n                        'gain': [2.7, 2.2, 1.6, 1.4, 0.6, 0, 0, 0, 0, 0],\n                        'Q': [1.4, 1.4, 1.4, 1.4, 1.4, 1, 1, 1, 1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }, {\n                        'preset': 'bassBoostClassic',\n                        'name': 'Classic Bass Boost',\n                        'frequencies': [32, 63, 160, 250, 500, 1000, 2000, 3500, 8000, 20000],\n                        'gain': [2.7, 2.2, 1.6, 1.4, 0.6, 0, 0, 0, 0, 0],\n                        'Q': [0.7, 0.7, 0.7, 0.7, 0.7, 1, 1, 1, 1, 1],\n                        'mix': 1,\n                        'vibrantBass': 0,\n                        'userGenerated': false\n                    }]\n            }\n        },\n        props: [\"src\", \"url\"],\n        mounted() {\n        },\n        methods: {\n            presetOptions(event) {\n                let menu = {\n                    items: {\n                        \"new\": {\n                            \"icon\": \"./assets/feather/plus.svg\",\n                            \"name\": app.getLz('action.newpreset'),\n                            action: () => {\n                                this.addPreset()\n                            }\n                        },\n                        \"delete\": {\n                            \"icon\": \"./assets/feather/x-circle.svg\",\n                            \"name\": app.getLz('action.deletepreset'),\n                            action: () => {\n                                this.deletePreset()\n                            }\n                        },\n                        \"import\": {\n                            \"icon\": \"./assets/feather/share.svg\",\n                            \"name\": app.getLz('action.import'),\n                            action: () => {\n                                this.importPreset()\n                            }\n                        },\n                        \"export\": {\n                            \"icon\": \"./assets/feather/share.svg\",\n                            \"name\": app.getLz('action.export'),\n                            action: () => {\n                                this.exportPreset()\n                            }\n                        },\n                    }\n                }\n\n                if (!this.$root.cfg.audio.equalizer.userGenerated) {\n                    delete menu.items.delete\n                }\n\n                app.showMenuPanel(menu, event)\n            },\n            sharePreset(event) {\n                let menu = {\n                    items: [\n                        {\n                            \"icon\": \"./assets/feather/share.svg\",\n                            \"name\": app.getLz('action.import'),\n                            \"action\": function () {\n                                notyf.error(\"Not implemented yet\")\n                            }\n                        },\n                        {\n                            \"icon\": \"./assets/feather/share.svg\",\n                            \"name\": app.getLz('action.export'),\n                            \"action\": function () {\n                                notyf.error(\"Not implemented yet\")\n                            }\n                        },\n                    ]\n                }\n                app.showMenuPanel(menu, event)\n            },\n            deletePreset() {\n                let presets = this.$root.cfg.audio.equalizer.presets\n                app.confirm(app.getLz('term.deletepreset.warn'), (result) => {\n                    if (result) {\n                        this.changePreset(\"default\")\n                        // find the preset by id (preset) and remove it\n                        let index = presets.findIndex(p => p.preset == this.preset)\n                        presets.splice(index, 1)\n                        notyf.success(app.getLz('term.deletedpreset'))\n                    }\n                })\n            },\n            close() {\n                app.modals.equalizer = false\n            },\n            changeVibrantBass() {\n                if (app.cfg.audio.equalizer.vibrantBass !== '0') {\n                    try {\n                        for (var i = 0; i < 21; i++) {\n                            CiderAudio.audioNodes.vibrantbassNode[i].gain.value = app.cfg.audio.maikiwiAudio.vibrantBass.gain[i] * (app.cfg.audio.equalizer.vibrantBass / 10);\n                        } CiderAudio.intelliGainComp_n0_0();\n                    }\n                    catch (e) {\n                        CiderAudio.hierarchical_loading();\n                    }\n                }\n\n                else {\n                    CiderAudio.hierarchical_loading();\n                }\n            },\n            changeMix() {\n                if (Math.max(...app.cfg.audio.equalizer.gain) != 0) {\n                    try {\n                        for (var i = 0; i < 10; i++) {\n                            CiderAudio.audioNodes.audioBands[i].gain.value = app.cfg.audio.equalizer.gain[i] * app.cfg.audio.equalizer.mix\n                        }\n                        CiderAudio.intelliGainComp_n0_0();\n                    } catch (e) { CiderAudio.hierarchical_loading(); }\n                }\n            },\n            changeGain(i) {\n                if (Math.max(...app.cfg.audio.equalizer.gain) != 0) {\n                    try {\n                        CiderAudio.audioNodes.audioBands[i].gain.value = app.cfg.audio.equalizer.gain[i] * app.cfg.audio.equalizer.mix\n                        CiderAudio.intelliGainComp_n0_0();\n                    }\n                    catch (e) { CiderAudio.hierarchical_loading(); }\n                }\n                else {\n                    CiderAudio.hierarchical_loading();\n                }\n            },\n            changeFreq(i) {\n                CiderAudio.audioNodes.audioBands[i].frequency.value = app.cfg.audio.equalizer.frequencies[i]\n            },\n            changeQ(i) {\n                CiderAudio.audioNodes.audioBands[i].Q.value = app.cfg.audio.equalizer.Q[i]\n            },\n            resetGain() {\n                this.applyPreset({\n                    'frequencies': [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000],\n                    'gain': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n                    'Q': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n                    'mix': 1,\n                    'vibrantBass': 0,\n                })\n                if (app.cfg.audio.equalizer.userGenerated) {\n                    this.saveSelectedPreset()\n                }\n            },\n            addPreset() {\n                let self = this\n                app.prompt(app.getLz('term.newpreset.name'), (res) => {\n                    if (res) {\n                        let eqSettings = Clone(app.cfg.audio.equalizer)\n                        let newPreset = new self.eqPreset()\n                        newPreset.name = res\n                        newPreset.frequencies = eqSettings.frequencies\n                        newPreset.gain = eqSettings.gain\n                        newPreset.Q = eqSettings.Q\n                        newPreset.mix = eqSettings.mix\n                        newPreset.vibrantBass = eqSettings.vibrantBass\n                        app.cfg.audio.equalizer.presets.push(newPreset)\n                        notyf.success(app.getLz('term.addedpreset'))\n                        self.changePreset(newPreset.preset)\n                    }\n                })\n            },\n            saveSelectedPreset() {\n                // Save the current settings to the selected preset\n                let self = this\n                //let preset = app.cfg.audio.equalizer.presets[app.cfg.audio.equalizer.preset]\n                // find the preset by its id (preset)\n                let preset = app.cfg.audio.equalizer.presets.find(p => p.preset == app.cfg.audio.equalizer.preset)\n                preset.frequencies = app.cfg.audio.equalizer.frequencies\n                preset.gain = app.cfg.audio.equalizer.gain\n                preset.Q = app.cfg.audio.equalizer.Q\n                preset.mix = app.cfg.audio.equalizer.mix\n                preset.vibrantBass = app.cfg.audio.equalizer.vibrantBass\n                notyf.success(\"Saved Preset\")\n            },\n            exportPreset() {\n                let preset = app.cfg.audio.equalizer.presets.find(p => p.preset == app.cfg.audio.equalizer.preset)\n                this.$root.copyToClipboard(btoa(JSON.stringify(preset)))\n            },\n            importPreset() {\n                let self = this\n                app.prompt(\"Enter preset share code\", (res) => {\n                    if (res) {\n                        let preset = JSON.parse(atob(res))\n                        if (preset.frequencies && preset.gain && preset.Q && preset.mix && preset.vibrantBass) {\n                            // self.applyPreset(preset)\n                            app.cfg.audio.equalizer.presets.push(preset)\n                            notyf.success(`${preset.name} has been imported.`)\n                        }\n                        else {\n                            notyf.error(\"Invalid Preset\")\n                        }\n                    }\n                })\n            },\n            applyPreset(preset) {\n                Object.assign(this.$root.cfg.audio.equalizer, preset)\n                this.changeVibrantBass()\n                for (var i = 0; i < 10; i++) {\n                    try { CiderAudio.audioNodes.audioBands[i].gain.value = app.cfg.audio.equalizer.gain[i] * app.cfg.audio.equalizer.mix }\n                    catch (e) {\n                        CiderAudio.hierarchical_loading();\n                        CiderAudio.audioNodes.audioBands[i].gain.value = app.cfg.audio.equalizer.gain[i] * app.cfg.audio.equalizer.mix\n                    }\n\n                    CiderAudio.audioNodes.audioBands[i].frequency.value = app.cfg.audio.equalizer.frequencies[i]\n                    CiderAudio.audioNodes.audioBands[i].Q.value = app.cfg.audio.equalizer.Q[i]\n                }\n                CiderAudio.intelliGainComp_n0_0();\n            },\n            changePreset(id) {\n                let userPresets = app.cfg.audio.equalizer.presets\n                let defaultPresets = Clone(this.defaultPresets)\n\n                let presets = defaultPresets.concat(userPresets)\n                console.log(presets)\n                let preset = presets.find(p => p.preset == id)\n\n                console.log(preset)\n\n                if (preset) {\n                    this.applyPreset(preset)\n                }\n            }\n        }\n    });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/fullscreen.ejs",
    "content": "<script type=\"text/x-template\" id=\"fullscreen-view\">\n    <div class=\"fullscreen-view\" tabindex=\"0\">\n        <div class=\"background\">\n            <div class=\"bgArtworkMaterial\">\n                <div class=\"bg-artwork-container\">\n                    <img v-if=\"(app.cfg.visual.bg_artwork_rotation && app.animateBackground)\" class=\"bg-artwork a\"\n                         :src=\"(image ?? '').replace('{w}','30').replace('{h}','30')\">\n                    <img v-if=\"(app.cfg.visual.bg_artwork_rotation && app.animateBackground)\" class=\"bg-artwork b\"\n                         :src=\"(image ?? '').replace('{w}','30').replace('{h}','30')\">\n                    <img v-if=\"!(app.cfg.visual.bg_artwork_rotation && app.animateBackground)\"\n                         class=\"bg-artwork no-animation\" :src=\"(image ?? '').replace('{w}','30').replace('{h}','30')\">\n                </div>\n            </div>\n        </div>\n        <div class=\"fs-header\" v-if=\"immersiveEnabled\">\n            <div class=\"top-nav-group\">\n                <sidebar-library-item @click.native=\"tabMode = 'catalog'\" :name=\"$root.getLz('home.title')\"\n                                      svg-icon=\"./assets/feather/home.svg\" svg-icon-name=\"home\" page=\"home\">\n                </sidebar-library-item>\n                <sidebar-library-item @click.native=\"tabMode = 'catalog'\" :name=\"$root.getLz('term.listenNow')\"\n                                      svg-icon=\"./assets/feather/play-circle.svg\" svg-icon-name=\"listenNow\"\n                                      page=\"listen_now\"></sidebar-library-item>\n                <sidebar-library-item @click.native=\"tabMode = 'catalog'\" :name=\"$root.getLz('term.browse')\"\n                                      svg-icon=\"./assets/feather/globe.svg\" svg-icon-name=\"browse\" page=\"browse\">\n                </sidebar-library-item>\n                <sidebar-library-item @click.native=\"tabMode = 'catalog'\" :name=\"$root.getLz('term.radio')\"\n                                      svg-icon=\"./assets/feather/radio.svg\" svg-icon-name=\"radio\" page=\"radio\">\n                </sidebar-library-item>\n                <sidebar-library-item @click.native=\"tabMode = 'catalog'\" :name=\"$root.getLz('term.library')\"\n                                      svg-icon=\"./assets/feather/radio.svg\" svg-icon-name=\"library\" page=\"library\">\n                </sidebar-library-item>\n                <sidebar-library-item @click.native=\"tabMode = ''\" :name=\"$root.getLz('term.nowPlaying')\"\n                                      svg-icon=\"./assets/play.svg\" svg-icon-name=\"nowPlaying\" page=\"nowPlaying\">\n                </sidebar-library-item>\n                <sidebar-library-item @click.native=\"tabMode = 'catalog'\" name=\"\" svg-icon=\"./assets/search.svg\"\n                                      svg-icon-name=\"search\" page=\"search\">\n                </sidebar-library-item>\n            </div>\n        </div>\n        <div class=\"row fs-row\" v-if=\"tabMode != 'catalog'\">\n            <div class=\"col artwork-col\">\n                <div class=\"artwork\" :class=\"$root.mk.isPlaying && 'playing'\" @click=\"app.fullscreen(false)\">\n                    <mediaitem-artwork\n                            :size=\"600\"\n                            :video=\"video\"\n                            :videoPriority=\"true\"\n                            :url=\"(image ?? '').replace('{w}','600').replace('{h}','600')\"\n                    ></mediaitem-artwork>\n                </div>\n                <div class=\"controls-parents\" v-if=\"app.mkReady()\">\n                        <div class=\"app-playback-controls\" @mouseover=\"app.chrome.progresshover = true\"\n                             @mouseleave=\"app.chrome.progresshover = false\" @contextmenu=\"app.nowPlayingContextMenu\">\n                            <div class=\"playback-info\">\n                                <div class=\"song-name\">\n                                    {{ app.mk.nowPlayingItem[\"attributes\"][\"name\"] }}\n                                </div>\n                                <div style=\"display: inline-block; -webkit-box-orient: horizontal; white-space: nowrap; margin-top: 0.25vh; overflow: hidden;\">\n                                    <div class=\"item-navigate song-artist\" style=\"display: inline-block;\"\n                                         @click=\"app.getNowPlasssyingItemDetailed(`artist`) && app.fullscreen(false)\">\n                                        {{ app.mk.nowPlayingItem[\"attributes\"][\"artistName\"] }}\n                                    </div>\n                                    <div class=\"song-artist\" style=\"display: inline-block;\">\n                                        {{ (app.mk.nowPlayingItem[\"attributes\"][\"albumName\"]) ? \" — \" : \"\" }}\n                                    </div>\n                                    <div class=\"song-artist item-navigate\" style=\"display: inline-block;\"\n                                         @click=\"app.getNowPlayingItemDetailed('album') && app.fullscreen(false)\">\n                                        {{ (app.mk.nowPlayingItem[\"attributes\"][\"albumName\"]) ?\n                                        (app.mk.nowPlayingItem[\"attributes\"][\"albumName\"]) : \"\" }}\n                                    </div>\n                                </div>\n                                <div class=\"song-progress\">\n                                    <div class=\"song-duration\" style=\"justify-content: space-between; height: 1px;\"\n                                         :style=\"[app.chrome.progresshover ? {'display': 'flex'} : {'display' : 'none'} ]\">\n                                        <p style=\"width: auto\">{{ app.convertTime(app.getSongProgress()) }}</p>\n                                        <p style=\"width: auto\">{{ app.convertTime(app.mk.currentPlaybackDuration) }}</p>\n                                    </div>\n                                    <input type=\"range\" step=\"0.01\" min=\"0\" :style=\"app.progressBarStyle()\"\n                                           @input=\"app.playerLCD.desiredDuration = $event.target.value;app.playerLCD.userInteraction = true\"\n                                           @mouseup=\"app.mk.seekToTime($event.target.value);app.playerLCD.desiredDuration = 0;app.playerLCD.userInteraction = false\"\n                                           :max=\"app.mk.currentPlaybackDuration\" :value=\"app.getSongProgress()\">\n                                </div>\n                            </div>\n                            <div class=\"control-buttons\">\n                                <div class=\"app-chrome-item display--large\">\n                                    <button class=\"playback-button--small shuffle\" v-if=\"$root.mk.shuffleMode == 0\"\n                                            :class=\"$root.isDisabled() && 'disabled'\"\n                                            @click=\"$root.mk.shuffleMode = 1\" :title=\"$root.getLz('term.enableShuffle')\"\n                                            v-b-tooltip.hover></button>\n                                    <button class=\"playback-button--small shuffle active\" v-else\n                                            :class=\"$root.isDisabled() && 'disabled'\"\n                                            @click=\"$root.mk.shuffleMode = 0\"\n                                            :title=\"$root.getLz('term.disableShuffle')\" v-b-tooltip.hover></button>\n                                </div>\n                                <div class=\"app-chrome-item display--large\">\n                                    <button class=\"playback-button previous\" @click=\"$root.prevButton()\"\n                                            :class=\"$root.isPrevDisabled() && 'disabled'\"\n                                            :title=\"$root.getLz('term.previous')\" v-b-tooltip.hover></button>\n                                </div>\n                                <div class=\"app-chrome-item display--large\">\n                                    <button class=\"playback-button stop\" @click=\"$root.mk.stop()\"\n                                            v-if=\"$root.mk.isPlaying && $root.mk.nowPlayingItem.attributes.playParams.kind == 'radioStation'\"\n                                            :title=\"$root.getLz('term.stop')\" v-b-tooltip.hover></button>\n                                    <button class=\"playback-button pause\" @click=\"$root.mk.pause()\"\n                                            v-else-if=\"$root.mk.isPlaying\"\n                                            :title=\"$root.getLz('term.pause')\" v-b-tooltip.hover></button>\n                                    <button class=\"playback-button play\" @click=\"$root.mk.play()\" v-else\n                                            :title=\"$root.getLz('term.play')\"\n                                            v-b-tooltip.hover></button>\n                                </div>\n                                <div class=\"app-chrome-item display--large\">\n                                    <button class=\"playback-button next\" @click=\"$root.skipToNextItem()\"\n                                            :class=\"$root.isNextDisabled() && 'disabled'\"\n                                            :title=\"$root.getLz('term.next')\" v-b-tooltip.hover></button>\n                                </div>\n                                <div class=\"app-chrome-item display--large\">\n                                    <button class=\"playback-button--small repeat\" v-if=\"$root.mk.repeatMode == 0\"\n                                            :class=\"$root.isDisabled() && 'disabled'\"\n                                            @click=\"$root.mk.repeatMode = 1\"\n                                            :title=\"$root.getLz('term.enableRepeatOne')\" v-b-tooltip.hover></button>\n                                    <button class=\"playback-button--small repeat repeatOne\" @click=\"mk.repeatMode = 2\"\n                                            :class=\"$root.isDisabled() && 'disabled'\"\n                                            v-else-if=\"$root.mk.repeatMode == 1\"\n                                            :title=\"$root.getLz('term.disableRepeatOne')\" v-b-tooltip.hover></button>\n                                    <button class=\"playback-button--small repeat active\"\n                                            @click=\"$root.mk.repeatMode = 0\"\n                                            :class=\"$root.isDisabled() && 'disabled'\"\n                                            v-else-if=\"$root.mk.repeatMode == 2\"\n                                            :title=\"$root.getLz('term.disableRepeat')\"\n                                            v-b-tooltip.hover></button>\n                                </div>\n                            </div>\n                        </div>\n                        <div class=\"app-chrome-item volume display--large\">\n                            <div class=\"input-container\">\n                                <button class=\"volume-button--small volume\" @click=\"app.muteButtonPressed()\"\n                                        :class=\"{'active': app.cfg.audio.volume == 0}\"\n                                        :title=\"app.cfg.audio.muted ? $root.getLz('term.unmute') : $root.getLz('term.mute')\"\n                                        v-b-tooltip.hover></button>\n                                <input type=\"range\" class=\"slider\" @wheel=\"app.volumeWheel\"\n                                       :step=\"app.cfg.audio.volumeStep\" min=\"0\" :max=\"app.cfg.audio.maxVolume\"\n                                       v-model=\"app.mk.volume\"\n                                       v-if=\"typeof app.mk.volume != 'undefined'\" @change=\"app.checkMuteChange()\"\n                                       v-b-tooltip.hover :title=\"$root.formatVolumeTooltip()\">\n                            </div>\n                        </div>\n                </div>\n            </div>\n            <div class=\"col right-col\" v-if=\"tabMode !== ''\">\n                <div class=\"lyrics-col\" v-if=\"tabMode == 'lyrics'\">\n                    <lyrics-view :yoffset=\"120\" :time=\"time\" :lyrics=\"lyrics\"\n                                 :richlyrics=\"richlyrics\"></lyrics-view>\n                </div>\n                <div class=\"queue-col\" v-else>\n                    <cider-queue ref=\"queue\"></cider-queue>\n                </div>\n            </div>\n        </div>\n        <div class=\"app-content-container\" v-else>\n            <app-content-area></app-content-area>\n        </div>\n        <div class=\"tab-toggles\">\n            <div class=\"lyrics\" :class=\"{active: tabMode == 'lyrics'}\"\n                 @click=\"tabMode = (tabMode == 'lyrics') ? '' : 'lyrics'\"></div>\n            <div class=\"queue\" :class=\"{active: tabMode == 'queue'}\"\n                 @click=\"tabMode =  (tabMode == 'queue') ? '' :'queue'\"></div>\n            <div class=\"queue\" :class=\"{active: tabMode == 'catalog'}\"\n                 v-if=\"false\"\n                 @click=\"tabMode =  (tabMode == 'catalog') ? '' :'catalog'\"></div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('fullscreen-view', {\n    template: '#fullscreen-view',\n    props: {\n      time: {\n        type: Number,\n        required: false\n      },\n      lyrics: {\n        type: Array,\n        required: false\n      },\n      richlyrics: {\n        type: Array,\n        required: false\n      },\n      image: {\n        type: String,\n        required: false\n      },\n    },\n    data: function() {\n      return {\n        app: this.$root,\n        tabMode: \"lyrics\",\n        video: null,\n        immersiveEnabled: app.cfg.advanced.experiments.includes(\"immersive-preview\")\n      }\n    },\n    async mounted() {\n      if (app.mk.nowPlayingItem._container.type == \"albums\") {\n        try {\n          const result = (await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/${app.mk.nowPlayingItem._container.type}/${app.mk.nowPlayingItem._container.id}`, {\n            \"fields\": \"editorialArtwork,editorialVideo\",\n          })).data.data[0].attributes?.editorialVideo?.motionDetailSquare?.video\n          if (result) {\n            this.video = result\n          } else {\n            this.video = null\n          }\n        } catch (e) {\n          this.video = null\n          e = null\n        }\n      } else if (app.mk.nowPlayingItem._container.type == \"library-albums\") {\n        try {\n          const result = (await app.mk.api.v3.music(`/v1/me/library/albums/${app.mk.nowPlayingItem._container.id}/catalog`\n            , { \"fields\": \"editorialArtwork,editorialVideo\" })).data.data[0].attributes?.editorialVideo?.motionDetailSquare?.video\n          if (result) {\n            this.video = result\n          } else {\n            this.video = null\n          }\n        } catch (e) {\n          e = null\n          this.video = null\n        }\n      }\n    },\n    beforeMount() {\n      window.addEventListener('keyup', this.onEscapeKeyUp);\n    },\n    beforeDestroy() {\n      window.removeEventListener('keyup', this.onEscapeKeyUp)\n    },\n    methods: {\n      onEscapeKeyUp(event) {\n        if (event.which === 27) {\n          app.fullscreen(false);\n          console.log('js')\n        }\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/hello-world.ejs",
    "content": "<script type=\"text/x-template\" id=\"hello-world\">\n    <button @click=\"sayHello()\">Hello world!</button>\n</script>\n\n<script>\n  var hw = Vue.component('hello-world', {\n    template: '#hello-world',\n    methods: {\n      sayHello: function() {\n        alert('Hello world!');\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/inline-collection-list.ejs",
    "content": "<script type=\"text/x-template\" id=\"inline-collection-list\">\n    <div class=\"collection-page\">\n        <h3 class=\"header-text\" v-observe-visibility=\"{callback: headerVisibility}\">{{ title }}</h3>\n        <div v-if=\"data['data'] != 'null'\" class=\"well itemContainer\">\n            <template v-for=\"(item, key) in data.data\">\n                <template v-if=\"item.type == 'artists'\">\n                    <mediaitem-square :item=\"item\"></mediaitem-square>\n                </template>\n                <template v-else>\n                    <mediaitem-list-item\n                            v-if=\"getKind(item) == 'song'\"\n                            :index=\"key\"\n                            :item=\"item\"></mediaitem-list-item>\n                    <mediaitem-square v-else :item=\"item\" :type=\"getKind(item)\"></mediaitem-square>\n                </template>\n            </template>\n            <button v-if=\"triggerEnabled\" style=\"opacity:0;height: 32px;\"\n                    v-observe-visibility=\"{callback: visibilityChanged}\">{{this.app.getLz('term.showMore')}}\n            </button>\n        </div>\n        <transition name=\"fabfade\">\n            <button class=\"top-fab\" v-show=\"showFab\" @click=\"scrollToTop()\"\n                    :aria-label=\"app.getLz('action.scrollToTop')\">\n                <%- include(\"../svg/arrow-up.svg\") %>\n            </button>\n        </transition>\n        <div class=\"well itemContainer\" v-show=\"loading\">\n            <div class=\"spinner\"></div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('inline-collection-list', {\n    template: \"#inline-collection-list\",\n    props: {\n      data: {\n        required: true\n      },\n      title: {\n        type: String,\n        required: false\n      },\n      type: {\n        type: String,\n        required: false,\n        default: \"artists\"\n      },\n      parentSelector: {\n        type: String,\n        required: false,\n        default: null\n      },\n    },\n    data: function() {\n      return {\n        triggerEnabled: true,\n        canSeeTrigger: false,\n        showFab: false,\n        commonKind: \"song\",\n        api: this.$root.mk.api,\n        loading: false,\n        app: this.$root,\n      }\n    },\n    methods: {\n      getKind(item) {\n        if (typeof item.kind != \"undefined\") {\n          this.commonKind = item.kind;\n          return item.kind\n        }\n        if (typeof item.attributes.playParams != \"undefined\") {\n          this.commonKind = item.attributes.playParams.kind\n          return item.attributes.playParams.kind\n        }\n        return this.commonKind\n      },\n      scrollToTop() {\n        let target = document.querySelector(\".header-text\")\n        document.querySelector(this.parentSelector ?? \".collection-page\").scrollTo({\n          top: 0,\n          left: 0,\n          behavior: 'smooth'\n        })\n      },\n      getNext() {\n        let self = this\n        this.triggerEnabled = false;\n        if (typeof this.data.next == \"undefined\") {\n          return\n        }\n        this.loading = true\n\n        this.api.v3.music(this.data.next, app.collectionList.requestBody).then((response) => {\n          console.log(response)\n          if (!app.collectionList.response.groups) {\n            this.data.data = this.data.data.concat(response.data.data);\n            if (response.data.next) {\n              this.data.next = response.data.next;\n              this.triggerEnabled = true;\n            }\n            this.loading = false\n          } else {\n            if (!response.data.results[app.collectionList.response.groups]) {\n              this.loading = false\n              return\n            }\n            this.data.data = this.data.data.concat(response.data.results[app.collectionList.response.groups].data);\n            if (response.data.results[app.collectionList.response.groups].next) {\n              this.data.next = response.data.results[app.collectionList.response.groups].next;\n              this.triggerEnabled = true;\n              this.loading = false\n            }\n          }\n        })\n      },\n      headerVisibility: function(isVisible, entry) {\n        if (isVisible) {\n          this.showFab = false;\n        } else {\n          this.showFab = true;\n        }\n      },\n      visibilityChanged: function(isVisible, entry) {\n        if (isVisible) {\n          this.canSeeTrigger = true;\n          this.getNext();\n        } else {\n          this.canSeeTrigger = false;\n        }\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/karaoke-in.ejs",
    "content": "<script type=\"text/x-template\" id=\"karaoke-in\">\n    <div class=\"karaoke-viewer\">\n        <div class=\"lyric\">\n            <template v-for=\"segment in lyrics\" v-if=\"segmentInRange(segment.ts, segment.te, segment.x)\">\n                <div class=\"verse-group active\">\n                    <template v-for=\"(verse, verseIndex) in segment.l\"\n                              v-if=\"verseInRange(segment.ts, segment.te, verse.o)\">\n                        <span class=\"verse verse-active\">{{ verse.c }}</span>\n                    </template>\n                    <template v-else>\n                        <span class=\"verse\">{{ verse.c }}</span>\n                    </template>\n                </div>\n            </template>\n            <template v-else>\n                <div class=\"verse-group\">{{ segment.x }}</div>\n            </template>\n        </div>\n    </div>\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/libraryartist-item.ejs",
    "content": "<script type=\"text/x-template\" id=\"libraryartist-item\">\n    <div v-observe-visibility=\"{callback: visibilityChanged}\"\n         @click=\"select\"\n         class=\"cd-mediaitem-list-item\"\n         :class=\"{'mediaitem-selected': app.select_hasMediaItem(guid)}\"\n         @contextmenu=\"contextMenu\">\n        <div class=\"artwork\" v-show=\"isVisible\" v-if=\"showArtwork == true\">\n            <mediaitem-artwork\n                    :url=\"getArtwork()\"\n                    size=\"50\"\n                    :type=\"item.type\"></mediaitem-artwork>\n        </div>\n        <div class=\"info-rect\" :style=\"{'padding-left': (showArtwork ? '' : '16px')}\"\n             @dblclick=\"app.routeView(item)\">\n            <div class=\"title text-overflow-elipsis\">\n                {{ item.attributes.name }}\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('libraryartist-item', {\n    template: '#libraryartist-item',\n    data: function() {\n      return {\n        isVisible: false,\n        addedToLibrary: false,\n        guid: this.uuidv4(),\n        app: this.$root\n      }\n    },\n    props: {\n      'item': { type: Object, required: true },\n      'parent': { type: String, required: false },\n      'index': { type: Number, required: false, default: -1 },\n      'show-artwork': { type: Boolean, default: true },\n      'show-library-status': { type: Boolean, default: true },\n      'show-meta-data': { type: Boolean, default: false },\n      'show-duration': { type: Boolean, default: true },\n      'contextExt': { type: Object, required: false },\n    },\n    methods: {\n      uuidv4() {\n        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n        );\n      },\n      msToMinSec(ms) {\n        var minutes = Math.floor(ms / 60000);\n        var seconds = ((ms % 60000) / 1000).toFixed(0);\n        return minutes + \":\" + (seconds < 10 ? '0' : '') + seconds;\n      },\n      getDataType() {\n        return this.item.type\n      },\n      async select(e) {\n        let u = this.item\n        let u1 = await app.mk.api.v3.music(`/v1/me/library/artists/${u.id}/albums`, {\n          \"platform\": \"web\",\n          \"include[library-albums]\": \"artists,tracks\",\n          \"include[library-artists]\": \"catalog\",\n          \"fields[artists]\": \"url\",\n          \"includeOnly\": \"catalog,artists\"\n        })\n        app.showCollection({ data: Object.assign({}, u1.data.data) }, u.attributes.name ?? '', '');\n        app.select_selectMediaItem(u.id, this.getDataType(), this.index, this.guid, true)\n      },\n      getArtwork() {\n        let u = \"\"\n        try {\n          u = this.item.relationships.catalog.data[0].attributes.artwork.url\n        } catch (e) {\n        }\n        ;\n        return u;\n      },\n      contextMenu(event) {\n\n        let self = this\n        let data_type = this.getDataType()\n\n        let item = self.item\n        item.attributes.artistName = item.attributes.name;\n\n        let useMenu = \"normal\"\n        if (app.selectedMediaItems.length <= 1) {\n          app.selectedMediaItems = []\n          app.select_selectMediaItem(this.item.id, data_type, this.index, this.guid, true)\n        } else {\n          useMenu = \"multiple\"\n        }\n\n        let menus = {\n          multiple: {\n            items: [] //\n          },\n          normal: {\n            items: [\n              {\n                \"name\": app.getLz('action.goToArtist'),\n                \"icon\": \"./assets/feather/user.svg\",\n                \"action\": function() {\n                  app.searchAndNavigate(self.item, 'artist')\n                  console.log(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/radio.svg\",\n                \"name\": app.getLz('action.startRadio'),\n                \"action\": function() {\n                  app.mk.setStationQueue({ song: self.item.attributes.playParams.id ?? self.item.id }).then(() => {\n                    app.mk.play()\n                    app.selectedMediaItems = []\n                  })\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/share.svg\",\n                \"name\": app.getLz('action.share'),\n                \"action\": function() {\n                  if (!self.item.attributes.url && self.item.relationships) {\n                    if (self.item.relationships.catalog) {\n                      app.mkapi(self.item.attributes.playParams.kind, false, self.item.relationships.catalog.data[0].id).then(u => {\n                        self.app.copyToClipboard((u.data.data.length && u.data.data.length > 0) ? u.data.data[0].attributes.url : u.data.data.attributes.url)\n                      })\n                    }\n                  } else {\n                    self.app.copyToClipboard(self.item.attributes.url)\n                  }\n                }\n              },\n            ]\n          }\n        }\n        if (this.contextExt) {\n          // if this.context-ext.normal is true append all options to the 'normal' menu which is a kvp of arrays\n          if (this.contextExt.normal) {\n            menus.normal.items = menus.normal.items.concat(this.contextExt.normal)\n          }\n          if (this.contextExt.multiple) {\n            menus.multiple.items = menus.multiple.items.concat(this.contextExt.multiple)\n          }\n        }\n        //CiderContextMenu.Create(event, menus[useMenu]); // Depreciated Context Menu\n        app.showMenuPanel(menus[useMenu], event);\n\n      },\n      visibilityChanged: function(isVisible, entry) {\n        this.isVisible = isVisible\n      },\n      addToLibrary() {\n        let item = this.item\n        if (item.attributes.playParams.id) {\n          console.log('adding to library', item.attributes.playParams.id)\n          app.addToLibrary(item.attributes.playParams.id.toString())\n          this.addedToLibrary = true\n        } else if (item.id) {\n          console.log('adding to library', item.id)\n          app.addToLibrary(item.id.toString())\n          this.addedToLibrary = true\n        }\n      },\n      async removeFromLibrary() {\n        let item = this.item\n        let params = { \"fields[songs]\": \"inLibrary\", \"fields[albums]\": \"inLibrary\", \"relate\": \"library\" }\n        let id = item.id ?? item.attributes.playParams.id\n        let res = await app.mkapi(item.attributes.playParams.kind ?? item.type, item.attributes.playParams.isLibrary ?? false, item.attributes.playParams.id ?? item.id, params);\n        if (res && res.relationships && res.relationships.library && res.relationships.library.data && res.relationships.library.data.length > 0) {\n          id = res.relationships.library.data[0].id\n        }\n        let kind = this.item.attributes.playParams.kind ?? this.data.item ?? '';\n        let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        if (item.attributes.playParams.id) {\n          console.log('remove from library', id)\n          app.removeFromLibrary(truekind, id)\n          this.addedToLibrary = false\n        } else if (item.id) {\n          console.log('remove from library', id)\n          app.removeFromLibrary(truekind, id)\n          this.addedToLibrary = false\n        }\n      },\n      playTrack() {\n        let item = this.item\n        let parent = this.parent\n        let childIndex = this.index\n        console.log(item, parent, childIndex)\n        if (parent != null && childIndex != null) {\n          app.queueParentandplayChild(parent, childIndex, item);\n        } else {\n          app.playMediaItemById(item.attributes.playParams.id ?? item.id, item.attributes.playParams.kind ?? item.type, item.attributes.playParams.isLibrary ?? false, item.attributes.url)\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/listennow-child.ejs",
    "content": "<script type=\"text/x-template\" id=\"listennow-child\">\n    <div v-observe-visibility=\"{callback: visibilityChanged}\">\n        <template v-if=\"isVisible && recom.attributes.display.kind != 'MusicSuperHeroShelf'\">\n            <div class=\"row\">\n                <div class=\"col\" v-if=\"recom?.relationships['primary-content']?.data?.length > 0\"\n                     style=\"display: flex; margin-block:1rem;\">\n                    <div @click=\"navigateContent(recom?.relationships['primary-content']?.data[0] ?? recom?.attributes?.title?.contentIds[0] ?? '')\"\n                         class=\"listennow-chip\" style=\"height: 40px;width: 40px;align-self: center;margin-right: 10px;\"\n                         :class=\"{ 'circle': recom?.relationships['primary-content']?.data[0]?.type == 'artists'  }\">\n                        <mediaitem-artwork\n                                v-if=\"recom?.relationships['primary-content']?.data[0]?.attributes?.artwork != null\"\n                                :url=\"recom?.relationships['primary-content']?.data[0]?.attributes?.artwork?.url\"\n                                :size=\"100\"></mediaitem-artwork>\n                    </div>\n                    <div @click=\"navigateContent(recom?.relationships['primary-content']?.data[0] ?? recom?.attributes?.title?.contentIds[0] ?? '')\"\n                         style=\"width: fit-content;\"\n                         :class=\"{'item-navigate' : (recom?.attributes?.title?.contentIds?.length ?? 0) > 0 | recom?.relationships['primary-content']?.data?.length > 0}\">\n                        <span style=\"opacity: 0.5; font-weight: bold;\"> {{ recom.attributes.titleWithoutName.stringForDisplay }} </span>\n                        <h3 style=\"margin-block: 0\"> {{\n                            recom?.relationships['primary-content']?.data[0].attributes?.name ??\n                            recom.attributes.title.stringForDisplay.replace(recom.attributes.titleWithoutName.stringForDisplay,\n                            '') }}</h3>\n\n                    </div>\n                </div>\n                <div class=\"col\" v-else style=\"display: flex; margin-block:1rem;\">\n                    <h3 @click=\"navigateContent(recom?.relationships['primary-content']?.data[0] ?? recom?.attributes?.title?.contentIds[0] ?? '')\"\n                        style=\"width: fit-content; margin-block:0;\"\n                        :class=\"{'item-navigate' : (recom?.attributes?.title?.contentIds?.length ?? 0) > 0 | recom?.relationships['primary-content']?.data?.length > 0}\">\n                        {{ recom.attributes.title ? recom.attributes.title.stringForDisplay : \" \"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"recom.relationships.contents.data.length >= 10\">\n                    <button class=\"cd-btn-seeall\" @click=\"showCollection(recom)\">{{app.getLz('term.seeAll')}}</button>\n                </div>\n            </div>\n            <template\n                    v-if=\"recom.attributes.display.kind == 'MusicCoverShelf' || recom.attributes.display.kind == 'MusicCircleCoverShelf'\">\n                <mediaitem-scroller-horizontal-large\n                        :items=\"recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n            </template>\n            <template v-else>\n                <mediaitem-scroller-horizontal-sp\n                        :withReason=\"index==0\"\n                        :items=\"recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-sp>\n            </template>\n        </template>\n        <template v-else-if=\"recom.attributes.display.kind != 'MusicSuperHeroShelf'\">\n            <div style=\"height:330px\"></div>\n        </template>\n\n    </div>\n</script>\n<script>\n  Vue.component('listennow-child', {\n    template: \"#listennow-child\",\n    props: [\"recom\", \"index\"],\n    data: function() {\n      return {\n        isVisible: true,\n        app: this.$root\n      }\n    },\n    methods: {\n      visibilityChanged: function(isVisible, entry) {\n        // this.isVisible = isVisible\n      },\n      showCollection: function(recom) {\n        console.debug(recom)\n        app.showCollection(recom.relationships.contents, recom.attributes.title ? recom.attributes.title.stringForDisplay : '', 'listen_now')\n      },\n      navigateContent: async function(id) {\n\n        if (typeof id != \"string\") {\n          app.routeView(id)\n        } else {\n          try {\n            let a = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}?ids[albums]=${id}`)\n            let q1 = a.data?.data[0]\n            if (q1) {\n              app.routeView(q1)\n            } else {\n              let b = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}?ids[artists]=${id}`)\n              let q2 = b.data?.data[0]\n              if (q2) {\n                app.routeView(q2)\n              } else {\n                let c = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}?ids[playlists]=${id}`)\n                let q3 = c.data?.data[0]\n                if (q3) {\n                  app.routeView(q3)\n                }\n              }\n            }\n          } catch (e) {\n            let b = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}?ids[artists]=${id}`)\n            let q2 = b.data?.data[0]\n            if (q2) {\n              app.routeView(q2)\n            }\n          }\n        }\n\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/listitem-horizontal.ejs",
    "content": "<script type=\"text/x-template\" id=\"listitem-horizontal\">\n    <div class=\"listitem-horizontal\">\n        <vue-horizontal>\n            <div v-for=\"items in itemPages\">\n                <mediaitem-list-item\n                        v-for=\"(song, index) in items\" :show-library-status=\"showLibraryStatus\"\n                        v-bind:key=\"song.id\"\n                        :parent=\"'listitem-hr' + simplifiedParent\"\n                        :index=\"song.index\"\n                        :item=\"song\"></mediaitem-list-item>\n            </div>\n        </vue-horizontal>\n    </div>\n</script>\n\n<script>\n  Vue.component('listitem-horizontal', {\n    template: '#listitem-horizontal',\n    name: \"listitem-horizontal\",\n    props: {\n      items: {\n        type: Array,\n        required: true\n      },\n      showLibraryStatus: {\n        type: Boolean,\n        default: true\n      }\n    },\n    data: function() {\n      return {\n        itemPages: [],\n        simplifiedParent: []\n      }\n    },\n    mounted() {\n      // give every item an id\n      this.items.forEach(function(item, index) {\n        item.id = index;\n      });\n      // split items into pages\n      this.itemPages = app.arrayToChunk(this.items, 4);\n      try {\n        this.simplifiedParent = JSON.stringify(this.items.map(function(x) {\n          return x.attributes.playParams\n        }));\n        console.debug(\"simplifiedParent: \" + this.simplifiedParent);\n      } catch (e) {\n      }\n\n    },\n    watch: {\n      items: function(items) {\n        // give every item an id\n        this.items.forEach(function(item, index) {\n          item.id = index;\n        });\n        // split items into pages\n        this.itemPages = app.arrayToChunk(this.items, 4);\n        try {\n          this.simplifiedParent = JSON.stringify(this.items.map(function(x) {\n            return x.attributes.playParams\n          }));\n          console.log(\"simplifiedParent: \" + this.simplifiedParent);\n        } catch (e) {\n        }\n      }\n    },\n    methods: {\n      sayHello: function() {\n        alert('Hello world!');\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/lyrics-view.ejs",
    "content": "<script type=\"text/x-template\" id=\"lyrics-view\">\n    <div ref=\"lyricsview\" class=\"md-body lyric-body\">\n        <template v-if=\"lyrics && lyrics != [] && lyrics.length > 0 && !qqInstrumental(lyrics)\">\n            <template v-for=\"(lyric, index) in lyrics\" v-if=\"lyric && lyric.line && lyric.line != 'lrcInstrumental'\">\n                <h3 class=\"lyric-line\" @click=\"seekTo(lyric.startTime)\" :class=\"{unsynced : lyric.startTime == 9999999}\"\n                    v-bind:line-index=\"index.toString()\">\n                    <template v-if=\"richlyrics && richlyrics != [] && richlyrics.length > 0\">\n                        <div class=\"richl\">\n                            <template v-for=\"verse in getVerseLine(index-1)\">\n                                <span class=\"verse\" :lyricstart=\"lyric.startTime\"\n                                      :versestart=\"verse.o\">{{ verse.c }}</span>\n                            </template>\n                        </div>\n                    </template>\n                    <template v-else>\n                        <div class=\"norm\">\n                            {{ lyric.line }}\n                        </div>\n                    </template>\n                    <div class=\"lyrics-translation\" v-if=\"lyric.translation && lyric.translation != ''\">\n                        {{ lyric.translation }}\n                    </div>\n                </h3>\n            </template>\n            <template v-else>\n                <h3 class=\"lyric-line\" @click=\"seekTo(lyric.startTime)\"\n                    :start=\"lyric.startTime\"\n                    :end=\"lyric.endTime\" v-bind:line-index=\"index.toString()\">\n                    <div class=\"lyricWaiting\">\n                        <div class='WaitingDot1'></div>\n                        <div class='WaitingDot2'></div>\n                        <div class='WaitingDot3'></div>\n                    </div>\n                </h3>\n            </template>\n        </template>\n        <template v-else>\n            <div class=\"no-lyrics\">\n                {{app.getLz('term.noLyrics')}}\n            </div>\n        </template>\n    </div>\n</script>\n<script>\n  Vue.component('lyrics-view', {\n    template: '#lyrics-view',\n    props: [\"time\", \"lyrics\", \"richlyrics\", \"translation\", \"onindex\", \"yoffset\"],\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    watch: {\n      time: function() {\n        if (((app.lyricon && app.drawer.open) || app.appMode == 'fullscreen') && this.$refs.lyricsview) {\n          let currentLine = this.$refs.lyricsview.querySelector(`.lyric-line.active`)\n          if (currentLine && currentLine.getElementsByClassName('lyricWaiting').length > 0) {\n            let duration = currentLine.getAttribute(\"end\") - currentLine.getAttribute(\"start\");\n            let u = (this.time - currentLine.getAttribute(\"start\")) / duration;\n            if (u < 0.25 && !currentLine.classList.contains('mode1')) {\n              try {\n                currentLine.classList.add('mode1');\n                currentLine.classList.remove('mode3');\n                currentLine.classList.remove('mode2');\n              } catch (e) {\n              }\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.animation = `dotOpacity ${0.25 * duration}s cubic-bezier(0.42, 0, 0.58, 1) forwards`;\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot3')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.opacity = 0.25;\n              currentLine.getElementsByClassName('WaitingDot3')[0].style.opacity = 0.25;\n\n            } else if (u >= 0.25 && u < 0.5 && !currentLine.classList.contains('mode2')) {\n              try {\n                currentLine.classList.add('mode2');\n                currentLine.classList.remove('mode1');\n                currentLine.classList.remove('mode3');\n              } catch (e) {\n              }\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.animation = `dotOpacity ${0.25 * duration}s cubic-bezier(0.42, 0, 0.58, 1) forwards`;\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot3')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.opacity = 1;\n              currentLine.getElementsByClassName('WaitingDot3')[0].style.opacity = 0.25;\n            } else if (u >= 0.5 && u < 0.75 && !currentLine.classList.contains('mode3')) {\n              try {\n                currentLine.classList.add('mode3');\n                currentLine.classList.remove('mode1');\n                currentLine.classList.remove('mode2');\n              } catch (e) {\n              }\n              currentLine.getElementsByClassName('WaitingDot3')[0].style.animation = `dotOpacity ${0.25 * duration}s cubic-bezier(0.42, 0, 0.58, 1) forwards`;\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.opacity = 1;\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.opacity = 1;\n            } else if (u >= 0.75 && currentLine.classList.contains('mode3')) {\n              try {\n                currentLine.classList.remove('mode1');\n                currentLine.classList.remove('mode2');\n                currentLine.classList.remove('mode3');\n              } catch (e) {\n              }\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.animation = ``;\n              currentLine.getElementsByClassName('WaitingDot1')[0].style.opacity = 1;\n              currentLine.getElementsByClassName('WaitingDot2')[0].style.opacity = 1;\n\n            }\n\n          }\n\n        }\n        this.getActiveLyric();\n      }\n\n    },\n    methods: {\n      seekTo(startTime) {\n        if (startTime != 9999999) this.app.seekTo(startTime, false);\n      },\n      getActiveLyric() {\n        const delayfix = app.activeCasts[0]?.hasOwnProperty('airplay2') ? -2.5 : 0.1\n        const prevLine = app.currentLyricsLine;\n        for (var i = 0; i < this.lyrics.length; i++) {\n          if ((this.time + delayfix >= this.lyrics[i].startTime) && (this.time + delayfix <= app.lyrics[i].endTime)) {\n            if (app.currentLyricsLine != i) {\n              app.currentLyricsLine = i;\n              if (((app.lyricon && app.drawer.open) || app.appMode == 'fullscreen') && this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${i}\"]`)) {\n                if (this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${prevLine}\"]`)) {\n                  this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${prevLine}\"]`).classList.remove(\"active\");\n                }\n                this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${i}\"]`).classList.add(\"active\")\n                if (this.checkIfScrollIsStatic) {\n                  let lyricElement = this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${i}\"]`)\n                  // this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${i}\"]`).scrollIntoView({\n                  //     behavior: \"smooth\",\n                  //     block: \"nearest\", inline: 'start'\n                  // })\n                  let parent = lyricElement.parentElement\n                  let parentRect = parent.getBoundingClientRect()\n                  let lyricElementRect = lyricElement.getBoundingClientRect()\n                  let parentScrollTop = parent.scrollTop\n                  let parentScrollLeft = parent.scrollLeft\n                  let parentScrollTopDiff = parentScrollTop - parentRect.top\n                  let parentScrollLeftDiff = parentScrollLeft - parentRect.left\n                  let lyricElementScrollTop = lyricElementRect.top + parentScrollTopDiff\n                  let lyricElementScrollLeft = lyricElementRect.left + parentScrollLeftDiff\n                  let scrollTopDiff = lyricElementScrollTop - parentScrollTop\n                  let scrollLeftDiff = lyricElementScrollLeft - parentScrollLeft\n                  let scrollTop = parent.scrollTop + scrollTopDiff\n                  let scrollLeft = parent.scrollLeft + scrollLeftDiff\n                  parent.scrollTo({\n                    top: scrollTop - (this.yoffset ?? 128),\n                    left: scrollLeft,\n                    behavior: 'smooth'\n                  })\n\n                }\n              }\n            } else if (app.currentLyricsLine == 0 && app.drawer.open) {\n              if (this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"0\"]`) && !this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"0\"]`).classList.contains(\"active\"))\n                this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"0\"]`).classList.add(\"active\");\n            }\n            break;\n          }\n        }\n        try {\n          if ((app.drawer.open) || app.appMode == 'fullscreen') {\n            try {\n              this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${prevLine}\"]`).childNodes.classList.remove(\"verse-active\");\n            } catch (e) {\n            }\n            for (child of this.$refs.lyricsview.querySelector(`.lyric-line[line-index=\"${app.currentLyricsLine}\"]`).querySelectorAll(\".verse\")) {\n              if (this.time + delayfix >= child.getAttribute(\"lyricstart\") * 1 + child.getAttribute(\"versestart\") * 1) {\n                child.classList.add(\"verse-active\");\n              } else {\n                child.classList.remove(\"verse-active\");\n              }\n            }\n          }\n        } catch (e) {\n        }\n\n      },\n      getActiveVerse(timeStart, timeEnd, verseTime) {\n        let relativeTime = this.time - timeStart\n        console.log(this.time, timeEnd, timeStart, relativeTime >= verseTime && relativeTime <= timeEnd - timeStart)\n        return relativeTime >= verseTime && relativeTime <= timeEnd - timeStart\n      },\n      getVerseLine(index) {\n        if (this.richlyrics[index] != null && this.richlyrics[index].l != null) {\n          return this.richlyrics[index].l\n        } else return []\n      },\n      qqInstrumental(lyrics) {\n        for (lyric of lyrics) {\n          if (lyric.line.includes(\"纯音乐\") && lyric.line.includes(\"欣赏\")) {\n            return true\n          }\n        }\n        return false\n      },\n      checkIfScrollIsStatic: setInterval(() => {\n        try {\n          if (position === this.$refs.lyricsview.scrollTop) {\n            clearInterval(checkIfScrollIsStatic)\n            // do something\n          }\n          position = this.$refs.lyricsview.scrollTop\n        } catch (e) {\n        }\n      }, 50)\n      ,\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-artwork.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-artwork\">\n    <div class=\"mediaitem-artwork\" :style=\"awStyle\" @contextmenu=\"contextMenu\"\n         :class=\"[{'rounded': (type == 'artists')}, classes]\" :key=\"url\">\n        <img :src=\"imgSrc\"\n             ref=\"image\"\n             decoding=\"async\"\n             loading=\"lazy\"\n             :style=\"imgStyle\"\n             @load=\"imgLoaded()\"\n             class=\"mediaitem-artwork--img\">\n        <div v-if=\"video && getVideoPriority()\" class=\"animatedartwork-view-box\">\n            <animatedartwork-view :priority=\"getVideoPriority()\" :video=\"video\"></animatedartwork-view>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('mediaitem-artwork', {\n    template: '#mediaitem-artwork',\n    props: {\n      size: {\n        type: [String, Number],\n        default: '120'\n      },\n      width: {\n        type: [String, Number],\n        required: false\n      },\n      bgcolor: {\n        type: String,\n        default: ''\n      },\n      url: {\n        type: String,\n        default: ''\n      },\n      type: {\n        type: String,\n        default: ''\n      },\n      video: {\n        type: String,\n        required: false\n      },\n      videoPriority: {\n        type: Boolean,\n        required: false\n      },\n      shadow: {\n        type: String,\n        default: ''\n      },\n      upscaling: {\n        type: Boolean,\n        default: false\n      }\n    },\n    data: function() {\n      return {\n        app: this.$root,\n        isVisible: false,\n        style: {\n          \"box-shadow\": \"\"\n        },\n        awStyle: {\n          background: this.bgcolor\n        },\n        imgStyle: {\n          opacity: 0,\n          transition: \"opacity .25s linear\"\n        },\n        classes: [],\n        imgSrc: \"\"\n      }\n    },\n    computed: {\n      windowRelativeScale: function() {\n        return app.$store.state.windowRelativeScale;\n      }\n    },\n    watch: {\n      windowRelativeScale: function(newValue, oldValue) {\n        this.swapImage(newValue)\n      },\n      url: function(newValue, oldValue) {\n        this.imgSrc = app.getMediaItemArtwork(this.url, this.size, this.width)\n      }\n    },\n    mounted() {\n      this.getClasses()\n      this.imgSrc = app.getMediaItemArtwork(this.url, this.size, this.width)\n    },\n    methods: {\n      swapImage(newValue) {\n        if (!this.upscaling || window.devicePixelRatio !== 1) return\n        if (newValue > 1.5) {\n          this.imgSrc = app.getMediaItemArtwork(this.url, parseInt(this.size * 2.0), parseInt(this.size * 2.0));\n        }\n      },\n      imgLoaded() {\n        this.imgStyle.opacity = 1\n        this.swapImage(app.$store.state.windowRelativeScale)\n        // this.awStyle.background = \"\"\n      },\n      contextMenu(event) {\n        let self = this\n        app.showMenuPanel({\n          items: {\n            \"save\": {\n              name: app.getLz('action.openArtworkInBrowser'),\n              action: () => {\n                window.open(app.getMediaItemArtwork(self.url, 1024, 1024))\n              }\n            }\n          }\n        }, event)\n      },\n      getVideoPriority() {\n        if (app.cfg.visual.animated_artwork == \"always\") {\n          return true;\n        } else if (this.videoPriority && app.cfg.visual.animated_artwork == \"limited\") {\n          return true\n        } else if (app.cfg.visual.animated_artwork == \"disabled\") {\n          return false\n        }\n        return this.videoPriority\n      },\n      getClasses() {\n        switch (this.shadow) {\n          case \"none\":\n            this.classes.push(\"no-shadow\")\n            break;\n          case \"large\":\n            this.classes.push(\"shadow\")\n            break;\n          case \"subtle\":\n            this.classes.push(\"subtle-shadow\")\n            break;\n          default:\n            break;\n        }\n        return this.classes;\n      },\n      getArtworkStyle() {\n        return {\n          width: this.size + 'px',\n          height: this.size + 'px'\n        };\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-hrect.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-hrect\">\n    <template>\n        <div @click=\"app.playMediaItemById(item.attributes.playParams.id ?? item.id, item.attributes.playParams.kind ?? item.type, item.attributes.playParams.isLibrary ?? false, item.attributes.url)\"\n             class=\"cd-mediaitem-hrect\">\n            <div class=\"artwork\">\n                <mediaitem-artwork\n                        :url=\"item.attributes.artwork ? item.attributes.artwork.url : ''\"\n                        size=\"70\"\n                        :type=\"item.type\"></mediaitem-artwork>\n            </div>\n            <div class=\"info-rect\">\n                <div class=\"title text-overflow-elipsis\">\n                    {{ item.attributes.name }}\n                </div>\n                <div class=\"subtitle text-overflow-elipsis\">\n                    {{ item.type }}\n                    <template v-if=\"item.attributes.artistName\">\n                        ∙ {{ item.attributes.artistName }}\n                    </template>\n                </div>\n            </div>\n        </div>\n    </template>\n</script>\n\n<script>\n  Vue.component('mediaitem-hrect', {\n    template: '#mediaitem-hrect',\n    props: ['item'],\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-info.ejs",
    "content": ""
  },
  {
    "path": "src/renderer/views/components/mediaitem-list-item.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-list-item\">\n    <div v-observe-visibility=\"{callback: visibilityChanged, throttle: 100}\"\n         @contextmenu=\"contextMenu\"\n         @click=\"select\"\n         :data-id=\"itemId\"\n         :data-type=\"getDataType()\"\n         :data-index=\"index\"\n         :data-guid=\"guid\"\n         :data-islibrary=\"isLibrary\"\n         :key=\"itemId\"\n         class=\"cd-mediaitem-list-item\"\n         @mouseenter=\"checkLibrary\"\n         @mouseover=\"showInLibrary = true\"\n         @mouseleave=\"showInLibrary = false\"\n         @dblclick=\"route()\"\n         @controller-click=\"route()\"\n         tabindex=\"0\"\n         :class=\"[{'mediaitem-selected': app.select_hasMediaItem(guid)}, addClasses]\">\n        <div v-show=\"isVisible\" class=\"listitem-content\">\n            <div class=\"popular\"\n                 v-if=\"!showInLibrary && item?.meta?.popularity != null && item?.meta?.popularity > 0.7\"></div>\n            <div class=\"isLibrary\" v-if=\"showLibraryStatus == true\">\n                <div v-if=\"showInLibrary\" :style=\"{display: (showInLibrary ? 'block' : 'none'), 'margin-left':'11px'}\">\n                    <button @click=\"addToLibrary()\"\n                            v-if=\"!addedToLibrary && (showIndex == false ||(showIndex == true && showIndexPlaylist != false))\"\n                            :aria-label=\"$root.getLz('action.addToLibrary')\">\n                        <div class=\"svg-icon addIcon\"\n                             :style=\"{'--color': 'var(--keyColor)', '--url': 'url(./assets/feather/plus.svg)'}\"></div>\n                    </button>\n                    <button v-else-if='!(showArtwork == true && (showIndex == false ||(showIndex == true && showIndexPlaylist != false)))'\n                            @click=\"playTrack()\" :aria-label=\"$root.getLz('term.play')\">\n                        <div class=\"svg-icon playIcon\"\n                             :style=\"{'--color': 'var(--keyColor)', '--url': 'url(./assets/feather/play.svg)'}\"></div>\n                    </button>\n                </div>\n                <div v-if=\"!(app.mk.isPlaying && (((app.mk.nowPlayingItem._songId ?? (app.mk.nowPlayingItem.songId ?? app.mk.nowPlayingItem.id ))  == itemId) || (app.mk.nowPlayingItem.id  == item.id ))) && showIndex\"\n                     :style=\"{display: ((showIndex && !showInLibrary) ? 'block' : 'none'), 'margin-left':'11px'}\">\n                    <div>\n                        <div>{{ (item.attributes && !showIndexPlaylist) ? (item.attributes.trackNumber ?? '') : ((index\n                            * 1 + 1 ) ?? '')}}\n                        </div>\n                    </div>\n                </div>\n                <div v-if=\"app.mk.isPlaying && (((app.mk.nowPlayingItem._songId ?? (app.mk.nowPlayingItem.songId ?? app.mk.nowPlayingItem.id ))  == itemId) || (app.mk.nowPlayingItem.id == item.id))\"\n                     :style=\"{display: (showInLibrary ? 'none' : 'block')}\">\n                    <div class=\"loadbar-sound\"></div>\n                </div>\n            </div>\n            <div class=\"artwork\"\n                 v-if=\"showArtwork == true && (showIndex == false ||(showIndex == true && showIndexPlaylist != false)) \">\n                <mediaitem-artwork\n                        :url=\"item.attributes.artwork ? item.attributes.artwork.url : ''\"\n                        :size=\"48\"\n                        :bgcolor=\"getBgColor()\"\n                        :type=\"item.type\"></mediaitem-artwork>\n                <button class=\"overlay-play\" @click=\"playTrack()\" :aria-label=\"$root.getLz('term.play')\">\n                    <%- include(\"../svg/play.svg\") %>\n                </button>\n            </div>\n            <div class=\"info-rect\" :style=\"{'padding-left': (showArtwork ? '' : '16px')}\"\n                 @dblclick=\"route()\">\n                <div class=\"title text-overflow-elipsis\" :title=\"item.attributes.name\">\n                    {{ item.attributes.name }}\n                </div>\n                <div class=\"subtitle text-overflow-elipsis\"\n                     style=\"-webkit-box-orient: horizontal;\">\n                    <template v-if=\"item.attributes.artistName\">\n                        <div class=\"artist item-navigate text-overflow-elipsis\"\n                             :title=\"item.attributes.artistName\"\n                             @click=\"app.searchAndNavigate(item,'artist')\">\n                            {{ item.attributes.artistName }}\n                        </div>\n                        <template v-if=\"item.attributes.albumName\">&nbsp;—&nbsp;</template>\n                        <template v-if=\"item.attributes.albumName\">\n                            <div class=\"artist item-navigate text-overflow-elipsis\"\n                                 :title=\"item.attributes.albumName\"\n                                 @click=\"app.searchAndNavigate(item,'album')\">\n                                {{ item.attributes.albumName }}\n                            </div>\n                        </template>\n                    </template>\n                </div>\n            </div>\n            <div class=\"heart-icon\">\n                <!-- <div class=\"heart-unfilled\" v-if=\"isLoved == false\" :style=\"{'--url': 'url(./assets/feather/heart.svg)'}\" /> -->\n                <div class=\"heart-filled\" v-if=\"isLoved == true\"\n                     :style=\"{'--url': 'url(./assets/feather/heart-fill.svg)'}\" />\n            </div>\n            <div class=\"explicit-icon\" v-if=\"item.attributes && item.attributes.contentRating == 'explicit'\"></div>\n            <template v-if=\"showMetaData == true\" @dblclick=\"route()\">\n                <div class=\"metainfo\">\n                    {{ item.attributes.releaseDate ? new Date(item.attributes.releaseDate).toLocaleDateString()\n                    : \"\" }}\n                </div>\n                <div class=\"metainfo\">\n                    {{ item.attributes.genreNames[0] ?? \"\" }}\n                </div>\n            </template>\n            <div class=\"duration\" v-if=\"displayDuration\" @dblclick=\"route()\">\n                {{ msToMinSec(item.attributes.durationInMillis ?? 0) }}\n            </div>\n            <div class=\"duration\" v-if=\"item.attributes.playCount\" @dblclick=\"route()\">\n                {{ item.attributes.playCount }}\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('mediaitem-list-item', {\n    template: '#mediaitem-list-item',\n    data: function() {\n      return {\n        showInLibrary: false,\n        isVisible: false,\n        addedToLibrary: false,\n        guid: this.uuidv4(),\n        app: this.$root,\n        displayDuration: true,\n        addClasses: {},\n        itemId: 0,\n        isLibrary: false,\n        isLoved: null\n      }\n    },\n    props: {\n      'item': { type: Object, required: true },\n      'parent': { type: String, required: false },\n      'index': { type: Number, required: false, default: -1 },\n      'show-artwork': { type: Boolean, default: true },\n      'show-library-status': { type: Boolean, default: true },\n      'show-meta-data': { type: Boolean, default: false },\n      'show-duration': { type: Boolean, default: true },\n      'showIndex': { type: Boolean, required: false },\n      'showIndexPlaylist': { type: Boolean, required: false },\n      'contextExt': { type: Object, required: false },\n      'class-list': { type: String, required: false, default: \"\" },\n    },\n    mounted() {\n      if (this.item.attributes.playParams) {\n        this.itemId = this.item.attributes.playParams?.id ?? this.item.id;\n        this.isLibrary = this.item.attributes.playParams?.isLibrary ?? false;\n      } else {\n        this.itemId = this.item.id;\n      }\n      if (this.item.attributes.playParams && this.$root.cfg.general.showLovedTracksInline) {\n        this.getHeartStatus();\n      }\n      let duration = this.item.attributes.durationInMillis ?? 0\n      if (duration == 0 || !this.showDuration) {\n        this.displayDuration = false\n      }\n      this.getClasses()\n    },\n    methods: {\n      getBgColor() {\n        let color = `#${(this.item.attributes.artwork != null && this.item.attributes.artwork.bgColor != null) ? (this.item.attributes.artwork.bgColor) : ``}`\n        return color\n      },\n      async checkLibrary() {\n        if ((this.item?.id ?? '').toString().startsWith('ciderlocal')) {\n          return true\n        }\n        if (this.addedToLibrary) {\n          return this.addedToLibrary\n        }\n        if (this.item.type.includes(\"library-playlists\") || this.item.type.includes(\"station\")) {\n          this.addedToLibrary = true\n          return\n        }\n        this.$root.inLibrary([this.item]).then(res => {\n          this.addedToLibrary = res[0]?.attributes?.inLibrary ?? false\n        })\n        return this.addedToLibrary\n      },\n      getClasses() {\n        this.addClasses = {}\n        if (typeof this.item.attributes.playParams == \"undefined\" && this.item.type != \"podcast-episodes\") {\n          this.addClasses[\"disabled\"] = true\n        }\n        if (this.classList) {\n          let classList = this.classList.split(' ')\n          for (let i = 0; i < classList.length; i++) {\n            this.addClasses[classList[i]] = true\n          }\n        }\n      },\n      dragStart(evt) {\n        evt.dataTransfer.setData('text/plain', JSON.stringify({\n          type: this.item.attributes.playParams?.kind ?? this.item.type,\n          id: this.item.id\n        }))\n      },\n      uuidv4() {\n        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n        );\n      },\n      msToMinSec(ms) {\n        var minutes = Math.floor(ms / 60000);\n        var seconds = ((ms % 60000) / 1000).toFixed(0);\n        return minutes + \":\" + (seconds < 10 ? '0' : '') + seconds;\n      },\n      getDataType() {\n        let type = ''\n        if (typeof this.item.attributes.playParams != \"undefined\") {\n          if (this.item.attributes.playParams?.isLibrary) {\n            type = this.item.type\n          } else {\n            type = this.item.attributes.playParams?.kind\n          }\n        } else {\n          type = this.item.type\n        }\n        if (type == 'podcast-episodes') type = 'episode';\n        return type;\n      },\n      select(e) {\n        let data_type = this.getDataType()\n        let item_id = this.item.attributes.playParams?.id ?? this.item.id\n        let isLibrary = this.item.attributes.playParams?.isLibrary ?? false\n\n        if (e.shiftKey) {\n          if (this.index != -1) {\n\n            if (app.selectedMediaItems.length == 0) {\n              app.select_selectMediaItem(item_id, this.getDataType(), this.index, this.guid, isLibrary)\n            }\n            let allMediaItems = document.querySelectorAll(\".cd-mediaitem-list-item[data-index]\")\n            let startIndex = Math.min(...app.selectedMediaItems.map(item => item.index))\n            let endIndex = Math.max(...app.selectedMediaItems.map(item => item.index))\n            if (this.index < startIndex) {\n              for (let i = this.index; i <= endIndex; i++) {\n                let item = allMediaItems[i]\n                if (item) {\n                  app.select_selectMediaItem(item.getAttribute(\"data-id\"),\n                    item.getAttribute(\"data-type\"),\n                    item.getAttribute(\"data-index\"),\n                    item.getAttribute(\"data-guid\")),\n                    item.getAttribute(\"data-islibrary\")\n                }\n              }\n            } else if (this.index > endIndex) {\n              for (let i = startIndex; i <= this.index; i++) {\n                let item = allMediaItems[i]\n                if (item) {\n                  app.select_selectMediaItem(item.getAttribute(\"data-id\"),\n                    item.getAttribute(\"data-type\"),\n                    item.getAttribute(\"data-index\"),\n                    item.getAttribute(\"data-guid\")),\n                    item.getAttribute(\"data-islibrary\")\n                }\n              }\n            } else {\n              for (let i = startIndex; i <= endIndex; i++) {\n                let item = allMediaItems[i]\n                if (item) {\n                  app.select_selectMediaItem(item.getAttribute(\"data-id\"),\n                    item.getAttribute(\"data-type\"),\n                    item.getAttribute(\"data-index\"),\n                    item.getAttribute(\"data-guid\")),\n                    item.getAttribute(\"data-islibrary\")\n                }\n              }\n            }\n          }\n        } else if (e.ctrlKey) {\n          if (app.select_hasMediaItem(this.guid)) {\n            app.select_removeMediaItem(this.guid)\n          } else {\n            app.select_selectMediaItem(item_id, this.getDataType(), this.index, this.guid, isLibrary)\n          }\n        } else {\n          if (app.select_hasMediaItem(this.guid)) {\n            app.selectedMediaItems = []\n          } else {\n            app.selectedMediaItems = []\n            app.select_selectMediaItem(item_id, this.getDataType(), this.index, this.guid, isLibrary)\n          }\n        }\n      },\n      async contextMenu(event) {\n        let self = this\n        let data_type = this.getDataType()\n        let item_id = this.item.attributes.playParams?.id ?? this.item.id\n        let isLibrary = this.item.attributes.playParams?.isLibrary ?? false\n\n        let useMenu = \"normal\"\n        if (app.selectedMediaItems.length <= 1) {\n          app.selectedMediaItems = []\n          app.select_selectMediaItem(item_id, data_type, this.index, this.guid, isLibrary)\n        } else {\n          useMenu = \"multiple\"\n        }\n        let menus = {\n          multiple: {\n            items: [\n              {\n                \"name\": app.getLz('action.addToPlaylist'),\n                \"icon\": \"./assets/feather/plus.svg\",\n                \"action\": function() {\n                  app.promptAddToPlaylist()\n                }\n              },\n              {\n                name: app.getLz('action.playTracksNext').replace(\"${app.selectedMediaItems.length}\", app.selectedMediaItems.length),\n                \"icon\": \"./assets/arrow-bend-up.svg\",\n                action: () => {\n                  let itemsToPlay = {}\n                  app.selectedMediaItems.forEach(item => {\n                    if (!itemsToPlay[item.kind]) {\n                      itemsToPlay[item.kind] = []\n                    }\n                    itemsToPlay[item.kind].push(item.id)\n                  })\n                  // loop through itemsToPlay\n                  for (let kind in itemsToPlay) {\n                    let ids = itemsToPlay[kind]\n                    if (ids.length > 0) {\n                      app.mk.playNext({ [kind + \"s\"]: itemsToPlay[kind] })\n                    }\n                  }\n                  console.log(itemsToPlay)\n                  app.selectedMediaItems = []\n                }\n              },\n              {\n                name: app.getLz('action.playTracksLater').replace(\"${app.selectedMediaItems.length}\", app.selectedMediaItems.length),\n                \"icon\": \"./assets/arrow-bend-down.svg\",\n                action: () => {\n                  let itemsToPlay = {}\n                  app.selectedMediaItems.forEach(item => {\n                    if (!itemsToPlay[item.kind]) {\n                      itemsToPlay[item.kind] = []\n                    }\n                    itemsToPlay[item.kind].push(item.id)\n                  })\n                  // loop through itemsToPlay\n                  for (let kind in itemsToPlay) {\n                    let ids = itemsToPlay[kind]\n                    if (ids.length > 0) {\n                      app.mk.playLater({ [kind + \"s\"]: itemsToPlay[kind] })\n                    }\n                  }\n                  console.log(itemsToPlay)\n                  app.selectedMediaItems = []\n                }\n              },\n            ]\n          },\n          normal: {\n            headerItems: [\n              {\n                \"icon\": \"./assets/feather/heart.svg\",\n                \"id\": \"love\",\n                \"name\": this.app.getLz('action.love'),\n                \"hidden\": false,\n                \"disabled\": true,\n                \"action\": function() {\n                  self.isLoved = true\n                  app.love(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/heart.svg\",\n                \"id\": \"unlove\",\n                \"active\": true,\n                \"name\": this.app.getLz('action.unlove'),\n                \"hidden\": true,\n                \"action\": function() {\n                  self.isLoved = false\n                  app.unlove(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/thumbs-down.svg\",\n                \"id\": \"dislike\",\n                \"name\": this.app.getLz('action.dislike'),\n                \"hidden\": false,\n                \"disabled\": true,\n                \"action\": function() {\n                  app.dislike(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/thumbs-down.svg\",\n                \"id\": \"undo_dislike\",\n                \"name\": this.app.getLz('action.undoDislike'),\n                \"active\": true,\n                \"hidden\": true,\n                \"action\": function() {\n                  app.unlove(self.item)\n                }\n              },\n            ],\n            items: [\n              {\n                \"id\": \"addToLibrary\",\n                \"icon\": \"./assets/feather/plus.svg\",\n                \"name\": this.app.getLz('action.addToLibrary'),\n                \"hidden\": false,\n                \"disabled\": true,\n                \"action\": function() {\n                  self.addToLibrary()\n                }\n              },\n              {\n                \"id\": \"removeFromLibrary\",\n                \"icon\": \"./assets/feather/x-circle.svg\",\n                \"name\": app.getLz('action.removeFromLibrary'),\n                \"hidden\": true,\n                \"action\": function() {\n                  self.removeFromLibrary()\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/list.svg\",\n                \"name\": app.getLz('action.addToPlaylist'),\n                \"action\": function() {\n                  app.promptAddToPlaylist()\n                }\n              },\n              {\n                \"name\": app.getLz('action.playNext'),\n                \"icon\": \"./assets/arrow-bend-up.svg\",\n                \"action\": function() {\n                  let type = self.item.attributes.playParams?.kind ?? self.item.type\n                  if (type == \"podcast-episodes\") {\n                    type = \"episode\"\n                  }\n                  app.mk.playNext({ [type]: self.item.attributes.playParams?.id ?? self.item.id })\n                  app.mk.queue._reindex()\n                  app.selectedMediaItems = []\n                }\n              },\n              {\n                \"name\": app.getLz('action.playLater'),\n                \"icon\": \"./assets/arrow-bend-down.svg\",\n                \"action\": function() {\n                  let type = self.item.attributes.playParams?.kind ?? self.item.type\n                  if (type == \"podcast-episodes\") {\n                    type = \"episode\"\n                  }\n                  app.mk.playLater({ [type]: self.item.attributes.playParams?.id ?? self.item.id })\n                  app.mk.queue._reindex()\n                  app.selectedMediaItems = []\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/radio.svg\",\n                \"name\": app.getLz('action.startRadio'),\n                \"action\": function() {\n                  app.mk.setStationQueue({ song: self.item.attributes.playParams?.id ?? self.item.id }).then(() => {\n                    app.mk.play()\n                    app.selectedMediaItems = []\n                  })\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/user.svg\",\n                \"name\": app.getLz('action.goToArtist'),\n                \"action\": function() {\n                  app.searchAndNavigate(self.item, 'artist')\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/disc.svg\",\n                \"name\": app.getLz('action.goToAlbum'),\n                \"action\": function() {\n                  app.searchAndNavigate(self.item, 'album')\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/share.svg\",\n                \"name\": app.getLz('action.share'),\n                \"action\": async function() {\n                  let item = self.item\n                  if (!item.attributes.url) {\n                    if (item.type.includes(\"library\")) {\n                      let result = (await app.mk.api.v3.music(`/v1/me/library/${item.type.replace(\"library-\", '')}/${item.id}/catalog`)).data.data[0]\n                      if (result.attributes.url) {\n                        self.app.copyToClipboard(result.attributes.url)\n                      } else {\n                        notyf.error(\"Failed to get share URL\")\n                      }\n                    }\n                  } else {\n                    self.app.copyToClipboard(self.item.attributes.url)\n                  }\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/share.svg\",\n                \"name\": `${app.getLz('action.share')} (song.link)`,\n                \"action\": async function() {\n                  let item = self.item\n                  if(item.type.startsWith('library-')) {\n                    self.item.attributes.url = self.item.relationships.catalog.data[0].attributes.url\n                    item.attributes.url = item.relationships.catalog.data[0].attributes.url\n                  }\n                  if (!item.attributes.url) {\n                    if (item.type.includes(\"library\")) {\n                      let result = (await app.mk.api.v3.music(`/v1/me/library/${item.type.replace(\"library-\", '')}/${item.id}/catalog`)).data.data[0]\n                      if (result.attributes.url) {\n                        self.app.copyToClipboard(result.attributes.url)\n                      } else {\n                        notyf.error(\"Failed to get share URL\")\n                      }\n                    }\n                  } else {\n                    self.app.songLinkShare(self.item.attributes.url)\n                  }\n                }\n              }\n            ]\n          }\n        }\n        if (this.contextExt) {\n          // if this.context-ext.normal is true append all options to the 'normal' menu which is a kvp of arrays\n          if (this.contextExt.normal) {\n            menus.normal.items = menus.normal.items.concat(this.contextExt.normal)\n          }\n          if (this.contextExt.multiple) {\n            menus.multiple.items = menus.multiple.items.concat(this.contextExt.multiple)\n          }\n        }\n        app.showMenuPanel(menus[useMenu], event)\n\n        try {\n          await this.checkLibrary().then(res => {\n            console.log(res)\n            if (res) {\n              menus.normal.items.find(x => x.id == 'addToLibrary').hidden = true\n              menus.normal.items.find(x => x.id == 'removeFromLibrary').hidden = false\n            } else {\n              menus.normal.items.find(x => x.id == 'addToLibrary').disabled = false\n            }\n          })\n\n        } catch (e) {\n\n        }\n        try {\n          let rating = await app.getRating(self.item)\n          if (rating == 0) {\n            menus.normal.headerItems.find(x => x.id == 'love').disabled = false\n            menus.normal.headerItems.find(x => x.id == 'dislike').disabled = false\n          } else if (rating == 1) {\n            menus.normal.headerItems.find(x => x.id == 'unlove').hidden = false\n            menus.normal.headerItems.find(x => x.id == 'love').hidden = true\n          } else if (rating == -1) {\n            menus.normal.headerItems.find(x => x.id == 'undo_dislike').hidden = false\n            menus.normal.headerItems.find(x => x.id == 'dislike').hidden = true\n          }\n        } catch (err) {\n          console.log(err)\n        }\n      },\n      visibilityChanged: function(isVisible, entry) {\n        this.isVisible = isVisible\n      },\n      async getHeartStatus() {\n        try {\n          await app.getRating(this.item).then(res => {\n            if (res == 1) {\n              this.isLoved = true\n            } else {\n              this.isLoved = false\n            }\n          })\n        } catch (err) {\n          console.log(err)\n        }\n      },\n      addToLibrary() {\n        let item = this.item\n        if (item.attributes.playParams?.id) {\n          console.log('adding to library', item.attributes.playParams?.id)\n          app.addToLibrary(item.attributes.playParams?.id.toString())\n          this.addedToLibrary = true\n        } else if (item.id) {\n          console.log('adding to library', item.id)\n          app.addToLibrary(item.id.toString())\n          this.addedToLibrary = true\n        }\n      },\n      async removeFromLibrary() {\n        let item = this.item\n        let params = { \"fields[songs]\": \"inLibrary\", \"fields[albums]\": \"inLibrary\", \"relate\": \"library\" }\n        let id = item.id ?? item.attributes.playParams?.id\n        let res = await app.mkapi(item.attributes.playParams?.kind ?? item.type, item.attributes.playParams?.isLibrary ?? false, item.attributes.playParams?.id ?? item.id, params);\n        if (res && res.relationships && res.relationships.library && res.relationships.library.data && res.relationships.library.data.length > 0) {\n          id = res.relationships.library.data[0].id\n        }\n        let kind = this.item.attributes.playParams?.kind ?? this.data.item ?? '';\n        let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        if (item.attributes.playParams?.id) {\n          console.log('remove from library', id)\n          app.removeFromLibrary(truekind, id)\n          this.addedToLibrary = false\n        } else if (item.id) {\n          console.log('remove from library', id)\n          app.removeFromLibrary(truekind, id)\n          this.addedToLibrary = false\n        }\n      },\n      playTrack() {\n        let item = this.item\n        let parent = this.parent\n        let childIndex = this.index\n        let kind = (item.attributes.playParams ? (item.attributes.playParams?.kind ?? (item.type ?? '')) : (item.type ?? ''));\n        let id = (item.attributes.playParams ? (item.attributes.playParams?.id ?? (item.id ?? '')) : (item.id ?? ''));\n        ;\n        let isLibrary = item.attributes.playParams ? (item.attributes.playParams?.isLibrary ?? false) : false;\n        let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        console.log(item, parent, childIndex, kind, id, isLibrary, kind == \"playlists\", id.startsWith(\"p.\") || id.startsWith(\"pl.u\"))\n        app.mk.stop().then(() => {\n          if (parent != null && childIndex != null) {\n            app.queueParentandplayChild(parent, childIndex, item);\n          } else if (kind.includes(\"playlist\") && (id.startsWith(\"p.\") || id.startsWith(\"pl.\"))) {\n            function shuffleArray(array) {\n              for (var i = array.length - 1; i > 0; i--) {\n                var j = Math.floor(Math.random() * (i + 1));\n                var temp = array[i];\n                array[i] = array[j];\n                array[j] = temp;\n              }\n            }\n\n            app.mk.setQueue({\n              [truekind]: [item.attributes.playParams?.id ?? item.id],\n              parameters: { l: this.app.mklang }\n            }).then(function() {\n              app.mk.play().then(function() {\n                var playlistId = id\n\n                function getPlaylist(id, isLibrary) {\n                  if (isLibrary) {\n                    return this.app.mk.api.v3.music(`/v1/me/library/playlists/${id}`)\n                  } else {\n                    return this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/playlists/${id}`)\n                  }\n                }\n\n                try {\n                  getPlaylist(id, isLibrary).then(res => {\n                    //let query = res.relationships.tracks.data.map(item => new MusicKit.MediaItem(item));\n                    //if (app.mk.shuffleMode == 1){shuffleArray(query); }\n                    // console.log(query)\n                    // app.mk.queue.append(query)\n                    if (!res.data.relationships.tracks.next) {\n                      return\n                    } else {\n                      getPlaylistTracks(res.data.relationships.tracks.next)\n                    }\n\n                    function getPlaylistTracks(next) {\n                      app.apiCall(app.musicBaseUrl + next, res => {\n                        // if (res.id != playlistId || next.includes(playlistId)) {\n                        //     return\n                        // }\n                        console.log('nextres', res)\n                        let query = res.data.map(item => new MusicKit.MediaItem(item))\n                        if (app.mk.shuffleMode == 1) {\n                          shuffleArray(query);\n                          console.log('shf')\n                        }\n                        app.mk.queue.append(query)\n\n                        if (res.next) {\n                          getPlaylistTracks(res.next)\n                        }\n                      })\n                    }\n                  })\n                } catch (e) {\n                }\n\n\n              })\n            })\n\n\n          } else {\n            app.playMediaItemById(item.attributes.playParams?.id ?? item.id, item.attributes.playParams?.kind ?? item.type, item.attributes.playParams?.isLibrary ?? false, item.attributes.url)\n          }\n        })\n      },\n      route() {\n        let kind = (this.item.attributes.playParams ? (this.item.attributes.playParams?.kind ?? (this.item.type ?? '')) : (this.item.type ?? ''));\n        if (kind.toLowerCase().includes('album') || kind.toLowerCase().includes('playlist')) {\n          app.routeView(this.item)\n        } else {\n          this.playTrack()\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-mvview-sp.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-mvview-sp\">\n    <div v-if=\"(item.attributes?.editorialArtwork?.subscriptionHero?.url ?? item.attributes?.artwork?.url ?? '') !='' \" style=\"position: relative; display: inline-flex;\">\n        <div @click.self='log(item);app.routeView(item)'\n             class=\"cd-mediaitem-mvview\">\n            <div style=\"height: 70px; min-height: 70px; max-height: 70px; width: 100%; margin-left: 5px;\">\n                <div class=\"title-browse-sp bold \" @click='log(item);app.routeView(item)' style=\"color: darkgrey;\">\n                    {{ badge ? badge?.designBadge : ''}}\n                </div>\n                <div class=\"title-browse-sp \">\n                    {{ (badge != null && badge?.designTag != null) ? badge?.designTag : (item.attributes?.name ?? '') }}\n                </div>\n                <div class=\"title-browse-sp semibold\" style=\"color: darkgrey;\">\n                    {{ (item?.attributes?.artistName ?? (item?.attributes?.curatorName ?? '')) }}\n                </div>\n            </div>\n            <div class=\"artwork\">\n                <mediaitem-artwork\n                        :url=\"item.attributes?.editorialArtwork?.subscriptionHero?.url ?? item.attributes?.artwork?.url\"\n                        :video=\"(item.attributes != null && item.attributes?.editorialVideo != null) ? (item.attributes?.editorialVideo?.motionDetailSquare ? item.attributes?.editorialVideo?.motionDetailSquare?.video : (item.attributes?.editorialVideo?.motionSquareVideo1x1 ? item?.attributes?.editorialVideo?.motionSquareVideo1x1?.video : '')) : '' \"\n                        :size=\"516\" :width=\"900\"\n                ></mediaitem-artwork>\n            </div>\n            <div class=\"cd-mediaitem-mvview-overlay\" @click.self='log(item);app.routeView(item)'>\n                <div class=\"button\" style=\"\n                    border-radius: 50%;\n                    background: rgba(50,50,50,0.7);\"\n                     :style=\"[(!(item.attributes?.playParams ? (item.attributes?.playParams?.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes?.playParams ? (item.attributes?.playParams?.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ?\n                     {'margin': '205px',\n                        'margin-left': '260px', 'margin-bottom': '140px',\n                        width: '30px',\n                        height: '30px',} :\n                        {'margin': '205px',\n                        'margin-left': '260px', 'margin-bottom': '140px',\n                        width: '30px',\n                        height: '30px',}]\" @click=\"app.playMediaItem(item)\">\n                    <%- include(\"../svg/play.svg\") %>\n                </div>\n            </div>\n        </div>\n        <div class=\"cd-mediaitem-mvview-overlay\" @click.self='log(item);app.routeView(item)' tabindex=\"0\">\n            <div class=\"button\" style=\"\n                border-radius: 50%;\n                background: rgba(50,50,50,0.7);\"\n                 :style=\"[(!(item.attributes?.playParams ? (item.attributes?.playParams?.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes?.playParams ? (item.attributes?.playParams?.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ?\n                  {'margin': '205px',\n                    'margin-left': '260px', 'margin-bottom': '140px',\n                    width: '30px',\n                    height: '30px',} :\n                    {'margin': '205px',\n                    'margin-left': '260px', 'margin-bottom': '140px',\n                    width: '30px',\n                    height: '30px',}]\" @click=\"app.playMediaItem(item)\">\n                <%- include(\"../svg/play.svg\") %>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('mediaitem-mvview-sp', {\n    template: '#mediaitem-mvview-sp',\n    props: ['item', \"imagesize\", \"badge\"],\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    methods: {\n      log(item) {\n        console.log(item);\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-mvview.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-mvview\">\n    <template>\n        <div style=\"position: relative; display: inline-flex;\">\n            <div @click.self='app.routeView(item)'\n                 class=\"cd-mediaitem-mvview\">\n                <div class=\"artwork\">\n                    <mediaitem-artwork\n                            :url=\"item.attributes.artwork ? item.attributes.artwork.url : ''\"\n                            :video=\"(item.attributes != null && item.attributes.editorialVideo != null) ? (item.attributes.editorialVideo.motionDetailSquare ? item.attributes.editorialVideo.motionDetailSquare.video : (item.attributes.editorialVideo.motionSquareVideo1x1 ? item.attributes.editorialVideo.motionSquareVideo1x1.video : '')) : '' \"\n                            :size=\"imagesize ?? 300\"\n                    ></mediaitem-artwork>\n                </div>\n                <div class=\"cd-mediaitem-mvview-overlay\" @click.self='app.routeView(item)'>\n                    <div class=\"button\" style=\"\n                    border-radius: 50%;\n                    background: rgba(50,50,50,0.7);\"\n                         :style=\"[(!(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ? {'margin': '140px',\n                        'margin-left': '250px',\n                        width: '40px',\n                        height: '40px',} :\n                        {margin: '35px',  'margin-left': '95px',\n                        width: '120px',\n                        height: '120px',}]\" @click=\"app.playMediaItem(item)\">\n                        <%- include(\"../svg/play.svg\") %>\n                    </div>\n                </div>\n                <div class=\"title text-overflow-elipsis\" @click='app.routeView(item)'>\n                    {{ item.attributes.name ?? '' }}\n                </div>\n                <div class=\"subtitle text-overflow-elipsis item-navigate\" v-if=\"item.attributes.artistName\"\n                     :style=\"{'z-index': ((item.attributes.editorialNotes == null) && item.attributes.artistName) ? '4' : ''}\"\n                     @click=\"if (item.attributes.artistName)app.searchAndNavigate(item,'artist')\">\n                    {{ item.attributes.artistName ?? '' }}\n                </div>\n\n            </div>\n            <div class=\"cd-mediaitem-mvview-overlay\" @click.self='app.routeView(item)' tabindex=\"0\">\n                <div class=\"button\" style=\"\n                border-radius: 50%;\n                background: rgba(50,50,50,0.7);\"\n                     :style=\"[(!(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('radioStation') && !(item.attributes.playParams ? (item.attributes.playParams.kind ?? (item.type ?? '')): (item.type ?? '')).includes('song')) ? {'margin': '140px',\n                    'margin-left': '250px',\n                    width: '40px',\n                    height: '40px',} :\n                    {margin: '35px',  'margin-left': '95px',\n                    width: '120px',\n                    height: '120px',}]\" @click=\"app.playMediaItem(item)\">\n                    <%- include(\"../svg/play.svg\") %>\n                </div>\n            </div>\n        </div>\n    </template>\n</script>\n\n<script>\n  Vue.component('mediaitem-mvview', {\n    template: '#mediaitem-mvview',\n    props: ['item', \"imagesize\"],\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-scroller-horizontal-large.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-scroller-horizontal-large\">\n    <vue-horizontal>\n        <mediaitem-square :item=\"item\" :key=\"item?.id ?? ''\"\n                          v-for=\"item in items\"></mediaitem-square>\n    </vue-horizontal>\n</script>\n\n\n<script>\n  Vue.component('mediaitem-scroller-horizontal-large', {\n    template: '#mediaitem-scroller-horizontal-large',\n    props: ['items']\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-scroller-horizontal-mvview.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-scroller-horizontal-mvview\">\n    <vue-horizontal>\n        <template v-if=\"browsesp\">\n            <mediaitem-mvview-sp\n                    :item=\"\n                    ((item?.attributes?.kind != null || item?.attributes?.type == 'editorial-elements')\n                     ? item :\n                     ((item.relationships && item.relationships.contents ) ? item.relationships.contents.data[0] : item)) ?? (item)\"\n                    :imagesize=\"imagesize\" v-bind:key=\"item.id\"\n                    :badge=\"item.attributes ?? [] \" v-for=\"item in items\"></mediaitem-mvview-sp>\n        </template>\n        <template v-else>\n            <mediaitem-square :kind=\"kind\" size=\"600\" :key=\"item?.id ?? ''\"\n                              :item=\"item ? ((item.attributes?.kind != null || item.type == 'editorial-elements') ? item : ((item.relationships && item.relationships.contents ) ? item.relationships.contents.data[0] : item)) : []\"\n                              :imagesize=\"imagesize\"\n                              v-bind:key=\"item.id\"\n                              v-for=\"item in items\"></mediaitem-square>\n        </template>\n    </vue-horizontal>\n</script>\n\n\n<script>\n  Vue.component('mediaitem-scroller-horizontal-mvview', {\n    template: '#mediaitem-scroller-horizontal-mvview',\n    props: {\n      items: {\n        type: Array,\n        required: true\n      },\n      imagesize: {\n        type: Number,\n        required: false\n      },\n      browsesp: {\n        type: Boolean,\n        required: false\n      },\n      kind: {\n        type: String,\n        required: false,\n        default: \"\"\n      }\n    },\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    // mounted(){\n    //     console.log('hes',this.items)\n    // }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-scroller-horizontal-sp.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-scroller-horizontal-sp\">\n    <div class=\"cd-hmedia-scroller hmedia-scroller-card\">\n        <vue-horizontal>\n            <template>\n                <mediaitem-square kind=\"card\" :item=\"item\" size=\"300\" :reasonShown=\"withReason\" v-bind:key=\"item.id\"\n                                  v-for=\"item in items\"></mediaitem-square>\n            </template>\n        </vue-horizontal>\n    </div>\n</script>\n\n<script>\n  Vue.component('mediaitem-scroller-horizontal-sp', {\n    template: '#mediaitem-scroller-horizontal-sp',\n    props: {\n      'items': { type: Array, required: false },\n      'withReason': { type: Boolean, required: false, default: false },\n    },\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-scroller-horizontal.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-scroller-horizontal\">\n    <vue-horizontal ref=\"horizontal\">\n        <slot></slot>\n        <mediaitem-square :key=\"item?.id ?? ''\" :kind=\"kind\" :item=\"item\" v-for=\"item in items\"></mediaitem-square>\n    </vue-horizontal>\n</script>\n\n<script>\n  Vue.component('mediaitem-scroller-horizontal', {\n    template: '#mediaitem-scroller-horizontal',\n    props: {\n      'items': {\n        type: Array,\n        required: false\n      },\n      'kind': {\n        type: String,\n        required: false,\n        defualt: \"\"\n      }\n    },\n    data: function() {\n      return {\n        app: this.$root,\n      }\n    },\n    mounted() {\n      // this.$refs.horizontal.refresh()\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/mediaitem-square.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-square\">\n  <div tabindex=\"0\" class=\"cd-mediaitem-square-container\"\n       @click.self=\"app.routeView(item)\"\n       @controller-click=\"app.routeView(item)\"\n       @contextmenu.self=\"getContextMenu\"\n       v-observe-visibility=\"{callback: visibilityChanged}\"\n  >\n      <div v-if=\"reasonShown\" class=\"reasonSP \">{{item?.meta?.reason?.stringForDisplay ?? ''}}</div>\n      <div style=\"{'--spcolor': getBgColor()}\"\n           class=\"cd-mediaitem-square\" :class=\"getClasses()\" @contextmenu=\"getContextMenu\">\n              <div class=\"artwork-container\" v-show=\"isVisible\">\n                  <div class=\"unavailable-overlay\" v-if=\"unavailable\">\n                      <div class=\"codicon codicon-circle-slash\"></div>\n                  </div>\n                  <div class=\"artwork\" @click='app.routeView(item)'>\n                      <mediaitem-artwork\n                              :url=\"getArtworkUrl()\"\n                              :video=\"(item.attributes != null && item.attributes.editorialVideo != null) ? (item.attributes.editorialVideo.motionDetailSquare ? item.attributes.editorialVideo.motionDetailSquare.video : (item.attributes.editorialVideo.motionSquareVideo1x1 ? item.attributes.editorialVideo.motionSquareVideo1x1.video : '')) : '' \"\n                              :size=\"size\"\n              :upscaling=\"true\"\n                              shadow=\"subtle\"\n                              :bgcolor=\"getBgColor()\"\n                              :video-priority=\"forceVideo\"\n                              :type=\"item.type\"></mediaitem-artwork>\n                  </div>\n                  <button class=\"menu-btn\" v-if=\"!nomenu.includes(item.type)\"\n                          @click=\"getContextMenu\" :aria-label=\"$root.getLz('term.more')\">\n                      <%- include(\"../svg/more.svg\") %>\n                  </button>\n                  <button class=\"play-btn\" v-if=\"!noplay.includes(item.type)\"\n                          @click=\"app.playMediaItem(item)\" :aria-label=\"$root.getLz('term.play')\">\n                      <%- include(\"../svg/play.svg\") %>\n                  </button>\n                  <div class=\"badge-container\" v-if=\"itemBadges.length != 0\">\n                      <div class=\"socialBadge\" v-for=\"badge in itemBadges.limit(1)\" v-bind:key=\"badge.id\">\n                          <mediaitem-artwork\n                                  :url=\"(badge.attributes.artwork ? badge.attributes.artwork.url : '')\"\n                                  :size=\"32\"></mediaitem-artwork>\n                      </div>\n                  </div>\n              </div>\n              <div class=\"info-rect\" :class=\"{'info-rect-card': kind == 'card'}\"\n        v-show=\"isVisible\"\n                   :style=\"{'--bgartwork': getArtworkUrl(size, true)}\">\n                  <div class=\"title\"\n                       :title=\"item.attributes?.name ?? (item.relationships?.contents?.data[0]?.attributes?.name ?? (item.attributes?.editorialNotes?.name ?? ''))\"\n                       v-if=\"item.attributes.artistNames == null || kind != 'card'\" @click='app.routeView(item)'>\n                      <div class=\"item-navigate text-overflow-elipsis\">{{ (item.attributes?.editorialElementKind == \"394\" && item.relationships?.contents?.data[0]?.attributes?.shortName != null ) ? item.relationships?.contents?.data[0]?.attributes?.shortName : (item.attributes?.name ? ((removeamtext ) ? item.attributes?.name.replace(/&nbsp;/g, ' ').replace(/Apple Music |^Apple |/g, '') : item.attributes?.name.replace(/&nbsp;/g, ' ')) :\n                          (item.relationships?.contents?.data[0]?.attributes?.name ??\n                          (item.attributes?.editorialNotes?.name ?? ''))) }}\n                      </div>\n                      <div class=\"explicit-icon\" v-if=\"item.attributes && item.attributes.contentRating == 'explicit'\"\n                           style=\"background-image: url(./assets/explicit.svg);height: 12px;width: 12px;filter: contrast(0);background-repeat: no-repeat;margin-top: 2.63px;margin-left: 4px;\"></div>\n                  </div>\n                  <div :title=\"getSubtitle()\" class=\"subtitle item-navigate text-overflow-elipsis\"\n                       @click=\"getSubtitleNavigation()\"\n                       v-if=\"getSubtitle() != ''\">\n                      {{ getSubtitle() }}\n                  </div>\n                  <div class=\"subtitle\" v-if=\"getSubtitle() == '' && kind != 'card'\">&nbsp;</div>\n              </div>\n      </div>\n  </div>\n</script>\n\n<script>\nVue.component('mediaitem-square', {\n  template: '#mediaitem-square',\n  props: {\n    item: {\n      type: Object,\n      required: true\n    },\n    kind: {\n      type: String,\n      default: ''\n    },\n    size: {\n      type: String,\n      default: '190'\n    },\n    forceVideo: {\n      type: Boolean,\n      default: false\n    },\n    reasonShown: {\n      type: Boolean,\n      default: false,\n      required: false\n    },\n          noScale: {\n              type: Boolean,\n              default: false,\n              required: false\n          },\n    imageformat: {\n              type: String,\n              default: 'cc',\n              required: false\n          },\n    removeamtext: {\n              type: Boolean,\n              default: false,\n              required: false\n    },\n    'contextExt': { type: Object, required: false },\n  },\n  data: function () {\n    return {\n      isVisible: false,\n      addedToLibrary: false,\n      guid: this.uuidv4(),\n      noplay: [\"apple-curators\", \"editorial-elements\", \"editorial-items\"],\n      nomenu: [\"stations\", \"apple-curators\", \"editorial-elements\", \"editorial-items\"],\n      app: this.$root,\n      badges: this.$root.socialBadges.badgeMap,\n      itemBadges: [],\n      unavailable: false\n    }\n  },\n  async mounted() {\n    await this.getBadges()\n    if (typeof this.item.attributes.playParams == \"object\") {\n      if (this.item.attributes.playParams.kind.includes(\"radioStation\") && (this.item.attributes.playParams.streamingKind == 1)) {\n        this.unavailable = true\n      }\n    } else {\n      if (this.item.type == \"music-movies\" || this.item.type == \"tv-episodes\") {\n        this.unavailable = true\n      }\n    }\n  },\n  methods: {\n    getBgColor() {\n      return `#${(this.item.attributes.artwork != null && this.item.attributes.artwork.bgColor != null) ? (this.item.attributes.artwork.bgColor) : ``}`\n    },\n    getContextMenu(event) {\n      if (this.item.type === \"artists\") {\n        return this.artistMenu(event)\n      } else {\n        return this.contextMenu(event)\n      }\n    },\n    getSubtitle() {\n      if (this.kind == \"card\") {\n        if (typeof this.item.attributes.artistNames != \"undefined\") {\n          return this.item.attributes.artistNames\n        } else if (typeof this.item.attributes.editorialNotes != \"undefined\") {\n          return this.item?.attributes?.editorialNotes?.short ?? (this.item.attributes?.editorialNotes?.name ?? '')\n        } else if (typeof this.item.attributes.artistName != \"undefined\") {\n          return this.item.attributes.artistName\n        } else {\n          return ''\n        }\n      } else {\n        if (typeof this.item.attributes.artistName != \"undefined\") {\n          return this.item.attributes.artistName\n        } else if (typeof this.item.attributes.artist != \"undefined\") {\n          return this.item.attributes.artist.attributes.name\n        } else if (typeof this.item.attributes.curatorName != \"undefined\") {\n          return this.item.attributes.curatorName\n        } else {\n          return ''\n        }\n      }\n    },\n    getSubtitleNavigation() {\n      if (this.kind === 'card' || this.item.type === \"playlists\") {\n        try {\n          if (typeof this.item.attributes.artistName != \"undefined\") {\n            return app.searchAndNavigate(this.item, 'artist')\n          } else {\n            return app.routeView(this.item)\n          }\n        } catch (e) {\n          return app.routeView(this.item)\n        }\n      } else {\n        if (typeof this.item.attributes.artistName != \"undefined\") {\n          return app.searchAndNavigate(this.item, 'artist')\n        } else {\n          return app.routeView(this.item)\n        }\n      }\n    },\n    async getBadges() {\n      const self = this\n      const id = ((this.item.attributes?.playParams ?? false) ? this.item.attributes?.playParams.id : null) || this.item.id\n      if (id && this.badges[id]) {\n        let friends = this.badges[id]\n        if (friends) {\n          friends.forEach(function (friend) {\n            self.app.mk.api.v3.music(`/v1/social/${app.mk.storefrontId}/social-profiles/${friend}`).then(data => {\n              self.itemBadges.push(data.data.data[0])\n            })\n          })\n        }\n      }\n    },\n    revisedRandId() {\n      return Math.random().toString(36).replace(/[^a-z]+/g, '').slice(2, 10);\n    },\n    async isInLibrary() {\n      if (this.item.type && !this.item.type.includes(\"library\")) {\n        let params = {\n          relate: \"library\",\n          \"fields\": \"inLibrary\",\n          \"extend\": this.revisedRandId()\n        }\n        let kind = this.item.type ?? this.item.attributes.playParams.kind\n        let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        if (truekind === \"musicVideos\") {\n          truekind = \"music-videos\"\n        }\n        let res = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/?ids[${truekind}]=${this.item.attributes.playParams.id ?? this.item.id}`, params);\n        res = res.data.data[0]\n        this.addedToLibrary = (res && res.attributes && res.attributes.inLibrary) ? res.attributes.inLibrary : false\n      } else {\n        this.addedToLibrary = true\n      }\n    },\n    async removeFromLibrary(id) {\n      let params = {\n        relate: \"library\",\n        \"fields\": \"inLibrary\",\n        \"extend\": this.revisedRandId()\n      }\n      let kind = this.item.type ?? this.item.attributes.playParams.kind\n      let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n      if (truekind == \"musicVideos\") {\n        truekind = \"music-videos\"\n      }\n      let res = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/?ids[${truekind}]=${this.item.attributes.playParams.id ?? this.item.id}`, params);\n      res = res.data.data[0]\n      if (res && res.relationships && res.relationships.library && res.relationships.library.data && res.relationships.library.data.length > 0) {\n        id = res.relationships.library.data[0].id\n      }\n\n      app.mk.api.v3.music(`v1/me/library/${truekind}/${id.toString()}`, {},\n        {\n          fetchOptions: {\n            method: \"DELETE\"\n          }\n        })\n      this.addedToLibrary = true\n    },\n    uuidv4() {\n      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n      );\n    },\n    getArtworkUrl(size = -1, includeUrl = false) {\n      let artwork = this.item?.attributes?.artwork ? this.item?.attributes?.artwork?.url : (this.item?.attributes?.editorialArtwork?.subscriptionCover?.url ?? '')\n      if (size != -1) {\n        artwork = artwork.replace('{w}', size).replace('{h}', size).replace('{f}', \"webp\").replace('{c}', (size === 900 || size === 380 || size === 600 ) ? \"sr\" : this.imageformat);\n      }\n      switch (this.kind) {\n        case \"385\":\n          artwork = (this.item.attributes.editorialArtwork?.subscriptionHero?.url ?? (this.item.attributes.artwork?.url ?? (this.item.relationships?.contents?.data[0]?.attributes?.editorialArtwork?.subscriptionHero?.url ?? ''))).replace('{c}', (size === 900 || size === 380 || size === 600 ) ? \"sr\" : this.imageformat);\n          break;\n      }\n      if (!includeUrl) {\n        return artwork\n      } else {\n        return `url(\"${artwork}\")`\n      }\n    },\n    getClasses() {\n      let type = []\n              let classes = []\n              if(this.noScale) {\n                  classes.push(\"noscale\")\n              }\n      try {\n        type = this.item.type\n\n      } catch (e) {\n        console.log('sd', this.item)\n      }\n\n      if (this.kind !== \"\") {\n        type = this.kind\n      }\n      switch (type) {\n        default:\n\n          break;\n        case \"editorial-elements\":\n        case \"card\":\n          classes.push(\"mediaitem-card\")\n          break;\n        case \"385\": // editorial\n                      classes.push(\"mediaitem-brick\")\n          break;\n        case \"small\":\n          classes.push(\"mediaitem-small\")\n          break;\n        case \"music-videos\":\n        case \"uploadedVideo\":\n        case \"uploaded-videos\":\n        case \"library-music-videos\":\n          classes.push(\"mediaitem-video\")\n          break;\n      }\n              return classes\n    },\n    visibilityChanged: function (isVisible, entry) {\n      this.isVisible = isVisible\n    },\n    async contextMenu(event) {\n      if (this.nomenu.includes(this.item.type)) {\n        return\n      }\n      if (!event) {\n        event = this.$refs.main\n      } else {\n        console.log(event)\n      }\n      let self = this\n      let useMenu = \"normal\"\n      if (app.selectedMediaItems.length <= 1) {\n        app.selectedMediaItems = []\n        app.select_selectMediaItem(this.item.attributes.playParams.id ?? this.item.id, this.item.attributes.playParams.kind ?? this.item.type, this.index, this.guid, this.item.attributes.playParams.isLibrary ?? false)\n      } else {\n        useMenu = \"multiple\"\n      }\n      let menus = {\n        multiple: {\n          items: [\n            {\n              name: app.getLz('action.playTracksNext').replace(\"${app.selectedMediaItems.length}\", app.selectedMediaItems.length),\n              \"icon\": \"./assets/arrow-bend-up.svg\",\n              action: () => {\n                let itemsToPlay = {}\n                app.selectedMediaItems.forEach(item => {\n                  if (!itemsToPlay[item.kind]) {\n                    itemsToPlay[item.kind] = []\n                  }\n                  itemsToPlay[item.kind].push(item.id)\n                })\n                // loop through itemsToPlay\n                for (let kind in itemsToPlay) {\n                  let ids = itemsToPlay[kind]\n                  if (ids.length > 0) {\n                    app.mk.playNext({ [kind + \"s\"]: itemsToPlay[kind] })\n                  }\n                }\n                console.log(itemsToPlay)\n                app.selectedMediaItems = []\n              }\n            },\n            {\n              name: app.getLz('action.playTracksLater').replace(\"${app.selectedMediaItems.length}\", app.selectedMediaItems.length),\n              \"icon\": \"./assets/arrow-bend-down.svg\",\n              action: () => {\n                let itemsToPlay = {}\n                app.selectedMediaItems.forEach(item => {\n                  if (!itemsToPlay[item.kind]) {\n                    itemsToPlay[item.kind] = []\n                  }\n                  itemsToPlay[item.kind].push(item.id)\n                })\n                // loop through itemsToPlay\n                for (let kind in itemsToPlay) {\n                  let ids = itemsToPlay[kind]\n                  if (ids.length > 0) {\n                    app.mk.playLater({ [kind + \"s\"]: itemsToPlay[kind] })\n                  }\n                }\n                app.selectedMediaItems = []\n              }\n            },\n          ]\n        },\n        normal: {\n          headerItems: [\n            {\n              \"icon\": \"./assets/feather/heart.svg\",\n              \"id\": \"love\",\n              \"name\": app.getLz('action.love'),\n              \"hidden\": false,\n              \"disabled\": true,\n              \"action\": function () {\n                app.love(self.item)\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/heart.svg\",\n              \"id\": \"unlove\",\n              \"active\": true,\n              \"name\": app.getLz('action.unlove'),\n              \"hidden\": true,\n              \"action\": function () {\n                app.unlove(self.item)\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/thumbs-down.svg\",\n              \"id\": \"dislike\",\n              \"name\": app.getLz('action.dislike'),\n              \"hidden\": false,\n              \"disabled\": true,\n              \"action\": function () {\n                app.dislike(self.item)\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/thumbs-down.svg\",\n              \"id\": \"undo_dislike\",\n              \"name\": app.getLz('action.undoDislike'),\n              \"active\": true,\n              \"hidden\": true,\n              \"action\": function () {\n                app.unlove(self.item)\n              }\n            },\n          ],\n          items: [\n            {\n              \"icon\": \"./assets/feather/list.svg\",\n              \"id\": \"addToPlaylist\",\n              \"name\": app.getLz('action.addToPlaylist'),\n              \"action\": function () {\n                app.promptAddToPlaylist()\n              }\n            },\n            {\n              \"id\": \"addToLibrary\",\n              \"icon\": \"./assets/feather/plus.svg\",\n              \"name\": app.getLz('action.addToLibrary'),\n              \"hidden\": false,\n              \"disabled\": true,\n              \"action\": function () {\n                let item_id = self.item.attributes.playParams.id ?? self.item.id;\n                let data_type = self.item.attributes.playParams.kind ?? self.item.type;\n                app.addToLibrary(item_id);\n                self.addedToLibrary = true;\n              }\n            },\n            {\n              \"id\": \"removeFromLibrary\",\n              \"icon\": \"./assets/feather/x-circle.svg\",\n              \"name\": app.getLz('action.removeFromLibrary'),\n              \"hidden\": true,\n              \"action\": async function () {\n                console.log(\"remove\");\n                let item_id = self.item.attributes.playParams.id ?? self.item.id;\n                let data_type = self.item.attributes.playParams.kind ?? self.item.type;\n                await self.removeFromLibrary(item_id);\n                self.addedToLibrary = false\n              }\n            },\n            {\n              \"name\": app.getLz('action.playNext'),\n              \"icon\": \"./assets/arrow-bend-up.svg\",\n              \"action\": function () {\n                app.mk.playNext({ [self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id })\n                app.mk.queue._reindex()\n                app.selectedMediaItems = []\n              }\n            },\n            {\n              \"name\": app.getLz('action.playLater'),\n              \"icon\": \"./assets/arrow-bend-down.svg\",\n              \"action\": function () {\n                app.mk.playLater({ [self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id })\n                app.mk.queue._reindex()\n                app.selectedMediaItems = []\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/share.svg\",\n              \"name\": app.getLz('action.share'),\n              \"action\": function () {\n                if (!self.item.attributes.url && self.item.relationships) {\n                  if (self.item.relationships.catalog) {\n                    app.mkapi(self.item.attributes.playParams.kind, false, self.item.relationships.catalog.data[0].id).then(u => {\n                      self.app.copyToClipboard((u.data.data.length && u.data.data.length > 0) ? u.data.data[0].attributes.url : u.data.data.attributes.url)\n                    })\n                  }\n                } else {\n                  self.app.copyToClipboard(self.item.attributes.url)\n                }\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/share.svg\",\n              \"name\": `${app.getLz('action.share')} (song.link)`,\n              \"action\": function () {\n                if (!self.item.attributes.url && self.item.relationships) {\n                  if (self.item.relationships.catalog) {\n                    app.mkapi(self.item.attributes.playParams.kind, false, self.item.relationships.catalog.data[0].id).then(u => {\n                      self.app.songLinkShare((u.data.data.length && u.data.data.length > 0) ? u.data.data[0].attributes.url : u.data.data.attributes.url)\n                    })\n                  }\n                } else {\n                  self.app.songLinkShare(self.item.attributes.url)\n                }\n              }\n            }\n          ]\n        }\n      }\n      if ((self.item.attributes.playParams.kind ?? self.item.type).includes(\"playlist\")) {\n        // remove the add to playlist option by id \"addToPlaylist\" using the .filter() method\n        menus.normal.items = menus.normal.items.filter(function (item) {\n          return item.id != \"addToPlaylist\"\n        })\n      }\n      app.showMenuPanel(menus[useMenu], event)\n\n      try {\n        await this.isInLibrary().then((_) => {\n          if (self.addedToLibrary) {\n            menus.normal.items.find(x => x.id == 'addToLibrary').hidden = true\n            menus.normal.items.find(x => x.id == 'removeFromLibrary').hidden = false\n          } else {\n            menus.normal.items.find(x => x.id == 'addToLibrary').disabled = false\n          }\n        })\n\n      } catch (e) {\n\n      }\n      try {\n        let rating = await app.getRating(self.item)\n        if (rating == 0) {\n          menus.normal.headerItems.find(x => x.id == 'love').disabled = false\n          menus.normal.headerItems.find(x => x.id == 'dislike').disabled = false\n        } else if (rating == 1) {\n          menus.normal.headerItems.find(x => x.id == 'unlove').hidden = false\n          menus.normal.headerItems.find(x => x.id == 'love').hidden = true\n        } else if (rating == -1) {\n          menus.normal.headerItems.find(x => x.id == 'undo_dislike').hidden = false\n          menus.normal.headerItems.find(x => x.id == 'dislike').hidden = true\n        }\n      } catch (err) {\n\n      }\n\n      if (this.contextExt) {\n        if (this.contextExt.normal) {\n          menus.normal.items = menus.normal.items.concat(this.contextExt.normal)\n        }\n        if (this.contextExt.multiple) {\n          menus.multiple.items = menus.multiple.items.concat(this.contextExt.multiple)\n        }\n      }\n    },\n    async artistMenu(event) {\n      console.debug(this.item)\n      let self = this\n      let followAction = \"follow\"\n      let followActions = {\n        follow: {\n          icon: \"./assets/star.svg\",\n          name: app.getLz('action.favorite'),\n          action: () => {\n            self.$root.setArtistFavorite(this.item.id, true)\n          }\n        },\n        unfollow: {\n          icon: \"./assets/star.svg\",\n          name: app.getLz('action.removeFavorite'),\n          action: () => {\n            self.$root.setArtistFavorite(this.item.id, false)\n          }\n        }\n      }\n      if (self.app.cfg.home.followedArtists.includes(this.item.id)) {\n        followAction = \"unfollow\"\n      }\n      app.showMenuPanel({\n        items: [\n          {\n            icon: \"./assets/feather/play.svg\",\n            name: app.getLz('action.startRadio'),\n            action: () => {\n              app.mk.setStationQueue({ artist: 'a-'+this.item.id }).then(() => {\n                app.mk.play()\n              })\n            }\n          },\n          followActions[followAction],\n          {\n            icon: \"./assets/feather/share.svg\",\n            name: app.getLz('term.share'),\n            action: () => {\n              self.app.copyToClipboard(this.item.attributes.url)\n            }\n          },\n          {\n            icon: \"./assets/feather/external-link.svg\",\n            name: app.getLz('action.openArtworkInBrowser'),\n            action: () => {\n              window.open(app.getMediaItemArtwork(this.getArtworkUrl(), 1024, 1024))\n            }\n          }\n        ]\n      }, event)\n    },\n  },\n  beforeDestroy: function () {\n    // this.item = null;\n    // this.kind = null;\n    // this.size = null;\n  }\n});\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/menu-panel.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-menu-panel\">\n    <div class=\"menu-panel\" @click.self=\"menuPanel.visible = false; if($root.hintscontext){$root.hintscontext = false;focusOther()}\" @contextmenu.self=\"menuPanel.visible = false; if($root.hintscontext){$root.hintscontext = false;focusOther()}\">\n\n        <div class=\"menu-panel-body\" ref=\"menubody\" :style=\"elStyle\" :class=\"getBodyClasses()\">\n            <div class=\"menu-header-text\" v-if=\"content.name != ''\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3 class=\"queue-header-text\">{{ content.name }}</h3>\n                    </div>\n                </div>\n            </div>\n            <div class=\"menu-header-body\" v-if=\"Object.keys(content.headerItems).length != 0\">\n                <template v-for=\"item in content.headerItems\">\n                    <button class=\"menu-option-header\" :class=\"getClasses(item)\" v-b-tooltip.hover :title=\"item.name\"\n                            v-if=\"canDisplay(item)\" :style=\"getItemStyle(item)\" @click=\"action(item)\">\n                        <div class=\"sidebar-icon\" style=\"margin: 0;\" v-if=\"item.icon\">\n                            <div class=\"svg-icon\" :style=\"{'--url': 'url(' + item.icon + ')'}\"></div>\n                        </div>\n                    </button>\n                </template>\n            </div>\n            <div class=\"menu-body\">\n                <template v-for=\"item in content.items\">\n                    <button class=\"menu-option\" v-if=\"canDisplay(item)\" :style=\"getItemStyle(item)\"\n                            @click=\"action(item)\">\n                        <div class=\"sidebar-icon\" v-if=\"item.icon\">\n                            <div class=\"svg-icon\" :style=\"{'--url': 'url(' + item.icon + ')'}\"></div>\n                        </div>\n                        {{ item.name }}\n                    </button>\n                </template>\n            </div>\n        </div>\n    </div>\n</script>\n\n\n<script>\n  Vue.component('cider-menu-panel', {\n    template: '#cider-menu-panel',\n    data: function() {\n      return {\n        app: this.$root,\n        menuPanel: this.$root.menuPanel,\n        content: this.$root.menuPanel.content,\n        getSvgIcon: this.$root.getSvgIcon,\n        position: [0, 0],\n        size: [0, 0],\n        event: this.$root.menuPanel.event,\n        direction: \"down\",\n        elStyle: {\n          opacity: 0\n        }\n      }\n    },\n    mounted() {\n      if (this.event) {\n        this.position = [this.event.clientX, this.event.clientY];\n        this.$nextTick(() => {\n        // this.size = [document.querySelector(\".menu-panel-body\").offsetWidth, document.querySelector(\".menu-panel-body\").offsetHeight];\n        // ugly hack\n        setTimeout(this.getStyle, 0.8)\n      });\n      }\n      else {\n        document.addEventListener('mouseover', event => {\n          this.event = event\n          this.position = [event.clientX, event.clientY] \n          console.log(\"pos\", this.position)\n          this.$nextTick(() => {\n          setTimeout(this.getStyle, 0.8)})\n        },{once: true})\n      }\n      \n    },\n    methods: {\n      getBodyClasses() {\n        if (this.direction == \"down\") {\n          return [\"menu-panel-body-down\"]\n        } else if (this.direction == \"up\") {\n          return [\"menu-panel-body-up\"]\n        } else {\n          return [\"foo\"]\n        }\n      },\n      getClasses(item) {\n        if (item[\"active\"]) {\n          return \"active\";\n        }\n      },\n      focusOther(){\n        document.querySelector('.search-input-container input').focus()\n      },\n      getStyle() {\n        let style = {}\n        this.size = [this.$refs.menubody.offsetWidth, this.$refs.menubody.offsetHeight];\n        if (this.event) {\n          style[\"position\"] = \"absolute\";\n          style[\"left\"] = this.event.clientX + \"px\";\n          style[\"top\"] = this.event.clientY + \"px\";\n          // make sure the menu panel isnt off the screen\n          if (this.event.clientX + this.size[0] > window.innerWidth) {\n            style[\"left\"] = (this.event.clientX - this.size[0]) + \"px\";\n          }\n          if (this.event.clientY + this.size[1] > window.innerHeight) {\n            style[\"top\"] = (this.event.clientY - this.size[1]) + \"px\";\n          }\n\n\n          // if the panel is above the mouse, set the direction to up\n          if (this.event.clientY < this.size[1]) {\n            this.direction = \"up\";\n          } else {\n            this.direction = \"down\";\n          }\n          // check if the panel is too long and goes off the screen vertically,\n          // if so move it upwards\n          if (this.event.clientY + this.size[1] > window.innerHeight) {\n            style[\"top\"] = (this.event.clientY - this.size[1]) + \"px\";\n          }\n        }\n        style[\"opacity\"] = 1\n        this.elStyle = style;\n      },\n      getItemStyle(item) {\n        let style = {}\n        if (item[\"disabled\"]) {\n          style = Object.assign(style, {\n            \"pointer-events\": \"none\",\n            \"opacity\": \"0.5\",\n          });\n        }\n        return style\n      },\n      canDisplay(item) {\n        if (!item[\"hidden\"]) {\n          return true\n        } else {\n          return false\n        }\n      },\n      async getActions() {\n        return this.content.items;\n      },\n      action(item) {\n        item.action()\n        if (!item[\"keepOpen\"]) {\n          this.menuPanel.visible = false;if(app.hintscontext){ app.hintscontext = false; document.querySelector('.search-input-container input').focus(); app.search.showHints = false}\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/miniplayer.ejs",
    "content": "<script type=\"text/x-template\" id=\"mini-view\">\n    <div class=\"mini-view\" tabindex=\"0\">\n        <div class=\"background\">\n        </div>\n        <div class=\"player-pin\" title=\"Pin to Top\" v-if=\"app.cfg.visual.miniplayer_top_toggle === false\"\n             @click=\"app.pinMiniPlayer()\">\n            <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 28 28\" fill=\"none\" class=\"feather feather-pin\">\n                <path d=\"M7.05664 16.3613C7.05664 17.1523 7.59277 17.6797 8.42773 17.6797H13.1299V21.8369C13.1299 23.0762 13.7539 24.3242 14 24.3242C14.2373 24.3242 14.8613 23.0762 14.8613 21.8369V17.6797H19.5635C20.3984 17.6797 20.9346 17.1523 20.9346 16.3613C20.9346 14.4717 19.4316 12.5293 16.9531 11.6152L16.6631 7.52832C17.9727 6.78125 19.0098 5.96387 19.4668 5.38379C19.7041 5.06738 19.8271 4.75098 19.8271 4.46973C19.8271 3.88965 19.3789 3.45898 18.7197 3.45898H9.27148C8.6123 3.45898 8.16406 3.88965 8.16406 4.46973C8.16406 4.75098 8.28711 5.06738 8.52441 5.38379C8.98145 5.96387 10.0186 6.78125 11.3281 7.52832L11.0469 11.6152C8.55957 12.5293 7.05664 14.4717 7.05664 16.3613Z\"\n                      fill=\"#ff2654\" />\n            </svg>\n        </div>\n        <div class=\"player-pin\" title=\"Unpin to Top\" v-if=\"app.cfg.visual.miniplayer_top_toggle === true\"\n             @click=\"app.pinMiniPlayer(false)\">\n            <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 28 28\" fill=\"none\" class=\"feather feather-pin-slashed\">\n                <path d=\"M9.271 3.459c-.659 0-1.107.43-1.107 1.01 0 .282.114.59.352.897.448.59 1.494 1.415 2.777 2.162l-.07 1.02 8.99 8.991c.458-.202.722-.615.722-1.178 0-1.89-1.503-3.832-3.947-4.746l-.29-4.087c1.275-.747 2.312-1.555 2.76-2.144.246-.308.37-.633.37-.914 0-.58-.45-1.011-1.108-1.011H9.27ZM5.15 6.061l16.076 16.057c.272.281.73.273.993 0a.703.703 0 0 0 0-.984L6.15 5.076a.716.716 0 0 0-1.002 0 .711.711 0 0 0 0 .985Zm1.908 10.3c0 .791.536 1.319 1.37 1.319h4.703v4.157c0 1.24.624 2.487.861 2.487.246 0 .87-1.248.87-2.487V17.81h.413l-5.537-5.545c-1.678 1.002-2.68 2.557-2.68 4.095Z\"\n                      fill=\"#ff2654\" />\n            </svg>\n        </div>\n        <div class=\"player-exit\" title=\"Close\" @click=\"app.miniPlayer(false)\">\n            <svg fill=\"#323232e3\" width=\"21\" height=\"21\" viewBox=\"0 0 21 21\" aria-role=\"presentation\" focusable=\"false\"\n                 xmlns=\"http://www.w3.org/2000/svg\">\n                <defs>\n                    <radialGradient gradientUnits=\"userSpaceOnUse\" cx=\"10.5\" cy=\"10.5\" r=\"10.5\" id=\"gradient-0\">\n                        <stop offset=\"0\" style=\"stop-color: rgba(168, 163, 163, 1)\" />\n                        <stop offset=\"1\" style=\"stop-color: rgba(118, 111, 111, 1)\" />\n                    </radialGradient>\n                </defs>\n                <path d=\"M10.5 21C4.724 21 0 16.275 0 10.5S4.724 0 10.5 0 21 4.725 21 10.5 16.276 21 10.5 21zm-3.543-5.967a.96.96 0 00.693-.295l2.837-2.842 2.85 2.842c.167.167.41.295.693.295.552 0 1.001-.461 1.001-1.012 0-.281-.115-.512-.295-.704L11.899 10.5l2.85-2.855a.875.875 0 00.295-.68c0-.55-.45-.998-1.001-.998a.871.871 0 00-.668.295l-2.888 2.855-2.862-2.843a.891.891 0 00-.668-.281.99.99 0 00-1.001.986c0 .269.116.512.295.678L9.088 10.5l-2.837 2.843a.926.926 0 00-.295.678c0 .551.45 1.012 1.001 1.012z\"\n                      fill-rule=\"nonzero\"\n                      style=\"stroke-miterlimit: 11; vector-effect: non-scaling-stroke; stroke-width: 31px; fill: url(#gradient-0);\" />\n            </svg>\n        </div>\n        <div class=\"col artwork-col\">\n            <div class=\"artwork\" @click=\"app.miniPlayer(false)\">\n                <mediaitem-artwork\n                        :size=\"600\"\n                        :url=\"image ?? ''\"\n                ></mediaitem-artwork>\n            </div>\n            <div class=\"controls-parents\">\n                <template v-if=\"app.mkReady()\">\n                    <div class=\"app-playback-controls\" @mouseover=\"app.chrome.progresshover = true\"\n                         @mouseleave=\"app.chrome.progresshover = false\" @contextmenu=\"app.nowPlayingContextMenu\">\n                        <div class=\"playback-info\">\n                            <div class=\"song-name\">\n                                {{ app.mk.nowPlayingItem[\"attributes\"][\"name\"] }}\n                            </div>\n                            <div\n                                    style=\"display: inline-block; -webkit-box-orient: horizontal; white-space: nowrap; margin-top: 0.25vh; overflow: hidden; margin-bottom: 5px;\">\n                                <div class=\"item-navigate song-artist\" style=\"display: inline-block;\"\n                                     @click=\"app.getNowPlayingItemDetailed(`artist`)\">\n                                    {{ app.mk.nowPlayingItem[\"attributes\"][\"artistName\"] }}\n                                </div>\n                                <div class=\"song-artist item-navigate\" style=\"display: inline-block;\"\n                                     @click=\"app.getNowPlayingItemDetailed('album')\">\n                                    {{ (app.mk.nowPlayingItem[\"attributes\"][\"albumName\"]) ? (\" — \" +\n                                    app.mk.nowPlayingItem[\"attributes\"][\"albumName\"]) : \"\" }}\n                                </div>\n                            </div>\n\n                            <div class=\"song-progress\">\n                                <div class=\"song-duration\"\n                                     style=\"justify-content: space-between; height: 1px; margin-bottom: 1px;\"\n                                     :style=\"[app.chrome.progresshover ? {'display': 'flex'} : {'display' : 'none'} ]\">\n                                    <p style=\"width: auto\">{{ app.convertTime(app.getSongProgress()) }}</p>\n                                    <p style=\"width: auto\">{{ app.convertTime(app.mk.currentPlaybackDuration) }}</p>\n                                </div>\n\n                                <input type=\"range\" step=\"0.01\" min=\"0\" :style=\"app.progressBarStyle()\"\n                                       @input=\"app.playerLCD.desiredDuration = $event.target.value;app.playerLCD.userInteraction = true\"\n                                       @mouseup=\"app.mk.seekToTime($event.target.value);app.playerLCD.desiredDuration = 0;app.playerLCD.userInteraction = false\"\n                                       :max=\"app.mk.currentPlaybackDuration\" :value=\"app.getSongProgress()\">\n                            </div>\n                        </div>\n                        <div class=\"control-buttons\">\n                            <div class=\"app-chrome-item display--large\">\n                                <button class=\"playback-button--small shuffle\" v-if=\"$root.mk.shuffleMode == 0\"\n                                        :class=\"$root.isDisabled() && 'disabled'\"\n                                        @click=\"$root.mk.shuffleMode = 1\" :title=\"$root.getLz('term.enableShuffle')\"\n                                        v-b-tooltip.hover></button>\n                                <button class=\"playback-button--small shuffle active\" v-else\n                                        :class=\"$root.isDisabled() && 'disabled'\"\n                                        @click=\"$root.mk.shuffleMode = 0\" :title=\"$root.getLz('term.disableShuffle')\"\n                                        v-b-tooltip.hover></button>\n                            </div>\n                            <div class=\"app-chrome-item display--large\">\n                                <button class=\"playback-button previous\" @click=\"$root.prevButton()\"\n                                        :class=\"$root.isPrevDisabled() && 'disabled'\"\n                                        :title=\"$root.getLz('term.previous')\" v-b-tooltip.hover></button>\n                            </div>\n                            <div class=\"app-chrome-item display--large\">\n                                <button class=\"playback-button stop\" @click=\"$root.mk.stop()\"\n                                        v-if=\"$root.mk.isPlaying && $root.mk.nowPlayingItem.attributes.playParams.kind == 'radioStation'\"\n                                        :title=\"$root.getLz('term.stop')\" v-b-tooltip.hover></button>\n                                <button class=\"playback-button pause\" @click=\"$root.mk.pause()\"\n                                        v-else-if=\"$root.mk.isPlaying\"\n                                        :title=\"$root.getLz('term.pause')\" v-b-tooltip.hover></button>\n                                <button class=\"playback-button play\" @click=\"$root.mk.play()\" v-else\n                                        :title=\"$root.getLz('term.play')\"\n                                        v-b-tooltip.hover></button>\n                            </div>\n                            <div class=\"app-chrome-item display--large\">\n                                <button class=\"playback-button next\" @click=\"$root.skipToNextItem()\"\n                                        :class=\"$root.isNextDisabled() && 'disabled'\"\n                                        :title=\"$root.getLz('term.next')\" v-b-tooltip.hover></button>\n                            </div>\n                            <div class=\"app-chrome-item display--large\">\n                                <button class=\"playback-button--small repeat\" v-if=\"$root.mk.repeatMode == 0\"\n                                        :class=\"$root.isDisabled() && 'disabled'\"\n                                        @click=\"$root.mk.repeatMode = 1\" :title=\"$root.getLz('term.enableRepeatOne')\"\n                                        v-b-tooltip.hover></button>\n                                <button class=\"playback-button--small repeat repeatOne\" @click=\"$root.mk.repeatMode = 2\"\n                                        :class=\"$root.isDisabled() && 'disabled'\" v-else-if=\"$root.mk.repeatMode == 1\"\n                                        :title=\"$root.getLz('term.disableRepeatOne')\" v-b-tooltip.hover></button>\n                                <button class=\"playback-button--small repeat active\" @click=\"$root.mk.repeatMode = 0\"\n                                        :class=\"$root.isDisabled() && 'disabled'\" v-else-if=\"$root.mk.repeatMode == 2\"\n                                        :title=\"$root.getLz('term.disableRepeat')\"\n                                        v-b-tooltip.hover></button>\n                            </div>\n                        </div>\n                        <div class=\"app-chrome-item volume display--large\">\n                            <div class=\"input-container\">\n                                <button class=\"volume-button--small volume\" @click=\"app.muteButtonPressed()\"\n                                        :class=\"{'active': app.cfg.audio.volume == 0}\"></button>\n                                <input type=\"range\" class=\"slider\" @wheel=\"app.volumeWheel\"\n                                       :step=\"app.cfg.audio.volumeStep\" min=\"0\" :max=\"app.cfg.audio.maxVolume\"\n                                       v-model=\"app.mk.volume\"\n                                       v-if=\"typeof app.mk.volume != 'undefined'\" @change=\"app.checkMuteChange()\">\n                            </div>\n                        </div>\n                    </div>\n            </div>\n            </template>\n        </div>\n    </div>\n    <!-- <div class=\"row fs-row\">\n\n        <div class=\"col right-col\" v-if=\"tabMode != ''\">\n             <div class=\"fs-info\">\n                <div>Name</div>\n                <div>Name</div>\n                <div>Name</div>\n            </div>\n            <div class=\"lyrics-col\" v-if=\"tabMode == 'lyrics'\">\n                <lyrics-view :yoffset=\"120\" :time=\"time\" :lyrics=\"lyrics\"\n                :richlyrics=\"richlyrics\"></lyrics-view>\n            </div>\n            <div class=\"queue-col\" v-if=\"tabMode == 'queue'\">\n                <cider-queue v-if=\"tabMode == 'queue'\" ref=\"queue\" ></cider-queue>\n            </div>\n        </div>\n    </div> -->\n    <!-- <div class=\"tab-toggles\">\n        <div class=\"lyrics\" :class=\"{active: tabMode == 'lyrics'}\" @click=\"tabMode = (tabMode == 'lyrics') ? '' : 'lyrics'\"></div>\n        <div class=\"queue\"  :class=\"{active: tabMode == 'queue'}\" @click=\"tabMode =  (tabMode == 'queue') ? '' :'queue'\"></div>\n    </div>  -->\n    </div>\n\n\n</script>\n\n<script>\n  Vue.component('mini-view', {\n    template: '#mini-view',\n    props: {\n      time: {\n        type: Number,\n        required: false\n      },\n      lyrics: {\n        type: Array,\n        required: false\n      },\n      richlyrics: {\n        type: Array,\n        required: false\n      },\n      image: {\n        type: String,\n        required: false\n      },\n    },\n    data: function() {\n      return {\n        app: this.$root,\n        tabMode: \"\",\n      }\n    },\n    beforeMount() {\n      window.addEventListener('keyup', this.onEscapeKeyUp);\n    },\n    beforeDestroy() {\n      window.removeEventListener('keyup', this.onEscapeKeyUp)\n    },\n    mounted() {\n      app.pinMiniPlayer(true)\n    },\n    methods: {\n      onEscapeKeyUp(event) {\n        if (event.which === 27) {\n          app.miniPlayer(false);\n          console.log('js')\n        }\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/moreinfo-modal.ejs",
    "content": "<script type=\"text/x-template\" id=\"moreinfo-modal\">\n    <div class=\"modal-fullscreen spatialproperties-panel moreinfo-modal\" @click.self=\"if(timedelay) close()\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{data.title}}</div>\n                <div class=\"modal-subtitle modal-title\">{{data.subtitle ?? \"\"}}</div>\n                <button class=\"close-btn\" @click=\"close()\" :aria-label=\"app.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n                <div class=\"content\" v-html=\"data.content\">\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('moreinfo-modal', {\n    template: '#moreinfo-modal',\n    data: function() {\n      return {\n        app: this.$root,\n        timedelay: false,\n      }\n    },\n    props: [\"data\"],\n    mounted() {\n      let self = this;\n      this.$nextTick(() => {\n        setTimeout(function() {\n          self.timedelay = true\n        }, 1000);\n      })\n\n    },\n    methods: {\n      close() {\n        app.modals.moreInfo = false;\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/pagination.ejs",
    "content": "<script type=\"text/x-template\" id=\"pagination\">\n    <div class=\"pagination-container\" v-if=\"!isInfinite\">\n        <button\n                class=\"md-btn page-btn\"\n                :disabled=\"effectivePage === 1\"\n                @click=\"goToPage(1)\"\n        >\n            <img class=\"md-ico-first\" />\n        </button>\n        <button\n                class=\"md-btn page-btn prev\"\n                :disabled=\"effectivePage === 1\"\n                @click=\"goToPrevious()\"\n        >\n            <img class=\"md-ico-prev\" />\n        </button>\n        <button\n                :class=\"`md-btn page-btn${ isCurrentPage(page) ? ' md-btn-primary': ''}`\"\n                @click=\"goToPage(page)\"\n                v-for=\"page in pagesToShow\"\n        >{{ page }}\n        </button>\n        <button\n                class=\"md-btn page-btn next\"\n                :disabled=\"effectivePage === numPages\"\n                @click=\"goToNext()\"\n        >\n            <img class=\"md-ico-next\" />\n        </button>\n        <button\n                class=\"md-btn page-btn last\"\n                :disabled=\"effectivePage === numPages\"\n                @click=\"goToEnd()\"\n        >\n            <img class=\"md-ico-last\" />\n        </button>\n        <div class=\"page-btn md-input-number\">\n            <input type=\"number\" min=\"1\" :max=\"numPages\" :value=\"effectivePage\" @change=\"changePage\" />\n            <span>/ {{ numPages }}</span>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('pagination', {\n    template: \"#pagination\",\n    props: {\n      'length': { type: Number, required: true },\n      'pageSize': { type: Number, required: true },\n      'scroll': { type: String, required: true },\n      'scrollSelector': { type: String, required: true }\n    },\n    data: function() {\n      return { currentPage: 1 }\n    },\n    mounted() {\n      document.querySelector(this.scrollSelector)\n        .addEventListener(\"scroll\", this.handleScroll)\n    },\n    destroyed() {\n      document.querySelector(this.scrollSelector)\n        .removeEventListener(\"scroll\", this.handleScroll)\n    },\n    watch: {\n      'length': function() {\n        if (this.isInfinite) {\n          // If a search reduces the number of things to show, we want to limit\n          // the number of songs shown as well. This is to prevent you scrolling\n          // to load your entire library, searching for one song, and then having\n          // th re-render the entire library\n          if (this.currentPage > this.numPages) {\n            this.currentPage = this.numPages;\n            this.$emit(\"onRangeChange\", this.currentRange);\n          }\n        } else {\n          this.$emit(\"onRangeChange\", this.currentRange);\n        }\n      },\n      'scroll': function() {\n        // When changing modes, set the page to 1. This is primarily to\n        // prevent going to a high page (e.g., 50) and then switching to infinite\n        // and showing 12.5k songs\n        this.currentPage = 1;\n        this.$emit(\"onRangeChange\", this.currentRange);\n      }\n    },\n    computed: {\n      isInfinite: function() {\n        return this.scroll === \"infinite\"\n      },\n      currentRange: function() {\n        if (this.isInfinite) {\n          return [0, this.currentPage * this.pageSize];\n        } else {\n          const startingPage = Math.min(this.numPages, this.currentPage);\n\n          return [\n            (startingPage - 1) * this.pageSize,\n            startingPage * this.pageSize\n          ];\n        }\n      },\n      effectivePage: function() {\n        return Math.min(this.currentPage, this.numPages)\n      },\n      numPages: function() {\n        return Math.ceil(this.length / this.pageSize) || 1;\n      },\n      pagesToShow: function() {\n        let start = this.currentPage - 2;\n        let end = this.currentPage + 2;\n\n        if (start < 1) {\n          end += (1 - start);\n          start = 1;\n        }\n\n        const endDifference = end - this.numPages;\n        if (endDifference > 0) {\n          end = this.numPages;\n          start = Math.max(1, start - endDifference);\n        }\n\n        const array = [];\n        for (let idx = start; idx <= end; idx++) {\n          array.push(idx);\n        }\n        return array;\n      }\n    },\n    methods: {\n      // Infinite Scrolling\n      handleScroll: function(event) {\n        if (this.isInfinite &&\n          this.currentPage < this.numPages &&\n          event.target.scrollTop >= event.target.scrollHeight - event.target.clientHeight) {\n          this.currentPage += 1;\n          this.$emit(\"onRangeChange\", this.currentRange);\n        }\n      },\n      // Pagination\n      isCurrentPage: function(idx) {\n        return idx === this.currentPage ||\n          (idx === this.numPages && this.currentPage > this.numPages);\n      },\n      changePage: function(event) {\n        const value = event.target.valueAsNumber;\n\n        if (!isNaN(value) && value >= 1 && value <= this.numPages) {\n          this.currentPage = value;\n          this.$emit(\"onRangeChange\", this.currentRange);\n        }\n      },\n      goToPage: function(page) {\n        this.currentPage = page;\n        this.$emit(\"onRangeChange\", this.currentRange);\n      },\n      goToPrevious: function() {\n        if (this.currentPage > 1) {\n          this.currentPage -= 1;\n          this.$emit(\"onRangeChange\", this.currentRange);\n        }\n      },\n      goToNext: function() {\n        if (this.currentPage < this.numPages) {\n          this.currentPage += 1;\n          this.$emit(\"onRangeChange\", this.currentRange);\n        }\n      },\n      goToEnd: function() {\n        this.currentPage = this.numPages;\n        this.$emit(\"onRangeChange\", this.currentRange);\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/pathmenu.ejs",
    "content": "<script type=\"text/x-template\" id=\"pathmenu\">\n    <div class=\"spatialproperties-panel castmenu pathmenu modal-fullscreen\" @click.self=\"close()\"\n         @contextmenu.self=\"close()\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{'Edit Paths'}}</div>\n                <button class=\"close-btn\" @click=\"close()\" :aria-label=\"$root.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n                <template v-for=\"folder of folders\">\n                    <div class=\"md-option-line\">\n                        <div class=\"md-option-segment\">\n                            {{folder}}\n                        </div>\n                        <div class=\"md-option-segment md-option-segment_auto\">\n                            <button class=\"md-btn\" @click=\"remove(folder)\">\n                                {{'Remove'}}\n                            </button>\n                        </div>\n                    </div>\n                </template>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <button class=\"md-btn\" @click=\"add()\">\n                            {{'Add Path'}}\n                        </button>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('pathmenu', {\n    template: '#pathmenu',\n    data: function() {\n      return {\n        folders: [],\n      }\n    },\n    mounted() {\n      this.folders = this.$root.cfg.libraryPrefs.localPaths;\n    },\n    watch: {},\n    methods: {\n      close() {\n        this.$root.modals.pathMenu = false\n      },\n      async add() {\n        const result = await ipcRenderer.invoke('folderSelector')\n        for (i of result) {\n          if (this.folders.findIndex(x => x.startsWith(i)) == -1) {\n            this.folders.push(i)\n          }\n        }\n        this.$root.cfg.libraryPrefs.localPaths = this.folders;\n        ipcRenderer.invoke(\"scanLibrary\")\n      },\n      remove(dir) {\n        this.folders = this.folders.filter(item => item !== dir)\n        this.$root.cfg.libraryPrefs.localPaths = this.folders;\n        ipcRenderer.invoke(\"scanLibrary\")\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/playlists.ejs",
    "content": ""
  },
  {
    "path": "src/renderer/views/components/plugin-menu.ejs",
    "content": "<script type=\"text/x-template\" id=\"plugin-menu\">\n    <div class=\"modal-fullscreen addtoplaylist-panel\" @click.self=\"app.resetState()\"\n         @contextmenu.self=\"app.resetState()\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{$root.getLz('term.pluginMenu')}}</div>\n                <button class=\"close-btn\" @click=\"app.resetState()\" :aria-label=\"app.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n            <span class=\"playlist-item\" v-if=\"!app.pluginInstalled\">\n                <span class=\"icon\"><%- include(\"../svg/x.svg\") %></span>\n                <span class=\"name\" style=\"top: 0.5px;\">{{$root.getLz('term.pluginMenu.none')}}</span>\n            </span>\n                <button class=\"playlist-item\" @click=\"entry.onClick(); closeMenu();\"\n                        v-for=\"entry in app.pluginMenuEntries\">\n                    <span class=\"icon\"><%- include(\"../svg/grid.svg\") %></span>\n                    <span class=\"name\" style=\"top: 0.5px;\">{{ entry.name }}</span>\n                </button>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('plugin-menu', {\n      template: '#plugin-menu',\n      data: function() {\n        return {\n          app: this.$root,\n        }\n      },\n      props: {},\n      mounted() {\n      },\n      methods: {\n        closeMenu() {\n          app.modals.pluginMenu = false\n        },\n      },\n    }\n  );\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/qrcode-modal.ejs",
    "content": "<script type=\"text/x-template\" id=\"qrcode-modal\">\n    <div class=\"modal-fullscreen spatialproperties-panel\">\n        <div class=\"modal-window\">\n            <div class=\"modal-header\">\n                <div class=\"modal-title\">{{`Web Remote QR : ` + url }}</div>\n                <button class=\"close-btn\" @click=\"close()\" :aria-label=\"app.getLz('action.close')\"></button>\n            </div>\n            <div class=\"modal-content\">\n                <img class=\"qrimg\" :src=\"src\" />\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('qrcode-modal', {\n    template: '#qrcode-modal',\n    data: function() {\n      return {\n        app: this.$root,\n\n      }\n    },\n    props: [\"src\", \"url\"],\n    mounted() {\n\n    },\n    methods: {\n      close() {\n        app.resetState()\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/queue.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-queue\">\n    <div class=\"queue-panel\">\n        <div class=\"row\">\n            <div class=\"col\">\n                <h3 class=\"queue-header-text\" v-if=\"page == 'queue'\">{{app.getLz('term.queue')}}</h3>\n                <h3 class=\"queue-header-text\" v-if=\"page == 'history'\">{{app.getLz('term.history')}}</h3>\n            </div>\n            <div class=\"col-auto cider-flex-center\">\n                <button class=\"autoplay\" :style=\"{'background': app.mk.autoplayEnabled ? 'var(--keyColor)' : ''}\"\n                        @click=\"app.mk.autoplayEnabled = !app.mk.autoplayEnabled\"\n                        :title=\"app.getLz('term.autoplay')\" v-b-tooltip.hover>\n                    <img class=\"infinity\">\n                </button>\n            </div>\n        </div>\n        <div class=\"queue-body\" v-if=\"page == 'history'\">\n            <mediaitem-list-item :show-library-status=\"false\" v-for=\"item in history\"\n                                 v-bind:key=\"item.id\"\n                                 :item=\"item\"></mediaitem-list-item>\n        </div>\n        <div class=\"queue-body\" v-if=\"page == 'queue'\">\n            <draggable v-model=\"queueItems\" @start=\"drag=true\" @end=\"drag=false;move()\">\n                <template v-for=\"(queueItem, position) in displayQueueItems\">\n                    <div v-if=\"position === 0\" :key=\"queueItem.item.id\"></div>\n                    <div class=\"cd-queue-item\" v-else\n                         :class=\"{selected: selectedItems.includes(queueItem.item.id)}\"\n                         @click=\"select($event, queueItem.item.id)\"\n                         @dblclick=\"playQueueItem(queueItem.item.id)\" :key=\"queueItem.item.id\"\n                         @contextmenu=\"queueContext($event, queueItem.item)\">\n                        <div class=\"row\">\n                            <div class=\"col-auto cider-flex-center\">\n                                <div class=\"artwork\">\n                                    <mediaitem-artwork\n                                            :url=\"queueItem.item.attributes.artwork ? queueItem.item.attributes.artwork.url : ''\"\n                                            :size=\"32\"></mediaitem-artwork>\n                                </div>\n                            </div>\n                            <div class=\"col queue-info\">\n                                <div class=\"queue-title text-overflow-elipsis\">{{ queueItem.item.attributes.name }}\n                                </div>\n                                <div class=\"queue-subtitle text-overflow-elipsis\">{{\n                                    queueItem.item.attributes.artistName }} — {{ queueItem.item.attributes.albumName }}\n                                </div>\n                            </div>\n                            <div class=\"queue-explicit-icon cider-flex-center\"\n                                 v-if=\"queueItem.item.attributes.contentRating == 'explicit'\">\n                                <div class=\"explicit-icon\"></div>\n                            </div>\n                            <div class=\"col queue-duration-info\">\n                                <div class=\"queue-duration cider-flex-center\">\n                                    {{app.convertTime(queueItem.item.attributes.durationInMillis / 1000)}}\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </template>\n            </draggable>\n        </div>\n        <div class=\"queue-footer\">\n            <div class=\"btn-group\" style=\"width:100%;\">\n                <button class=\"md-btn md-btn-small\" :class=\"{'md-btn-primary': (page == 'queue')}\"\n                        @click=\"page = 'queue'\">{{app.getLz('term.queue')}}\n                </button>\n                <button class=\"md-btn md-btn-small\" :class=\"{'md-btn-primary': (page == 'history')}\"\n                        @click=\"getHistory();page = 'history'\">{{app.getLz('term.history')}}\n                </button>\n            </div>\n            <button class=\"md-btn md-btn-small\" style=\"width:100%;margin-top:6px;\" v-if=\"queueItems.length > 1\"\n                    @click=\"app.mk.clearQueue();updateQueue()\">{{app.getLz('term.clearAll')}}\n            </button>\n        </div>\n    </div>\n</script>\n\n\n<script>\n  Vue.component('cider-queue', {\n    template: '#cider-queue',\n    data: function() {\n      return {\n        drag: false,\n        queuePosition: 0,\n        queueItems: [],\n        selected: -1,\n        selectedItems: [],\n        history: [],\n        page: \"queue\",\n        app: this.$root\n      }\n    },\n    computed: {\n      displayQueueItems() {\n        const displayLimit = 50;\n        const lastDisplayPosition = Math.min(displayLimit + this.queuePosition, this.queueItems.length);\n        return this.queueItems.slice(this.queuePosition, lastDisplayPosition);\n      }\n    },\n    mounted() {\n      this.updateQueue()\n    },\n    methods: {\n      async getHistory() {\n        let history = await app.mk.api.v3.music(`/v1/me/recent/played/tracks`, { l: this.$root.mklang })\n        this.history = history.data.data\n      },\n      select(e, id) {\n        if (e.ctrlKey || e.shiftKey) {\n          if (this.selectedItems.indexOf(id) === -1) {\n            this.selectedItems.push(id)\n          } else {\n            this.selectedItems.splice(this.selectedItems.indexOf(id), 1)\n          }\n        } else {\n          this.selectedItems = [id]\n        }\n      },\n      queueContext(event, item) {\n        const self = this\n        const useMenu = this.selectedItems.length > 1 ? \"multiple\" : \"single\"\n        const menus = {\n          single: {\n            items: [{\n              \"name\": app.getLz('action.removeFromQueue'),\n              \"action\": function() {\n                self.queueItems.splice(self.queueItems.findIndex(queueItem => queueItem.item.id === item.id), 1)\n                app.mk.queue._queueItems = self.queueItems;\n                app.mk.queue._reindex()\n              }\n            },\n              {\n                \"name\": app.getLz('action.startRadio'),\n                \"action\": function() {\n                  app.mk.setStationQueue({\n                    song: item.attributes.playParams.id ?? item.id\n                  }).then(() => {\n                    app.mk.play()\n                  })\n                }\n              },\n              {\n                \"name\": app.getLz('action.goToArtist'),\n                \"action\": function() {\n                  app.searchAndNavigate(item, 'artist')\n                }\n              },\n              {\n                \"name\": app.getLz('action.goToAlbum'),\n                \"action\": function() {\n                  app.searchAndNavigate(item, 'album')\n                }\n              },\n            ]\n          },\n          multiple: {\n            items: [{\n              \"name\": app.getLz('action.removeTracks').replace('${self.selectedItems.length}', self.selectedItems.length.toString()),\n              \"action\": function() {\n                // add property to items to be removed\n                self.selectedItems.forEach(function(item) {\n                  self.queueItems.find(x => x.item.id === item).remove = true;\n                })\n                // remove items\n                self.queueItems = self.queueItems.filter(function(item) {\n                  return !item.remove\n                })\n                app.mk.queue._queueItems = self.queueItems;\n                app.mk.queue._reindex()\n                self.selectedItems = []\n              }\n            }]\n          }\n        }\n        app.showMenuPanel(menus[useMenu], event);\n      },\n      playQueueItem(id) {\n        app.mk.changeToMediaAtIndex(app.mk.queue._itemIDs.indexOf(id))\n      },\n      updateQueue() {\n        this.selected = -1\n        if (app.mk.queue) {\n          this.queuePosition = app.mk.queue.position;\n          this.queueItems = app.mk.queue._queueItems;\n        } else {\n          this.queuePosition = 0;\n          this.queueItems = [];\n        }\n      },\n      move() {\n        this.selected = -1\n        app.mk.queue._queueItems = this.queueItems;\n        app.mk.queue._reindex()\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/settings-keybinds.ejs",
    "content": "<script type=\"text/x-template\" id=\"keybinds-settings\">\n    <div class=\"keybinds-page\">\n        <div class=\"md-option-header\">\n            <span>{{$root.getLz('settings.option.general.keybindings')}}</span>\n        </div>\n        <div class=\"settings-option-body\">\n            <div class=\"md-option-header-sub\">\n                <span>{{$root.getLz('settings.option.general.keybindings.library')}}</span>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.search')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('search')\">\n                        {{app.cfg.general.keybindings.search.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.listnow')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('listnow')\">\n                        {{app.cfg.general.keybindings.listnow.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.browse')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('browse')\">\n                        {{app.cfg.general.keybindings.browse.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.recentAdd')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('recentAdd')\">\n                        {{app.cfg.general.keybindings.recentAdd.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.songs')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('songs')\">\n                        {{app.cfg.general.keybindings.songs.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.albums')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('albums')\">\n                        {{app.cfg.general.keybindings.albums.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.artists')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('artists')\">\n                        {{app.cfg.general.keybindings.artists.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-header-sub\">\n                <span>{{$root.getLz('settings.option.general.keybindings.session')}}</span>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.private')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('togglePrivateSession')\">\n                        {{app.cfg.general.keybindings.togglePrivateSession.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-header-sub\">\n                <span>{{$root.getLz('settings.option.general.keybindings.control')}}</span>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.remote')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('webRemote')\">\n                        {{app.cfg.general.keybindings.webRemote.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.audio')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('audioSettings')\">\n                        {{app.cfg.general.keybindings.audioSettings.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.plugins')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('pluginMenu')\">\n                        {{app.cfg.general.keybindings.pluginMenu.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.cast')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('castToDevices')\">\n                        {{app.cfg.general.keybindings.castToDevices.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.settings')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('settings')\">\n                        {{app.cfg.general.keybindings.settings.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-header-sub\" v-if=\"app.platform !== 'darwin'\">\n                <span>{{$root.getLz('settings.option.general.keybindings.interface')}}</span>\n            </div>\n            <div class=\"md-option-line\" v-if=\"app.platform !== 'darwin'\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('term.zoomin')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('zoomn')\">\n                        {{app.cfg.general.keybindings.zoomn.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\" v-if=\"app.platform !== 'darwin'\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('term.zoomout')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('zoomt')\">\n                        {{app.cfg.general.keybindings.zoomt.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-line\" v-if=\"app.platform !== 'darwin'\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('term.zoomreset')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('zoomrst')\">\n                        {{app.cfg.general.keybindings.zoomrst.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-option-header-sub\">\n                <span>{{$root.getLz('settings.option.general.keybindings.advanced')}}</span>\n            </div>\n            <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('settings.description.developer')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <button class=\"md-btn md-btn-small md-btn-block\"\n                            @click=\"keyBindUpdate('openDeveloperTools')\">\n                        {{app.cfg.general.keybindings.openDeveloperTools.join(' + ')}}\n                    </button>\n                </div>\n            </div>\n            <button class=\"md-btn md-btn-large md-btn-block\" @click=\"keyBindReset()\">\n                {{$root.getLz('term.reset')}}\n            </button>\n        </div>\n\n    </div>\n</script>\n\n<script>\n  Vue.component('keybinds-settings', {\n    template: \"#keybinds-settings\",\n    props: [],\n    data: function() {\n      return {\n        app: this.$root\n      }\n    },\n    methods: {\n      keyBindUpdate: function(action) {\n        const blur = document.createElement('div');\n        blur.className = 'blur';\n        blur.style.backgroundColor = 'rgba(0,0,0,0.25)';\n        blur.style.position = 'fixed';\n        blur.style.top = '0';\n        blur.style.left = '0';\n        blur.style.width = '100%';\n        blur.style.height = '100%';\n        blur.style.zIndex = '9999';\n        blur.style.display = 'flex';\n        blur.style.alignItems = 'center';\n        blur.style.justifyContent = 'center';\n        blur.style.fontSize = '2em';\n        blur.style.color = 'white';\n        blur.innerHTML = `<center>${app.getLz('settings.option.general.keybindings.pressCombination')}<br />${app.getLz('settings.option.general.keybindings.pressEscape')}</center>`\n        document.body.appendChild(blur);\n\n        let keyBind = [];\n        const keyBindTimeout = setTimeout(function() {\n          keyBind = [];\n          document.body.removeChild(blur);\n        }, 30000);\n        const keyBindUpdate = function(e) {\n          if (document.body.contains(blur)) {\n            if (e.key == 'Escape') {\n              document.body.removeChild(blur);\n              clearTimeout(keyBindTimeout);\n              return;\n            } else {\n              if (e.keyCode >= 65 && e.keyCode <= 90 && e.keyCode <= 97 && e.keyCode <= 122) {\n                keyBind.push(e.key.toUpperCase());\n              } else {\n                keyBind.push(e.key);\n              }\n              if (keyBind.length === 2) {\n                if (keyBind[0] !== keyBind[1]) {\n                  app.cfg.general.keybindings[action] = keyBind\n                  document.body.removeChild(blur);\n                  clearTimeout(keyBindTimeout);\n                  notyf.success(app.getLz('settings.notyf.general.keybindings.update.success'));\n                  app.confirm(app.getLz(\"settings.prompt.general.keybindings.update.success\"), (ok) => {\n                    if (ok) ipcRenderer.invoke(\"relaunchApp\")\n                  })\n                } else {\n                  keyBind = [];\n                }\n              }\n            }\n          }\n        };\n        document.addEventListener('keydown', keyBindUpdate);\n      },\n      keyBindReset: function() {\n        app.cfg.general.keybindings.search = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"F\"];\n        app.cfg.general.keybindings.listnow = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"L\"];\n        app.cfg.general.keybindings.browse = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"B\"];\n        app.cfg.general.keybindings.recentAdd = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"G\"];\n        app.cfg.general.keybindings.songs = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"J\"];\n        app.cfg.general.keybindings.albums = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"A\"];\n        app.cfg.general.keybindings.artists = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"D\"];\n        app.cfg.general.keybindings.togglePrivateSession = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"P\"];\n        app.cfg.general.keybindings.webRemote = [app.platform == \"darwin\" ? \"Command\" : \"Control\", app.platform == \"darwin\" ? \"Option\" : (app.platform == \"linux\" ? \"Shift\" : \"Alt\"), \"W\"];\n        app.cfg.general.keybindings.audioSettings = [app.platform == \"darwin\" ? \"Command\" : \"Control\", app.platform == \"darwin\" ? \"Option\" : (app.platform == \"linux\" ? \"Shift\" : \"Alt\"), \"A\"];\n        app.cfg.general.keybindings.pluginMenu = [app.platform == \"darwin\" ? \"Command\" : \"Control\", app.platform == \"darwin\" ? \"Option\" : (app.platform == \"linux\" ? \"Shift\" : \"Alt\"), \"P\"];\n        app.cfg.general.keybindings.castToDevices = [app.platform == \"darwin\" ? \"Command\" : \"Control\", app.platform == \"darwin\" ? \"Option\" : (app.platform == \"linux\" ? \"Shift\" : \"Alt\"), \"C\"];\n        app.cfg.general.keybindings.settings = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \",\"];\n        app.cfg.general.keybindings.zoomn = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"numadd\"];\n        app.cfg.general.keybindings.zoomt = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"numsub\"];\n        app.cfg.general.keybindings.zoomrst = [app.platform == \"darwin\" ? \"Command\" : \"Control\", \"num0\"];\n        app.cfg.general.keybindings.openDeveloperTools = [app.platform == \"darwin\" ? \"Command\" : \"Control\", app.platform == \"darwin\" ? \"Option\" : \"Shift\", \"I\"];\n        notyf.success(app.getLz('settings.notyf.general.keybindings.update.success'));\n        app.confirm(app.getLz(\"settings.prompt.general.keybindings.update.success\"), (ok) => {\n          if (ok) ipcRenderer.invoke(\"relaunchApp\")\n        })\n      },\n      getLanguages: function() {\n        let langs = this.$root.lzListing\n        let categories = {\n          \"main\": [],\n          \"fun\": [],\n          \"unsorted\": []\n        }\n        // sort by category if category is undefined or empty put it in \"unsorted\"\n        for (let i = 0; i < langs.length; i++) {\n          if (langs[i].category === undefined || langs[i].category === \"\") {\n            categories.unsorted.push(langs[i])\n          } else {\n            categories[langs[i].category].push(langs[i])\n          }\n        }\n        // return\n        return categories\n      },\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/settings-plugins-github.ejs",
    "content": "<script type=\"text/x-template\" id=\"plugins-github\">\n    <div class=\"github-themes-page\">\n        <div class=\"gh-header\">\n            <div class=\"row\">\n                <div class=\"col nopadding\">\n                    <h1 class=\"header-text\">{{$root.getLz('settings.header.visual.plugin.github.page')}}</h1>\n                </div>\n                <div class=\"col-auto nopadding cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"installThemeURL()\">\n                        {{$root.getLz('settings.option.visual.plugin.github.download')}}\n                    </button>\n                </div>\n            </div>\n        </div>\n        <div class=\"gh-content\">\n            <div class=\"repos-list\">\n                <ul class=\"list-group list-group-flush\">\n                    <li @click=\"showRepo(repo)\" class=\"list-group-item list-group-item-dark\"\n                        :style=\"{'background': (repo.id == openRepo.id) ? 'var(--keyColor)' : '', 'border-radius': '5px'}\"\n                        v-for=\"repo in repos\">\n                        <div class=\"row\">\n                            <div class=\"col cider-flex-center\">\n                                <div>\n                                    <h4 class=\"repo-name\">{{ (repo.description != null) ? repo.description :\n                                        repo.full_name }}</h4>\n                                    <div>⭐ {{ repo.stargazers_count }}</div>\n                                </div>\n                            </div>\n                        </div>\n                    </li>\n                </ul>\n            </div>\n\n            <div class=\"github-preview\" v-if=\"openRepo.full_name\">\n                <div class=\"gh-preview-header\">\n                    <div class=\"row nopadding\">\n                        <div class=\"col nopadding cider-flex-center\">\n                            <div>\n                                <h3 class=\"repo-preview-name\">{{ openRepo.description }}</h3>\n                                <div>\n                                    <div class=\"svg-icon inline\"\n                                         :style=\"{'--url': 'url(\\'./assets/github.svg\\')'}\"></div>\n                                    <a class=\"repo-url\" target=\"_blank\" :href=\"openRepo.html_url\">{{ openRepo.full_name\n                                        }}</a></div>\n                                <div>⭐ {{ openRepo.stargazers_count }}</div>\n                            </div>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"md-btn md-btn-primary\" @click=\"installThemeRepo(openRepo)\">\n                                <span v-if=\"!themesInstalled.includes(openRepo.full_name)\">{{$root.getLz('action.install')}}</span>\n                                <span v-else>{{$root.getLz('action.update')}}</span>\n                            </button>\n                        </div>\n                    </div>\n                </div>\n                <hr>\n                <div v-html=\"openRepo.readme\" class=\"github-content\"></div>\n            </div>\n            <div class=\"github-preview\" v-else>\n\n            </div>\n            </transition>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('plugins-github', {\n    template: \"#plugins-github\",\n    props: [],\n    data: function() {\n      return {\n        repos: [],\n        openRepo: {\n          id: -1,\n          name: '',\n          description: '',\n          html_url: '',\n          stargazers_count: 0,\n          owner: {\n            avatar_url: ''\n          },\n          readme: \"\"\n        },\n        themesInstalled: []\n      }\n    },\n    mounted() {\n      this.getRepos();\n      // this.getInstalledThemes();\n    },\n    methods: {\n      getInstalledThemes() {\n        let self = this\n        const themes = ipcRenderer.sendSync(\"get-themes\")\n        // for each theme, get the github_repo property and push it to the themesInstalled array, if not blank\n        themes.forEach(theme => {\n          if (theme.github_repo !== \"\") {\n            self.themesInstalled.push(theme.github_repo)\n          }\n        })\n      },\n      showRepo(repo) {\n        const self = this\n        const readmeUrl = `https://raw.githubusercontent.com/${repo.full_name}/main/README.md`;\n        var requestOptions = {\n          method: 'GET',\n          redirect: 'follow'\n        };\n\n        app._fetch(readmeUrl, requestOptions)\n          .then(response => response.text())\n          .then(result => {\n            self.openRepo = repo\n            self.openRepo.readme = self.convertReadMe(result);\n          })\n          .catch(error => {\n            self.openRepo = repo\n            self.openRepo.readme = `This repository doesn't have a README.md file.`;\n            console.log('error', error)\n          });\n      },\n      convertReadMe(text) {\n        return marked.parse(text)\n      },\n      installThemeRepo(repo) {\n        let self = this\n        let msg = app.stringTemplateParser(app.getLz('settings.option.visual.plugin.github.install.confirm'), {\n          repo: repo.full_name\n        });\n        app.confirm(msg, (res) => {\n          if (res) {\n            ipcRenderer.once(\"plugin-installed\", (event, arg) => {\n              if (arg.success) {\n                self.themes = []\n                notyf.success(app.getLz('settings.notyf.visual.plugin.install.success'));\n                app.confirm(app.getLz(\"settings.prompt.visual.plugin.github.success\"), (ok) => {\n                  if (ok) {\n                    ipcRenderer.invoke(\"relaunchApp\")\n                  } else {\n                    return\n                  }\n                })\n              } else {\n                notyf.error(app.getLz('settings.notyf.visual.plugin.install.error'));\n              }\n            });\n            ipcRenderer.invoke(\"get-github-plugin\", repo.html_url)\n          }\n        })\n      },\n      installThemeURL() {\n        let self = this\n        app.prompt(app.getLz('settings.prompt.visual.plugin.github.URL'), (result) => {\n          if (result) {\n            ipcRenderer.once(\"plugin-installed\", (event, arg) => {\n              if (arg.success) {\n                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                app.confirm(app.getLz(\"settings.prompt.visual.plugin.github.success\"), (ok) => {\n                  if (ok) {\n                    ipcRenderer.invoke(\"relaunchApp\")\n                  } else {\n                    return\n                  }\n                })\n                notyf.success(app.getLz('settings.notyf.visual.plugin.install.success'));\n              } else {\n                notyf.error(app.getLz('settings.notyf.visual.plugin.install.error'));\n              }\n            });\n            ipcRenderer.invoke(\"get-github-plugin\", result)\n          }\n        });\n      },\n      getRepos() {\n        let self = this\n        var requestOptions = {\n          method: 'GET',\n          redirect: 'follow'\n        };\n\n        app._fetch(\"https://api.github.com/search/repositories?q=topic:cidermusicplugin fork:true&per_page=100\", requestOptions)\n          .then(response => response.text())\n          .then(result => {\n            self.repos = JSON.parse(result).items\n          })\n          .catch(error => console.log('error', error));\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/settings-themes-github.ejs",
    "content": "<script type=\"text/x-template\" id=\"themes-github\">\n    <div class=\"github-themes-page\">\n        <div class=\"gh-header\">\n            <div class=\"row\">\n                <div class=\"col nopadding\">\n                    <h1 class=\"header-text\">{{$root.getLz('settings.header.visual.theme.github.page')}}</h1>\n                </div>\n                <div class=\"col-auto nopadding cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.openSettingsPage('styles')\">\n                        {{$root.getLz('settings.option.visual.theme.manageStyles')}}\n                    </button>\n                </div>\n                <div class=\"col-auto cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.checkForThemeUpdates()\">\n                        {{ $root.getLz('settings.option.visual.theme.checkForUpdates') }}\n                    </button>\n                </div>\n                <div class=\"col-auto nopadding cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"installThemeURL()\">\n                        {{$root.getLz('settings.option.visual.theme.github.download')}}\n                    </button>\n                </div>\n            </div>\n        </div>\n        <div class=\"gh-content\">\n            <div class=\"repos-list\">\n                <ul class=\"list-group list-group-flush\">\n                    <li @click=\"showRepo(repo)\" class=\"list-group-item list-group-item-dark\"\n                        :style=\"{'background': (repo.id == openRepo.id) ? 'var(--keyColor)' : ''}\"\n                        v-for=\"repo in repos\">\n                        <div class=\"row\">\n                            <div class=\"col cider-flex-center\">\n                                <div>\n                                    <h4 class=\"repo-name\">{{ (repo.description != null) ? repo.description :\n                                        repo.full_name }}</h4>\n                                    <div>⭐ {{ repo.stargazers_count }}</div>\n                                </div>\n                            </div>\n                            <div class=\"col-auto\">\n                                <span v-if=\"themesInstalled.includes(repo.full_name.toLowerCase())\"\n                                      class=\"codicon codicon-cloud-download\"></span>\n                            </div>\n                        </div>\n                    </li>\n                </ul>\n            </div>\n\n            <div class=\"github-preview\" v-if=\"openRepo.full_name\">\n                <div class=\"gh-preview-header\">\n                    <div class=\"row nopadding\">\n                        <div class=\"col nopadding cider-flex-center\">\n                            <div>\n                                <h3 class=\"repo-preview-name\">{{ openRepo.description }}</h3>\n                                <div>\n                                    <div class=\"svg-icon inline\"\n                                         :style=\"{'--url': 'url(\\'./assets/github.svg\\')'}\"></div>\n                                    <a class=\"repo-url\" target=\"_blank\" :href=\"openRepo.html_url\">{{ openRepo.full_name\n                                        }}</a></div>\n                                <div>⭐ {{ openRepo.stargazers_count }}</div>\n                            </div>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"md-btn md-btn-primary\" @click=\"installThemeRepo(openRepo)\">\n                                <span v-if=\"!themesInstalled.includes(openRepo.full_name.toLowerCase())\">{{$root.getLz('action.install')}}</span>\n                                <span v-else>{{$root.getLz('action.update')}}</span>\n                            </button>\n                        </div>\n                    </div>\n                </div>\n                <hr>\n                <div v-html=\"openRepo.readme\" class=\"github-content\"></div>\n            </div>\n            <div class=\"github-preview\" v-else>\n\n            </div>\n            </transition>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('themes-github', {\n    template: \"#themes-github\",\n    props: [],\n    data: function() {\n      return {\n        repos: [],\n        openRepo: {\n          id: -1,\n          name: '',\n          description: '',\n          html_url: '',\n          stargazers_count: 0,\n          owner: {\n            avatar_url: ''\n          },\n          readme: \"\"\n        },\n        themesInstalled: [],\n        themes: []\n      }\n    },\n    mounted() {\n      this.themes = ipcRenderer.sendSync(\"get-themes\")\n      this.getRepos();\n      this.getInstalledThemes();\n    },\n    methods: {\n      openThemesFolder() {\n        ipcRenderer.invoke(\"open-path\", \"themes\")\n      },\n      getInstalledThemes() {\n        let self = this\n        const themes = ipcRenderer.sendSync(\"get-themes\")\n        // for each theme, get the github_repo property and push it to the themesInstalled array, if not blank\n        themes.forEach(theme => {\n          if (theme.github_repo !== \"\" && typeof theme.commit != \"\") {\n            self.themesInstalled.push(theme.github_repo.toLowerCase())\n          }\n        })\n      },\n      showRepo(repo) {\n        const self = this\n        const readmeUrl = `https://raw.githubusercontent.com/${repo.full_name}/main/README.md`;\n        var requestOptions = {\n          method: 'GET',\n          redirect: 'follow'\n        };\n\n        app._fetch(readmeUrl, requestOptions)\n          .then(response => response.text())\n          .then(result => {\n            self.openRepo = repo\n            self.openRepo.readme = self.convertReadMe(result);\n          })\n          .catch(error => {\n            self.openRepo = repo\n            self.openRepo.readme = `This repository doesn't have a README.md file.`;\n            console.log('error', error)\n          });\n      },\n      convertReadMe(text) {\n        return marked.parse(text)\n      },\n      installThemeRepo(repo) {\n        let self = this\n        let msg = app.stringTemplateParser(app.getLz('settings.option.visual.theme.github.install.confirm'), {\n          repo: repo.full_name\n        });\n        app.confirm(msg, (res) => {\n          if (res) {\n            ipcRenderer.once(\"theme-installed\", (event, arg) => {\n              if (arg.success) {\n                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                self.getInstalledThemes()\n                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n              } else {\n                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n              }\n            });\n            ipcRenderer.invoke(\"get-github-theme\", repo.html_url)\n          }\n        })\n      },\n      installThemeURL() {\n        let self = this\n        app.prompt(app.getLz('settings.prompt.visual.theme.github.URL'), (result) => {\n          if (result) {\n            ipcRenderer.once(\"theme-installed\", (event, arg) => {\n              if (arg.success) {\n                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n              } else {\n                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n              }\n            });\n            ipcRenderer.invoke(\"get-github-theme\", result)\n          }\n        });\n      },\n      getRepos() {\n        let self = this\n        var requestOptions = {\n          method: 'GET',\n          redirect: 'follow'\n        };\n\n        app._fetch(\"https://api.github.com/search/repositories?q=topic:cidermusictheme fork:true&per_page=100\", requestOptions)\n          .then(response => response.text())\n          .then(result => {\n            let items = JSON.parse(result).items\n            self.repos = items\n          })\n          .catch(error => console.log('error', error));\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/settings-themes.ejs",
    "content": "<script type=\"text/x-template\" id=\"installed-themes\">\n    <div class=\"installed-themes-page\">\n        <div class=\"gh-header\">\n            <div class=\"row\">\n                <div class=\"col nopadding\">\n                    <h1 class=\"header-text\">\n                        {{ $root.getLz(\"settings.option.visual.theme.manageStyles\") }}\n                    </h1>\n                </div>\n                <div class=\"col-auto nopadding cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.openSettingsPage('github-themes')\">\n                        {{$root.getLz('settings.option.visual.theme.github.explore')}}\n                    </button>\n                </div>\n                <div class=\"col-auto  cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.checkForThemeUpdates()\">\n                        {{ $root.getLz('settings.option.visual.theme.checkForUpdates') }}\n                    </button>\n                </div>\n                <div class=\"col-auto nopadding cider-flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"openThemesFolder()\">\n                        {{$root.getLz('settings.option.visual.theme.github.openfolder')}}\n                    </button>\n                </div>\n            </div>\n        </div>\n        <div class=\"gh-content\">\n            <div class=\"repos-list\">\n                <div class=\"repo-header\">\n                    <h4>{{$root.getLz('settings.option.visual.theme.github.available')}}</h4>\n                </div>\n                <ul class=\"list-group list-group-flush\">\n                    <template v-for=\"theme in themes\">\n                        <li @click=\"addStyle(theme.file)\"\n                            @contextmenu=\"contextMenu($event, theme)\"\n                            class=\"list-group-item list-group-item-dark\"\n                            :class=\"{'applied': $root.cfg.visual.styles.includes(theme.file)}\">\n\n                            <b-row>\n                                <b-col class=\"themeLabel\">{{theme.name}}</b-col>\n                                <template v-if=\"$root.cfg.visual.styles.includes(theme.file)\">\n                                    <b-col sm=\"auto\" v-if=\"theme.pack\">\n                                        <button class=\"themeContextMenu codicon codicon-package\"></button>\n                                    </b-col>\n                                    <b-col sm=\"auto\">\n                                        <button class=\"themeContextMenu codicon codicon-check\"></button>\n                                    </b-col>\n                                </template>\n                                <template v-else>\n                                    <b-col sm=\"auto\" v-if=\"theme.pack\">\n                                        <button class=\"themeContextMenu codicon codicon-package\"></button>\n                                    </b-col>\n                                    <b-col sm=\"auto\">\n                                        <button @click.stop=\"contextMenu($event, theme)\"\n                                                class=\"themeContextMenu codicon codicon-list-unordered\"></button>\n                                    </b-col>\n                                </template>\n\n                            </b-row>\n                        </li>\n                        <li @click=\"addStyle(packEntry.file)\"\n                            @contextmenu=\"contextMenu($event, theme)\"\n                            class=\"list-group-item list-group-item-dark addon\"\n                            v-for=\"packEntry in theme.pack\"\n                            :class=\"{'applied': $root.cfg.visual.styles.includes(packEntry.file)}\"\n                            v-if=\"theme.pack\">\n\n                            <b-row>\n                                <b-col class=\"themeLabel\">{{packEntry.name}}</b-col>\n                                <template v-if=\"$root.cfg.visual.styles.includes(packEntry.file)\">\n                                    <b-col sm=\"auto\">\n                                        <button class=\"themeContextMenu codicon codicon-check\"></button>\n                                    </b-col>\n                                </template>\n                                <template v-else>\n                                    <b-col sm=\"auto\">\n                                        <button class=\"themeContextMenu codicon codicon-diff-added\"></button>\n                                    </b-col>\n                                </template>\n                            </b-row>\n                        </li>\n                    </template>\n                </ul>\n            </div>\n\n            <div class=\"style-editor-container\">\n                <div class=\"repo-header\">\n                    <h4>{{ $root.getLz(\"settings.option.visual.theme.github.applied\") }} </h4>\n                </div>\n                <stylestack-editor ref=\"stackEditor\" v-if=\"themes.length != 0\" :themes=\"themes\" />\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  // do not translate\n  Vue.component('stylestack-editor', {\n    /*html*/\n    template: `\n            <div class=\"stylestack-editor\" >\n                <draggable class=\"list-group\" v-model=\"$root.cfg.visual.styles\" @end=\"$root.reloadStyles()\">\n                    <b-list-group-item variant=\"dark\" v-for=\"theme in $root.cfg.visual.styles\" :key=\"theme\">\n                        <b-row>\n                            <b-col sm=\"auto\">\n                                <div class=\"handle codicon codicon-grabber\"></div>\n                            </b-col>\n                            <b-col class=\"themeLabel\">{{getThemeName(theme)}}</b-col>\n                            <b-col sm=\"auto\">\n                                <button class=\"removeItem codicon codicon-close\" @click=\"remove(theme)\"></button>\n                            </b-col>\n                        </b-row>\n                        </b-list-group-item>\n                </draggable>\n            </div>\n        `,\n    props: {\n      themes: {\n        type: Array,\n        default: [],\n        required: true\n      }\n    },\n    data: function() {\n      return {\n        selected: null,\n        newTheme: null,\n        themeList: []\n      }\n    },\n    mounted() {\n      console.log(this.themes)\n      this.themeList = [...this.themes]\n\n      this.themeList.forEach(theme => {\n        if (theme.pack) {\n          theme.pack.forEach(packEntry => {\n            packEntry.file = theme.file.replace('index.less', '') + packEntry.file\n            this.themeList.push(packEntry)\n          })\n        }\n      })\n    },\n    methods: {\n      gitHubExplore() {\n        this.$root.openSettingsPage(\"github-themes\")\n      },\n      getThemeName(filename) {\n        try {\n          return this.themeList.find(theme => theme.file === filename).name;\n        } catch (e) {\n          return filename;\n        }\n      },\n      moveUp() {\n        const styles = this.$root.cfg.visual.styles\n        const index = styles.indexOf(this.selected)\n        if (index > 0) {\n          styles.splice(index, 1)\n          styles.splice(index - 1, 0, this.selected)\n        }\n        this.$root.reloadStyles()\n      },\n      moveDown() {\n        const styles = this.$root.cfg.visual.styles\n        const index = styles.indexOf(this.selected)\n        if (index < styles.length - 1) {\n          styles.splice(index, 1)\n          styles.splice(index + 1, 0, this.selected)\n        }\n        this.$root.reloadStyles()\n      },\n      remove(style) {\n        const styles = this.$root.cfg.visual.styles\n        const index = styles.indexOf(style)\n        styles.splice(index, 1)\n        this.$root.reloadStyles()\n      },\n      addStyle(style) {\n        const styles = this.$root.cfg.visual.styles\n        styles.push(style)\n        this.$root.reloadStyles()\n      }\n    }\n  })\n</script>\n\n<script>\n  Vue.component('installed-themes', {\n    template: \"#installed-themes\",\n    props: [],\n    data: function() {\n      return {\n        repos: [],\n        openRepo: {\n          id: -1,\n          name: '',\n          description: '',\n          html_url: '',\n          stargazers_count: 0,\n          owner: {\n            avatar_url: ''\n          },\n          readme: \"\"\n        },\n        themesInstalled: [],\n        themes: []\n      }\n    },\n    mounted() {\n      this.getThemesList();\n    },\n    methods: {\n      getThemesList() {\n        let self = this\n        let themes = ipcRenderer.sendSync(\"get-themes\")\n        themes.unshift({\n          name: \"Acrylic Grain\",\n          file: \"grain.less\"\n        })\n        themes.unshift({\n          name: \"Sweetener\",\n          file: \"sweetener.less\"\n        })\n        themes.unshift({\n          name: \"Reduce Visuals\",\n          file: \"reduce_visuals.less\"\n        })\n        // themes.unshift({\n        //     name: \"Inline Drawer\",\n        //     file: \"inline_drawer.less\"\n        // })\n        themes.unshift({\n          name: \"Dark\",\n          file: \"dark.less\"\n        })\n        this.themes = themes\n      },\n      contextMenu(event, theme) {\n        let self = this\n        let menu = {\n          items: {\n            \"uninstall\": {\n              name: app.getLz(\"settings.option.visual.theme.uninstall\"),\n              disabled: true,\n              action: () => {\n                app.confirm(app.stringTemplateParser(app.getLz(\"settings.prompt.visual.theme.uninstallTheme\"), {\n                  theme: theme.name ?? theme.file\n                }), (res) => {\n                  if (res) {\n                    console.debug(theme)\n                    ipcRenderer.once(\"theme-uninstalled\", (event, args) => {\n                      console.debug(event, args)\n                      self.getThemesList()\n                    })\n                    ipcRenderer.invoke(\"uninstall-theme\", theme.path)\n                  }\n                })\n\n              }\n            },\n            \"viewInfo\": {\n              name: app.getLz(\"settings.option.visual.theme.viewInfo\"),\n              disabled: true,\n              action: () => {\n\n              }\n            }\n          }\n        }\n        if (theme.path) {\n          menu.items.uninstall.disabled = false\n        }\n        this.$root.showMenuPanel(menu, event)\n      },\n      openThemesFolder() {\n        ipcRenderer.invoke(\"open-path\", \"themes\")\n      },\n      getInstalledThemes() {\n        let self = this\n        const themes = ipcRenderer.sendSync(\"get-themes\")\n        // for each theme, get the github_repo property and push it to the themesInstalled array, if not blank\n        themes.forEach(theme => {\n          if (theme.github_repo !== \"\" && typeof theme.commit != \"\") {\n            self.themesInstalled.push(theme.github_repo.toLowerCase())\n          }\n        })\n      },\n      addStyle(filename) {\n        this.$refs.stackEditor.addStyle(filename)\n      },\n      showRepo(repo) {\n        const self = this\n        const readmeUrl = `https://raw.githubusercontent.com/${repo.full_name}/main/README.md`;\n        var requestOptions = {\n          method: 'GET',\n          redirect: 'follow'\n        };\n\n        app._fetch(readmeUrl, requestOptions)\n          .then(response => response.text())\n          .then(result => {\n            self.openRepo = repo\n            self.openRepo.readme = self.convertReadMe(result);\n          })\n          .catch(error => {\n            self.openRepo = repo\n            self.openRepo.readme = `This repository doesn't have a README.md file.`;\n            console.log('error', error)\n          });\n      },\n      convertReadMe(text) {\n        return marked.parse(text)\n      },\n      installThemeRepo(repo) {\n        let self = this\n        let msg = app.stringTemplateParser(app.getLz('settings.option.visual.theme.github.install.confirm'), {\n          repo: repo.full_name\n        });\n        app.confirm(msg, (res) => {\n          if (res) {\n            ipcRenderer.once(\"theme-installed\", (event, arg) => {\n              if (arg.success) {\n                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                self.getInstalledThemes()\n                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n              } else {\n                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n              }\n            });\n            ipcRenderer.invoke(\"get-github-theme\", repo.html_url)\n          }\n        })\n      },\n      installThemeURL() {\n        let self = this\n        app.prompt(app.getLz('settings.prompt.visual.theme.github.URL'), (result) => {\n          if (result) {\n            ipcRenderer.once(\"theme-installed\", (event, arg) => {\n              if (arg.success) {\n                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n              } else {\n                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n              }\n            });\n            ipcRenderer.invoke(\"get-github-theme\", result)\n          }\n        });\n      },\n      getRepos() {\n        let self = this\n        var requestOptions = {\n          method: 'GET',\n          redirect: 'follow'\n        };\n\n        fetch(\"https://api.github.com/search/repositories?q=topic:cidermusictheme fork:true\", requestOptions)\n          .then(response => response.text())\n          .then(result => {\n            let items = JSON.parse(result).items\n            self.repos = items\n          })\n          .catch(error => console.log('error', error));\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/settings-window.ejs",
    "content": "<script type=\"text/x-template\" id=\"settings-window\">\n    <div class=\"settings-panel\" @click.self=\"close()\">\n        <div class=\"settings-window\"\n             :class=\"{'maxed': $store.state.pageState['settings'].fullscreen, 'no-sidebar': sidebarVis()}\">\n            <button class=\"close-btn minmax-btn\"\n                    @click=\"$store.state.pageState['settings'].fullscreen = !$store.state.pageState['settings'].fullscreen\"\n                    :class=\"{'min': $store.state.pageState['settings'].fullscreen}\"></button>\n            <button class=\"close-btn\" @click=\"close()\"></button>\n            <b-tabs class=\"no-style\" pills vertical content-class=\"mt-3\"\n                    v-model=\"$store.state.pageState['settings'].currentTabIndex\">\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/settings.svg\" classes=\"svg-md\" name=\"settings-general\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.header.general') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <div class=\"md-option-container\">\n                            <!-- General Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.general')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('term.language')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" @change=\"$root.setLz('');$root.setLzManual()\"\n                                                    v-model=\"app.cfg.general.language\">\n                                                <optgroup :label=\"index\" v-for=\"(categories, index) in getLanguages()\">\n                                                    <option v-for=\"lang in categories\" :value=\"lang.code\">\n                                                        {{lang.nameNative}}\n                                                        ({{\n                                                        lang.nameEnglish }})\n                                                    </option>\n                                                </optgroup>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('term.accountSettings')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"app.appRoute('apple-account-settings')\">\n                                            {{$root.getLz('term.accountSettings')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('term.privateSession')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"$root.cfg.general.privateEnabled\"\n                                                   v-on:change=\"$root.mk.privateEnabled = $root.cfg.general.privateEnabled\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.platform !== 'linux'\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.window.openOnStartup')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.general.onStartup.enabled\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.cfg.general.onStartup.enabled\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.window.openOnStartup.hidden')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.general.onStartup.hidden\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.resumebehavior')}}<br>\n                                        <small>\n                                            {{$root.getLz('settings.option.general.resumebehavior.description')}}<br>\n                                            <b>{{$root.getLz('settings.option.general.resumebehavior.locally')}}: </b>\n                                            {{$root.getLz('settings.option.general.resumebehavior.locally.description')}}<br>\n                                            <b>{{$root.getLz('settings.option.general.resumebehavior.history')}}: </b>\n                                            {{$root.getLz('settings.option.general.resumebehavior.history.description')}}\n                                        </small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" style=\"width:180px;\"\n                                                    v-model=\"$root.cfg.general.resumeOnStartupBehavior\">\n                                                <option value=\"disabled\">{{$root.getLz('term.disabled')}}</option>\n                                                <option value=\"local\">\n                                                    {{$root.getLz('settings.option.general.resumebehavior.locally')}}\n                                                </option>\n                                                <option value=\"history\">\n                                                    {{$root.getLz('settings.option.general.resumebehavior.history')}}\n                                                </option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.resumetabs')}}<br>\n                                        <small>\n                                            {{$root.getLz('settings.option.general.resumetabs.description')}}<br>\n                                            <b>{{$root.getLz('settings.option.general.resumetabs.dynamic')}}: </b>\n                                            {{$root.getLz('settings.option.general.resumetabs.dynamic.description')}}\n                                        </small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" style=\"width:180px;\"\n                                                    v-model=\"$root.cfg.general.resumeTabs.tab\">\n                                                <option value=\"dynamic\">\n                                                    {{$root.getLz('settings.option.general.resumetabs.dynamic')}}\n                                                </option>\n                                                <option value=\"home\">{{$root.getLz('home.title')}}</option>\n                                                <option value=\"listen_now\">{{$root.getLz('term.listenNow')}}</option>\n                                                <option value=\"browse\">{{$root.getLz('term.browse')}}</option>\n                                                <option value=\"radio\">{{$root.getLz('term.radio')}}</option>\n                                                <option value=\"library-recentlyadded\">\n                                                    {{$root.getLz('term.recentlyAdded')}}\n                                                </option>\n                                                <option value=\"library-songs\">{{$root.getLz('term.songs')}}</option>\n                                                <option value=\"library-albums\">{{$root.getLz('term.albums')}}</option>\n                                                <option value=\"library-artists\">{{$root.getLz('term.artists')}}</option>\n                                                <option value=\"library-videos\">{{$root.getLz('term.videos')}}</option>\n                                                <option value=\"podcasts\">{{$root.getLz('term.podcasts')}}</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.customizeSidebar')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" v-b-modal.modal-1>\n                                            {{$root.getLz('settings.option.general.customizeSidebar.customize')}}\n                                        </button>\n                                    </div>\n                                    <b-modal id=\"modal-1\" centered size=\"lg\"\n                                             :title=\"$root.getLz('settings.option.general.customizeSidebar')\">\n                                        <div class=\"settings-option-body\">\n                                            <div class=\"md-option-line\">\n                                                <div class=\"md-option-segment\">\n                                                    {{ $root.getLz('term.recentlyAdded') }}\n                                                </div>\n                                                <div class=\"md-option-segment md-option-segment_auto\">\n                                                    <label>\n                                                        <input type=\"checkbox\"\n                                                               v-model=\"app.cfg.general.sidebarItems.recentlyAdded\"\n                                                               switch />\n                                                    </label>\n                                                </div>\n                                            </div>\n                                            <div class=\"md-option-line\">\n                                                <div class=\"md-option-segment\">\n                                                    {{ $root.getLz('term.songs') }}\n                                                </div>\n                                                <div class=\"md-option-segment md-option-segment_auto\">\n                                                    <label>\n                                                        <input type=\"checkbox\"\n                                                               v-model=\"app.cfg.general.sidebarItems.songs\"\n                                                               switch />\n                                                    </label>\n                                                </div>\n                                            </div>\n                                            <div class=\"md-option-line\">\n                                                <div class=\"md-option-segment\">\n                                                    {{ $root.getLz('term.albums') }}\n                                                </div>\n                                                <div class=\"md-option-segment md-option-segment_auto\">\n                                                    <label>\n                                                        <input type=\"checkbox\"\n                                                               v-model=\"app.cfg.general.sidebarItems.albums\"\n                                                               switch />\n                                                    </label>\n                                                </div>\n                                            </div>\n                                            <div class=\"md-option-line\">\n                                                <div class=\"md-option-segment\">\n                                                    {{ $root.getLz('term.artists') }}\n                                                </div>\n                                                <div class=\"md-option-segment md-option-segment_auto\">\n                                                    <label>\n                                                        <input type=\"checkbox\"\n                                                               v-model=\"app.cfg.general.sidebarItems.artists\"\n                                                               switch />\n                                                    </label>\n                                                </div>\n                                            </div>\n                                            <div class=\"md-option-line\">\n                                                <div class=\"md-option-segment\">\n                                                    {{ $root.getLz('term.videos') }}\n                                                </div>\n                                                <div class=\"md-option-segment md-option-segment_auto\">\n                                                    <label>\n                                                        <input type=\"checkbox\"\n                                                               v-model=\"app.cfg.general.sidebarItems.videos\"\n                                                               switch />\n                                                    </label>\n                                                </div>\n                                            </div>\n                                            <div class=\"md-option-line\">\n                                                <div class=\"md-option-segment\">\n                                                    {{ $root.getLz('term.podcasts') }}\n                                                </div>\n                                                <div class=\"md-option-segment md-option-segment_auto\">\n                                                    <label>\n                                                        <input type=\"checkbox\"\n                                                               v-model=\"app.cfg.general.sidebarItems.podcasts\"\n                                                               switch />\n                                                    </label>\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </b-modal>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.keybindings')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"$root.openSettingsPage('keybindings')\">\n                                            {{$root.getLz('action.open')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.themeUpdateNotification')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.general.themeUpdateNotification\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.showLovedTracksInline')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.general.showLovedTracksInline\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <!-- <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{'Local files path'}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"openLocalSongsPathMenu\">\n                                            {{'Edit Paths'}}\n                                        </button>\n                                    </div>\n                                </div> -->\n                            </div>\n                        </div>\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/headphones.svg\" classes=\"svg-md\" name=\"settings-audio\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.header.audio') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <div class=\"md-option-container\">\n                            <!-- Audio Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.audio')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.audio.quality')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" style=\"width:180px;\"\n                                                    v-model=\"app.cfg.audio.quality\"\n                                                    v-on:change=\"changeAudioQuality\">\n                                                <!-- // <option value=\"\">{{$root.getLz('settings.header.audio.quality.hireslossless')}}</option> -->\n                                                <!-- <option value=\"\">{{$root.getLz('settings.header.audio.quality.lossless')}}</option> -->\n                                                <option value=\"HIGH\">\n                                                    {{$root.getLz('settings.header.audio.quality.high')}}\n                                                    ({{$root.getLz('settings.header.audio.quality.high.description')}})\n                                                </option>\n                                                <option value=\"STANDARD\">\n                                                    {{$root.getLz('settings.header.audio.quality.standard')}}\n                                                    ({{$root.getLz('settings.header.audio.quality.standard.description')}})\n                                                </option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('term.audioControls')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" onclick=\"app.modals.audioControls = true\">\n                                            {{$root.getLz('term.audioControls')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.audio.changePlaybackRate')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" onclick=\"app.modals.audioPlaybackRate = true\">\n                                            {{$root.getLz('settings.option.audio.playbackRate.change')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.audio.seamlessTransition')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.audio.seamless_audio\"\n                                                   v-on:change=\"app.mk._bag.features['seamless-audio-transitions'] = app.cfg.audio.seamless_audio\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('term.equalizer')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" onclick=\"app.modals.equalizer = true\">\n                                            {{$root.getLz('term.equalizer')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\" style=\"white-space: pre-line;\">\n                                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.audioNormalization')}}\n                                        <small>{{app.cfg.audio.equalizer.vibrantBass != 0 ||\n                                            app.cfg.audio.maikiwiAudio.spatial\n                                            === true || app.cfg.audio.maikiwiAudio.ciderPPE === true ?\n                                            `${$root.getLz('settings.option.audio.enableAdvancedFunctionality.audioNormalization.description')}\\n${$root.getLz('settings.option.audio.enableAdvancedFunctionality.audioNormalization.disabled')}`\n                                            :\n                                            $root.getLz('settings.option.audio.enableAdvancedFunctionality.audioNormalization.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.audio.normalization\"\n                                                   v-on:change=\"toggleNormalization\"\n                                                   :disabled=\"app.cfg.audio.maikiwiAudio.spatial === true || app.cfg.audio.maikiwiAudio.ciderPPE === true || app.cfg.audio.maikiwiAudio.atmosphereRealizer1 === true || app.cfg.audio.maikiwiAudio.atmosphereRealizer2 === true\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\"\n                                     v-show=\"app.cfg.audio.normalization && app.cfg.audio.advanced\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.audio.dbspl.display')}}\n                                        <br>\n                                        <small>{{$root.getLz('settings.option.audio.dbspl.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.audio.dBSPL\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.cfg.audio.dBSPL\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.audio.dbfs.calibration')}}\n                                        <br>\n                                        <small>{{$root.getLz('settings.option.audio.dbfs.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"number\" v-model=\"app.cfg.audio.dBSPLcalibration\" />\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/zap.svg\" classes=\"svg-md\" name=\"settings-audiolabs\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.option.audio.audioLab') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <audiolabs-page />\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/style.svg\" classes=\"svg-md\" name=\"settings-styles\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.header.visual.styles') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <installed-themes />\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/pen-tool.svg\" classes=\"svg-md\" name=\"settings-visual\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.header.visual') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <div class=\"md-option-container\">\n                            <!-- Visual Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.visual')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <!--<div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.header.visual.theme')}}\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <button class=\"md-btn md-btn-block\" @click=\"$root.appRoute('installed-themes')\">\n                                                {{$root.getLz('settings.option.visual.theme.manageStyles')}}\n                                            </button>\n                                        </div>\n                                    </div>-->\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz(\"settings.option.visual.windowStyle\")}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\"\n                                                    v-model=\"$root.cfg.visual.directives.windowLayout\">\n                                                <option value=\"default\">Maverick</option>\n                                                <option value=\"twopanel\">Mojave</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{'Display Style'}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\"\n                                                    v-model=\"$root.cfg.visual.overrideDisplayTheme\"\n                                                    @change=\"changeDisplayTheme\">\n                                                <option value=\"system\">System</option>\n                                                <option value=\"dark\">Dark</option>\n                                                <option value=\"light\">Light</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.windowBackgroundStyle')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" @change=\"windowBgStyleChange\"\n                                                    v-model=\"app.cfg.visual.window_background_style\">\n                                                <option value=\"none\">\n                                                    {{$root.getLz('settings.header.visual.windowBackgroundStyle.none')}}\n                                                </option>\n                                                <option value=\"artwork\">\n                                                    {{$root.getLz('settings.header.visual.windowBackgroundStyle.artwork')}}\n                                                </option>\n                                                <option value=\"image\">\n                                                    {{$root.getLz('settings.header.visual.windowBackgroundStyle.image')}}\n                                                </option>\n                                                <option value=\"color\">\n                                                    {{$root.getLz('settings.header.visual.windowBackgroundStyle.color')}}\n                                                </option>\n                                                <option v-if=\"$root.platform == 'win32'\" value=\"mica\">\n                                                    Mica (Beta)\n                                                </option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line child\"\n                                     v-if=\"app.cfg.visual.window_background_style == 'color'\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.windowColor')}}\n                                    </div>\n                                    <div class=\"md-option-segment_auto\">\n                                        <input type=\"color\" v-model=\"app.cfg.visual.windowColor\" />\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.customAccentColor')}}\n                                    </div>\n                                    <div class=\"md-option-segment_auto\">\n                                        <input type=\"checkbox\" v-model=\"app.cfg.visual.customAccentColor\"\n                                               :disabled=\"app.cfg.visual.purplePodcastPlaybackBar\" switch />\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line child\" v-if=\"app.cfg.visual.customAccentColor\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.accentColor')}}\n                                    </div>\n                                    <div class=\"md-option-segment_auto\">\n                                        <input type=\"color\" v-model=\"app.cfg.visual.accentColor\" />\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.purplePodcastPlaybackBar')}}\n                                    </div>\n                                    <div class=\"md-option-segment_auto\">\n                                        <input type=\"checkbox\" v-model=\"app.cfg.visual.purplePodcastPlaybackBar\"\n                                               :disabled=\"app.cfg.visual.customAccentColor\" switch />\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.compactArtistHeader')}}\n                                    </div>\n                                    <div class=\"md-option-segment_auto\">\n                                        <input type=\"checkbox\" v-model=\"app.cfg.visual.compactArtistHeader\" switch />\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.hardwareAcceleration')}}<br>\n                                        <small>({{$root.getLz('settings.option.visual.hardwareAcceleration.description')}})</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" style=\"width:180px;\"\n                                                    v-model=\"app.cfg.visual.hw_acceleration\"\n                                                    @change=\"promptForRelaunch()\">\n                                                <option value=\"default\">\n                                                    {{$root.getLz('settings.header.visual.hardwareAcceleration.default')}}\n                                                </option>\n                                                <option value=\"webgpu\">\n                                                    {{$root.getLz('settings.header.visual.hardwareAcceleration.webGPU')}}\n                                                </option>\n                                                <option value=\"disabled\">{{$root.getLz('term.disabled')}}</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.showPersonalInfo')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.visual.showuserinfo\"\n                                                   v-on:change=\"toggleUserInfo\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                            <!-- Window Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.window')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz(\"settings.option.window.maxElementScale\")}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select @change=\"$root.setWindowScaleFactor()\" class=\"md-select\"\n                                                    v-model=\"app.cfg.visual.maxElementScale\">\n                                                <option value=\"-1\">Default (1.5x)</option>\n                                                <option value=\"1\">1.0x</option>\n                                                <option value=\"1.1\">1.1x</option>\n                                                <option value=\"1.2\">1.2x</option>\n                                                <option value=\"1.3\">1.3x</option>\n                                                <option value=\"1.4\">1.4x</option>\n                                                <option value=\"1.5\">1.5x</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.platform !== 'darwin'\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz(\"settings.option.window.close_button_hide\")}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.general.close_button_hide\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.platform !== 'darwin'\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz(\"settings.option.window.useNativeTitleBar\")}}<br>\n                                        <small>({{$root.getLz(\"settings.option.visual.hardwareAcceleration.description\")}})</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.visual.nativeTitleBar\" switch\n                                                   @change=\"promptForRelaunch()\" />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.platform !== 'darwin' && !app.cfg.visual.nativeTitleBar\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz(\"settings.option.window.windowControlStyle\")}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" v-model=\"app.cfg.visual.windowControlPosition\">\n                                                <option value=\"0\">\n                                                    {{$root.getLz(\"settings.option.window.windowControlStyle.right\")}}\n                                                </option>\n                                                <option value=\"1\">\n                                                    {{$root.getLz(\"settings.option.window.windowControlStyle.left\")}}\n                                                </option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                            <!-- Advanced Visual -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.advanced')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.animatedArtwork')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" v-model=\"app.cfg.visual.animated_artwork\">\n                                                <option value=\"always\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtwork.always')}}\n                                                </option>\n                                                <option value=\"limited\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtwork.limited')}}\n                                                </option>\n                                                <option value=\"disabled\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtwork.disable')}}\n                                                </option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\"\n                                     v-if=\"app.cfg.visual.animated_artwork == 'always' || app.cfg.visual.animated_artwork == 'limited'\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.animatedArtworkQuality')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\"\n                                                    v-model=\"app.cfg.visual.animated_artwork_qualityLevel\">\n                                                <option value=\"0\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtworkQuality.low')}}\n                                                </option>\n                                                <option value=\"1\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtworkQuality.medium')}}\n                                                </option>\n                                                <option value=\"2\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtworkQuality.high')}}\n                                                </option>\n                                                <option value=\"3\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtworkQuality.veryHigh')}}\n                                                </option>\n                                                <option value=\"4\">\n                                                    {{$root.getLz('settings.header.visual.animatedArtworkQuality.extreme')}}\n                                                </option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.animatedWindowBackground')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" switch\n                                                   v-model=\"app.cfg.visual.bg_artwork_rotation\" />\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/plugins.svg\" classes=\"svg-md\" name=\"settings-plugins\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('term.plugins') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <plugins-github />\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/mic.svg\" classes=\"svg-md\" name=\"settings-lyrics\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.header.lyrics') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <div class=\"md-option-container\">\n                            <!-- Lyric Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.lyrics')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.lyrics.enableMusixmatch')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.lyrics.enable_mxm\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-if=\"app.cfg.lyrics.enable_mxm\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.lyrics.enableMusixmatchKaraoke')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.lyrics.mxm_karaoke\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.lyrics.musixmatchPreferredLanguage')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" v-model=\"app.cfg.lyrics.mxm_language\">\n                                              <option value='disabled'>Disabled</option>\n                                              <option value='ab'>Abkhazian</option>\n                                              <option value='aa'>Afar</option>\n                                              <option value='af'>Afrikaans</option>\n                                              <option value='ak'>Akan</option>\n                                              <option value='sq'>Albanian</option>\n                                              <option value='am'>Amharic</option>\n                                              <option value='ar'>Arabic</option>\n                                              <option value='an'>Aragonese</option>\n                                              <option value='hy'>Armenian</option>\n                                              <option value='as'>Assamese</option>\n                                              <option value='a5'>Assamese-romaji</option>\n                                              <option value='a3'>Asturian</option>\n                                              <option value='av'>Avaric</option>\n                                              <option value='ae'>Avestan</option>\n                                              <option value='ay'>Aymara</option>\n                                              <option value='az'>Azerbaijani</option>\n                                              <option value='bm'>Bambara</option>\n                                              <option value='ba'>Bashkir</option>\n                                              <option value='eu'>Basque</option>\n                                              <option value='b1'>Bavarian</option>\n                                              <option value='be'>Belarusian</option>\n                                              <option value='bn'>Bengali</option>\n                                              <option value='b5'>Bengali-romaji</option>\n                                              <option value='bh'>Bihari languages</option>\n                                              <option value='b3'>Bishnupriya</option>\n                                              <option value='bi'>Bislama</option>\n                                              <option value='bs'>Bosnian</option>\n                                              <option value='br'>Breton</option>\n                                              <option value='bg'>Bulgarian</option>\n                                              <option value='my'>Burmese</option>\n                                              <option value='ca'>Catalan</option>\n                                              <option value='c2'>Cebuano</option>\n                                              <option value='b2'>Central bikol</option>\n                                              <option value='c3'>Central kurdish</option>\n                                              <option value='ch'>Chamorro</option>\n                                              <option value='c1'>Chavacano</option>\n                                              <option value='ce'>Chechen</option>\n                                              <option value='ny'>Chichewa</option>\n                                              <option value='zh'>Chinese (simplified)</option>\n                                              <option value='z1'>Chinese (traditional)</option>\n                                              <option value='rz'>Chinese-romaji</option>\n                                              <option value='cu'>Church slavic</option>\n                                              <option value='cv'>Chuvash</option>\n                                              <option value='kw'>Cornish</option>\n                                              <option value='co'>Corsican</option>\n                                              <option value='cr'>Cree</option>\n                                              <option value='c4'>Creoles and pidgins</option>\n                                              <option value='c5'>Creoles and pidgins, english based</option>\n                                              <option value='c6'>Creoles and pidgins, french-based</option>\n                                              <option value='c7'>Creoles and pidgins, portuguese-based</option>\n                                              <option value='hr'>Croatian</option>\n                                              <option value='cs'>Czech</option>\n                                              <option value='da'>Danish</option>\n                                              <option value='d1'>Dimli (individual language)</option>\n                                              <option value='dv'>Divehi</option>\n                                              <option value='d3'>Dotyali</option>\n                                              <option value='nl'>Dutch</option>\n                                              <option value='dz'>Dzongkha</option>\n                                              <option value='m2'>Eastern mari</option>\n                                              <option value='a2'>Egyptian arabic</option>\n                                              <option value='e1'>Emilian-romagnol</option>\n                                              <option value='en'>English</option>\n                                              <option value='m6'>Erzya</option>\n                                              <option value='eo'>Esperanto</option>\n                                              <option value='et'>Estonian</option>\n                                              <option value='ee'>Ewe</option>\n                                              <option value='fo'>Faroese</option>\n                                              <option value='h1'>Fiji hindi</option>\n                                              <option value='fj'>Fijian</option>\n                                              <option value='f1'>Filipino</option>\n                                              <option value='fi'>Finnish</option>\n                                              <option value='fr'>French</option>\n                                              <option value='f2'>Frisian, northern</option>\n                                              <option value='fy'>Frisian, western</option>\n                                              <option value='ff'>Fulah</option>\n                                              <option value='gl'>Galician</option>\n                                              <option value='lg'>Ganda</option>\n                                              <option value='ka'>Georgian</option>\n                                              <option value='de'>German</option>\n                                              <option value='n2'>German, low</option>\n                                              <option value='g1'>Goan konkani</option>\n                                              <option value='el'>Greek</option>\n                                              <option value='e2'>Greek-romaji</option>\n                                              <option value='kl'>Greenlandic</option>\n                                              <option value='gn'>Guarani</option>\n                                              <option value='gu'>Gujarati</option>\n                                              <option value='g2'>Gujarati-romaji</option>\n                                              <option value='ht'>Haitian creole</option>\n                                              <option value='ha'>Hausa</option>\n                                              <option value='he'>Hebrew</option>\n                                              <option value='hz'>Herero</option>\n                                              <option value='hi'>Hindi</option>\n                                              <option value='h3'>Hindi-romaji</option>\n                                              <option value='ho'>Hiri motu</option>\n                                              <option value='hu'>Hungarian</option>\n                                              <option value='is'>Icelandic</option>\n                                              <option value='io'>Ido</option>\n                                              <option value='ig'>Igbo</option>\n                                              <option value='i1'>Iloko</option>\n                                              <option value='id'>Indonesian</option>\n                                              <option value='ia'>Interlingua</option>\n                                              <option value='ie'>Interlingue</option>\n                                              <option value='iu'>Inuktitut</option>\n                                              <option value='ik'>Inupiaq</option>\n                                              <option value='ga'>Irish</option>\n                                              <option value='it'>Italian</option>\n                                              <option value='ja'>Japanese</option>\n                                              <option value='rj'>Japanese-romaji</option>\n                                              <option value='jv'>Javanese</option>\n                                              <option value='x1'>Kalmyk</option>\n                                              <option value='kn'>Kannada</option>\n                                              <option value='k2'>Kannada-romaji</option>\n                                              <option value='kr'>Kanuri</option>\n                                              <option value='k1'>Karachay-balkar</option>\n                                              <option value='ks'>Kashmiri</option>\n                                              <option value='kk'>Kazakh</option>\n                                              <option value='km'>Khmer, central</option>\n                                              <option value='ki'>Kikuyu</option>\n                                              <option value='rw'>Kinyarwanda</option>\n                                              <option value='ky'>Kirghiz</option>\n                                              <option value='kv'>Komi</option>\n                                              <option value='kg'>Kongo</option>\n                                              <option value='ko'>Korean</option>\n                                              <option value='rk'>Korean-romaji</option>\n                                              <option value='kj'>Kuanyama</option>\n                                              <option value='ku'>Kurdish</option>\n                                              <option value='lo'>Lao</option>\n                                              <option value='la'>Latin</option>\n                                              <option value='lv'>Latvian</option>\n                                              <option value='l1'>Lezghian</option>\n                                              <option value='li'>Limburgish</option>\n                                              <option value='ln'>Lingala</option>\n                                              <option value='lt'>Lithuanian</option>\n                                              <option value='j1'>Lojban</option>\n                                              <option value='l2'>Lombard</option>\n                                              <option value='lu'>Luba-katanga</option>\n                                              <option value='lb'>Luxembourgish</option>\n                                              <option value='mk'>Macedonian</option>\n                                              <option value='m1'>Maithili</option>\n                                              <option value='mg'>Malagasy</option>\n                                              <option value='ms'>Malay</option>\n                                              <option value='ml'>Malayalam</option>\n                                              <option value='m8'>Malayalam-romaji</option>\n                                              <option value='mt'>Maltese</option>\n                                              <option value='gv'>Manx</option>\n                                              <option value='mi'>Maori</option>\n                                              <option value='mr'>Marathi</option>\n                                              <option value='m9'>Marathi-romaji</option>\n                                              <option value='mh'>Marshallese</option>\n                                              <option value='m7'>Mazanderani</option>\n                                              <option value='m3'>Minangkabau</option>\n                                              <option value='x2'>Mingrelian</option>\n                                              <option value='m5'>Mirandese</option>\n                                              <option value='mo'>Moldavian</option>\n                                              <option value='mn'>Mongolian</option>\n                                              <option value='n4'>Nahuatl</option>\n                                              <option value='na'>Nauru</option>\n                                              <option value='nv'>Navajo</option>\n                                              <option value='nd'>Ndebele, north</option>\n                                              <option value='nr'>Ndebele, south</option>\n                                              <option value='ng'>Ndonga</option>\n                                              <option value='n1'>Neapolitan</option>\n                                              <option value='n3'>Nepal bhasa</option>\n                                              <option value='ne'>Nepali</option>\n                                              <option value='n5'>Nepali-romaji</option>\n                                              <option value='l3'>Northern luri</option>\n                                              <option value='no'>Norwegian</option>\n                                              <option value='nb'>Norwegian bokmål</option>\n                                              <option value='nn'>Norwegian nynorsk</option>\n                                              <option value='oc'>Occitan</option>\n                                              <option value='oj'>Ojibwa</option>\n                                              <option value='or'>Oriya</option>\n                                              <option value='o1'>Oriya-romaji</option>\n                                              <option value='om'>Oromo</option>\n                                              <option value='os'>Ossetian</option>\n                                              <option value='pi'>Pali</option>\n                                              <option value='p1'>Pampanga</option>\n                                              <option value='pa'>Panjabi</option>\n                                              <option value='p5'>Panjabi-romaji</option>\n                                              <option value='fa'>Persian</option>\n                                              <option value='p2'>Pfaelzisch</option>\n                                              <option value='p3'>Piemontese</option>\n                                              <option value='pl'>Polish</option>\n                                              <option value='pt'>Portuguese</option>\n                                              <option value='ps'>Pushto</option>\n                                              <option value='qu'>Quechua</option>\n                                              <option value='ro'>Romanian</option>\n                                              <option value='rm'>Romansh</option>\n                                              <option value='rn'>Rundi</option>\n                                              <option value='b4'>Russia buriat</option>\n                                              <option value='ru'>Russian</option>\n                                              <option value='r2'>Russian-romaji</option>\n                                              <option value='r1'>Rusyn</option>\n                                              <option value='se'>Sami, northern</option>\n                                              <option value='sm'>Samoan</option>\n                                              <option value='sg'>Sango</option>\n                                              <option value='sa'>Sanskrit</option>\n                                              <option value='s4'>Sanskrit-romaji</option>\n                                              <option value='sc'>Sardinian</option>\n                                              <option value='s3'>Scots</option>\n                                              <option value='gd'>Scottish gaelic</option>\n                                              <option value='sr'>Serbian</option>\n                                              <option value='sh'>Serbo-croatian</option>\n                                              <option value='sn'>Shona</option>\n                                              <option value='ii'>Sichuan yi</option>\n                                              <option value='s2'>Sicilian</option>\n                                              <option value='sd'>Sindhi</option>\n                                              <option value='si'>Sinhala</option>\n                                              <option value='sk'>Slovak</option>\n                                              <option value='sl'>Slovenian</option>\n                                              <option value='so'>Somali</option>\n                                              <option value='d2'>Sorbian, lower</option>\n                                              <option value='h2'>Sorbian, upper</option>\n                                              <option value='st'>Sotho, southern</option>\n                                              <option value='a4'>South azerbaijani</option>\n                                              <option value='es'>Spanish</option>\n                                              <option value='su'>Sundanese</option>\n                                              <option value='sw'>Swahili</option>\n                                              <option value='ss'>Swati</option>\n                                              <option value='sv'>Swedish</option>\n                                              <option value='tl'>Tagalog</option>\n                                              <option value='ty'>Tahitian</option>\n                                              <option value='tg'>Tajik</option>\n                                              <option value='ta'>Tamil</option>\n                                              <option value='t2'>Tamil-romaji</option>\n                                              <option value='tt'>Tatar</option>\n                                              <option value='te'>Telugu</option>\n                                              <option value='t3'>Telugu-romaji</option>\n                                              <option value='th'>Thai</option>\n                                              <option value='t4'>Thai-romaji</option>\n                                              <option value='bo'>Tibetan</option>\n                                              <option value='ti'>Tigrinya</option>\n                                              <option value='to'>Tonga (tonga islands)</option>\n                                              <option value='a1'>Tosk albanian</option>\n                                              <option value='ts'>Tsonga</option>\n                                              <option value='tn'>Tswana</option>\n                                              <option value='tr'>Turkish</option>\n                                              <option value='tk'>Turkmen</option>\n                                              <option value='t1'>Tuvinian</option>\n                                              <option value='tw'>Twi</option>\n                                              <option value='ug'>Uighur</option>\n                                              <option value='uk'>Ukrainian</option>\n                                              <option value='ur'>Urdu</option>\n                                              <option value='u1'>Urdu-romaji</option>\n                                              <option value='uz'>Uzbek</option>\n                                              <option value='ve'>Venda</option>\n                                              <option value='v1'>Venetian</option>\n                                              <option value='v2'>Veps</option>\n                                              <option value='vi'>Vietnamese</option>\n                                              <option value='v3'>Vlaams</option>\n                                              <option value='vo'>Volapük</option>\n                                              <option value='wa'>Walloon</option>\n                                              <option value='w1'>Waray</option>\n                                              <option value='cy'>Welsh</option>\n                                              <option value='m4'>Western mari</option>\n                                              <option value='p4'>Western panjabi</option>\n                                              <option value='wo'>Wolof</option>\n                                              <option value='w2'>Wu chinese</option>\n                                              <option value='xh'>Xhosa</option>\n                                              <option value='s1'>Yakut</option>\n                                              <option value='yi'>Yiddish</option>\n                                              <option value='yo'>Yoruba</option>\n                                              <option value='y1'>Yue chinese</option>\n                                              <option value='za'>Zhuang</option>\n                                              <option value='zu'>Zulu</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.lyrics.enableYoutubeLyrics')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.lyrics.enable_yt\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.lyrics.enableQQLyrics')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.lyrics.enable_qq\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/radio.svg\" classes=\"svg-md\" name=\"settings-connectivity\" />\n                        </div>\n                        <div>\n                            {{ $root.getLz('settings.header.connectivity') }}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <div class=\"md-option-container\">\n                            <!-- Connectivity Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.connectivity')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.playbackNotifications')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.general.playbackNotifications\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <!-- DiscordRPC -->\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.discordRPC')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.connectivity.discord_rpc.enabled\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div v-show=\"app.cfg.connectivity.discord_rpc.enabled != false\">\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.reload')}}\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <button class=\"md-btn\" @click=\"reloadDiscordRPC()\">\n                                                {{$root.getLz('menubar.options.reload')}}\n                                            </button>\n                                        </div>\n                                    </div>\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.clientName')}}\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <label>\n                                                <select class=\"md-select\" v-model=\"app.cfg.connectivity.discord_rpc.client\">\n                                                    <option value=\"Cider\">{{$root.getLz('app.name')}}</option>\n                                                    <option value=\"AppleMusic\">{{$root.getLz('term.appleMusic')}}\n                                                    </option>\n                                                </select>\n                                            </label>\n                                        </div>\n                                    </div>\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.clearOnPause')}}\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <label>\n                                                <input type=\"checkbox\"\n                                                       v-model=\"app.cfg.connectivity.discord_rpc.clear_on_pause\" switch />\n                                            </label>\n                                        </div>\n                                    </div>\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.hideTimestamp')}}\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <label>\n                                                <input type=\"checkbox\"\n                                                       v-model=\"app.cfg.connectivity.discord_rpc.activity.hide_timestamp\" switch />\n                                            </label>\n                                        </div>\n                                    </div>\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.detailsFormat')}}<br />\n                                            <small>{{$root.getLz('term.variables')}}: {artist}, {composer}, {title},\n                                                {album},\n                                                {trackNumber}</small>\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <label>\n                                                <input type=\"text\"\n                                                       v-model=\"app.cfg.connectivity.discord_rpc.activity.details_format\" />\n                                            </label>\n                                        </div>\n                                    </div>\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.stateFormat')}}\n                                            <small>{{$root.getLz('term.variables')}}: {artist}, {composer}, {title},\n                                                {album},\n                                                {trackNumber}</small>\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <label>\n                                                <input type=\"text\"\n                                                       v-model=\"app.cfg.connectivity.discord_rpc.activity.state_format\" />\n                                            </label>\n                                        </div>\n                                    </div>\n\n                                    <div class=\"md-option-line\">\n                                        <div class=\"md-option-segment\">\n                                            {{$root.getLz('settings.option.connectivity.discordRPC.showActivityButtons')}}\n                                        </div>\n                                        <div class=\"md-option-segment md-option-segment_auto\">\n                                            <label>\n                                                <input type=\"checkbox\"\n                                                       v-model=\"app.cfg.connectivity.discord_rpc.activity.buttons.enabled\" switch />\n                                            </label>\n                                        </div>\n                                    </div>\n\n                                    <div v-show=\"app.cfg.connectivity.discord_rpc.activity.buttons.enabled == true\">\n                                        <div class=\"md-option-line\">\n                                            <div class=\"md-option-segment\">\n                                                {{$root.getLz('settings.option.connectivity.discordRPC.firstButton')}}\n                                            </div>\n                                            <div class=\"md-option-segment md-option-segment_auto\">\n                                                <label>\n                                                    <select class=\"md-select\" v-model=\"app.cfg.connectivity.discord_rpc.activity.buttons.first\" @change=\"$event.target.value == 'disabled' ? app.cfg.connectivity.discord_rpc.activity.buttons.second = 'disabled' : ''\">\n                                                        <option v-for=\"option in app.cfg.connectivity.discord_rpc.activity.buttons.options\" v-bind:value=\"option\" v-show=\"app.cfg.connectivity.discord_rpc.activity.buttons.second != option\">{{ $root.getLz(`settings.option.connectivity.discordRPC.buttons.${option}`) }}</option>\n                                                        <option value=\"disabled\">{{$root.getLz('term.disabled')}}</option>\n                                                    </select>\n                                                </label>\n                                            </div>\n                                        </div>\n\n                                        <div class=\"md-option-line\" v-show=\"app.cfg.connectivity.discord_rpc.activity.buttons.first != 'disabled'\">\n                                            <div class=\"md-option-segment\">\n                                                {{$root.getLz('settings.option.connectivity.discordRPC.secondButton')}}\n                                            </div>\n                                            <div class=\"md-option-segment md-option-segment_auto\">\n                                                <label>\n                                                    <select class=\"md-select\" v-model=\"app.cfg.connectivity.discord_rpc.activity.buttons.second\">\n                                                        <option v-for=\"option in app.cfg.connectivity.discord_rpc.activity.buttons.options\" v-bind:value=\"option\" v-show=\"app.cfg.connectivity.discord_rpc.activity.buttons.first != option\">{{ $root.getLz(`settings.option.connectivity.discordRPC.buttons.${option}`) }}</option>\n                                                        <option value=\"disabled\">{{$root.getLz('term.disabled')}}</option>\n                                                    </select>\n                                                </label>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </div>\n\n                                <!-- LastFM -->\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.lastfmScrobble')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" id=\"lfmConnect\"\n                                                @click=\"app.cfg.connectivity.lastfm.enabled ? lfmDisconnect() : lfmAuthorize()\">\n                                            {{$root.getLz(`term.${$root.cfg.connectivity.lastfm.enabled ? \"disconnect\" :\n                                            \"connect\"}`)}}<br>\n                                            <small>{{app.cfg.connectivity.lastfm.enabled ?\n                                                `${$root.getLz('term.authed')}:\n                                                ${$root.cfg.connectivity.lastfm.secrets.username}` : '' }}</small>\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"lastfmConnecting\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.lastfmScrobble.manualToken')}}\n                                        <small>\n                                            <a href=\"https://www.last.fm/api/auth?api_key=f9986d12aab5a0fe66193c559435ede3\" target=\"_blank\">\n                                                {{$root.getLz('settings.option.connectivity.lastfmScrobble.manualToken.link')}}\n                                            </a>\n                                        </small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <form @submit.prevent=\"submitToken\">\n                                                <input type=\"text\" autofocus id=\"lfmToken\" />\n                                                <input type=\"submit\" class=\"md-btn\"\n                                                       @value=\"$root.getLz('action.submit')\" />\n                                            </form>\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.cfg.connectivity.lastfm.enabled\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.lastfmScrobble.delay')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"number\" min=\"50\" max=\"100\"\n                                                   v-model=\"app.cfg.connectivity.lastfm.scrobble_after\" />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.cfg.connectivity.lastfm.enabled\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.lastfmScrobble.filterLoop')}}\n                                        <small>{{$root.getLz('settings.option.connectivity.lastfmScrobble.filterLoop.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.connectivity.lastfm.filter_loop\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.cfg.connectivity.lastfm.enabled\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.lastfmScrobble.removeFeatured')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.connectivity.lastfm.remove_featured\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\" v-show=\"app.cfg.connectivity.lastfm.enabled\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.connectivity.lastfmScrobble.filterTypes')}}\n                                        <small>{{$root.getLz('settings.option.connectivity.lastfmScrobble.filterTypes.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.connectivity.lastfm.filter_types['song']\">{{$root.getLz('term.songs')}}<br>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.connectivity.lastfm.filter_types['musicVideo']\">{{$root.getLz('term.musicVideos')}}\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </b-tab>\n                <b-tab>\n                    <template #title>\n                        <div>\n                            <svg-icon url=\"./assets/feather/hard-drive.svg\" classes=\"svg-md\" name=\"settings-advanced\" />\n                        </div>\n                        <div>\n                            {{$root.getLz('settings.header.advanced')}}\n                        </div>\n                    </template>\n                    <div class=\"settings-tab-content\">\n                        <div class=\"md-option-container\">\n                            <!-- Debug Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.debug')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.debug.copy_log')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"copyLogs\">\n                                            {{$root.getLz('action.copy')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.debug.openAppData')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"openAppData\">\n                                            {{$root.getLz('action.open')}}\n                                        </button>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        Performant Logging\n                                        <small>Disables debug logging, resulting in a slightly faster Cider. (Requires\n                                            relaunch)</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.advanced.disableLogging\" switch />\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n\n                            <!-- Experimental Settings -->\n                            <div class=\"md-option-header\">\n                                <span>{{$root.getLz('settings.header.experimental')}}</span>\n                            </div>\n                            <div class=\"settings-option-body\">\n\n                                <!--<div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.plugin.github.explore')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"$root.openSettingsPage('github-plugins')\">{{\n                                            $root.getLz(\"settings.option.visual.plugin.github.explore\") }}\n                                        </button>\n                                    </div>\n                                </div> -->\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.experimental.reinstallwidevine')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <button class=\"md-btn\" @click=\"reinstallWidevineCDM\">\n                                            {{$root.getLz('settings.option.experimental.reinstallwidevine')}}\n                                        </button>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        Immersive Fullscreen Test\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\"\n                                                   v-model=\"app.cfg.advanced.experiments.includes('immersive-preview')\"\n                                                   @click=\"app.cfg.advanced.experiments.includes('immersive-preview') ? removeExperiment('immersive-preview') : addExperiment('immersive-preview')\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.experimental.unknownPlugin')}}\n                                        <br>\n                                        <small>{{$root.getLz('settings.option.experimental.unknownPlugin.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\"\n                                                   v-model=\"app.cfg.advanced.experiments.includes('unknown-sources')\"\n                                                   @click=\"app.cfg.advanced.experiments.includes('unknown-sources') ? removeExperiment('unknown-sources') : addExperiment('unknown-sources')\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        Theme & Plugin Mirror to Cider\n                                        <small>Only works in region where GitHub is blacklisted. Requires relaunch.</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\"\n                                                   v-model=\"app.cfg.advanced.experiments.includes('cider_mirror')\"\n                                                   @click=\"app.cfg.advanced.experiments.includes('cider_mirror') ? removeExperiment('cider_mirror') : addExperiment('cider_mirror')\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.advanced.playlistTrackMapping')}}\n                                        <br>\n                                        <small>{{$root.getLz('settings.option.advanced.playlistTrackMapping.description')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.advanced.playlistTrackMapping\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.experimental.compactUI')}}\n                                        <small\n                                                v-if=\"!!app.getThemeDirective('forceUI')\">{{$root.getLz('term.themeManaged')}}</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\"\n                                                   v-model=\"app.cfg.advanced.experiments.includes('compactui')\"\n                                                   @click=\"app.cfg.advanced.experiments.includes('compactui') ? removeExperiment('compactui') : addExperiment('compactui')\"\n                                                   switch :disabled=\"!!app.getThemeDirective('forceUI')\" />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.experimental.inline_playlists')}}\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" disabled\n                                                   v-model=\"app.cfg.advanced.experiments.includes('inline-playlists')\"\n                                                   @click=\"app.cfg.advanced.experiments.includes('inline-playlists') ? removeExperiment('inline-playlists') : addExperiment('inline-playlists')\"\n                                                   switch />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line update-check\" v-if=\"app.platform === 'win32' || app.platform === 'linux'\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.visual.transparent')}}<br>\n                                        <small>({{$root.getLz('settings.option.visual.transparent.description')}})</small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <input type=\"checkbox\" v-model=\"app.cfg.visual.transparent\" switch\n                                                   @change=\"promptForRelaunch()\" />\n                                        </label>\n                                    </div>\n                                </div>\n\n                                <div class=\"md-option-line\">\n                                    <div class=\"md-option-segment\">\n                                        {{$root.getLz('settings.option.general.pagination')}}<br>\n                                        <small>\n                                            {{$root.getLz('settings.options.general.pagination.description')}}<br>\n                                        </small>\n                                    </div>\n                                    <div class=\"md-option-segment md-option-segment_auto\">\n                                        <label>\n                                            <select class=\"md-select\" style=\"width:180px;\"\n                                                    v-model.number=\"$root.cfg.libraryPrefs.pageSize\" type=\"number\">\n                                                <option value=\"50\">50</option>\n                                                <option value=\"100\">100</option>\n                                                <option value=\"250\">250</option>\n                                                <option value=\"500\">500</option>\n                                                <option value=\"1000\">1000</option>\n                                            </select>\n                                        </label>\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </b-tab>\n                <!--keybinds Settings -->\n                <b-tab id=\"hid\">\n                    <template>\n                        <keybinds-settings />\n                    </template>\n                </b-tab>\n                <!--keybinds-settings -->\n                <!--Github-theme-settings -->\n                <b-tab id=\"hid\">\n                    <template>\n                        <themes-github />\n                    </template>\n                </b-tab>\n                <!--Github-theme-settings -->\n                <!-- Connect Settings -->\n                <!-- Not Prod Ready\n            <b-tab :title=\"$root.getLz('settings.header.connect')\">\n                <div class=\"md-option-container\">\n                    <!!!!!-- Cider Connect / Linking Settings -!->\n                    <div class=\"md-option-header\">\n                        <span>{{$root.getLz('settings.header.connect')}}</span>\n                    </div>\n                    <div class=\"settings-option-body\">\n                        <div class=\"md-option-line update-check\" v-if=\"app.cfg.connectUser.auth == null\">\n                            <div class=\"md-option-segment\">\n                                {{$root.getLz('settings.option.connect.link_account')}}\n                                <small>{{$root.getLz('settings.option.connect.link_account.description')}}</small>\n                                <br>\n                                <small>Debug Status: {{ app.cfg.connectUser }}</small>\n                            </div>\n                            <div class=\"md-option-segment md-option-segment_auto\">\n                                <button class=\"md-btn\" id='settings.option.general.updateCider.check' @click=\"authCC()\">\n                                    {{$root.getLz('term.connect')}}\n                                </button>\n                            </div>\n                        </div>\n                        <div v-if=\"app.cfg.connectUser.auth != null\">\n                            <div class=\"md-option-line\">\n                                <div class=\"md-option-segment\">\n                                    {{$root.getLz('settings.option.connect.link_account')}}\n                                    <small>{{$root.getLz('settings.option.connect.link_account.description')}}</small>\n                                    <br>\n                                </div>\n                                <div class=\"md-option-segment md-option-segment_auto\">\n                                    <button class=\"md-btn\" id='settings.option.general.updateCider.check'\n                                            @click=\"logoutCC()\" style=\"display: flex;align-items: center;gap: 0.4em;\">\n                                        <%- include(\"../svg/check.svg\") %>\n                                        <div v>Connected</div>\n                                    </button>\n                                </div>\n                            </div>\n                            <div class=\"md-option-header\" style=\"margin-left: -0.55em;\">\n                                <span>{{app.cfg.connectUser.username}}</span>\n                                <img :src=\"'https://cdn.discordapp.com/avatars/' + app.cfg.connectUser.id + '/' + app.cfg.connectUser.avatar + '.png?size=32'\"\n                                     alt=\"Discord Avatar\"></img>\n                            </div>\n\n                            <div class=\"md-option-line\">\n                                <div class=\"md-option-segment\">\n                                    Sync Settings\n                                </div>\n                                <div class=\"md-option-segment md-option-segment_auto\">\n                                    <label>\n                                        <input type=\"checkbox\" a-v-model=\"app.cfg.connectUser.sync.settings\"\n                                               @click=\"app.cfg.connectUser.sync.settings = !app.cfg.connectUser.sync.settings\"\n                                               switch/>\n                                    </label>\n                                </div>\n                            </div>\n\n                            <div class=\"md-option-line\">\n                                <div class=\"md-option-segment\">\n                                    Sync Themes\n                                </div>\n                                <div class=\"md-option-segment md-option-segment_auto\">\n                                    <label>\n                                        <input type=\"checkbox\" disabled a-v-model=\"app.cfg.connectUser.sync.themes\"\n                                               @click=\"app.cfg.connectUser.sync.themes = !app.cfg.connectUser.sync.themes\"\n                                               switch/>\n                                    </label>\n                                </div>\n                            </div>\n\n                            <div class=\"md-option-line\">\n                                <div class=\"md-option-segment\">\n                                    Sync Plugins\n                                </div>\n                                <div class=\"md-option-segment md-option-segment_auto\">\n                                    <label>\n                                        <input type=\"checkbox\" disabled a-v-model=\"app.cfg.connectUser.sync.plugins\"\n                                               @click=\"app.cfg.connectUser.sync.plugins = !app.cfg.connectUser.sync.plugins\"\n                                               switch/>\n                                    </label>\n                                </div>\n                            </div>\n\n                        </div>\n                    </div>\n                </div>\n            </b-tab>\n            -->\n            </b-tabs>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component(\"settings-window\", {\n    template: \"#settings-window\",\n    data: function() {\n      return {\n        app: this.$root,\n        themes: ipcRenderer.sendSync(\"get-themes\"),\n        tabIndex: 0,\n        canChangeHash: false,\n        lastfmConnecting: false\n      }\n    },\n    watch: {\n      tabIndex: function(val) {\n        if (this.canChangeHash) {\n          // window.location.hash = `#settings/${val}`\n        }\n      }\n    },\n    methods: {\n      sidebarVis() {\n        const tabIndex = app.$store.state.pageState['settings'].currentTabIndex\n        if (tabIndex == 3 || tabIndex == 5 || tabIndex == 10) {\n          return true;\n        }\n        return false\n      },\n      close() {\n        this.$root.modals.settings = false\n      },\n      windowBgStyleChange() {\n        this.$root.getNowPlayingArtworkBG(undefined, true)\n        if (this.$root.cfg.visual.window_background_style === \"mica\") {\n          this.$root.spawnMica()\n        }\n      },\n      reinstallWidevineCDM() {\n        app.confirm(app.getLz(\"settings.option.experimental.reinstallwidevine.confirm\"), (ok) => {\n          if (ok) {\n            ipcRenderer.invoke(\"reinstall-widevine-cdm\");\n          }\n        })\n      },\n      gitHubExplore() {\n        app.openSettingsPage(\"github-themes\")\n      },\n      copyLogs() {\n        ipcRenderer.send('fetch-log')\n        notyf.success(app.getLz('term.share.success'));\n      },\n      openAppData() {\n        ipcRenderer.send('open-appdata')\n      },\n      changeDisplayTheme(){\n        ipcRenderer.send('changeDisplayTheme',app.cfg.visual.overrideDisplayTheme)\n      },\n      getLanguages: function() {\n        let langs = this.$root.lzListing\n        let categories = {\n          \"main\": [],\n          \"fun\": [],\n          \"unsorted\": []\n        }\n        // sort by category if category is undefined or empty put it in \"unsorted\"\n        for (let i = 0; i < langs.length; i++) {\n          if (langs[i].category === undefined || langs[i].category === \"\") {\n            categories.unsorted.push(langs[i])\n          } else {\n            try {\n              categories[langs[i].category].push(langs[i])\n            }\n            catch {\n              categories[\"unsorted\"].push(langs[i])\n            }\n\n          }\n        }\n        // return\n        console.log(categories)\n        return categories\n      },\n      addExperiment(flag) {\n        app.cfg.advanced.experiments.push(flag);\n      },\n      removeExperiment(flag) {\n        app.cfg.advanced.experiments.splice(app.cfg.advanced.experiments.indexOf(flag), 1);\n      },\n      toggleNormalization: function() {\n        if (app.cfg.audio.normalization) {\n          CiderAudio.normalizerOn()\n        } else {\n          CiderAudio.normalizerOff()\n        }\n      },\n      changeAudioQuality: function() {\n        app.mk.bitrate = MusicKit.PlaybackBitrate[app.cfg.audio.quality];\n      },\n      toggleUserInfo: function() {\n        app.chrome.hideUserInfo = !app.cfg.visual.showuserinfo\n      },\n      sendDataToMTT: function() {\n        ipcRenderer.invoke('setStoreValue', 'general.close_behavior', app.cfg.general.close_behavior);\n        //  setStoreValue does not change plugin store values somehow\n        ipcRenderer.invoke('update-store-mtt', app.cfg.general.close_behavior);\n      },\n      checkIfUpdateDisabled() {\n        if (app.cfg.main.UPDATABLE) return;\n\n        let updateFields = document.getElementsByClassName('update-check');\n        for (let i = 0; i < updateFields.length; i++) {\n          updateFields[i].style = \"opacity: 0.5; pointer-events: none;\";\n          updateFields[i].title = \"Not available on this type of build\";\n        }\n\n      },\n      promptForRelaunch() {\n        app.confirm(app.getLz('action.relaunch.confirm'), function(result) {\n          if (result) {\n            ipcRenderer.send('relaunchApp', '');\n          }\n        });\n      },\n      authCC() {\n        ipcRenderer.send('cc-auth')\n      },\n      logoutCC() {\n        ipcRenderer.send('cc-logout')\n      },\n      reloadDiscordRPC() {\n        ipcRenderer.send('discordrpc:reload')\n      },\n      lfmDisconnect() {\n        this.$root.cfg.connectivity.lastfm.enabled = false;\n        this.$root.cfg.connectivity.lastfm.secrets.username = \"\";\n        this.$root.cfg.connectivity.lastfm.secrets.key = \"\";\n        ipcRenderer.send('lastfm:disconnect');\n      },\n      async lfmAuthorize() {\n        this.lastfmConnecting = true;\n        window.open(await ipcRenderer.invoke('lastfm:url'));\n        app.notyf.success(app.getLz('settings.notyf.connectivity.lastfmScrobble.connecting'));\n\n        /* Just a timeout for the button */\n        setTimeout(() => {\n          if (!this.$root.cfg.connectivity.lastfm.enabled) {\n            app.notyf.error(app.getLz('settings.notyf.connectivity.lastfmScrobble.connectError'));\n            console.warn('[lastfm:authorize] Last.fm authorization timed out.');\n            this.lastfmConnecting = false;\n          }\n        }, 40000);\n\n        ipcRenderer.once('lastfm:authenticated', (_e, session) => {\n          this.$root.cfg.connectivity.lastfm.secrets.username = session.username\n          this.$root.cfg.connectivity.lastfm.secrets.key = session.key\n          this.$root.cfg.connectivity.lastfm.enabled = true\n          this.lastfmConnecting = false;\n          app.notyf.success(app.getLz('settings.notyf.connectivity.lastfmScrobble.connectSuccess'));\n        })\n      },\n      filterChange(e) {\n        this.$root.cfg.connectivity.lastfm.filter_types[e.target.value] = e.target.checked;\n      },\n      submitToken() {\n        const token = document.getElementById('lfmToken').value;\n        ipcRenderer.send('lastfm:auth', token);\n      },\n      openLocalSongsPathMenu() {\n        app.modals.pathMenu = true\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/share-sheet.ejs",
    "content": "<script type=\"text/x-template\" id=\"add-to-playlist\">\n    <template>\n        <div class=\"modal-fullscreen addtoplaylist-panel\" @click.self=\"app.resetState()\"\n             @contextmenu.self=\"app.resetState()\">\n            <div class=\"modal-window\">\n                <div class=\"modal-header\">\n                    <div class=\"modal-title\">{{app.getLz('action.addToPlaylist')}}</div>\n                    <button class=\"close-btn\" @click=\"app.resetState()\"\n                            :aria-label=\"app.getLz('action.close')\"></button>\n                </div>\n                <div class=\"modal-content\">\n                    <button class=\"playlist-item\"\n                            @click=\"app.addSelectedToNewPlaylist()\" style=\"width:100%;\">\n                        <div class=\"icon\"><%- include(\"../svg/plus.svg\") %></div>\n                        <div class=\"name\">{{app.getLz('action.createPlaylist')}}</div>\n                    </button>\n                    <sidebar-playlist :playlist-select=\"playlistSelect\"\n                                      v-for=\"item in $root.getPlaylistFolderChildren('p.playlistsroot')\" v-bind:key=\"item.id\" :item=\"item\">\n                    </sidebar-playlist>\n                </div>\n                <div class=\"modal-search\">\n                    <div class=\"search-input-container\" style=\"width:100%;margin: 16px 0;\">\n                        <div class=\"search-input--icon\"></div>\n                        <input type=\"search\"\n                               ref=\"searchInput\"\n                               style=\"width:100%;\"\n                               spellcheck=\"false\"\n                               :placeholder=\"app.getLz('term.search') + '...'\"\n                               v-model=\"searchQuery\"\n                               @input=\"search()\"\n                               class=\"search-input\">\n                    </div>\n                </div>\n            </div>\n        </div>\n    </template>\n</script>\n\n<script>\n  Vue.component('add-to-playlist', {\n    template: '#add-to-playlist',\n    data: function() {\n      return {\n        playlistSorted: [],\n        searchQuery: \"\",\n        focused: \"\",\n        app: this.$root,\n      }\n    },\n    props: {\n      playlists: {\n        type: Array,\n        required: true\n      }\n    },\n    mounted() {\n      this.search()\n      this.$refs.searchInput.focus()\n      this.$refs.searchInput.addEventListener('keydown', (e) => {\n        if (e.keyCode == 13) {\n          if (this.focused != \"\") {\n            this.addToPlaylist(this.focused)\n          }\n        }\n      })\n    },\n    methods: {\n      playlistSelect(playlist) {\n        if (playlist.type != \"library-playlist-folders\") {\n          this.addToPlaylist(playlist.id)\n        }\n      },\n      addToPlaylist(id) {\n        app.addSelectedToPlaylist(id)\n      },\n      search() {\n        this.focused = \"\"\n        if (this.searchQuery == \"\") {\n          this.playlistSorted = this.playlists\n        } else {\n          this.playlistSorted = this.playlists.filter(playlist => {\n            return playlist.attributes.name.toLowerCase().indexOf(this.searchQuery.toLowerCase()) > -1\n          })\n          if (this.playlistSorted.length == 1) {\n            this.focused = this.playlistSorted[0].id\n          }\n        }\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/sidebar-playlist.ejs",
    "content": "<script type=\"text/x-template\" id=\"sidebar-playlist\">\n    <div class=\"sidebar-playlist\" :key=\"item.id\">\n        <button class=\"app-sidebar-item app-sidebar-item-playlist\" :key=\"item.id\"\n                :class=\"item.type != 'library-playlist-folders' ? {'active': $root.page.includes(item.id)} : ['playlist-folder', {'folder-button-active': folderOpened}, isPlaylistSelected]\"\n                @contextmenu=\"playlistContextMenu($event, item.id)\"\n                @dragstart=\"startDrag($event, item)\"\n                @dragover=\"dragOver\"\n                @drop=\"onDrop\"\n                :href=\"item.href\"\n                @click='clickEvent()'>\n            <template v-if=\"!renaming\">\n                <svg-icon :url=\"icon\" name=\"sidebar-playlist\" />\n                {{ item.attributes.name }}\n                <small class=\"presentNotice\" v-if=\"hasRelatedMediaItems\">(Track present)</small>\n            </template>\n            <input type=\"text\" v-model=\"item.attributes.name\" class=\"pl-rename-field\" @blur=\"rename()\"\n                   @keydown.enter=\"rename()\" v-else>\n        </button>\n        <div class=\"folder-body\" v-if=\"item.type === 'library-playlist-folders' && folderOpened\">\n            <template v-if=\"children.length != 0\">\n                <sidebar-playlist v-for=\"item in children\" :relate-media-items=\"relateMediaItems\"\n                                  :playlist-select=\"playlistSelect\" :item=\"item\" v-bind:key=\"item.id\"></sidebar-playlist>\n            </template>\n            <template v-else>\n                <div class=\"spinner\"></div>\n            </template>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('sidebar-playlist', {\n    template: '#sidebar-playlist',\n    props: {\n      item: {\n        type: Object,\n        required: true\n      },\n      playlistSelect: {\n        type: Function,\n        required: false\n      },\n      relateMediaItems: {\n        type: Array,\n        required: false,\n        default() {\n          return []\n        }\n      }\n    },\n    data: function() {\n      return {\n        folderOpened: false,\n        children: [],\n        playlistRoot: \"p.playlistsroot\",\n        renaming: false,\n        icon: \"\",\n        hasRelatedMediaItems: false\n      }\n    },\n    async mounted() {\n      if (this.item.type !== \"library-playlist-folders\") {\n        this.icon = (\"./assets/feather/list.svg\")\n      } else {\n        this.icon = (\"./assets/feather/folder.svg\")\n      }\n      let playlistMap = this.$root.playlists.trackMapping\n      if (this.relateMediaItems.length != 0) {\n        if (playlistMap[this.relateMediaItems[0]]) {\n          if (playlistMap[this.relateMediaItems[0]].includes(this.item.id)) {\n            this.hasRelatedMediaItems = true\n          }\n        }\n\n      }\n    },\n    methods: {\n      clickEvent() {\n        if (this.item.type != \"library-playlist-folders\") {\n          if (this.playlistSelect) {\n            this.playlistSelect(this.item)\n          } else {\n            this.openPlaylist(this.item)\n          }\n        } else {\n          this.getPlaylistChildren(this.item)\n        }\n      },\n      rename() {\n        this.renaming = false\n\n        if (this.item.type === \"library-playlist-folders\") {\n          this.$root.editPlaylistFolder(this.item.id, this.item.attributes.name)\n        } else {\n          this.$root.editPlaylist(this.item.id, this.item.attributes.name)\n        }\n      },\n      async getChildren() {\n        let self = this\n        this.children = []\n        this.children = this.$root.playlists.listing.filter(child => {\n          if (child.parent == self.item.id) {\n            return child\n          }\n        })\n      },\n      async move(item, sendTo) {\n        let self = this\n        console.log(sendTo)\n        let type = item.type.replace(\"library-\", \"\")\n        let typeTo = sendTo.type\n        this.$root.mk.api.v3.music(`/v1/me/library/${type}/${item.id}/parent`, {}, {\n          fetchOptions: {\n            method: \"PUT\",\n            body: JSON.stringify({\n              data: [{\n                id: sendTo.id,\n                type: typeTo\n              }]\n            })\n          }\n        })\n\n        // find the item in this.$root.playlists.listing and store it in a variable\n        this.$root.playlists.listing.filter(playlist => {\n          if (playlist.id == item.id) {\n            console.log(playlist)\n            playlist.parent = sendTo.id\n\n          }\n        })\n        if (typeof this.$root.getChildren == \"function\") {\n          this.$root.getChildren()\n          console.log(this.$root.children)\n        }\n        await this.getChildren()\n        this.$root.sortPlaylists()\n        // await this.$root.refreshPlaylists()\n      },\n      playlistContextMenu(event, playlist_id) {\n        let menu = {\n          items: {\n            \"moveToParent\": {\n              name: this.$root.getLz('action.moveToTop'),\n              action: () => {\n                let self = this\n                this.move(this.item, {\n                  id: this.playlistRoot,\n                  type: \"library-playlist-folders\"\n                })\n                setTimeout(() => {\n                  self.getChildren()\n                }, 2000)\n              }\n            },\n            \"rename\": {\n              name: this.$root.getLz('action.rename'),\n              action: () => {\n                this.renaming = true\n                setTimeout(() => {\n                  document.querySelector(\".pl-rename-field\").focus()\n                  document.querySelector(\".pl-rename-field\").select()\n                }, 100)\n              }\n            },\n            \"deleteFromPlaylist\": {\n              name: this.$root.getLz('action.removeFromLibrary'),\n              action: () => {\n                this.$root.deletePlaylist(playlist_id)\n              }\n            },\n            \"addToFavorites\": {\n              name: this.$root.getLz('action.addToFavorites'),\n              disabled: true,\n              hidden: true,\n              action: () => {\n                this.addFavorite(playlist_id, \"library-playlists\")\n              }\n            }\n          }\n        }\n        if (this.item.type === \"library-playlist-folders\") {\n          menu.items.addToFavorites.disabled = true\n        }\n        app.showMenuPanel(menu, event)\n      },\n      dragOver(evt) {\n        evt.preventDefault();\n        evt.dataTransfer.dropEffect = \"move\";\n      },\n      onDrop(evt) {\n        let data = JSON.parse(evt.dataTransfer.getData(\"text/plain\"))\n        evt.preventDefault();\n        if (data.id == this.item.id) {\n          return;\n        }\n        console.log(data)\n        if (data) {\n          if (this.item.type == \"library-playlists\" || this.item.type == \"library-playlist-folders\") {\n            if (data.type == \"library-playlists\" && this.item.type == \"library-playlists\") {\n              return\n            }\n            this.move(data, this.item)\n          }\n        }\n      },\n      startDrag(evt) {\n        evt.dataTransfer.dropEffect = 'move'\n        evt.dataTransfer.effectAllowed = 'move'\n        evt.dataTransfer.setData('text/plain', JSON.stringify(this.item))\n      },\n      openPlaylist(item) {\n        this.$root.appRoute(`playlist_` + item.id);\n        this.$root.showingPlaylist = [];\n        if (item.id == 'ciderlocal') {\n          this.$root.showingPlaylist = {\n            \"id\": \"ciderlocal\",\n            \"type\": \"library-playlists\",\n            \"href\": \"\",\n            \"attributes\": {\n              \"artwork\": {\n                \"width\": null,\n                \"height\": null,\n                \"url\": \"\",\n                \"hasP3\": false\n              },\n              \"dateAdded\": \"2021-02-16T03:39:47Z\",\n              \"name\": \"Local Songs\",\n              \"canDelete\": true,\n              \"hasCatalog\": true,\n              \"canEdit\": true,\n              \"playParams\": {\n                \"id\": \"ciderlocal\",\n                \"kind\": \"playlist\",\n                \"isLibrary\": true,\n              },\n              \"isPublic\": true,\n              \"description\": {\n                \"standard\": \"\"\n              }\n            },\n            \"relationships\": {\n              \"tracks\": {\n                \"href\": \"\",\n                \"data\": this.$root.library.localsongs\n              }\n            }\n          }\n          this.$root.playlists.loadingState = 1;\n        } else {\n          this.$root.getPlaylistFromID(this.$root.page.substring(9), true)\n        }\n      },\n      getPlaylistChildren(item) {\n        let self = this\n        this.children = []\n        this.getChildren()\n        this.toggleFolder()\n\n        this.$root.mk.api.v3.music(`v1/me/library/playlist-folders/${item.id}/children`).then(data => {\n          let children = data.data.data;\n          children.forEach(child => {\n            if (!self.$root.playlists.listing.find(listing => listing.id == child.id)) {\n              child.parent = self.item.id\n              self.$root.playlists.listing.push(child)\n            }\n          })\n\n          self.$root.playlists.listing.sort((a, b) => {\n            if (a.type === 'library-playlist-folders' && b.type !== 'library-playlist-folders') {\n              return -1\n            } else if (a.type !== 'library-playlist-folders' && b.type === 'library-playlist-folders') {\n              return 1\n            } else {\n              return 0\n            }\n          })\n          self.getChildren()\n        })\n      },\n      isPlaylistSelected(item) {\n        if (this.$root.showingPlaylist.id == item.id) {\n          return [\"active\"]\n        } else {\n          return []\n        }\n      },\n      toggleFolder() {\n        this.folderOpened = !this.folderOpened;\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/sidebar.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-app-sidebar\">\n    <div id=\"app-sidebar\">\n        <template v-if=\"$root.getThemeDirective('windowLayout') != 'twopanel'\">\n            <div class=\"app-sidebar-header\">\n                <div class=\"search-input-container\">\n                    <div class=\"search-input--icon\"></div>\n                    <input\n                            type=\"search\"\n                            spellcheck=\"false\"\n                            @click=\"$root.appRoute('search');$root.search.showHints = true\"\n                            @focus=\"$root.search.showHints = true\"\n                            @blur=\"$root.setTimeout(()=>{if($root.hintscontext != true){$root.search.showHints = false} }, 300)\"\n                            v-on:keyup.enter=\"$root.searchQuery($root.search.hints[$root.search.cursor]?.content ?? $root.search.hints[$root.search.cursor]?.searchTerm ?? $root.search.term);$root.search.showHints = false;$root.search.showSearchView = true;$root.search.cursor = -1\"\n                            v-on:keyup=\"$root.searchCursor\"\n                            @change=\"$root.appRoute('search');\"\n                            @input=\"$root.getSearchHints()\"\n                            :placeholder=\"$root.getLz('term.search') + '...'\"\n                            v-model=\"$root.search.term\"\n                            ref=\"searchInput\"\n                            class=\"search-input\"\n                    />\n\n                    <div\n                            class=\"search-hints-container\"\n                            v-if=\"$root.search.showHints && $root.search.hints.length != 0\"\n                    >\n                        <div class=\"search-hints\">\n                            <button\n                                    class=\"search-hint text-overflow-elipsis\"\n                                    v-for=\"(hint, index) in $root.search.hints.filter((a) => {return a.content == null})\" :class=\"{active: ($root.search.cursor == index)}\"\n                                    @click=\"$root.search.term = hint.searchTerm;$root.search.showHints = false;$root.searchQuery(hint.searchTerm);$root.search.cursor = -1\"\n                            >\n                                {{ hint.displayTerm }}\n                            </button>\n                            <template v-for=\"(item, position) in $root.search.hints.filter((a) => {return a.content != null})\">\n                                <mediaitem-smarthints :item=\"item.content\" :position=\"position\"> </mediaitem-smarthints>\n                            </template>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </template>\n        <div class=\"app-sidebar-content\" scrollaxis=\"y\">\n            <!-- AM Navigation -->\n            <div v-show=\"$root.getThemeDirective('windowLayout') != 'twopanel'\" class=\"sidebarCatalogSection\">\n                <div\n                        class=\"app-sidebar-header-text\"\n                        @click=\"$root.cfg.general.sidebarCollapsed.cider = !$root.cfg.general.sidebarCollapsed.cider\"\n                        :class=\"{collapsed: $root.cfg.general.sidebarCollapsed.cider}\"\n                >\n                    {{ $root.getLz(\"app.name\") }}\n                </div>\n                <template v-if=\"!$root.cfg.general.sidebarCollapsed.cider\">\n                    <sidebar-library-item\n                            :name=\"$root.getLz('home.title')\"\n                            svg-icon=\"./assets/feather/home.svg\"\n                            svg-icon-name=\"home\"\n                            page=\"home\"\n                    >\n                    </sidebar-library-item>\n                </template>\n\n                <div\n                        class=\"app-sidebar-header-text\"\n                        @click=\"$root.cfg.general.sidebarCollapsed.applemusic = !$root.cfg.general.sidebarCollapsed.applemusic\"\n                        :class=\"{collapsed: $root.cfg.general.sidebarCollapsed.applemusic}\"\n                >\n                    {{ $root.getLz(\"term.appleMusic\") }}\n                </div>\n                <template v-if=\"!$root.cfg.general.sidebarCollapsed.applemusic\">\n                    <sidebar-library-item\n                            :name=\"$root.getLz('term.listenNow')\"\n                            svg-icon=\"./assets/feather/play-circle.svg\"\n                            svg-icon-name=\"listenNow\"\n                            page=\"listen_now\"\n                    ></sidebar-library-item>\n                    <sidebar-library-item\n                            :name=\"$root.getLz('term.browse')\"\n                            svg-icon=\"./assets/feather/globe.svg\"\n                            svg-icon-name=\"browse\"\n                            page=\"browse\"\n                    >\n                    </sidebar-library-item>\n                    <sidebar-library-item\n                            :name=\"$root.getLz('term.radio')\"\n                            svg-icon=\"./assets/feather/radio.svg\"\n                            svg-icon-name=\"radio\"\n                            page=\"radio\"\n                    ></sidebar-library-item>\n                </template>\n            </div>\n\n            <div\n                    class=\"app-sidebar-header-text\"\n                    @click=\"$root.cfg.general.sidebarCollapsed.library = !$root.cfg.general.sidebarCollapsed.library\"\n                    :class=\"{collapsed: $root.cfg.general.sidebarCollapsed.library}\"\n            >\n                {{ $root.getLz(\"term.library\") }}\n            </div>\n            <template v-if=\"!$root.cfg.general.sidebarCollapsed.library\">\n                <sidebar-library-item\n                        :name=\"$root.getLz('term.recentlyAdded')\"\n                        svg-icon=\"./assets/feather/plus-circle.svg\"\n                        svg-icon-name=\"recentlyAdded\"\n                        v-if=\"$root.cfg.general.sidebarItems.recentlyAdded\"\n                        page=\"library-recentlyadded\"\n                ></sidebar-library-item>\n                <sidebar-library-item\n                        :name=\"$root.getLz('term.songs')\"\n                        svg-icon=\"./assets/feather/music.svg\"\n                        svg-icon-name=\"songs\"\n                        v-if=\"$root.cfg.general.sidebarItems.songs\"\n                        page=\"library-songs\"\n                ></sidebar-library-item>\n                <sidebar-library-item\n                        :name=\"$root.getLz('term.albums')\"\n                        svg-icon=\"./assets/feather/disc.svg\"\n                        svg-icon-name=\"albums\"\n                        v-if=\"$root.cfg.general.sidebarItems.albums\"\n                        page=\"library-albums\"\n                ></sidebar-library-item>\n                <sidebar-library-item\n                        :name=\"$root.getLz('term.artists')\"\n                        svg-icon=\"./assets/feather/user.svg\"\n                        svg-icon-name=\"artists\"\n                        v-if=\"$root.cfg.general.sidebarItems.artists\"\n                        page=\"library-artists\"\n                ></sidebar-library-item>\n                <sidebar-library-item\n                        :name=\"$root.getLz('term.videos')\"\n                        svg-icon=\"./assets/feather/video.svg\"\n                        svg-icon-name=\"videos\"\n                        v-if=\"$root.cfg.general.sidebarItems.videos\"\n                        page=\"library-videos\"\n                ></sidebar-library-item>\n                <sidebar-library-item\n                        :name=\"$root.getLz('term.podcasts')\"\n                        svg-icon=\"./assets/feather/mic.svg\"\n                        svg-icon-name=\"podcasts\"\n                        v-if=\"$root.cfg.general.sidebarItems.podcasts\"\n                        page=\"podcasts\"\n                >\n                </sidebar-library-item>\n            </template>\n            <!-- <template v-if=\"$root.cfg.libraryPrefs.localPaths.length != 0\">\n                <div class=\"app-sidebar-header-text\"\n                     @click=\"$root.cfg.general.sidebarCollapsed.localLibrary = !$root.cfg.general.sidebarCollapsed.localLibrary\"\n                     :class=\"{collapsed: $root.cfg.general.sidebarCollapsed.localLibrary}\">\n                    Local Library\n                </div>\n                <template v-if=\"!$root.cfg.general.sidebarCollapsed.localLibrary\">\n                    <sidebar-playlist :item=\"{attributes: { name:'Songs'} , id:'ciderlocal'}\"></sidebar-playlist>\n                </template>\n            </template> -->\n            <template v-if=\"$root.getPlaylistFolderChildren('p.applemusic').length != 0\">\n                <div\n                        class=\"app-sidebar-header-text\"\n                        @click=\"$root.cfg.general.sidebarCollapsed.amplaylists = !$root.cfg.general.sidebarCollapsed.amplaylists\"\n                        @contextmenu=\"$root.playlistHeaderContextMenu\"\n                        :class=\"{collapsed: $root.cfg.general.sidebarCollapsed.amplaylists}\"\n                >\n                    {{ $root.getLz(\"term.appleMusic\") }}\n                    {{ $root.getLz(\"term.playlists\") }}\n                </div>\n                <template v-if=\"!$root.cfg.general.sidebarCollapsed.amplaylists\">\n                    <sidebar-playlist\n                            v-for=\"item in $root.getPlaylistFolderChildren('p.applemusic')\"\n                            v-bind:key=\"item.id\"\n                            :item=\"item\"\n                    >\n                    </sidebar-playlist>\n                </template>\n            </template>\n            <div\n                    class=\"app-sidebar-header-text\"\n                    @click=\"$root.cfg.general.sidebarCollapsed.playlists = !$root.cfg.general.sidebarCollapsed.playlists\"\n                    @contextmenu=\"$root.playlistHeaderContextMenu\"\n                    :class=\"{collapsed: $root.cfg.general.sidebarCollapsed.playlists}\"\n            >\n                {{ $root.getLz(\"term.playlists\") }}\n            </div>\n            <template v-if=\"!$root.cfg.general.sidebarCollapsed.playlists\">\n                <button class=\"app-sidebar-item\" @click=\"$root.playlistHeaderContextMenu\">\n                    <svg-icon url=\"./assets/feather/plus.svg\"></svg-icon>\n                    <div class=\"sidebar-item-text\">\n                        {{ $root.getLz(\"action.createNew\") }}\n                    </div>\n                </button>\n                <sidebar-playlist\n                        v-for=\"item in $root.getPlaylistFolderChildren('p.playlistsroot')\"\n                        v-bind:key=\"item.id\"madeforyou\n                        :item=\"item\"\n                >\n                </sidebar-playlist>\n            </template>\n            <div v-if=\"$root.cfg.visual.artworkDisplayLayout == 'sidebar'\" @click.stop=\"switchArtworkDisplayLayout()\" class=\"artwork\" id=\"artworkLCD\" style=\"position:sticky;bottom:0px\">\n              <mediaitem-artwork :url=\"$root.currentArtUrl\"></mediaitem-artwork>\n            </div>\n        </div>\n        <div class=\"app-sidebar-footer display--small app-sidebar-footer--controls\">\n            <div class=\"app-playback-controls\" @contextmenu=\"$root.nowPlayingContextMenu\">\n                <div class=\"control-buttons\">\n                    <div class=\"app-chrome-item\">\n                        <button\n                                class=\"playback-button--small shuffle\"\n                                v-if=\"$root.mk.shuffleMode == 0\"\n                                @click=\"$root.mk.shuffleMode = 1\"\n                                :title=\"$root.getLz('term.enableShuffle')\"\n                                :class=\"$root.isDisabled() && 'disabled'\"\n                                v-b-tooltip.hover.righttop\n                        ></button>\n                        <button\n                                class=\"playback-button--small shuffle active\"\n                                v-else\n                                @click=\"$root.mk.shuffleMode = 0\"\n                                :title=\"$root.getLz('term.disableShuffle')\"\n                                :class=\"$root.isDisabled() && 'disabled'\"\n                                v-b-tooltip.hover.righttop\n                        ></button>\n                    </div>\n                    <div class=\"app-chrome-item\">\n                        <button\n                                class=\"playback-button previous\"\n                                @click=\"$root.prevButton()\"\n                                :class=\"$root.isPrevDisabled() && 'disabled'\"\n                                :title=\"$root.getLz('term.previous')\"\n                                v-b-tooltip.hover\n                        ></button>\n                    </div>\n                    <div class=\"app-chrome-item\">\n                        <button class=\"playback-button stop\" @click=\"$root.mk.stop()\"\n                                v-if=\"$root.mk.isPlaying && $root.mk.nowPlayingItem.attributes.playParams.kind == 'radioStation'\"\n                                :title=\"$root.getLz('term.stop')\" v-b-tooltip.hover></button>\n                        <button class=\"playback-button pause\" @click=\"$root.mk.pause()\"\n                                v-else-if=\"$root.mk.isPlaying\"\n                                :title=\"$root.getLz('term.pause')\" v-b-tooltip.hover></button>\n                        <button class=\"playback-button play\" @click=\"$root.mk.play()\" v-else\n                                :title=\"$root.getLz('term.play')\"\n                                v-b-tooltip.hover></button>\n                    </div>\n                    <div class=\"app-chrome-item\">\n                        <button\n                                class=\"playback-button next\"\n                                @click=\"$root.skipToNextItem()\"\n                                :title=\"$root.getLz('term.next')\"\n                                :class=\"$root.isNextDisabled() && 'disabled'\"\n                                v-b-tooltip.hover\n                        ></button>\n                    </div>\n                    <div class=\"app-chrome-item\">\n                        <button\n                                class=\"playback-button--small repeat\"\n                                v-if=\"$root.mk.repeatMode == 0\"\n                                @click=\"$root.mk.repeatMode = 1\"\n                                :class=\"$root.isDisabled() && 'disabled'\"\n                                :title=\"$root.getLz('term.enableRepeatOne')\"\n                                v-b-tooltip.hover\n                        ></button>\n                        <button\n                                class=\"playback-button--small repeat repeatOne\"\n                                @click=\"$root.mk.repeatMode = 2\"\n                                v-else-if=\"$root.mk.repeatMode == 1\"\n                                :title=\"$root.getLz('term.disableRepeatOne')\"\n                                :class=\"$root.isDisabled() && 'disabled'\"\n                                v-b-tooltip.hover\n                        ></button>\n                        <button\n                                class=\"playback-button--small repeat active\"\n                                @click=\"$root.mk.repeatMode = 0\"\n                                v-else-if=\"$root.mk.repeatMode == 2\"\n                                :title=\"$root.getLz('term.disableRepeat')\"\n                                :class=\"$root.isDisabled() && 'disabled'\"\n                                v-b-tooltip.hover\n                        ></button>\n                    </div>\n                </div>\n                <div class=\"app-chrome-item volume\">\n                    <div class=\"input-container\">\n                        <button\n                                class=\"volume-button--small volume\"\n                                @click=\"$root.muteButtonPressed()\"\n                                :class=\"{'active': $root.cfg.audio.volume == 0}\"\n                                :title=\"$root.cfg.audio.muted ? $root.getLz('term.unmute') : $root.getLz('term.mute')\"\n                                v-b-tooltip.hover\n                        ></button>\n                        <input\n                                type=\"range\"\n                                class=\"\"\n                                @wheel=\"$root.volumeWheel\"\n                                :step=\"$root.cfg.audio.volumeStep\"\n                                min=\"0\"\n                                :max=\"$root.cfg.audio.maxVolume\"\n                                v-model=\"$root.mk.volume\"\n                                v-if=\"typeof $root.mk.volume != 'undefined'\"\n                                @change=\"$root.checkMuteChange()\"\n                                v-b-tooltip.hover\n                                :title=\"$root.formatVolumeTooltip()\"\n                        />\n                    </div>\n                </div>\n            </div>\n        </div>\n        <div class=\"app-sidebar-notification backgroundNotification\" v-if=\"$root.library.backgroundNotification.show\" >\n            <div class=\"message\">\n                {{ $root.library.backgroundNotification.message }} ({{$root.library.backgroundNotification.progress }} / {{ $root.library.backgroundNotification.total }})\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component(\"cider-app-sidebar\", {\n    template: \"#cider-app-sidebar\",\n    methods: {\n      switchArtworkDisplayLayout: function() {\n      switch (app.cfg.visual.artworkDisplayLayout) {\n        case \"default\":\n        app.cfg.visual.artworkDisplayLayout = \"sidebar\";\n          break;\n        case \"sidebar\":\n        app.cfg.visual.artworkDisplayLayout = \"default\";\n          break;\n        default:\n        app.cfg.visual.artworkDisplayLayout = \"default\";\n          break;\n      }\n    },\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/components/smarthints.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-smarthints\">\n<div class=\"cd-queue-item\"  @click=\"$root.search.showHints = false;$root.routeView(item);$root.search.cursor = -1;$root.search.term == ''\" @contextmenu=\"$root.hintscontext = true;getContextMenu()\"\n    :class=\"{'hintactive': ($root.search.cursor == position + $root.search.hints.filter((a) => {return a.content == null}).length)}\">\n    <div class=\"row\"  @contextmenu=\"$root.hintscontext = true;getContextMenu()\">\n        <div class=\"col-auto cider-flex-center\" @contextmenu=\"$root.hintscontext = true;getContextMenu()\">\n            <div class=\"artwork\"  :class=\"{'circle': item.type == 'artists'}\">\n                <mediaitem-artwork\n                :url=\"item.attributes.artwork ? item.attributes.artwork.url : ''\"\n                :size=\"32\"\n                :style=\"{'position': 'relative', 'z-index': '-1'}\"\n                ></mediaitem-artwork>\n                <button class=\"circular-play-button\" @click.stop=\"playTrack(item)\">\n                  <div class=\"_svg-icon\" style=\"--icon:url(\\.\\/assets\\/play\\.svg); width: 15px;\">\n                  </div>\n                </button>\n            </div>\n        </div>\n        <div class=\"col queue-info\" @contextmenu=\"$root.hintscontext = true;getContextMenu()\">\n            <div class=\"queue-title text-overflow-elipsis\">{{ item.attributes.name }}\n            </div>\n            <div class=\"queue-subtitle text-overflow-elipsis\">{{\n                item.attributes.artistName }}\n            </div>\n        </div>\n        <div class=\"queue-explicit-icon cider-flex-center\"\n             v-if=\"item.attributes.contentRating == 'explicit'\">\n            <div class=\"explicit-icon\"></div>\n        </div>\n        <!-- <div class=\"col queue-duration-info\">\n            <div class=\"queue-duration cider-flex-center\">\n                {{convertTimeToString(item.content.attributes.durationInMillis)}}\n            </div>\n        </div> -->\n    </div>\n</div>\n</script>\n<script>\n    Vue.component('mediaitem-smarthints', {\n      template: '#mediaitem-smarthints',\n      props: {\n        item: {\n          type: Object,\n          required: true\n        },\n        position: {\n          type: Number,\n          required: true\n        }\n      },\n      data: function () {\n        return {\n          app: this.$root,\n          guid: this.uuidv4(),\n        }\n      },\n      async mounted() {\n      },\n      methods: {\n        async isInLibrary() {\n              if (this.item.type && !this.item.type.includes(\"library\")) {\n                let params = {\n                  relate: \"library\",\n                  \"fields\": \"inLibrary\",\n                  \"extend\": this.revisedRandId()\n                }\n                let kind = this.item.type ?? this.item.attributes.playParams.kind\n                let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n                if (truekind === \"musicVideos\") {\n                  truekind = \"music-videos\"\n                }\n                let res = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/?ids[${truekind}]=${this.item.attributes.playParams.id ?? this.item.id}`, params);\n                res = res.data.data[0]\n                this.addedToLibrary = (res && res.attributes && res.attributes.inLibrary) ? res.attributes.inLibrary : false\n              } else {\n                this.addedToLibrary = true\n              }\n        },\n        revisedRandId() {\n            return Math.random().toString(36).replace(/[^a-z]+/g, '').slice(2, 10);\n        },\n        uuidv4() {\n            return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n              (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n            );\n        },\n        getContextMenu(event) {\n          if (event){\n            if (this.item.type === \"artists\") {\n            return this.artistMenu(event)\n          } else {\n            return this.contextMenu(event)\n          }\n          } else {\n          document.addEventListener('mouseover', event => {\n            if (this.item.type === \"artists\") {\n            return this.artistMenu(event)\n          } else {\n            return this.contextMenu(event)\n          }\n        },{once: true})}\n\n        },\n        async contextMenu(event) {\n          let self = this\n          let useMenu = \"normal\"\n          if (app.selectedMediaItems.length <= 1) {\n            app.selectedMediaItems = []\n            app.select_selectMediaItem(this.item.attributes.playParams.id ?? this.item.id, this.item.attributes.playParams.kind ?? this.item.type, this.index, this.guid, this.item.attributes.playParams.isLibrary ?? false)\n          } else {\n            useMenu = \"multiple\"\n          }\n          let menus = {\n            multiple: {\n              items: [\n                {\n                  name: app.getLz('action.playTracksNext').replace(\"${app.selectedMediaItems.length}\", app.selectedMediaItems.length),\n                  \"icon\": \"./assets/arrow-bend-up.svg\",\n                  action: () => {\n                    let itemsToPlay = {}\n                    app.selectedMediaItems.forEach(item => {\n                      if (!itemsToPlay[item.kind]) {\n                        itemsToPlay[item.kind] = []\n                      }\n                      itemsToPlay[item.kind].push(item.id)\n                    })\n                    // loop through itemsToPlay\n                    for (let kind in itemsToPlay) {\n                      let ids = itemsToPlay[kind]\n                      if (ids.length > 0) {\n                        app.mk.playNext({ [kind + \"s\"]: itemsToPlay[kind] })\n                      }\n                    }\n                    console.log(itemsToPlay)\n                    app.selectedMediaItems = []\n                  }\n                },\n                {\n                  name: app.getLz('action.playTracksLater').replace(\"${app.selectedMediaItems.length}\", app.selectedMediaItems.length),\n                  \"icon\": \"./assets/arrow-bend-down.svg\",\n                  action: () => {\n                    let itemsToPlay = {}\n                    app.selectedMediaItems.forEach(item => {\n                      if (!itemsToPlay[item.kind]) {\n                        itemsToPlay[item.kind] = []\n                      }\n                      itemsToPlay[item.kind].push(item.id)\n                    })\n                    // loop through itemsToPlay\n                    for (let kind in itemsToPlay) {\n                      let ids = itemsToPlay[kind]\n                      if (ids.length > 0) {\n                        app.mk.playLater({ [kind + \"s\"]: itemsToPlay[kind] })\n                      }\n                    }\n                    app.selectedMediaItems = []\n                  }\n                },\n              ]\n            },\n            normal: {\n              headerItems: [\n                {\n                  \"icon\": \"./assets/feather/heart.svg\",\n                  \"id\": \"love\",\n                  \"name\": app.getLz('action.love'),\n                  \"hidden\": false,\n                  \"disabled\": true,\n                  \"action\": function () {\n                    app.love(self.item)\n                  }\n                },\n                {\n                  \"icon\": \"./assets/feather/heart.svg\",\n                  \"id\": \"unlove\",\n                  \"active\": true,\n                  \"name\": app.getLz('action.unlove'),\n                  \"hidden\": true,\n                  \"action\": function () {\n                    app.unlove(self.item)\n                  }\n                },\n                {\n                  \"icon\": \"./assets/feather/thumbs-down.svg\",\n                  \"id\": \"dislike\",\n                  \"name\": app.getLz('action.dislike'),\n                  \"hidden\": false,\n                  \"disabled\": true,\n                  \"action\": function () {\n                    app.dislike(self.item)\n                  }\n                },\n                {\n                  \"icon\": \"./assets/feather/thumbs-down.svg\",\n                  \"id\": \"undo_dislike\",\n                  \"name\": app.getLz('action.undoDislike'),\n                  \"active\": true,\n                  \"hidden\": true,\n                  \"action\": function () {\n                    app.unlove(self.item)\n                  }\n                },\n              ],\n              items: [\n                {\n                  \"icon\": \"./assets/feather/list.svg\",\n                  \"id\": \"addToPlaylist\",\n                  \"name\": app.getLz('action.addToPlaylist'),\n                  \"action\": function () {\n                    app.promptAddToPlaylist()\n                  }\n                },\n                {\n                  \"id\": \"addToLibrary\",\n                  \"icon\": \"./assets/feather/plus.svg\",\n                  \"name\": app.getLz('action.addToLibrary'),\n                  \"hidden\": false,\n                  \"disabled\": true,\n                  \"action\": function () {\n                    let item_id = self.item.attributes.playParams.id ?? self.item.id;\n                    let data_type = self.item.attributes.playParams.kind ?? self.item.type;\n                    app.addToLibrary(item_id);\n                    self.addedToLibrary = true;\n                  }\n                },\n                {\n                  \"id\": \"removeFromLibrary\",\n                  \"icon\": \"./assets/feather/x-circle.svg\",\n                  \"name\": app.getLz('action.removeFromLibrary'),\n                  \"hidden\": true,\n                  \"action\": async function () {\n                    console.log(\"remove\");\n                    let item_id = self.item.attributes.playParams.id ?? self.item.id;\n                    let data_type = self.item.attributes.playParams.kind ?? self.item.type;\n                    await self.removeFromLibrary(item_id);\n                    self.addedToLibrary = false\n                  }\n                },\n                {\n                  \"name\": app.getLz('action.playNext'),\n                  \"icon\": \"./assets/arrow-bend-up.svg\",\n                  \"action\": function () {\n                    app.mk.playNext({ [self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id })\n                    app.mk.queue._reindex()\n                    app.selectedMediaItems = []\n                  }\n                },\n                {\n                  \"name\": app.getLz('action.playLater'),\n                  \"icon\": \"./assets/arrow-bend-down.svg\",\n                  \"action\": function () {\n                    app.mk.playLater({ [self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id })\n                    app.mk.queue._reindex()\n                    app.selectedMediaItems = []\n                  }\n                },\n                {\n                  \"icon\": \"./assets/feather/share.svg\",\n                  \"name\": app.getLz('action.share'),\n                  \"action\": function () {\n                    if (!self.item.attributes.url && self.item.relationships) {\n                      if (self.item.relationships.catalog) {\n                        app.mkapi(self.item.attributes.playParams.kind, false, self.item.relationships.catalog.data[0].id).then(u => {\n                          self.app.copyToClipboard((u.data.data.length && u.data.data.length > 0) ? u.data.data[0].attributes.url : u.data.data.attributes.url)\n                        })\n                      }\n                    } else {\n                      self.app.copyToClipboard(self.item.attributes.url)\n                    }\n                  }\n                },\n                {\n                  \"icon\": \"./assets/feather/share.svg\",\n                  \"name\": `${app.getLz('action.share')} (song.link)`,\n                  \"action\": function () {\n                    if (!self.item.attributes.url && self.item.relationships) {\n                      if (self.item.relationships.catalog) {\n                        app.mkapi(self.item.attributes.playParams.kind, false, self.item.relationships.catalog.data[0].id).then(u => {\n                          self.app.songLinkShare((u.data.data.length && u.data.data.length > 0) ? u.data.data[0].attributes.url : u.data.data.attributes.url)\n                        })\n                      }\n                    } else {\n                      self.app.songLinkShare(self.item.attributes.url)\n                    }\n                  }\n                }\n              ]\n            }\n          }\n          if ((self.item.attributes.playParams.kind ?? self.item.type).includes(\"playlist\")) {\n            // remove the add to playlist option by id \"addToPlaylist\" using the .filter() method\n            menus.normal.items = menus.normal.items.filter(function (item) {\n              return item.id != \"addToPlaylist\"\n            })\n          }\n          app.showMenuPanel(menus[useMenu], event)\n          try {\n            await this.isInLibrary().then((_) => {\n              if (self.addedToLibrary) {\n                menus.normal.items.find(x => x.id == 'addToLibrary').hidden = true\n                menus.normal.items.find(x => x.id == 'removeFromLibrary').hidden = false\n              } else {\n                menus.normal.items.find(x => x.id == 'addToLibrary').disabled = false\n              }\n            })\n\n          } catch (e) {\n            console.log(e)\n          }\n          try {\n            let rating = await app.getRating(self.item)\n            if (rating == 0) {\n              menus.normal.headerItems.find(x => x.id == 'love').disabled = false\n              menus.normal.headerItems.find(x => x.id == 'dislike').disabled = false\n            } else if (rating == 1) {\n              menus.normal.headerItems.find(x => x.id == 'unlove').hidden = false\n              menus.normal.headerItems.find(x => x.id == 'love').hidden = true\n            } else if (rating == -1) {\n              menus.normal.headerItems.find(x => x.id == 'undo_dislike').hidden = false\n              menus.normal.headerItems.find(x => x.id == 'dislike').hidden = true\n            }\n          } catch (err) {\n\n          }\n\n          if (this.contextExt) {\n            if (this.contextExt.normal) {\n              menus.normal.items = menus.normal.items.concat(this.contextExt.normal)\n            }\n            if (this.contextExt.multiple) {\n              menus.multiple.items = menus.multiple.items.concat(this.contextExt.multiple)\n            }\n          }\n        },\n        async artistMenu(event) {\n          let self = this\n          let followAction = \"follow\"\n          let followActions = {\n            follow: {\n              icon: \"./assets/star.svg\",\n              name: app.getLz('action.favorite'),\n              action: () => {\n                self.$root.setArtistFavorite(this.item.id, true)\n              }\n            },\n            unfollow: {\n              icon: \"./assets/star.svg\",\n              name: app.getLz('action.removeFavorite'),\n              action: () => {\n                self.$root.setArtistFavorite(this.item.id, false)\n              }\n            }\n          }\n          if (self.app.cfg.home.followedArtists.includes(this.item.id)) {\n            followAction = \"unfollow\"\n          }\n          app.showMenuPanel({\n            items: [\n              {\n                icon: \"./assets/feather/play.svg\",\n                name: app.getLz('action.startRadio'),\n                action: () => {\n                  app.mk.setStationQueue({ artist: 'a-'+this.item.id }).then(() => {\n                    app.mk.play()\n                  })\n                }\n              },\n              followActions[followAction],\n              {\n                icon: \"./assets/feather/share.svg\",\n                name: app.getLz('term.share'),\n                action: () => {\n                  self.app.copyToClipboard(this.item.attributes.url)\n                }\n              },\n              {\n                icon: \"./assets/feather/external-link.svg\",\n                name: app.getLz('action.openArtworkInBrowser'),\n                action: () => {\n                  window.open(app.getMediaItemArtwork(this.getArtworkUrl(), 1024, 1024))\n                }\n              },\n\n            ]\n          }, event)\n        },\n        getArtworkUrl(size = -1, includeUrl = false) {\n            let artwork = this.item.attributes.artwork ? this.item.attributes.artwork.url : ''\n            if (size != -1) {\n              artwork = artwork.replace('{w}', size).replace('{h}', size).replace('{f}', \"webp\").replace('{c}', ((size === 900) ? \"sr\" : \"cc\"))\n            }\n            switch (this.kind) {\n              case \"385\":\n                artwork = this.item.attributes?.editorialArtwork?.subscriptionHero?.url\n                break;\n            }\n            if (!includeUrl) {\n              return artwork\n            } else {\n              return `url(\"${artwork}\")`\n        }\n      },\n      playTrack(item) {\n        let parent = this.parent\n        let childIndex = this.index\n        let kind = (item.attributes.playParams ? (item.attributes.playParams?.kind ?? (item.type ?? '')) : (item.type ?? ''));\n        let id = (item.attributes.playParams ? (item.attributes.playParams?.id ?? (item.id ?? '')) : (item.id ?? ''));\n        ;\n        let isLibrary = item.attributes.playParams ? (item.attributes.playParams?.isLibrary ?? false) : false;\n        let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        console.log(item, parent, childIndex, kind, id, isLibrary, kind == \"playlists\", id.startsWith(\"p.\") || id.startsWith(\"pl.u\"))\n        app.mk.stop().then(() => {\n          if (parent != null && childIndex != null) {\n            app.queueParentandplayChild(parent, childIndex, item);\n          } else if (kind.includes(\"playlist\") && (id.startsWith(\"p.\") || id.startsWith(\"pl.\"))) {\n            function shuffleArray(array) {\n              for (var i = array.length - 1; i > 0; i--) {\n                var j = Math.floor(Math.random() * (i + 1));\n                var temp = array[i];\n                array[i] = array[j];\n                array[j] = temp;\n              }\n            }\n\n            app.mk.setQueue({\n              [truekind]: [item.attributes.playParams?.id ?? item.id],\n              parameters: { l: this.app.mklang }\n            }).then(function() {\n              app.mk.play().then(function() {\n                var playlistId = id\n\n                function getPlaylist(id, isLibrary) {\n                  if (isLibrary) {\n                    return this.app.mk.api.v3.music(`/v1/me/library/playlists/${id}`)\n                  } else {\n                    return this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/playlists/${id}`)\n                  }\n                }\n\n                try {\n                  getPlaylist(id, isLibrary).then(res => {\n                    //let query = res.relationships.tracks.data.map(item => new MusicKit.MediaItem(item));\n                    //if (app.mk.shuffleMode == 1){shuffleArray(query); }\n                    // console.log(query)\n                    // app.mk.queue.append(query)\n                    if (!res.data.relationships.tracks.next) {\n                      return\n                    } else {\n                      getPlaylistTracks(res.data.relationships.tracks.next)\n                    }\n\n                    function getPlaylistTracks(next) {\n                      app.apiCall(app.musicBaseUrl + next, res => {\n                        // if (res.id != playlistId || next.includes(playlistId)) {\n                        //     return\n                        // }\n                        console.log('nextres', res)\n                        let query = res.data.map(item => new MusicKit.MediaItem(item))\n                        if (app.mk.shuffleMode == 1) {\n                          shuffleArray(query);\n                          console.log('shf')\n                        }\n                        app.mk.queue.append(query)\n\n                        if (res.next) {\n                          getPlaylistTracks(res.next)\n                        }\n                      })\n                    }\n                  })\n                } catch (e) {\n                }\n\n\n              })\n            })\n\n\n          } else {\n            app.playMediaItemById(item.attributes.playParams?.id ?? item.id, item.attributes.playParams?.kind ?? item.type, item.attributes.playParams?.isLibrary ?? false, item.attributes.url)\n          }\n        })\n        },\n      },\n      beforeDestroy: function () {\n        // this.item = null;\n        // this.kind = null;\n        // this.size = null;\n      }\n    });\n</script>\n"
  },
  {
    "path": "src/renderer/views/main.ejs",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <link rel=\"preconnect\" href=\"https://amp-api.music.apple.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://api.music.apple.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://is1-ssl.mzstatic.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://is2-ssl.mzstatic.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://is3-ssl.mzstatic.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://is4-ssl.mzstatic.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://is5-ssl.mzstatic.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://play.itunes.apple.com/\" crossorigin />\n    <link rel=\"preconnect\" href=\"https://aod-ssl.itunes.apple.com/\" crossorigin />\n    <meta charset=\"UTF-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover\">\n    <title>Cider</title>\n    <link rel=\"<%- (env.dev ? \" stylesheet\" : \"stylesheet/less\") %>\" type=\"text/css\" href=\"style.<%- (env.dev ? \"css\"\n            : \"less\") %>\" />\n    <!--    <link rel=\"stylesheet/less\" type=\"text/css\" id=\"userTheme\" href=\"themes/default.less\"/>-->\n    <script src=\"./lib/less.js\"></script>\n    <script src=\"<%- (env.dev ? \" ./lib/vue.js\" : \"./lib/vue.dev.js\"); %>\"></script>\n    <script src=\"./lib/smoothscroll.js\"></script>\n    <link rel=\"manifest\" href=\"./manifest.json?v=2\">\n    <script src=\"https://js-cdn.music.apple.com/hls.js/2.141.0/hls.js/hls.js\"></script>\n    <script src=\"hlscider.js\"></script>\n    <script src=\"./lib/jquery-3.2.1.slim.min.js\"></script>\n    <script src=\"./lib/popper.min.js\"></script>\n    <script src=\"./lib/bootstrap.min.js\"></script>\n    <script src=\"./lib/bootbox.min.js\"></script>\n    <script src=\"./lib/notyf.min.js\"></script>\n    <script src=\"./lib/marked.js\"></script>\n    <script src=\"./lib/velocity.min.js\"></script>\n    <script src=\"./lib/fast-plural-rules.js\"></script>\n    <script src=\"./lib/resonance-audio.min.js\"></script>\n    <script src=\"./lib/stackblur.min.js\"></script>\n\n    <style>\n      #LOADER {\n        position: fixed;\n        top: 0;\n        left: 0;\n        width: 100%;\n        height: 100%;\n        background-color: #1E1E1E;\n        z-index: 99999;\n        display: flex;\n        justify-content: center;\n        align-items: center;\n      }\n\n      #LOADER > svg {\n        width: 128px;\n      }\n\n      @media (prefers-color-scheme: light) {\n        #LOADER {\n          background-color: #eee;\n        }\n      }\n    </style>\n</head>\n\n<body class=\"notransparency\" oncontextmenu=\"return false;\" loading=\"1\" os-release=\"<%= parseInt(env.osRelease) ;%>\"\n      platform=\"<%= env.platform ;%>\">\n<script src=\"./lib/vue-horizontal.js\"></script>\n<script src=\"./lib/bootstrap-vue.min.js\"></script>\n<script src=\"./lib/vuex.min.js\"></script>\n<script src=\"./lib/sortable.min.js\"></script>\n<script src=\"./lib/vue-observe-visibility.min.js\"></script>\n<script src=\"./lib/vuedraggable.umd.min.js\"></script>\n<script>\n  window.quasarConfig = {\n    brand: {\n      primary: '#fc3c44'\n    },\n    config: {\n      dark: true\n    },\n    loadingBar: { skipHijack: true }\n  }\n</script>\n<!-- <script src=\"./lib/quasar/quasar.umd.min.js\"></script> -->\n<script type=\"module\" src=\"./main/app.js\"></script>\n\n<div id=\"LOADER\">\n    <%- include(\"../assets/cider-round.svg\") %>\n</div>\n<div id=\"app\" :class=\"getAppClasses()\" v-if=\"appVisible\" :window-state=\"chrome.windowState\" :style=\"getAppStyle()\"\n     :library-visible=\"(chrome.sidebarCollapsed ? 0 : 1)\" :window-style=\"cfg.visual.directives.windowLayout\">\n    <transition name=\"fsModeSwitch\">\n        <div id=\"app-main\" v-show=\"appMode == 'player'\">\n            <%- include('app/chrome-top'); %>\n            <%- include('app/app-navigation'); %>\n            <%- include('app/chrome-bottom'); %>\n        </div>\n    </transition>\n    <transition name=\"fsModeSwitch\">\n        <div class=\"fullscreen-view-container\" v-if=\"appMode == 'fullscreen'\">\n            <fullscreen-view ref=\"fsView\" :image=\"currentArtUrlRaw\" :time=\"mk.currentPlaybackTime - lyricOffset\" :lyrics=\"lyrics\"\n                             :richlyrics=\"richlyrics\"></fullscreen-view>\n        </div>\n    </transition>\n    <transition name=\"fsModeSwitch\">\n        <div class=\"fullscreen-view-container\" v-if=\"appMode == 'mini'\">\n            <mini-view :image=\"currentArtUrlRaw\" :time=\"mk.currentPlaybackTime - lyricOffset\" :lyrics=\"lyrics\"\n                       :richlyrics=\"richlyrics\">\n            </mini-view>\n        </div>\n    </transition>\n    <transition name=\"fsModeSwitch\">\n        <div class=\"fullscreen-view-container oobe\" v-if=\"appMode == 'oobe'\">\n            <cider-oobe></cider-oobe>\n        </div>\n    </transition>\n    <%- include('app/panels'); %>\n    <div class=\"cursor\" v-if=\"chrome.showCursor\"></div>\n</div>\n\n<% for(var i = 0; i < Object.keys(env.components).length ; i++) { %>\n    <%- include(env.components[i]); %>\n<% } %>\n\n<script async\n        src=\"<%- (env.useV3 ? \"https://js-cdn.music.apple.com/musickit/v3/amp/musickit.js\" : \"https://js-cdn.music.apple.com/musickit/v2/amp/musickit.js\"); %>\"\n        data-web-components>\n</script>\n<script src=\"index.js?v=1\"></script>\n\n<script type=\"text/x-template\" id=\"am-musiccovershelf\">\n    <h1>{{ component.attributes.title.stringForDisplay }}</h1>\n</script>\n\n</body>\n\n</html>\n"
  },
  {
    "path": "src/renderer/views/pages/about.ejs",
    "content": "<script type=\"text/x-template\" id=\"about-page\">\n    <div class=\"content-inner about-page\">\n        <div class=\"row\">\n            <div class=\"col\">\n                <img src=\"assets/banner.png\" alt=\"Cider Logo\" style=\"display:block;margin:0 auto;width: 500px;\">\n                <p style=\"text-align: center\" id=\"version\">{{ $root.getLz(\"term.version\") }} {{ $root.version }}</p>\n                <p style=\"text-align: center\"> {{$root.getLz('about.thanks')}} </p>\n\n                <p style=\"text-align: center\">\"{{$root.getLz('term.appleMusic')}}\" - {{$root.getLz('term.copyright')}} ©\n                    2022 <a href=\"https://www.apple.com/\" class=\"dt-footer__link\"\n                            target=\"_blank\"\n                            rel=\"noopener\" data-dt-link-to-exclude=\"\">{{$root.getLz('term.appleInc')}}</a>\n                    {{$root.getLz('term.rightsReserved')}}</p>\n                <hr>\n                <h3>{{$root.getLz('term.sponsor')}}</h3>\n                <button onclick=\"window.open('https://github.com/sponsors/ciderapp')\"\n                        class=\"md-btn sponsorBtn githubBtn\"><img src=\"./assets/github.svg\" />GitHub Sponsors\n                </button>\n                <button onclick=\"window.open('https://ko-fi.com/cryptofyre')\" class=\"md-btn sponsorBtn kofiBtn\"><img\n                            src=\"./assets/ko_fi.svg\" />Ko-fi\n                </button>\n                <button onclick=\"window.open('https://opencollective.com/ciderapp')\"\n                        class=\"md-btn sponsorBtn opencollectiveBtn\"><img src=\"./assets/open_collective.svg\" />Open\n                    Collective\n                </button>\n                <h3>{{$root.getLz('term.socials')}}</h3>\n                <button onclick=\"window.open('https://github.com/ciderapp/Cider')\" class=\"md-btn sponsorBtn githubBtn\">\n                    <img src=\"./assets/github.svg\" />{{$root.getLz('term.github')}}\n                </button>\n                <button onclick=\"window.open('https://discord.gg/applemusic')\" class=\"md-btn sponsorBtn discordBtn\"><img\n                            style=\"height: 26px;\" src=\"./assets/discord.svg\" />{{$root.getLz('term.discord')}}\n                </button>\n                <button onclick=\"window.open('https://twitter.com/UseCider')\" class=\"md-btn sponsorBtn twitterBtn\"><img\n                            src=\"./assets/twitter.svg\" />Twitter\n                </button>\n                <button onclick=\"window.open('https://jq.qq.com/?_wv=1027&k=2VP4cdyo')\" class=\"md-btn sponsorBtn qqBtn\"><img\n                            src=\"./assets/qq.svg\" />QQ\n                </button>\n\n            </div>\n            <div class=\"col\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3>{{$root.getLz('term.ciderTeam')}}</h3>\n                        <div class=\"md-btn teamBtn\" v-for=\"member in team\" @click=\"window.open(member.link)\">\n                            <img :src=\"member.avatar\" />\n                            <div class=\"row\" style=\"width:100%;\">\n                                <div class=\"col\" style=\"text-align: left;\">\n                                    {{ member.name }}\n                                </div>\n                                <div class=\"col\" style=\"text-align: right\">\n                                    <button @click.stop=\"window.open(member.twitter)\" class=\"social-btn\"\n                                            v-if=\"member.twitter\">\n                                        <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\"\n                                             viewBox=\"0 0 24 24\" fill=\"white\" style=\"\">\n                                            <path d=\"M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z\"></path>\n                                        </svg>\n                                    </button>\n                                </div>\n                                <div class=\"col-auto\">\n                                    <b>{{ member.role }}</b>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3></h3>\n                    <h3>{{$root.getLz('term.contributors')}}</h3>\n                    <img class=\"md-contributors\"\n                         style=\"cursor:pointer;width:100%;\"\n                         onclick=\"window.open('https://github.com/ciderapp/Cider/graphs/contributors')\"\n                         src=\"https://contrib.rocks/image?repo=ciderapp/Cider&columns=25\" />\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('about-page', {\n    template: '#about-page',\n    data: function() {\n      return {\n        window: window,\n        version: app.version,\n        team: [\n          {\n            name: 'cryptofyre',\n            link: 'https://github.com/cryptofyre',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/33162551?v=4',\n            twitter: 'https://twitter.com/cryptofyre'\n          },\n          {\n            name: 'Core',\n            link: 'https://github.com/coredev-uk',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/64542347?v=4',\n            twitter: 'https://twitter.com/core_hdd'\n          },\n          {\n            name: 'Quacksire',\n            link: 'https://github.com/quacksire',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/19170969?v=4',\n            twitter: 'https://twitter.com/duckdoquack'\n          },\n          {\n            name: 'booploops',\n            link: 'https://github.com/booploops',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/49113086?v=4',\n            twitter: 'https://twitter.com/boopl00ps'\n          },\n          {\n            name: 'vapormusic',\n            link: 'https://github.com/vapormusic',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/27716185?v=4'\n          },\n          {\n            name: 'Maikiwi',\n            link: 'https://github.com/maikirakiwi',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/74925636?v=4',\n            twitter: 'https://twitter.com/notmaikiwi'\n          },\n          {\n            name: 'yazninja',\n            link: 'https://github.com/yazninja',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/71800112?v=4',\n            twitter: 'https://twitter.com/YazNinjaa'\n          },\n          {\n            name: 'GamingLiamStudios',\n            link: 'https://github.com/GamingLiamStudios',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/58615717?v=4',\n            twitter: 'https://twitter.com/GLStudios_'\n          },\n          {\n            name: 'Amaru',\n            link: 'https://github.com/Amaru8',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/52407090?v=4'\n          },\n          {\n            name: 'lockieluke',\n            link: 'https://github.com/lockieluke',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/25424409?v=4',\n            twitter: 'https://twitter.com/lockie_luke'\n          },\n          {\n            name: 'Swiftzerr',\n            link: 'https://github.com/Swiftzerr',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/67812203?v=4'\n          },\n          {\n            name: 'Ishmeet',\n            link: 'https://github.com/StupeFied',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/89881655?v=4'\n          },\n          {\n            name: 'Monochromish',\n            link: 'https://github.com/Monochromish',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/79590499?v=4'\n          },\n          {\n            name: 'd3rpp',\n            link: 'https://github.com/d3rpp',\n            role: app.getLz('term.developer'),\n            avatar: 'https://avatars.githubusercontent.com/u/45675641?v=4'\n          },\n          {\n            name: 'Void',\n            link: 'https://twitter.com/MoonyVoid',\n            role: app.getLz('term.socialTeam'),\n            avatar: 'https://pbs.twimg.com/profile_images/1226463559472816129/8LScNYED_400x400.jpg'\n          },\n          {\n            name: 'NoseySG',\n            link: 'https://twitter.com/noah_grose',\n            role: app.getLz('term.socialTeam'),\n            avatar: 'https://pbs.twimg.com/profile_images/1496944907260420099/D5gl6H4J_400x400.jpg'\n          }\n        ]\n      }\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/apple-account-settings.ejs",
    "content": "<script type=\"text/x-template\" id=\"apple-account-settings\">\n    <div style=\"display:flex;width:100%;height:100%;padding-top: var(--navigationBarHeight);position:absolute;top:0;left:0;\">\n        <webview id=\"foo\"\n                 src=\"https://beta.music.apple.com/includes/commerce/account/settings?product=music&isFullscreen=false&isModal=false&expectsModalLayout=false&isFullScreen=true\"\n                 style=\"display:inline-flex; width:100%;\"></webview>\n    </div>\n</script>\n<script>\n  Vue.component('apple-account-settings', {\n    template: '#apple-account-settings',\n    mounted() {\n      document.querySelector(\"#foo\").addEventListener(\"dom-ready\", () => {\n        // document.querySelector(\"#foo\").executeJavaScript(`document.body.innerHTML += (\"<style>.header {display: none!important;} </style>\")`)\n      })\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/apple-curator.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-applecurator\">\n    <div class=\"content-inner\">\n        <h1 class=\"header-text\">{{ data.attributes?.shortName ?? data.attributes.name}}</h1>\n        <template v-if=\"data.relationships && data.relationships.grouping\">\n            <template\n                    v-for=\"(recom,index) in data.relationships.grouping.data[0].relationships.tabs.data[0].relationships.children.data\">\n                <div class=\"row\">\n                    <div class=\"col\" v-if=\"recom.attributes.name != 'Chart Set'\">\n                        <h3>{{ recom.attributes.name ?? \"\"}}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\"\n                         v-if=\"index != 0 && recom.relationships && ((recom.relationships.children &&  recom.relationships.children.data.length > 10) || (recom.relationships.contents && recom.relationships.contents.data.length > 10))\">\n                        <button class=\"cd-btn-seeall\"\n                                @click=\"app.showCollection(recom.relationships.children ? recom.relationships.children : recom.relationships.contents, recom.attributes.name ?? '', 'listen_now')\">\n                            {{app.getLz('term.seeAll')}}\n                        </button>\n                    </div>\n                </div>\n                <template\n                        v-if=\"recom.relationships && ((recom.relationships.children && recom.relationships.children.data) || (recom.relationships.contents && recom.relationships.contents.data))\">\n                    <template v-if=\"(recom.attributes.name && recom.attributes.name.includes('ideo')) || index === 0\">\n                        <mediaitem-scroller-horizontal-mvview :imagesize=\"800\" :browsesp=\"index == 0\"\n                                                              :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                    </template>\n                    <template v-else-if=\"recom.attributes.name == 'Chart Set'\">\n\n                    </template>\n                    <template v-else>\n                        <mediaitem-scroller-horizontal-large\n                                :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                    </template>\n                </template>\n            </template>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-applecurator', {\n    template: \"#cider-applecurator\",\n    props: [\"data\"],\n    data: function() {\n      return {\n        app: this.$root\n      }\n    },\n    mounted() {\n        console.log('ping')\n    },\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/artist-feed.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-artist-feed\">\n    <div class=\"content-inner\">\n        <div>\n            <div class=\"row\">\n                <div class=\"col\">\n                    <div class=\"row nopadding\">\n                        <div class=\"col nopadding\">\n                            <h3>{{app.getLz('home.followedArtists')}}</h3>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"cd-btn-seeall\" @click=\"syncFavorites()\" v-if=\"!syncingFavs\">\n                                {{app.getLz('home.syncFavorites')}}\n                            </button>\n                            <div class=\"spinner\" style=\"height: 26px;\" v-else></div>\n                        </div>\n                    </div>\n                    <vue-horizontal>\n                        <div v-for=\"artist in artists\" style=\"margin: 6px;\">\n                            <mediaitem-square :item=\"artist\" kind=\"small\"></mediaitem-square>\n                            <button @click=\"unfollow(artist.id)\" class=\"md-btn md-btn-glyph\" style=\"display:flex;\">\n                                <div class=\"sidebar-icon\">\n                                    <div class=\"svg-icon\"\n                                         :style=\"{'--url': 'url(./assets/feather/x-circle.svg)'}\"></div>\n                                </div>\n                                {{app.getLz('action.removeFavorite')}}\n                            </button>\n                        </div>\n                    </vue-horizontal>\n                </div>\n            </div>\n        </div>\n\n\n        <div>\n            <div class=\"row\">\n                <div class=\"col\">\n                    <div class=\"row nopadding\">\n                        <div class=\"col nopadding\">\n                            <h3>{{app.getLz('home.artistsFeed')}}</h3>\n                        </div>\n                    </div>\n                    <div class=\"well\" style=\"margin-top:0;\">\n                        <template v-if=\"artistFeed.length > 0\">\n                            <mediaitem-list-item v-for=\"item in artistFeed\" v-bind:key=\"item.id\" :item=\"item\"></mediaitem-list-item>\n                        </template>\n                        <template v-else>\n                            <div class=\"spinner\"></div>\n                        </template>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-artist-feed', {\n    template: '#cider-artist-feed',\n    data: function() {\n      return {\n        app: this.$root,\n        followedArtists: this.$root.cfg.home.followedArtists,\n        artistFeed: [],\n        artists: [],\n        syncingFavs: false\n      }\n    },\n    async mounted() {\n      let self = this\n      await this.getArtistFeed()\n    },\n    methods: {\n      async syncFavorites() {\n        this.syncingFavs = true\n        await app.syncFavorites()\n        await this.getArtistFeed()\n        this.syncingFavs = false\n      },\n      async unfollow(id) {\n        let index = this.followedArtists.indexOf(id)\n        if (index > -1) {\n          this.followedArtists.splice(index, 1)\n        }\n        let artist = this.artists.find(a => a.id == id)\n        let index2 = this.artists.indexOf(artist)\n        if (index2 > -1) {\n          this.artists.splice(index2, 1)\n        }\n        await app.mk.api.v3.music(`/v1/me/favorites`, {\n          \"art[url]\": \"f\",\n          \"ids[artists]\": id,\n          \"l\": app.mklang,\n          \"platform\": \"web\"\n        }, {\n          fetchOptions: {\n            method: \"DELETE\"\n          }\n        })\n        this.getArtistFeed()\n      },\n      async getArtistFeed() {\n        let artists = this.followedArtists\n        let self = this\n        this.artists = []\n        this.artistFeed = []\n\n        // Apple limits the number of IDs we can provide in a single API call to 50.\n        // Divide it into groups of 50 and send parallel requests\n        let chunks = []\n        for (let artistIdx = 0; artistIdx < artists.length; artistIdx += 50) {\n          chunks.push(artists.slice(artistIdx, artistIdx + 50))\n        }\n        try {\n          const chunkArtistData = await Promise.all(chunks.map(chunk =>\n            this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists?ids=${chunk.toString()}&views=latest-release&include[songs]=albums&fields[albums]=artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url,trackCount&limit[artists:top-songs]=2&art[url]=f`)))\n          chunkArtistData.forEach(chunkResult =>\n            chunkResult.data.data.forEach(item => {\n              self.artists.push(item)\n              if (item.views[\"latest-release\"].data.length != 0) {\n                self.artistFeed.push(item.views[\"latest-release\"].data[0])\n              }\n            }))\n          // sort artistFeed by attributes.releaseDate descending, date is formatted as \"YYYY-MM-DD\"\n          this.artistFeed.sort((a, b) => {\n            let dateA = new Date(a.attributes.releaseDate)\n            let dateB = new Date(b.attributes.releaseDate)\n            return dateB - dateA\n          })\n        } catch (err) {\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/artist.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-artist\">\n    <div class=\"content-inner artist-page\"\n         :class=\"[(data.attributes.editorialVideo && (data.attributes.editorialVideo.motionArtistWide16x9 || data.attributes.editorialVideo.motionArtistFullscreen16x9) || hasHero()) ? 'animated' : '']\">\n        <div :class=\"['artist-header', { 'artist-header-compact': app.cfg.visual.compactArtistHeader }]\" :key=\"data.id\"\n             v-observe-visibility=\"{callback: isHeaderVisible}\">\n            <animatedartwork-view\n                    :priority=\"true\"\n                    v-if=\"hasAnimated()\"\n                    :video=\"data.attributes.editorialVideo.motionArtistWide16x9.video ?? (data.attributes.editorialVideo.motionArtistFullscreen16x9.video ?? '')\">\n            </animatedartwork-view>\n            <div class=\"header-content\" style=\"pointer-events: all;\">\n                <div class=\"row\">\n                    <div class=\"col-auto\" style=\"width: auto;\">\n                        <div class=\"artist-image\"\n                             v-if=\"!(data.attributes.editorialVideo && (data.attributes.editorialVideo.motionArtistWide16x9 || data.attributes.editorialVideo.motionArtistFullscreen16x9))&& !hasHero()\">\n                            <mediaitem-artwork\n                                    shadow=\"large\"\n                                    :url=\"data.attributes.artwork ? data.attributes.artwork.url : ''\"\n                                    size=\"190\" type=\"artists\"></mediaitem-artwork>\n                            <button class=\"overlay-play\" @click=\"app.mk.setStationQueue({artist:'a-'+data.id}).then(()=>{\n                            app.mk.play()\n                        })\" :aria-label=\"app.getLz('term.play')\">\n                                <%- include(\"../svg/play.svg\") %>\n                            </button>\n                        </div>\n                    </div>\n                    <div class=\"col cider-flex-center artist-title\"\n                         :class=\"{'artist-animation-on': (data.attributes.editorialVideo && (data.attributes.editorialVideo.motionArtistWide16x9 || data.attributes.editorialVideo.motionArtistFullscreen16x9)) || hasHero() }\"\n                         :style=\"{ 'color': '#' +hasHeroObject()?.textColor1 ?? ''}\"\n                    >\n                        <button class=\"artist-play\" @click=\"app.mk.setStationQueue({artist:'a-'+data.id}).then(()=>{\n                        app.mk.play()\n                    })\" :aria-label=\"app.getLz('term.play')\"><%- include(\"../svg/play.svg\") %></button>\n                        <h1>{{ data.attributes.name }}</h1>\n                    </div>\n                </div>\n                <button class=\"more-btn-round favorite\" @click=\"artistMenu\" style=\"pointer-events: all;\"\n                        :aria-label=\"app.getLz('term.more')\">\n                    <div class=\"svg-icon\"></div>\n                </button>\n                <button class=\"more-btn-round menu\" @click=\"artistMenu\" style=\"pointer-events: all;\"\n                        :aria-label=\"app.getLz('term.more')\">\n                    <div class=\"svg-icon\"></div>\n                </button>\n            </div>\n            <div class=\"artworkContainer\"\n                 v-if=\"!(data.attributes.editorialVideo && (data.attributes.editorialVideo.motionArtistWide16x9 || data.attributes.editorialVideo.motionArtistFullscreen16x9)) && !hasHero()\">\n                <artwork-material :url=\"data.attributes.artwork.url\" size=\"190\" images=\"1\"></artwork-material>\n            </div>\n            <div class=\"artist-hero\" v-if=\"hasHero() && !hasAnimated()\">\n                <mediaitem-artwork shadow=\"none\" :url=\"hasHero()\" size=\"2048\" />\n            </div>\n        </div>\n        <div class=\"floating-header\"\n             :style=\"{opacity: (headerVisible ? 0 : 1),'pointer-events': (headerVisible ? 'none' : '')}\">\n            <div class=\"row\">\n                <div class=\"col-auto cider-flex-center\">\n                    <button class=\"artist-play\" style=\"display:block;\" @click=\"app.mk.setStationQueue({artist:'a-'+data.id}).then(()=>{\n                        app.mk.play()\n                    })\" :aria-label=\"app.getLz('term.play')\"><%- include(\"../svg/play.svg\") %></button>\n                </div>\n                <div class=\"col\">\n                    <h3>{{ data.attributes.name }}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\">\n                    <button class=\"more-btn-round menu\" @click=\"artistMenu\" :aria-label=\"app.getLz('term.more')\">\n                        <div class=\"svg-icon\"></div>\n                    </button>\n                </div>\n            </div>\n        </div>\n        <div class=\"artist-body\">\n            <div class=\"arow well\" :class=\"{arowb: data.views['latest-release'].data.length == 0}\">\n                <div class=\"latestRelease\" v-if=\"data.views['latest-release'].data.length != 0\">\n                    <h3>{{app.getLz('term.latestReleases')}}</h3>\n                    <div style=\"width: auto;margin: 0 auto;\">\n                        <mediaitem-square kind=\"card\" :no-scale=\"true\" v-for=\"song in data.views['latest-release'].data\"\n                                          :item=\"song\">\n                        </mediaitem-square>\n                    </div>\n                </div>\n                <div class=\"topSongs\" v-if=\"data.views['top-songs']\">\n                    <div class=\"row\">\n                        <div class=\"col\" style=\"padding:0;\">\n                            <h3>{{app.getLz('term.topSongs')}}</h3>\n                        </div>\n                        <div class=\"col-auto cider-flex-center\" v-if=\"data.views['top-songs'].data.length >= 20\"\n                             style=\"padding:0;\">\n                            <button class=\"cd-btn-seeall\"\n                                    @click=\"app.showArtistView(data.id, data.attributes.name + ' - Top Songs', 'top-songs')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <div class=\"row\">\n                        <div class=\"col cider-flex-center\" style=\"padding:0;\">\n                            <div class=\"mediaitem-list-item__grid\">\n                                <listitem-horizontal :items=\"data.views['top-songs'].data.limit(20)\">\n                                </listitem-horizontal>\n                            </div>\n                        </div>\n                    </div>\n\n                </div>\n            </div>\n            <div class=\"row well\">\n                <div class=\"col\">\n                    <template v-for=\"(view) in data.meta.views.order\"\n                              v-if=\"(data.views[view].data.length != 0) && (view != 'latest-release') && (view != 'top-songs')\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                <h3>{{ data.views[view].attributes.title ?\n                                    data.views[view].attributes.title : \"???\"}}\n                                </h3>\n                            </div>\n                            <div class=\"col-auto cider-flex-center\" v-if=\"data.views[view].data.length >= 10\">\n                                <button class=\"cd-btn-seeall\"\n                                        @click=\"app.showArtistView(data.id, data.attributes.name + ' - ' + data.views[view].attributes.title, view)\">\n                                    {{app.getLz('term.seeAll')}}\n                                </button>\n                            </div>\n                        </div>\n                        <template v-if=\"!((data.views[view].attributes.title ?\n                        data.views[view].attributes.title : '???').includes('Video') || (data.views[view].attributes.title ?\n                        data.views[view].attributes.title : '???').includes('More To See'))\">\n                            <mediaitem-scroller-horizontal-large :items=\"data.views[view].data.limit(10)\">\n                            </mediaitem-scroller-horizontal-large>\n                        </template>\n                        <template v-else>\n                            <mediaitem-scroller-horizontal-mvview\n                                    :items=\"data.views[view].data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                        </template>\n                    </template>\n                    <div class=\"row\">\n                        <div class=\"col\" v-if=\"data.attributes.artistBio\">\n                            <h3>{{ $root.stringTemplateParser($root.getLz('term.aboutArtist'), {\"artistName\":\n                                data.attributes.name}) }}</h3>\n                            <p v-html=\"data.attributes.artistBio\"></p>\n                        </div>\n                        <div class=\"col\">\n                            <div v-if=\"data.attributes.origin\">\n                                <h3>{{ data.attributes.isGroup ? \"Origin\" : \"Hometown\" }}</h3>\n                                {{ data.attributes.origin }}\n                            </div>\n                            <div v-if=\"data.attributes.bornOrFormed\">\n                                <h3>{{ data.attributes.isGroup ? \"Formed\" : \"Born\" }}</h3>\n                                {{ data.attributes.bornOrFormed }}\n                            </div>\n                            <div v-if=\"data.attributes.genreNames\">\n                                <h3>{{app.getLz('term.sortBy.genre')}}</h3>\n                                {{ data.attributes.genreNames.join(', ') }}\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('cider-artist', {\n    template: \"#cider-artist\",\n    props: ['data'],\n    data: function() {\n      return {\n        topSongsExpanded: false,\n        app: this.$root,\n        headerVisible: true\n      }\n    },\n    methods: {\n      hasAnimated() {\n        if (this.data.attributes?.editorialVideo && (this.data.attributes?.editorialVideo?.motionArtistWide16x9 || this.data.attributes?.editorialVideo?.motionArtistFullscreen16x9)) {\n          return true;\n        }\n        return false;\n      },\n      hasHero() {\n        if (this.data.attributes?.editorialArtwork?.centeredFullscreenBackground) {\n          return this.data.attributes?.editorialArtwork?.centeredFullscreenBackground.url\n        } else if (this.data.attributes?.editorialArtwork?.bannerUber) {\n          return this.data.attributes?.editorialArtwork?.bannerUber.url\n        } else if (this.data.attributes?.editorialArtwork?.subscriptionHero) {\n          return this.data.attributes?.editorialArtwork?.subscriptionHero.url\n        }\n        return false;\n      },\n      hasHeroObject() {\n        if (this.data.attributes?.editorialArtwork?.centeredFullscreenBackground) {\n          return this.data.attributes?.editorialArtwork?.centeredFullscreenBackground\n        } else if (this.data.attributes?.editorialArtwork?.bannerUber) {\n          return this.data.attributes?.editorialArtwork?.bannerUber\n        } else if (this.data.attributes?.editorialArtwork?.subscriptionHero) {\n          return this.data.attributes?.editorialArtwork?.subscriptionHero\n        }\n        return [];\n      },\n      isHeaderVisible(visible) {\n        this.headerVisible = visible\n      },\n      async artistMenu(event) {\n        let self = this\n        let followAction = \"follow\"\n        let followActions = {\n          follow: {\n            icon: \"./assets/feather/plus-circle.svg\",\n            name: app.getLz('action.follow'),\n            action: () => {\n              self.app.cfg.home.followedArtists.push(self.data.id)\n            }\n          },\n          unfollow: {\n            icon: \"./assets/feather/x-circle.svg\",\n            name: app.getLz('action.unfollow'),\n            action: () => {\n              let index = self.app.cfg.home.followedArtists.indexOf(self.data.id)\n              if (index > -1) {\n                self.app.cfg.home.followedArtists.splice(index, 1)\n              }\n            }\n          }\n        }\n        let favoriteActions = {\n          favorite: {\n            icon: \"./assets/star.svg\",\n            name: app.getLz('action.favorite'),\n            action: () => {\n              app.setArtistFavorite(app.artistPage.data.id, true)\n            }\n          },\n          removeFavorite: {\n            icon: \"./assets/star.svg\",\n            name: app.getLz('action.removeFavorite'),\n            action: () => {\n              app.setArtistFavorite(app.artistPage.data.id, false)\n            }\n          }\n        }\n        if (this.app.cfg.home.followedArtists.includes(self.data.id)) {\n          followAction = \"unfollow\"\n        }\n        const inFavorites = (await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists/${app.artistPage.data.id}`, {\n          \"fields[artists]\": \"inFavorites\"\n        })).data.data[0].attributes?.inFavorites\n        app.showMenuPanel({\n          items: [\n            {\n              icon: \"./assets/feather/play.svg\",\n              name: app.getLz('action.startRadio'),\n              action: () => {\n                app.mk.setStationQueue({ artist: self.data.id }).then(() => {\n                  app.mk.play()\n                })\n              }\n            },\n            favoriteActions[inFavorites ? \"removeFavorite\" : \"favorite\"],\n            // followActions[followAction],\n            {\n              icon: \"./assets/feather/share.svg\",\n              name: app.getLz('term.share'),\n              action: () => {\n                self.app.copyToClipboard(self.data.attributes.url)\n              }\n            }\n          ]\n        }, event)\n      },\n      getArtistPalette(artist) {\n        if (artist[\"attributes\"][\"artwork\"]) {\n          return {\n            \"background\": \"#\" + artist[\"attributes\"][\"artwork\"][\"bgColor\"],\n            \"color\": \"#\" + artist[\"attributes\"][\"artwork\"][\"textColor1\"],\n          }\n        } else {\n          return {\n            \"background\": \"#000000\",\n            \"color\": \"#ffffff\",\n          }\n        }\n      },\n      getTopResult() {\n        if (this.search.results[\"meta\"]) {\n          return this.search.results[this.search.results.meta.results.order[0]][\"data\"][0]\n        } else {\n          return false;\n        }\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/audiolabs.ejs",
    "content": "<script type=\"text/x-template\" id=\"audiolabs-page\">\n    <div class=\"audiolabs-page\">\n        <div class=\"md-option-container\">\n            <div class=\"settings-option-body\">\n                <div class=\"md-option-line\">\n                    <b-jumbotron :header=\"$root.getLz('settings.option.audio.audioLab')\"\n                                 lead=\"Designed by Cider Acoustic Technologies in California\"></b-jumbotron>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPE')}}\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPE.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <input type=\"checkbox\" v-model=\"app.cfg.audio.maikiwiAudio.ciderPPE\"\n                            v-on:change=\"CiderAudio.hierarchical_loading();\" switch/>\n                    </div>\n                </div>\n                <div class=\"md-option-line\" v-show=\"app.cfg.audio.maikiwiAudio.ciderPPE === true\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength')}}\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <select class=\"md-select\" style=\"width:180px;\"\n                                v-model=\"app.cfg.audio.maikiwiAudio.ciderPPE_value\"\n                                v-on:change=\"CiderAudio.hierarchical_loading()\">\n                            <option v-for=\"(item, index) in ciderPPE\"\n                            :value=\"item.name\"\n                            :key=\"index.name\">\n                              {{item.displayName}}\n                            </option>\n                        </select>\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        Cider Opportunistic Correction System\n                        <br>\n                        <small>Takes advantage of the sonic characteristics of a specific equipment and adapts it to be more 'Cider' oriented.</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <select class=\"md-select\" style=\"width:180px;\"\n                                v-model=\"app.cfg.audio.maikiwiAudio.opportunisticCorrection_state\"\n                                v-on:change=\"CiderAudio.hierarchical_loading()\">\n                            <option value=\"OFF\">OFF</option>\n                            <option value=\"CHU\">Moondrop Chu</option>\n                        </select>\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizer')}} [1]\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizer.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <input type=\"checkbox\" v-model=\"app.cfg.audio.maikiwiAudio.atmosphereRealizer1\"\n                            v-on:change=\"CiderAudio.hierarchical_loading();\" switch/>\n                    </div>\n                </div>\n                <div class=\"md-option-line\" v-show=\"app.cfg.audio.maikiwiAudio.atmosphereRealizer1 === true\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizerMode')}} [1]\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizerMode.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <select class=\"md-select\" style=\"width:230px;\"\n                                v-model=\"$root.cfg.audio.maikiwiAudio.atmosphereRealizer1_value\"\n                                v-on:change=\"CiderAudio.hierarchical_loading();\">\n                            <option v-for=\"profile in arprofiles\" :value=\"profile.id\">{{ $root.getProfileLz(\"CAR\", profile.id) }}</option>\n                        </select>\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizer')}} [2]\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizer.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <input type=\"checkbox\" v-model=\"app.cfg.audio.maikiwiAudio.atmosphereRealizer2\"\n                            v-on:change=\"CiderAudio.hierarchical_loading();\" switch/>\n                    </div>\n                </div>\n                <div class=\"md-option-line\" v-show=\"app.cfg.audio.maikiwiAudio.atmosphereRealizer2 === true\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizerMode')}} [2]\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.atmosphereRealizerMode.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <select class=\"md-select\" style=\"width:230px;\"\n                                v-model=\"$root.cfg.audio.maikiwiAudio.atmosphereRealizer2_value\"\n                                v-on:change=\"CiderAudio.hierarchical_loading();\">\n                            <option v-for=\"profile in arprofiles\" :value=\"profile.id\">{{ $root.getProfileLz(\"CAR\", profile.id) }}</option>\n                        </select>\n                    </div>\n                </div>\n                <div class=\"md-option-line\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization')}}\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <input type=\"checkbox\" v-model=\"app.cfg.audio.maikiwiAudio.spatial\"\n                            v-on:change=\"CiderAudio.hierarchical_loading();\" switch/>\n                    </div>\n                </div>\n                <div class=\"md-option-line\"\n                    v-show=\"app.cfg.audio.maikiwiAudio.spatial === true\">\n                    <div class=\"md-option-segment\">\n                        {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization.profile')}}\n                        <br>\n                        <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.tunedAudioSpatialization.profile.description')}}</small>\n                    </div>\n                    <div class=\"md-option-segment md-option-segment_auto\">\n                        <select class=\"md-select\" style=\"width:180px;\"\n                                v-model=\"$root.cfg.audio.maikiwiAudio.spatialProfile\"\n                                v-on:change=\"CiderAudio.hierarchical_loading();\">\n                            <option v-for=\"profile in spprofiles\" :value=\"profile.id\">{{ $root.getProfileLz(\"CTS\", profile.name) }}</option>\n                        </select>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n    Vue.component('audiolabs-page', {\n        template: \"#audiolabs-page\",\n        props: [],\n        data: function () {\n            return {\n                app: this.$root,\n                arprofiles: CiderAudio.atmosphereRealizerProfiles,\n                spprofiles: CiderAudio.spatialProfiles,\n                ciderPPE: [{name: \"MAIKIWI\", displayName: \"Maikiwi \" + app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.adaptive')},\n                {name: \"MAIKIWI_LEGACY\", displayName: \"Maikiwi \" + app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.legacy')},\n                {name: \"NATURAL\", displayName: app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.standard')},\n                {name: \"LEGACY\", displayName: app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.legacy')}]\n            }\n        },\n        mounted: function () {\n          return {\n            ciderPPE: [{name: \"MAIKIWI\", displayName: \"Maikiwi \" + app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.adaptive')},\n                {name: \"MAIKIWI_LEGACY\", displayName: \"Maikiwi \" + app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.legacy')},\n                {name: \"NATURAL\", displayName: app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.standard')},\n                {name: \"LEGACY\", displayName: app.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPEStrength.legacy')}]\n          }\n        },\n        methods: {\n        }\n    })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/browse.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-browse\">\n    <div class=\"content-inner\">\n        <h1 class=\"header-text\">{{$root.getLz(\"term.browse\")}}</h1>\n        <template v-if=\"data.relationships && data.relationships.tabs\">\n            <template v-for=\"(recom,index) in data.relationships.tabs.data[0].relationships.children.data\">\n                <div class=\"row\">\n                    <div class=\"col\" v-if=\"recom.attributes.name != 'Chart Set'\">\n                        <h3>{{ recom.attributes.name ?? \"\"}}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\"\n                         v-if=\"index != 0 && recom.relationships && ((recom.relationships.children &&  recom.relationships.children.data.length > 10) || (recom.relationships.contents && recom.relationships.contents.data.length > 10))\">\n                        <button class=\"cd-btn-seeall\" v-if=\"recom.relationships.room\"\n                                @click=\"app.showRoom(recom.relationships.room?.data[0].href)\">\n                            {{app.getLz('term.seeAll')}}\n                        </button>\n                        <button class=\"cd-btn-seeall\" v-else\n                                @click=\"app.showCollection(recom.relationships.children ? recom.relationships.children : recom.relationships.contents, recom.attributes.name ?? '', 'listen_now')\">\n                            {{app.getLz('term.seeAll')}}\n                        </button>\n                    </div>\n                </div>\n                <template\n                        v-if=\"(recom.relationships != null && ((recom.relationships.children && recom.relationships.children.data) || (recom.relationships.contents && recom.relationships.contents.data)))\">\n                    <template\n                            v-if=\"index === 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\">\n                        <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                              :browsesp=\"index == 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\"\n                                                              :kind=\"recom.attributes.editorialElementKind\"\n                                                              :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                    </template>\n                    <template v-else-if=\"(['327']).includes(recom.attributes.editorialElementKind)\">\n                        <div class=\"mediaitem-list-item__grid\">\n                            <listitem-horizontal :items=\"recom.relationships.contents.data.limit(20)\">\n                            </listitem-horizontal>\n                        </div>\n                    </template>\n                    <template v-else-if=\"(['385']).includes(recom.attributes.editorialElementKind)\">\n                        <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                              :kind=\"recom.attributes.editorialElementKind\"\n                                                              :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                    </template>\n                    <template v-else-if=\"recom.attributes.name == 'Chart Set'\">\n                        <!-- ignored -->\n                    </template>\n                    <template v-else>\n                        <mediaitem-scroller-horizontal-large\n                                :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                    </template>\n                </template>\n                <template v-else>\n                    <template v-if=\"recom.attributes.links && recom.attributes.editorialElementKind.includes('391')\">\n                        <div class=\"grouping-container\">\n                            <button class=\"grouping-btn\" @click=\"$root.goToGrouping(link.url)\"\n                                    v-for=\"link in recom.attributes.links\">{{ link.label }}\n                            </button>\n                        </div>\n                    </template>\n                </template>\n            </template>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component(\"cider-browse\", {\n    template: \"#cider-browse\",\n    props: [\"data\"],\n    data: function() {\n      return {\n        app: this.$root,\n      };\n    },\n    mounted() {\n      this.$root.getBrowsePage();\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/charts.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-charts\">\n    <div class=\"content-inner\">\n        <h1 class=\"header-text\">{{$root.getLz(\"term.charts\")}}</h1>\n        <template v-if=\"songs != []\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3>{{ songs.name ?? \"\"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"songs.data.length > 12\">\n                    <button class=\"cd-btn-seeall\"\n                            @click=\"app.showCollection((songs ?? []), songs.name ?? '', 'default')\">\n                        {{app.getLz('term.seeAll')}}\n                    </button>\n                </div>\n            </div>\n            <div class=\"mediaitem-list-item__grid\">\n                <listitem-horizontal :items=\"(songs?.data ?? []).limit(12)\">\n                </listitem-horizontal>\n            </div>\n        </template>\n        <template v-if=\"albums != []\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3>{{ albums.name ?? \"\"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"songs.data.length > 12\">\n                    <button class=\"cd-btn-seeall\"\n                            @click=\"app.showCollection((albums ?? []), albums.name ?? '', 'default')\">\n                        {{app.getLz('term.seeAll')}}\n                    </button>\n                </div>\n            </div>\n            <mediaitem-scroller-horizontal-large\n                    :items=\"(albums?.data ?? []).limit(10)\"></mediaitem-scroller-horizontal-large>\n        </template>\n        <template v-if=\"playlists != []\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3>{{ playlists.name ?? \"\"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"playlists.data.length > 12\">\n                    <button class=\"cd-btn-seeall\"\n                            @click=\"app.showCollection((playlists ?? []), playlists.name ?? '', 'default')\">\n                        {{app.getLz('term.seeAll')}}\n                    </button>\n                </div>\n            </div>\n            <mediaitem-scroller-horizontal-large\n                    :items=\"(playlists?.data ?? []).limit(10)\"></mediaitem-scroller-horizontal-large>\n        </template>\n        <template v-if=\"musicvideos != []\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3>{{ musicvideos.name ?? \"\"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"musicvideos.data.length > 12\">\n                    <button class=\"cd-btn-seeall\"\n                            @click=\"app.showCollection((musicvideos ?? []), musicvideos.name ?? '', 'default')\">\n                        {{app.getLz('term.seeAll')}}\n                    </button>\n                </div>\n            </div>\n            <mediaitem-scroller-horizontal-large\n                    :items=\"(musicvideos?.data ?? []).limit(10)\"></mediaitem-scroller-horizontal-large>\n        </template>\n        <template v-if=\"globalcharts != []\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3>{{ globalcharts.name ?? \"\"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"globalcharts.data.length > 12\">\n                    <button class=\"cd-btn-seeall\"\n                            @click=\"app.showCollection((globalcharts ?? []), globalcharts.name ?? '', 'default')\">\n                        {{app.getLz('term.seeAll')}}\n                    </button>\n                </div>\n            </div>\n            <mediaitem-scroller-horizontal-large\n                    :items=\"(globalcharts?.data ?? []).limit(10)\"></mediaitem-scroller-horizontal-large>\n        </template>\n        <template v-if=\"citycharts != []\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <h3>{{ citycharts.name ?? \"\"}}</h3>\n                </div>\n                <div class=\"col-auto cider-flex-center\" v-if=\"citycharts.data.length > 12\">\n                    <button class=\"cd-btn-seeall\"\n                            @click=\"app.showCollection((citycharts ?? []), citycharts.name ?? '', 'default')\">\n                        {{app.getLz('term.seeAll')}}\n                    </button>\n                </div>\n            </div>\n            <mediaitem-scroller-horizontal-large\n                    :items=\"(citycharts?.data ?? []).limit(10)\"></mediaitem-scroller-horizontal-large>\n        </template>\n\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-charts', {\n    template: \"#cider-charts\",\n    data: function() {\n      return {\n        app: this.$root,\n        songs: [],\n        albums: [],\n        playlists: [],\n        musicvideos: [],\n        citycharts: [],\n        globalcharts: [],\n        categories: [],\n      }\n    },\n    mounted() {\n      this.getData();\n    },\n    methods: {\n      getData() {\n        let self = this;\n        app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/charts`, {\n          types: 'albums,songs,music-videos,playlists',\n          l: 'en-gb',\n          platform: 'auto',\n          limit: '50',\n          genre: '34',\n          include: 'tracks',\n          with: 'cityCharts,dailyGlobalTopCharts',\n          extend: 'artistUrl',\n          'fields[albums]': 'artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url',\n          'fields[playlists]': 'artistName,artistUrl,artwork,contentRating,editorialArtwork,name,playParams,releaseDate,url,curatorName'\n        }).then(res => {\n          let page = res.data?.results ?? [];\n          self.songs = page.songs[0] ?? [];\n          self.albums = page.albums[0] ?? [];\n          self.playlists = page.playlists[0] ?? [];\n          self.musicvideos = page['music-videos'][0] ?? [];\n          self.citycharts = page.cityCharts[0] ?? [];\n          self.globalcharts = page.dailyGlobalTopCharts[0] ?? [];\n        })\n        // let self = this;\n        // app.mk.api.music(`/v1/catalog/${app.mk.storefrontId}/charts?types=songs%2Calbums%2Cplaylists&limit=36`).then(res => {\n        //     let page = res.data?.results ?? [];\n        //     self.songs = page.songs[0] ?? [];\n        //     self.albums = page.albums[0] ?? [];\n        //     self.playlists = page.playlists[0] ?? [];\n        // })\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/cider-multiroom.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-multiroom\">\n    <div class=\"content-inner cider-multiroom\">\n        <div class=\"artworkContainer\" v-if=\"data.attributes?.uber?.masterArt?.url\">\n            <artwork-material :url=\"data.attributes?.uber?.masterArt?.url ?? ''\" size=\"800\"\n                              images=\"1\"></artwork-material>\n        </div>\n        <div class=\"detail\">\n            <h1 class=\"header-text\">{{data.attributes?.title ?? \"\"}}</h1>\n            <h2 class=\"header-desc\" v-html='data.relationships?.children?.data[0]?.attributes?.description ?? \"\"'></h2>\n            <template v-if=\"data.relationships\">\n                <template v-if=\"data.type=='rooms' &&  (data?.relationships?.contents?.data ?? []).length > 0\">\n                    <!-- <div class=\"row\">\n                        <div class=\"col-auto cider-flex-center\"\n                             v-if=\"data?.relationships?.contents?.data.length > 10\">\n                            <button class=\"cd-btn-seeall\"\n                                    @click=\"app.showCollection(recom, data.attributes.name ?? '', 'listen_now')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div> -->\n                    <template>\n                            <mediaitem-square :item=\"item\" :key=\"item?.id ?? ''\"\n                            v-for=\"item in data?.relationships?.contents?.data\"></mediaitem-square>\n                    </template>\n                </template>\n                <template v-else v-for=\"(recom,index) in (data.relationships?.children?.data ?? recom?.relationships?.contents?.data)\">\n                    <template v-if=\"(recom.relationships?.contents?.data ?? []).length > 0\">\n                        <div class=\"row\">\n                            <div class=\"col\" v-if=\"recom.attributes.name != 'Chart Set'\">\n                                <h3>{{ recom.attributes?.title ?? \"\"}}</h3>\n                            </div>\n                            <div class=\"col-auto cider-flex-center\"\n                                 v-if=\"index != 0 && recom.relationships && ((recom.relationships.children &&  recom.relationships.children.data.length > 10) || (recom.relationships.contents && recom.relationships.contents.data.length > 10))\">\n                                <button class=\"cd-btn-seeall\"\n                                        @click=\"app.showCollection(recom.relationships.children ? recom.relationships.children : recom.relationships.contents, recom.attributes.name ?? '', 'listen_now')\">\n                                    {{app.getLz('term.seeAll')}}\n                                </button>\n                            </div>\n                        </div>\n                        <template\n                                v-if=\"recom.relationships && ((recom.relationships.children && recom.relationships.children.data) || (recom.relationships.contents && recom.relationships.contents.data))\">\n                            <template\n                                    v-if=\"(recom.attributes.name && recom.attributes.name.includes('ideo')) || index === 0\">\n                                <mediaitem-scroller-horizontal-mvview :imagesize=\"800\" :browsesp=\"index == 0\"\n                                                                      :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                            </template>\n                            <template v-else-if=\"recom.attributes.name == 'Chart Set'\">\n\n                            </template>\n                            <template v-else>\n                                <mediaitem-scroller-horizontal-large\n                                        :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                            </template>\n                        </template>\n                    </template>  \n                </template>\n            </template>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-multiroom', {\n    template: \"#cider-multiroom\",\n    props: [\"data\"],\n    data: function() {\n      return {\n        app: this.$root\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/cider-playlist.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-playlist\">\n    <div class=\"content-inner playlist-page\" :class=\"classes\" :is-album=\"isAlbum()\"\n         v-if=\"data != [] && data.attributes != null\"\n\n         :style=\"{'--bgColor': (data.attributes.artwork != null && data.attributes.artwork['bgColor'] != null) ? ('#' + data.attributes.artwork.bgColor) : ''}\">\n        <template v-if=\"app.playlists.loadingState == 0\">\n            <div class=\"content-inner centered\">\n                <div class=\"spinner\"></div>\n            </div>\n        </template>\n        <template v-if=\"app.playlists.loadingState == 1\">\n            <div class=\"playlist-display\" :style=\"{ 'background-color': '#' +hasHeroObject()?.bgColor ?? '' }\"\n                 @mouseover.self=\"minClass(false)\">\n                <div class=\"playlistInfo\">\n                    <div class=\"playlist-hero\" v-if=\"hasHero()\">\n                        <mediaitem-artwork shadow=\"none\" :url=\"hasHero()\" size=\"2160\" />\n                        <div class=\"hero-tint\"\n                             :style=\"{'background-color': '#' + hasHeroObject()?.bgColor ?? ''}\"></div>\n                    </div>\n                    <div class=\"row\">\n                        <div class=\"col-auto cider-flex-center\" @mouseover=\"minClass(false)\">\n                            <div class=\"mediaContainer\">\n                                <mediaitem-artwork\n                                        shadow=\"large\"\n                                        :video-priority=\"true\"\n                                        :url=\"(data.attributes != null && data.attributes.artwork != null) ? data.attributes.artwork.url : ((data.relationships != null && data.relationships.tracks.data.length > 0 && data.relationships.tracks.data[0].attributes != null) ? ((data.relationships.tracks.data[0].attributes.artwork != null)? data.relationships.tracks.data[0].attributes.artwork.url : ''):'')\"\n                                        :video=\"(data.attributes != null && data.attributes.editorialVideo != null) ? (data.attributes.editorialVideo.motionDetailSquare ? data.attributes.editorialVideo.motionDetailSquare.video : (data.attributes.editorialVideo.motionSquareVideo1x1 ? data.attributes.editorialVideo.motionSquareVideo1x1.video : '')) : '' \"\n                                        size=\"500\"\n                                ></mediaitem-artwork>\n                            </div>\n                        </div>\n                        <div class=\"col playlist-info\">\n                            <template v-if=\"!editorialNotesExpanded\">\n                                <div>\n                                    <div class=\"playlist-name\" @mouseover=\"minClass(false)\" @click=\"editPlaylistName()\"\n                                         v-show=\"!nameEditing\"\n                                         :style=\"{ 'color': '#' +hasHeroObject()?.textColor1 ?? '', 'filter' : 'drop-shadow(1px 3px 8px #' + hasHeroObject()?.textColor4 ?? '' +')' }\">\n                                        {{data.attributes ? (data.attributes.name ??\n                                        (data.attributes.title ?? '') ?? '') : ''}}\n                                    </div>\n                                    <div class=\"playlist-name\" @mouseover=\"minClass(false)\" v-show=\"nameEditing\"><input\n                                                type=\"text\"\n                                                spellcheck=\"false\"\n                                                class=\"nameEdit\"\n                                                v-model=\"data.attributes.name\"\n                                                @blur=\"editPlaylist\"\n                                                @change=\"editPlaylist\"\n                                                @keydown.enter=\"editPlaylist\" />\n                                    </div>\n                                    <div class=\"playlist-time genre\" style=\"margin: 0px;\"\n                                         :style=\"{ 'color': '#' + hasHeroObject()?.textColor2 ?? '' }\">\n                                        {{getAlbumGenre()}}\n                                    </div>\n                                    <div class=\"playlist-artist item-navigate\"\n                                         v-if=\"getArtistName(data) != '' && !useArtistChip\"\n                                         @click=\"data.attributes && data.attributes.artistName ? app.searchAndNavigate(data,'artist') : ''\">\n                                        {{getArtistName(data)}}\n                                    </div>\n                                    <template v-if=\"useArtistChip\">\n                                        <artist-chip v-for=\"artist in data.relationships.artists?.data\"\n                                                     :style=\"{ 'color': '#' +hasHeroObject()?.textColor3 ?? '' }\"\n                                                     :item=\"artist\"></artist-chip>\n                                    </template>\n                                    <div class=\"playlist-desc\"\n                                         :style=\"{ 'color': '#' +hasHeroObject()?.textColor3 ?? '' }\"\n                                         v-if=\"(data.attributes.description && (data.attributes.description.standard || data.attributes.description.short)) || (data.attributes.editorialNotes && (data.attributes.editorialNotes.standard || data.attributes.editorialNotes.short))\">\n                                        <div v-if=\"(data.attributes.description?.short ?? data.attributes.editorialNotes?.short) != null\"\n                                             class=\"content\"\n                                             v-html=\"data.attributes.description?.short ?? data.attributes.editorialNotes?.short\"\n                                             @click=\"openInfoModal()\"></div>\n                                        <div v-else-if=\"((data.attributes.description?.standard ?? data.attributes.editorialNotes?.standard) != null) && (descriptionEditing == false)\"\n                                             @mouseover=\"minClass(false)\" @click=\"editPlaylistDescription()\"\n                                             v-html=\"(data.attributes.description?.standard ?? (data.attributes.editorialNotes?.standard ?? '')).substring(0, 255) +'...'\"\n                                        ></div>\n                                        <div v-else-if=\"((data.attributes.description?.standard ?? data.attributes.editorialNotes?.standard) != null) && (descriptionEditing)\"\n                                             @mouseover=\"minClass(false)\"><input type=\"text\"\n                                                                                 spellcheck=\"false\"\n                                                                                 class=\"descriptionEdit\"\n                                                                                 v-model=\"data.attributes.description.standard\"\n                                                                                 @blur=\"editPlaylist\"\n                                                                                 @change=\"editPlaylist\"\n                                                                                 @keydown.enter=\"editPlaylist\" /></div>\n                                        <!-- <button v-if=\"(data.attributes.description?.short ?? data.attributes.editorialNotes?.short ) != null\" class=\"more-btn\"\n                                                @click=\"editorialNotesExpanded = !editorialNotesExpanded\">\n                                            {{app.getLz('term.showMore')}}\n                                        </button> -->\n                                    </div>\n                                </div>\n                            </template>\n                            <template v-if=\"editorialNotesExpanded\">\n                                <div class=\"playlist-desc-expanded\">\n                                    <div class=\"content\"\n                                         v-html=\"((data.attributes.editorialNotes) ? (data.attributes.editorialNotes.standard ?? (data.attributes.editorialNotes.short ?? '') ) : (data.attributes.description ? (data.attributes.description.standard ?? (data.attributes.description.short ?? '')) : ''))\"></div>\n                                    <button class=\"more-btn\" @click=\"editorialNotesExpanded = !editorialNotesExpanded\">\n                                        {{app.getLz('term.showLess')}}\n                                    </button>\n                                </div>\n                            </template>\n                            <div class=\"playlist-controls\" v-observe-visibility=\"{callback: isHeaderVisible}\"\n                                 style=\"z-index: 20;\">\n                                <button class=\"md-btn md-btn-primary md-btn-icon\" style=\"min-width: 100px;\"\n                                        :style=\"{'background': '#' +hasHeroObject()?.textColor4 ?? '','border-top': '#' +hasHeroObject()?.textColor3 ?? '','border': '#' +hasHeroObject()?.textColor2 ?? ''}\"\n                                        @click=\"app.mk.shuffleMode = 0; play()\"><img class=\"md-ico-play\">\n                                    {{app.getLz('term.play')}}\n                                </button>\n                                <button class=\"md-btn md-btn-primary md-btn-icon\" style=\"min-width: 100px;\"\n                                        :style=\"{'background': '#' +hasHeroObject()?.textColor4 ?? '','border-top': '#' +hasHeroObject()?.textColor3 ?? '','border': '#' +hasHeroObject()?.textColor2 ?? ''}\"\n                                        @click=\"app.mk.shuffleMode = 1;play()\"><img class=\"md-ico-shuffle\">\n                                    {{app.getLz('term.shuffle')}}\n                                </button>\n                                <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\"\n                                        v-if=\"inLibrary!=null && confirm!=true\"\n                                        @click=\"confirmButton()\"><img\n                                            :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                    {{ (!inLibrary) ? app.getLz('action.addToLibrary') :\n                                    app.getLz(\"action.removeFromLibrary\") }}\n                                </button>\n                                <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\" v-if=\"confirm==true\"\n                                        @click=\"(!inLibrary) ? addToLibrary(data.attributes.playParams.id.toString()) : removeFromLibrary(data.attributes.playParams.id.toString()) \">\n                                    <img :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                    {{app.getLz('term.confirm')}}\n                                </button>\n                                <select v-if=\"shouldPaginate\" class=\"md-select\" v-model=\"prefs.scroll\">\n                                    <optgroup :label=\"app.getLz('term.scroll')\">\n                                        <option value=\"infinite\">{{app.getLz('term.scroll.infinite')}}</option>\n                                        <option value=\"paged\">\n                                            {{app.getLz('term.scroll.paged').replace(\"${songsPerPage}\", pageSize)}}\n                                        </option>\n                                    </optgroup>\n                                </select>\n                                <div style=\"display: flex; float: right;\">\n                                    <button :style=\"{ 'background': '#' + hasHeroObject()?.textColor4 ?? '' }\"\n                                            :class=\"['search-btn', showSearch ? 'active' : '']\" @click=\"toggleSearch()\"\n                                            :aria-label=\"showSearch ? app.getLz('term.hideSearch') : app.getLz('term.showSearch')\">\n                                        <svg-icon\n                                                :style=\"{ 'width': '15px', 'background-color': '#' + hasHeroObject()?.bgColor ?? '' }\"\n                                                :url=\"showSearch ? './assets/search-alt.svg' : './assets/search.svg'\">\n                                        </svg-icon>\n                                    </button>\n                                    <button :style=\"{ 'background': '#' + hasHeroObject()?.textColor4 ?? '' }\"\n                                            class=\"more-btn-round\" @click=\"menu\" :aria-label=\"app.getLz('term.more')\">\n                                        <div :style=\"{ 'background-color': '#' + hasHeroObject()?.bgColor ?? '' }\"\n                                             class=\"svg-icon\"></div>\n                                    </button>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <div class=\"artworkContainer\" v-if=\"data.attributes.artwork != null && !hasHero()\">\n                    <artwork-material :url=\"data.attributes.artwork.url\" size=\"500\" images=\"1\"></artwork-material>\n                </div>\n                <button class=\"md-btn md-btn-small editTracksBtn\"\n                        v-if=\"(data.attributes.canEdit && data.type == 'library-playlists')\"\n                        @click=\"editing = !editing\">\n                    <span v-if=\"!editing\">\n                        <div class='codicon codicon-edit'></div> {{$root.getLz(\"action.editTracklist\")}}\n                    </span>\n                    <span v-else>\n                        <div class='codicon codicon-check'></div> {{$root.getLz(\"action.done\")}}\n                    </span>\n                </button>\n            </div>\n            <div class=\"floating-header\"\n                 :style=\"{opacity: (headerVisible ? 0 : 1),'pointer-events': (headerVisible ? 'none' : '')}\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3>{{data.attributes ? (data.attributes.name ??\n                            (data.attributes.title ?? '') ?? '') : ''}}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\">\n                        <div>\n                            <button class=\"md-btn md-btn-primary  md-btn-icon\" style=\"min-width: 100px;\"\n                                    @click=\"app.mk.shuffleMode = 0; play()\"><img class=\"md-ico-play\">\n                                {{app.getLz('term.play')}}\n                            </button>\n                            <button class=\"md-btn md-btn-primary  md-btn-icon\" style=\"min-width: 100px;\"\n                                    @click=\"app.mk.shuffleMode = 1;play()\"><img class=\"md-ico-shuffle\">\n                                {{app.getLz('term.shuffle')}}\n                            </button>\n                            <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\"\n                                    v-if=\"inLibrary!=null && confirm!=true\"\n                                    @click=\"confirmButton()\"><img\n                                        :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                {{ (!inLibrary) ? app.getLz('action.addToLibrary') :\n                                app.getLz(\"action.removeFromLibrary\") }}\n                            </button>\n                            <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\" v-if=\"confirm==true\"\n                                    @click=\"(!inLibrary) ? addToLibrary(data.attributes.playParams.id.toString()) : removeFromLibrary(data.attributes.playParams.id.toString()) \">\n                                <img :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                {{app.getLz('term.confirm')}}\n                            </button>\n                            <select v-if=\"shouldPaginate\" class=\"md-select\" v-model=\"prefs.scroll\">\n                                <optgroup :label=\"app.getLz('term.scroll')\">\n                                    <option value=\"infinite\">{{app.getLz('term.scroll.infinite')}}</option>\n                                    <option value=\"paged\">{{app.getLz('term.scroll.paged').replace(\"${songsPerPage}\",\n                                        pageSize)}}\n                                    </option>\n                                </optgroup>\n                            </select>\n                        </div>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\">\n                        <button class=\"more-btn-round\" style=\"float:right;\" @click=\"menu\"\n                                :aria-label=\"app.getLz('term.more')\">\n                            <div class=\"svg-icon\"></div>\n                        </button>\n                    </div>\n                </div>\n            </div>\n            <div class=\"playlist-body scrollbody\">\n                <b-tabs pills class=\"track-pills pilldim fancy-pills\" align=\"center\" content-class=\"mt-3\"\n                        :nav-wrapper-class=\"navClass(data)\">\n                    <b-tab :title=\"$root.getLz('term.tracks')\" id=\"songList\" active>\n                        <div @wheel=\"minClass(true)\" @scroll=\"minClass(true)\">\n                            <div class=\"\">\n                                <div style=\"width:100%\" @click=\"minClass(true)\">\n                                    <div v-if=\"showSearch\" class=\"search-input-container\">\n                                        <div class=\"search-input--icon\"></div>\n                                        <input type=\"search\"\n                                               spellcheck=\"false\"\n                                               :placeholder=\"$root.getLz('term.search') + '...'\"\n                                               @input=\"search()\"\n                                               v-model=\"searchQuery\"\n                                               class=\"search-input\"\n                                               ref=\"search-bar\">\n                                    </div>\n                                    <pagination\n                                            v-if=\"shouldPaginate\"\n                                            style=\"margin-top: 10px\"\n                                            :length=\"hasNestedPlaylist ? nestedDisplayLength: displayListing.length\"\n                                            :pageSize=\"pageSize\"\n                                            :scroll=\"prefs.scroll\"\n                                            scrollSelector=\"#songList\"\n                                            @onRangeChange=\"onRangeChange\"\n                                    />\n                                    <draggable :options=\"{disabled: !editing}\"\n                                               v-model=\"data.relationships.tracks.data\" @start=\"drag=true\"\n                                               @end=\"drag=false;put()\">\n                                        <template v-if=\"!hasNestedPlaylist\">\n                                            <mediaitem-list-item :item=\"item\" :parent=\"getItemParent(data)\"\n                                                                 :index=\"index + start\"\n                                                                 :showIndex=\"true\"\n                                                                 :showIndexPlaylist=\"(data.attributes.playParams?.kind ?? data.type ?? '').includes('playlist')\"\n                                                                 :context-ext=\"buildContextMenu()\"\n                                                                 v-bind:key=\"item.id\"\n                                                                 v-for=\"(item,index) in currentSlice\"></mediaitem-list-item>\n                                        </template>\n                                        <template v-else>\n                                            <div v-for=\"disc in nestedSlices\">\n                                                <div class=\"playlist-time\">{{($root.getLz(\"term.discNumber\") ??\n                                                    \"\").replace(\"${discNumber}\",disc.disc)}}\n                                                </div>\n                                                <mediaitem-list-item :item=\"item\" :parent=\"getItemParent(data)\"\n                                                                     :index=\"index\"\n                                                                     :showIndex=\"true\"\n                                                                     :showIndexPlaylist=\"(data.attributes.playParams?.kind ?? data.type ?? '').includes('playlist')\"\n                                                                     :context-ext=\"buildContextMenu()\"\n                                                                     v-bind:key=\"item.id\"\n                                                                     v-for=\"(item,index) in disc.tracks\"></mediaitem-list-item>\n                                            </div>\n\n                                        </template>\n                                    </draggable>\n\n                                </div>\n\n                            </div>\n                            <div class=\"friends-info\" v-if=\"itemBadges.length != 0\">\n                                <div class=\"well\">\n                                    <div class=\"badge-container\">\n                                        <div class=\"socialBadge\"\n                                             :title=\"`${badge.attributes.name} - @${badge.attributes.handle}`\"\n                                             v-for=\"badge in itemBadges\">\n                                            <mediaitem-artwork\n                                                    :url=\"badge.attributes.artwork.url\"\n                                                    :size=\"60\"></mediaitem-artwork>\n                                        </div>\n                                    </div>\n                                </div>\n                            </div>\n                            <div class=\"playlist-time\">\n                                {{getFormattedDate()}}\n                            </div>\n                            <div class=\"playlist-time total\">{{app.getTotalTime()}}</div>\n                            <div class=\"playlist-time item-navigate\" @click=\"app.searchAndNavigate(data,'recordLabel') \"\n                                 style=\"width: 50%;\">\n                                {{data.attributes.copyright}}\n                            </div>\n                            <template\n                                    v-if=\"(data.attributes?.playParams?.kind ?? data.type ?? '').includes('album') &&  data.relationships.catalog != null && data.relationships.catalog != null && data.relationships.catalog.data.length > 0\">\n                                <div class=\"playlist-time showExtended item-navigate\"\n                                     style=\"color:#fa586a; font-weight: bold\"\n                                     @click=\"app.routeView(data.relationships.catalog.data[0])\">\n                                    {{$root.getLz(\"action.showAlbum\")}}\n                                </div>\n                            </template>\n                        </div>\n                    </b-tab>\n                    <template v-if=\"typeof data.views != 'undefined'\">\n                        <b-tab lazy :title=\"data.views[view].attributes.title\" v-for=\"view in data.meta.views.order\"\n                               v-if=\"data.views[view].data.length != 0\">\n                            <div>\n                                <div class=\"row\">\n                                    <div class=\"col\">\n                                        <h3>{{ data.views[view].attributes.title }}</h3>\n                                    </div>\n                                </div>\n                                <div class=\"row\">\n                                    <div class=\"col\">\n                                        <mediaitem-scroller-horizontal\n                                                :items=\"data.views[view].data\"></mediaitem-scroller-horizontal>\n                                    </div>\n                                </div>\n                            </div>\n                        </b-tab>\n                    </template>\n\n                </b-tabs>\n            </div>\n        </template>\n    </div>\n\n</script>\n\n<script>\n  Vue.component('cider-playlist', {\n    template: \"#cider-playlist\",\n    props: [\"data\"],\n\n    data: function() {\n      const pageSize = this.$root.cfg.libraryPrefs.pageSize;\n      return {\n        editorialNotesExpanded: false,\n        drag: false,\n        nameEditing: false,\n        descriptionEditing: false,\n        inLibrary: null,\n        confirm: false,\n        app: this.$root,\n        itemBadges: [],\n        badgesRequested: false,\n        headerVisible: true,\n        useArtistChip: false,\n        nestedPlaylist: [],\n        nestedDisplayLength: 0,\n        classes: [],\n        editing: false,\n        inPlaylist: false,\n        searchQuery: \"\",\n        displayListing: [],\n        hasNestedPlaylist: false,\n        showSearch: false,\n        pageSize: pageSize,\n        start: 0,\n        end: pageSize,\n        prefs: this.$root.cfg.libraryPrefs.playlists\n      }\n    },\n    mounted: function() {\n      this.$nextTick(function() {\n        if (this.data.id != \"ciderlocal\") {\n          this.isInLibrary()\n        } else {\n          if (this.data.relationships != null && this.data.id == \"ciderlocal\") {\n            this.displayListing = this.data.relationships.tracks.data\n          }\n\n          this.inPlaylist = this.data.type == \"library-playlists\";\n        }\n      })\n    },\n    beforeMount() {\n      if (window.location.hash.includes(\"playlist\")) {\n        window.addEventListener('keydown', this.getCopiedPlayListSongs);\n        window.addEventListener('keydown', this.pasteSongs);\n      }\n    },\n    beforeDestroy() {\n      if (window.location.hash.includes(\"playlist\")) {\n        window.removeEventListener('keydown', this.getCopiedPlayListSongs);\n        window.removeEventListener('keydown', this.pasteSongs);\n      }\n    },\n    watch: {\n      data: {\n        handler: function() {\n          this.isInLibrary()\n          this.getBadges()\n\n          if (this.data.relationships != null) {\n            if (this.data.id == \"ciderlocal\") {\n              this.displayListing = this.data.relationships.tracks.data\n            } else {\n              this.generateNestedPlaylist(this.data.relationships.tracks.data)\n              if (!this.hasNestedPlaylist) {\n                this.displayListing = this.data.relationships.tracks.data\n              }\n            }\n          }\n\n          this.inPlaylist = this.data.type == \"library-playlists\";\n        },\n        deep: true\n      }\n    },\n    computed: {\n      currentSlice() {\n        return this.displayListing.slice(this.start, this.end);\n      },\n      nestedSlices() {\n        if (this.shouldPaginate) {\n          let songsSeen = 0;\n          const discs = [];\n\n          for (const disc of this.nestedPlaylist) {\n            songsSeen += disc.tracks.length;\n\n            if (songsSeen >= this.end) {\n              discs.push({\n                disc: disc.disc,\n                tracks: disc.tracks.slice(0, this.end + disc.tracks.length - songsSeen)\n              })\n              break;\n            } else if (songsSeen > this.start) {\n              discs.push({\n                disc: disc.disc,\n                tracks: disc.tracks.slice(this.start - songsSeen)\n              })\n            }\n          }\n\n          return discs;\n        } else {\n          return this.nestedPlaylist\n        }\n      },\n      shouldPaginate() {\n        const result = this.data.relationships.tracks.data.length > this.pageSize\n        console.log(result)\n        return result\n      }\n    },\n    methods: {\n      onRangeChange(newRange) {\n        this.start = newRange[0];\n        this.end = newRange[1];\n      },\n      isAlbum() {\n        return (this.data.attributes?.playParams?.kind ?? this.data.type ?? '').includes('album')\n      },\n      minClass(val) {\n        if (app.appMode == 'fullscreen') {\n          return\n        }\n        if (val) {\n          this.classes = [\"plmin\"]\n        } else {\n          this.classes = []\n        }\n      },\n      openInfoModal() {\n        app.moreinfodata = [];\n        app.moreinfodata = {\n          title: this.data?.attributes ? (this.data?.attributes?.name ??\n            (this.data?.attributes?.title ?? '') ?? '') : '',\n          subtitle: this.data?.attributes?.artistName ?? '',\n          content: ((this.data?.attributes?.editorialNotes != null) ? (this.data?.attributes?.editorialNotes?.standard ?? (this.data?.attributes?.editorialNotes?.short ?? '')) : (data.attributes?.description ? (this.data.attributes?.description?.standard ?? (this.data?.attributes?.description?.short ?? '')) : ''))\n        }\n        app.modals.moreInfo = true;\n      },\n      generateNestedPlaylist(songlists) {\n        this.nestedPlaylist = [];\n        this.nestedDisplayLength = songlists.length;\n\n        if (this.data?.type?.includes(\"album\")) {\n          let discs = songlists.map(x => {\n            return x.attributes.discNumber\n          }).filter((item, i, ar) => ar.indexOf(item) === i);\n\n          if ((discs && discs.length > 1) || (discs && this.hasNestedPlaylist)) {\n            for (disc of discs) {\n              let songs = songlists.filter(x => x.attributes.discNumber == disc);\n              this.nestedPlaylist.push({ disc: disc, tracks: songs })\n            }\n          }\n          console.log(this.nestedPlaylist)\n        }\n\n        if (!this.hasNestedPlaylist)\n          this.hasNestedPlaylist = this.nestedPlaylist != [] && this.nestedPlaylist.length > 1;\n      },\n      isHeaderVisible(visible) {\n        this.headerVisible = visible\n      },\n      hasHero() {\n        if (this.data.attributes?.editorialArtwork?.bannerUber) {\n          return this.data.attributes?.editorialArtwork?.bannerUber.url\n        } else if (this.data.attributes?.editorialArtwork?.subscriptionHero) {\n          return this.data.attributes?.editorialArtwork?.subscriptionHero.url\n        } else if (this.data.attributes?.editorialArtwork?.storeFlowcase) {\n          return this.data.attributes?.editorialArtwork?.storeFlowcase.url\n        }\n        return false;\n      },\n      hasHeroObject() {\n        if (this.data.attributes?.editorialArtwork?.bannerUber) {\n          return this.data.attributes?.editorialArtwork?.bannerUber\n        } else if (this.data.attributes?.editorialArtwork?.subscriptionHero) {\n          return this.data.attributes?.editorialArtwork?.subscriptionHero\n        } else if (this.data.attributes?.editorialArtwork?.storeFlowcase) {\n          return this.data.attributes?.editorialArtwork?.storeFlowcase\n        }\n        return [];\n      },\n      getBadges() {\n        return\n        if (this.badgesRequested) {\n          return\n        }\n        this.badgesRequested = true\n        this.itemBadges = []\n        let self = this\n        var id = 0\n        try {\n          id = this.data.attributes.playParams.id\n        } catch (e) {\n          id = this.data.id\n        }\n        this.$root.getSocialBadges((badges) => {\n          let friends = badges[id]\n          if (friends) {\n            friends.forEach(function(friend) {\n              self.app.mk.api.v3.music(`/v1/social/${app.mk.storefrontId}/social-profiles/${friend}`).then(data => {\n                self.itemBadges.push(data.data.data[0])\n              })\n            })\n          }\n        })\n      },\n      confirmButton() {\n        // Return button to normal state after 3 seconds\n\n        this.confirm = true\n        setTimeout(() => this.confirm = false, 3000);\n      },\n      getArtistName(data) {\n        if (data.attributes.artistName) {\n          this.useArtistChip = true\n          return data.attributes.artistName\n        } else if (data.attributes.artist) {\n          this.useArtistChip = true\n          return data.attributes.artist.attributes.name\n        } else if (data.attributes.curatorName) {\n          return data.attributes.curatorName\n        } else {\n          return \"\"\n        }\n      },\n      getAlbumGenre: function() {\n        if (this.data.type.includes('albums')) {\n          let date = this.data.attributes.releaseDate;\n          if (date == null || date === \"\") return \"\";\n          return `${this.data.attributes.genreNames[0]} · ${new Date(date).getFullYear()}`\n        }\n      },\n      async isInLibrary() {\n        if (this.data.type && !this.data.type.includes(\"library\")) {\n          // please keep using vars here\n          const params = {\n            \"fields[playlists]\": \"inLibrary\",\n            \"fields[albums]\": \"inLibrary\",\n            \"relate\": \"library\"\n          };\n          const res = await app.mkapi(this.data.attributes.playParams.kind ?? this.data.type, this.data.attributes.playParams.isLibrary ?? false, this.data.attributes.playParams.id ?? this.data.id, params);\n          this.inLibrary = (res.data.data[0] && res.data.data[0].attributes && res.data.data[0].attributes.inLibrary) ? res.data.data[0].attributes.inLibrary : false\n          console.log(res)\n        } else {\n          this.inLibrary = true\n        }\n      },\n      editPlaylist() {\n        this.app.editPlaylist(this.data.id, this.data.attributes.name);\n        this.app.editPlaylistDescription(this.data.id, this.data.attributes.description.standard);\n        this.app.playlists.listing.forEach(playlist => {\n          if (playlist.id === this.data.id) {\n            playlist.attributes.name = this.data.attributes.name\n            playlist.attributes.description = this.data.attributes.description.standard\n          }\n        })\n        this.nameEditing = false\n        this.descriptionEditing = false\n      },\n      editPlaylistDescription() {\n        this.app.editPlaylistDescription(this.data.id, this.data.attributes.description.standard);\n        this.app.playlists.listing.forEach(playlist => {\n          if (playlist.id === this.data.id) {\n            playlist.attributes.description = this.data.attributes.description.standard\n          }\n        })\n        this.descriptionEditing = false\n      },\n      addToLibrary(id) {\n        app.mk.addToLibrary(id)\n        this.inLibrary = true\n        this.confirm = false\n      },\n      async removeFromLibrary(id) {\n        const params = { \"fields[songs]\": \"inLibrary\", \"fields[albums]\": \"inLibrary\", \"relate\": \"library\" };\n        var id = this.data.id ?? this.data.attributes.playParams.id\n        const res = await app.mkapi(this.data.attributes.playParams.kind ?? this.data.type, this.data.attributes.playParams.isLibrary ?? false, this.data.attributes.playParams.id ?? this.data.id, params);\n        if (res.data.data[0] && res.data.data[0].relationships && res.data.data[0].relationships.library && res.data.data[0].relationships.library.data && res.data.data[0].relationships.library.data.length > 0) {\n          id = res.data.data[0].relationships.library.data[0].id\n        }\n        let kind = this.data.attributes.playParams.kind ?? this.data.type ?? '';\n        const truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        app.mk.api.v3.music(`v1/me/library/${truekind}/${id.toString()}`, {},\n          {\n            fetchOptions: {\n              method: \"DELETE\"\n            }\n          })\n        this.inLibrary = false\n        this.confirm = false\n      },\n      editPlaylistName() {\n        if (this.data.attributes.canEdit && this.data.type === \"library-playlists\") {\n          this.nameEditing = true\n          setTimeout(() => {\n            document.querySelector(\".nameEdit\").focus()\n          }, 100)\n        }\n      },\n      editPlaylistDescription() {\n        if (this.data.attributes.canEdit && this.data.type === \"library-playlists\") {\n          this.descriptionEditing = true\n          setTimeout(() => {\n            document.querySelector(\".descriptionEdit\").focus()\n          }, 100)\n        }\n      },\n      buildContextMenu(index) {\n        let self = this\n        if (!this.data.attributes.canEdit) {\n          return\n        }\n        return {\n          normal: [\n            {\n              icon: \"./assets/feather/x-circle.svg\",\n              name: app.getLz('action.removeFromPlaylist'),\n              action: () => {\n                self.remove()\n              }\n            },\n          ],\n          multiple: [\n            {\n              icon: \"./assets/feather/x-circle.svg\",\n              name: app.getLz('action.removeFromPlaylist'),\n              action: () => {\n                self.remove()\n              }\n            },\n          ]\n        }\n      },\n      async put() {\n        if (!this.data.attributes.canEdit) {\n          return\n        }\n        console.log('sds', this.convert())\n        await app.mk.api.v3.music(\n          `/v1/me/library/playlists/${this.data.attributes.playParams.id}/tracks`,\n          {},\n          {\n            fetchOptions: {\n              method: \"PUT\",\n              body: JSON.stringify({\n                data: this.convert()\n              })\n            }\n          }\n        )\n      },\n      async remove() {\n        if (!this.data.attributes.canEdit) {\n          return\n        }\n        // for each app.selectedMediaItems splice the items from the playlist\n        for (let i = 0; i < app.selectedMediaItems.length; i++) {\n          let item = app.selectedMediaItems[i]\n          let index = this.data.relationships.tracks.data.findIndex(x => x.id == item.id)\n          if (index > -1) {\n            this.data.relationships.tracks.data.splice(index, 1)\n          }\n        }\n        await this.put()\n      },\n      convert() {\n        let pl_tracks = []\n        for (let i = 0; i < this.data.relationships.tracks.data.length; i++) {\n          pl_tracks.push({\n            id: this.data.relationships.tracks.data[i].id,\n            type: this.data.relationships.tracks.data[i].type\n          })\n        }\n        return pl_tracks\n      },\n      getRecursive(url) {\n        app.apiCall(app.musicBaseUrl + \"/v1/me/library/playlists/p.V7VYlrDso6kkYY/tracks?offset=100\", res => {\n          this.data.relationships.tracks.data = this.data.relationships.tracks.data.concat(res.data.data)\n          if (res.data.next) {\n            this.getRecursive(res.data.next)\n          }\n        })\n      },\n      async menu(event) {\n        let self = this\n        let artistId = null\n\n        if (typeof this.data.relationships.artists != \"undefined\") {\n          artistId = this.data.relationships.artists.data[0].id\n          if (this.data.relationships.artists.data[0].type == \"library-artists\") {\n            artistId = this.data.relationships.artists.data[0].relationships.catalog.data[0].id\n          }\n        }\n\n        let menuItems = {\n          headerItems: [\n            {\n              \"icon\": \"./assets/feather/heart.svg\",\n              \"id\": \"love\",\n              \"name\": app.getLz('action.love'),\n              \"hidden\": false,\n              \"disabled\": true,\n              \"action\": function() {\n                app.love(self.data)\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/heart.svg\",\n              \"id\": \"unlove\",\n              \"active\": true,\n              \"name\": app.getLz('action.unlove'),\n              \"hidden\": true,\n              \"action\": function() {\n                app.unlove(self.data)\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/thumbs-down.svg\",\n              \"id\": \"dislike\",\n              \"name\": app.getLz('action.dislike'),\n              \"hidden\": false,\n              \"disabled\": true,\n              \"action\": function() {\n                app.dislike(self.data)\n              }\n            },\n            {\n              \"icon\": \"./assets/feather/thumbs-down.svg\",\n              \"id\": \"undo_dislike\",\n              \"name\": app.getLz('action.undoDislike'),\n              \"active\": true,\n              \"hidden\": true,\n              \"action\": function() {\n                app.unlove(self.data)\n              }\n            },\n          ],\n          items: {\n            \"addToPlaylist\": {\n              name: app.getLz('action.addToPlaylist'),\n              \"icon\": \"./assets/feather/list.svg\",\n              action: () => {\n                app.selectedMediaItems = []\n                app.select_selectMediaItem(this.data.attributes.playParams.id ?? this.data.id, this.data.attributes.playParams.kind ?? this.data.type, 0, 0, this.data.attributes.playParams.isLibrary ?? false)\n                app.promptAddToPlaylist()\n              }\n            },\n            \"share\": {\n              name: app.getLz('term.share'),\n              icon: \"./assets/feather/share.svg\",\n              action: () => {\n                let route = \"\"\n                switch (this.data.type) {\n                  case 'albums':\n                    route = `/v1/catalog/${app.mk.storefrontId}/albums/${this.data.id}`\n                    break;\n                  case 'playlists':\n                    route = `/v1/catalog/${app.mk.storefrontId}/playlists/${this.data.id}`\n                    break;\n                  case \"library-playlists\":\n                    route = `/v1/me/library/playlists/${this.data.id}/catalog`\n                    break\n                  case \"library-albums\":\n                    route = `/v1/me/library/albums/${this.data.id}/catalog`\n                    break\n                }\n                if (route === '') {\n                  return\n                }\n                app.mk.api.v3.music(route).then(res => {\n                  console.log(res.data.data[0].attributes.url)\n                  app.copyToClipboard(res.data.data[0].attributes.url)\n                })\n              }\n            }\n          }\n        }\n        app.showMenuPanel(menuItems, event)\n\n        try {\n          let rating = await app.getRating(self.data)\n          if (rating == 0) {\n            menuItems.headerItems.find(x => x.id == 'love').disabled = false\n            menuItems.headerItems.find(x => x.id == 'dislike').disabled = false\n          } else if (rating == 1) {\n            menuItems.headerItems.find(x => x.id == 'unlove').hidden = false\n            menuItems.headerItems.find(x => x.id == 'love').hidden = true\n          } else if (rating == -1) {\n            menuItems.headerItems.find(x => x.id == 'undo_dislike').hidden = false\n            menuItems.headerItems.find(x => x.id == 'dislike').hidden = true\n          }\n        } catch (err) {\n        }\n\n\n      },\n      getItemParent: function(data) {\n        kind = data.attributes.playParams.kind;\n        id = data.attributes.playParams.id;\n        return `${kind}:${id}`\n      },\n      getFormattedDate: function() {\n        let date = (this.data.attributes.releaseDate ?? (this.data.attributes.lastModifiedDate ?? (this.data.attributes.dateAdded ?? '')))\n        let prefix = '';\n        if (date == null || date === \"\") return \"\";\n        switch (date) {\n          case this.data.attributes.releaseDate:\n            prefix = this.app.getLz('term.time.released') + ' '\n            break;\n          case this.data.attributes.lastModifiedDate:\n            prefix = this.app.getLz('term.time.updated') + ' '\n            break;\n          case this.data.attributes.dateAdded:\n            prefix = this.app.getLz('term.time.added') + ' '\n            break;\n        }\n        let month, year;\n        try {\n          const releaseDate = new Date(date);\n          // month = new Intl.DateTimeFormat(this.app.cfg.general.language.replace('_','-'), {month: 'long'}).format(releaseDate);\n          // date = releaseDate.getDate();\n          // year = releaseDate.getFullYear();\n          let formatted = ''\n          try {\n            formatted = new Intl.DateTimeFormat(this.app.cfg.general.language?.replace('_', '-') ?? 'en-US', {\n              day: 'numeric',\n              month: 'long',\n              year: 'numeric'\n            }).format(releaseDate);\n          } catch (e) {\n            // use the format in json instead\n            if (this.app.getLz('date.format') != null) {\n              formatted = new this.app.getLz('date.format').replace(\"${d}\", releaseDate.getDate()).replace(\"${m}\", releaseDate.getMonth()).replace(\"${y}\", releaseDate.getFullYear());\n            } else {\n              formatted = new Intl.DateTimeFormat('en-US', {\n                day: 'numeric',\n                month: 'long',\n                year: 'numeric'\n              }).format(releaseDate);\n            }\n          }\n          return prefix + formatted\n        } catch (e) {\n          return \"\"\n        }\n      },\n      play() {\n        function shuffleArray(array) {\n          for (var i = array.length - 1; i > 0; i--) {\n            var j = Math.floor(Math.random() * (i + 1));\n            var temp = array[i];\n            array[i] = array[j];\n            array[j] = temp;\n          }\n        }\n\n        const id = this.data.attributes.playParams?.id ?? this.data.id;\n        //console.log(\"1\")\n        const kind = this.data.attributes.playParams?.kind ?? this.data.type ?? '';\n        //console.log(\"1\")\n        if (kind == \"podcast-episodes\") {\n          kind = \"episode\"\n        }\n        const truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n\n        let query = (this.data ?? app.showingPlaylist).relationships.tracks.data.map(item => new MusicKit.MediaItem(item));\n\n        app.mk.stop().then(() => {\n          if (id != 'ciderlocal') {\n            app.mk.setQueue({ [truekind]: [id], parameters: { l: app.mklang } }).then(function() {\n              app.mk.play().then(function() {\n                if (query.length > 100) {\n                  let u = query.slice(100);\n                  if (app.mk.shuffleMode == 1) {\n                    shuffleArray(u)\n                  }\n                  app.mk.queue.append(u)\n                }\n              })\n            })\n          } else {\n            let u = app.library.localsongs.map(i => {\n              return i.id\n            })\n            app.mk.setQueue({ \"episodes\": u }).then(() => {\n              app.mk.play()\n            })\n          }\n        })\n\n\n      },\n      navClass(data) {\n        if (data && typeof data.views != \"undefined\") return \"\";\n        return \"d-none\";\n      },\n      async getCopiedPlayListSongs(event) {\n        if (event.ctrlKey && event.keyCode === 67) {\n          let urls = [];\n          app.selectedMediaItems.forEach(item => {\n            this.app.mk.api.v3.music(`/v1/me/library/songs/${item.id}`).then((response) => {\n              this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/songs/${response.data.data[0].attributes.playParams.catalogId}`).then((response1) => {\n                urls.push(response1.data.data[0].attributes.url)\n                navigator.clipboard.writeText(urls)\n              })\n            })\n          })\n          notyf.success(app.getLz('term.share.success'))\n        }\n      },\n      async pasteSongs(event) {\n        if (event.ctrlKey && event.keyCode === 86 && this.data.attributes.canEdit) {\n          let clipboard = await navigator.clipboard.readText()\n          let songs = []\n\n          clipboard = clipboard.split(\",\")\n          clipboard.forEach(item => {\n            songs.push({\n              id: item.substring(item.indexOf(\"i=\") + 2, item.length),\n              type: \"songs\",\n            })\n          })\n\n          this.app.mk.api.v3.music(`/v1/me/library/playlists/${this.data.id}/tracks`, {}, {\n            fetchOptions: {\n              method: \"POST\",\n              body: JSON.stringify({\n                data: songs\n              })\n            }\n          }).then((response) => {\n            songs.forEach(item => {\n              this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/songs/${item.id}`).then((response1) => {\n                this.displayListing.push(response1.data.data[0])\n              })\n            })\n          })\n        }\n      },\n      toggleSearch() {\n        this.showSearch = !this.showSearch;\n\n        if (!this.showSearch && this.searchQuery != \"\") {\n          // Clear search query if the search bar becomes hidden\n          this.searchQuery = \"\";\n          this.search();\n        } else if (this.showSearch) {\n          // Focus search bar\n          this.$nextTick(() => {\n            this.$refs[\"search-bar\"].focus();\n          });\n        }\n      },\n      search() {\n        let filtered = [];\n\n        if (this.searchQuery == \"\") {\n          filtered = this.data.relationships.tracks.data;\n        } else {\n          filtered = this.data.relationships.tracks.data.filter((item) => {\n            let itemName = item.attributes.name.toLowerCase();\n            let searchTerm = this.searchQuery.toLowerCase();\n            let artistName = \"\";\n            let albumName = \"\";\n            if (item.attributes.artistName != null) {\n              artistName = item.attributes.artistName.toLowerCase();\n            }\n            if (item.attributes.albumName != null) {\n              albumName = item.attributes.albumName.toLowerCase();\n            }\n\n            // remove any non-alphanumeric characters and spaces from search term and item name\n            searchTerm = searchTerm.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n            itemName = itemName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n            artistName = artistName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n            albumName = albumName.replace(/[^\\p{L}\\p{N} ]/gu, \"\");\n\n            let match = itemName.includes(searchTerm) || artistName.includes(searchTerm);\n            // only include album name in playlists\n            // this allows to search for the title track (itemName == albumName)\n            if (this.inPlaylist) match = match || albumName.includes(searchTerm)\n\n            if (match) return item;\n          });\n        }\n\n        if (!this.hasNestedPlaylist) {\n          // Regular album/playlist\n          this.displayListing = filtered;\n        } else {\n          // Album with multiple discs\n          this.generateNestedPlaylist(filtered);\n        }\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/cider-profile.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-socialprofile\">\n    <div class=\"content-inner artist-page profile-page\">\n        <div class=\"artist-header\" :style=\"getArtistPalette(data)\">\n            <div class=\"row\">\n                <div class=\"col-sm\" style=\"width: auto;\">\n                    <div class=\"artist-image\">\n                        <mediaitem-artwork\n                                shadow=\"large\"\n                                :url=\"data.attributes.artwork ? data.attributes.artwork.url : ''\"\n                                size=\"220\" type=\"artists\"></mediaitem-artwork>\n                    </div>\n                </div>\n                <div class=\"col cider-flex-center\">\n                    <h1>{{ data.attributes.name }}</h1>\n                </div>\n            </div>\n        </div>\n        <div class=\"artist-body\">\n            <template v-if=\"data.relationships && data.relationships['shared-playlists']\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3>{{ 'Shared Playlists' ?? \"\"}}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\"\n                         v-if=\"data.relationships['shared-playlists'].data.length >= 10\">\n                        <button class=\"cd-btn-seeall\"\n                                @click=\"app.showCollection(data.relationships['shared-playlists'],'Shared Playlists' ?? '', 'default')\">\n                            {{app.getLz('term.seeAll')}}\n                        </button>\n                    </div>\n                </div>\n                <mediaitem-square :item=\"item\" v-for=\"item in data.relationships['shared-playlists'].data.limit(10)\">\n                </mediaitem-square>\n            </template>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('cider-socialprofile', {\n    template: \"#cider-socialprofile\",\n    props: ['data'],\n    data: function() {\n      return {\n        topSongsExpanded: false,\n        app: this.$root\n      }\n    },\n    methods: {\n      getArtistPalette(artist) {\n        if (artist?.attributes?.artwork != null) {\n          return {\n            \"background\": \"#\" + artist[\"attributes\"][\"artwork\"][\"bgColor\"],\n            \"color\": \"#\" + artist[\"attributes\"][\"artwork\"][\"textColor1\"],\n          }\n        } else {\n          return {\n            \"background\": \"#000000\",\n            \"color\": \"#ffffff\",\n          }\n        }\n      },\n      getTopResult() {\n        if (this.search.results[\"meta\"]) {\n          return this.search.results[this.search.results.meta.results.order[0]][\"data\"][0]\n        } else {\n          return false;\n        }\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/collection-list.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-collection-list\">\n    <div class=\"content-inner collection-page\">\n        <h3 class=\"header-text\" v-observe-visibility=\"{callback: headerVisibility}\">{{ title }}</h3>\n        <div v-if=\"data['data'] != 'null'\" class=\"well itemContainer\" :class=\"getClasses()\">\n            <template v-for=\"(item, key) in data.data\">\n                <template v-if=\"item.type == 'artists'\">\n                    <mediaitem-square :item=\"item\"></mediaitem-square>\n                </template>\n                <template v-else>\n                    <mediaitem-list-item\n                            v-if=\"getKind(item) == 'song'\"\n                            :index=\"key\"\n                            :item=\"item\"></mediaitem-list-item>\n                    <mediaitem-square v-else :item=\"item\" :type=\"getKind(item)\"></mediaitem-square>\n                </template>\n            </template>\n            <button v-if=\"triggerEnabled\" style=\"opacity:0;height: 32px;\"\n                    v-observe-visibility=\"{callback: visibilityChanged}\">{{this.app.getLz('term.showMore')}}\n            </button>\n        </div>\n        <transition name=\"fabfade\">\n            <button class=\"top-fab\" v-show=\"showFab\" @click=\"scrollToTop()\"\n                    :aria-label=\"app.getLz('action.scrollToTop')\">\n                <%- include(\"../svg/arrow-up.svg\") %>\n            </button>\n        </transition>\n        <div class=\"well itemContainer\" v-show=\"loading\">\n            <div class=\"spinner\"></div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('cider-collection-list', {\n    template: \"#cider-collection-list\",\n    props: {\n      data: {\n        type: Object,\n        required: true\n      },\n      title: {\n        type: String,\n        required: false\n      },\n      type: {\n        type: String,\n        required: false,\n        default: \"artists\"\n      }\n    },\n    data: function() {\n      return {\n        triggerEnabled: true,\n        canSeeTrigger: false,\n        showFab: false,\n        commonKind: \"song\",\n        api: this.$root.mk.api,\n        loading: false,\n        app: this.$root,\n      }\n    },\n    methods: {\n      getClasses() {\n        if ((this.data?.data?.length ?? 0) > 0) {\n          let item = this.data.data[0]\n          if (typeof item.kind != \"undefined\") {\n            this.commonKind = item.kind;\n            return item.kind\n          }\n          if (typeof item.attributes.playParams != \"undefined\") {\n            this.commonKind = item.attributes.playParams.kind\n            return item.attributes.playParams.kind\n          }\n          if (this.commonKind != \"song\") {\n            return \"collection-list-square\";\n          } else {\n            return \"\";\n          }\n        } else {\n          return \"\";\n        }\n\n      },\n      getKind(item) {\n        if (typeof item.kind != \"undefined\") {\n          //  this.commonKind = item.kind;\n          return item.kind\n        }\n        if (typeof item.attributes.playParams != \"undefined\") {\n          //  this.commonKind = item.attributes.playParams.kind\n          return item.attributes.playParams.kind\n        }\n        return this.commonKind\n      },\n      scrollToTop() {\n        let target = document.querySelector(\".header-text\")\n        document.querySelector(\"#app-content\").scrollTo({\n          top: 0,\n          left: 0,\n          behavior: 'smooth'\n        })\n      },\n      getNext() {\n        let self = this\n        this.triggerEnabled = false;\n        if (typeof this.data.next == \"undefined\") {\n          return\n        }\n        this.loading = true\n\n        this.api.v3.music(this.data.next, app.collectionList.requestBody).then((response) => {\n          console.log(response)\n          if (!app.collectionList.response.groups) {\n            this.data.data = this.data.data.concat(response.data.data);\n            if (response.data.next) {\n              this.data.next = response.data.next;\n              this.triggerEnabled = true;\n            }\n            this.loading = false\n          } else {\n            if (!response.data.results[app.collectionList.response.groups]) {\n              this.loading = false\n              return\n            }\n            this.data.data = this.data.data.concat(response.data.results[app.collectionList.response.groups].data);\n            if (response.data.results[app.collectionList.response.groups].next) {\n              this.data.next = response.data.results[app.collectionList.response.groups].next;\n              this.triggerEnabled = true;\n              this.loading = false\n            }\n          }\n        })\n      },\n      headerVisibility: function(isVisible, entry) {\n        if (isVisible) {\n          this.showFab = false;\n        } else {\n          this.showFab = true;\n        }\n      },\n      visibilityChanged: function(isVisible, entry) {\n        if (isVisible) {\n          this.canSeeTrigger = true;\n          this.getNext();\n        } else {\n          this.canSeeTrigger = false;\n        }\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/connect-linked.ejs",
    "content": "<script type=\"text/x-template\" id=\"connected\">\n    <div style=\"display:flex;width:100%;height:100%;padding-top: var(--navigationBarHeight);position:absolute;top:0;left:0;\">\n        <webview id=\"foo\" src=\"https://cider.sh\" style=\"display:inline-flex; width:100%;\"></webview>\n    </div>\n</script>\n<script>\n  Vue.component('connected', {\n    template: '#connected',\n    async mounted() {\n      ipcRenderer.send('get-connected-url')\n      ipcRenderer.on('send-connected-url', (event, url) => {\n        this.url = url\n        app.webview.src = url\n        document.getElementById('foo').src = url;\n      })\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/groupings.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-groupings\">\n    <div class=\"content-inner\">\n        <template v-if=\"data != null\">\n            <h1 class=\"header-text\">{{data.attributes?.name}}</h1>\n\n            <template v-if=\"data.relationships && data.relationships.tabs\">\n                <template v-for=\"(recom,index) in data.relationships.tabs.data[0].relationships.children.data\">\n                    <div class=\"row\">\n                        <div class=\"col\" v-if=\"recom.attributes.name != 'Chart Set'\">\n                            <h3>{{ recom.attributes.name ?? \"\"}}</h3>\n                        </div>\n                        <div class=\"col-auto cider-flex-center\"\n                             v-if=\"index != 0 && recom.relationships && ((recom.relationships.children &&  recom.relationships.children.data.length > 10) || (recom.relationships.contents && recom.relationships.contents.data.length > 10))\">\n                            <button class=\"cd-btn-seeall\" v-if=\"recom.relationships.room\"\n                                    @click=\"app.showRoom(recom.relationships.room?.data[0].href)\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                            <button class=\"cd-btn-seeall\" v-else\n                                    @click=\"app.showCollection(recom.relationships.children ? recom.relationships.children : recom.relationships.contents, recom.attributes.name ?? '', 'listen_now')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <template\n                            v-if=\"(recom.relationships != null && ((recom.relationships.children && recom.relationships.children.data) || (recom.relationships.contents && recom.relationships.contents.data)))\">\n                        <template\n                                v-if=\"index === 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\">\n                            <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                                  :browsesp=\"index == 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\"\n                                                                  :kind=\"recom.attributes.editorialElementKind\"\n                                                                  :items=\"recom.relationships.children ? recom.relationships.children.data : recom.relationships.contents.data\"></mediaitem-scroller-horizontal-mvview>\n                        </template>\n                        <template v-else-if=\"(['327']).includes(recom.attributes.editorialElementKind)\">\n                            <div class=\"mediaitem-list-item__grid\">\n                                <listitem-horizontal :items=\"recom.relationships.contents.data.limit(20)\">\n                                </listitem-horizontal>\n                            </div>\n                        </template>\n                        <template v-else-if=\"(['385']).includes(recom.attributes.editorialElementKind)\">\n                            <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                                  :kind=\"recom.attributes.editorialElementKind\"\n                                                                  :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                        </template>\n                        <template v-else-if=\"recom.attributes.name == 'Chart Set'\">\n                            <!-- ignored -->\n                        </template>\n                        <template v-else>\n                            <mediaitem-scroller-horizontal-large\n                                    :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                        </template>\n                    </template>\n                    <template v-else>\n                        <template\n                                v-if=\"recom.attributes.links && recom.attributes.editorialElementKind.includes('391')\">\n                            <div class=\"grouping-container\">\n                                <button class=\"grouping-btn\" @click=\"$root.goToGrouping(link.url)\"\n                                        v-for=\"link in recom.attributes.links\">{{ link.label }}\n                                </button>\n                            </div>\n                        </template>\n                    </template>\n                </template>\n            </template>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component(\"cider-groupings\", {\n    template: \"#cider-groupings\",\n    data: function() {\n      return {\n        data: null,\n        app: this.$root,\n        query: \"\",\n      };\n    },\n    async mounted() {\n      const queryDefaults = {\n        \"platform\": \"web\",\n        \"l\": this.$root.mklang,\n        \"extend\": \"editorialArtwork,artistUrl\",\n        \"omit[resource:artists]\": \"relationships\",\n        \"include[groupings]\": \"curator\",\n        \"include[albums]\": \"artists\",\n        \"include[songs]\": \"artists\",\n        \"include[music-videos]\": \"artists\",\n        \"fields[artists]\": \"name,url,artwork,editorialArtwork,genreNames,editorialNotes\",\n      }\n      const hash = window.location.hash;\n      // get everything after the first / character but keep everything afterwards\n      const query = hash.substring(hash.indexOf(\"/\") + 1, hash.indexOf(\"&\") > 0 ? hash.indexOf(\"&\") : hash.length);\n      this.query = query;\n      // if(!this.query.includes(\"?\")) {\n      //   this.query += queryDefaults;\n      // }\n      console.debug(query);\n      const result = await this.$root.mk.api.v3.music(\n        `/v1/editorial/${this.$root.mk.storefrontId}/groupings/${this.query}`\n        , !this.query.includes(\"&\") ? queryDefaults : { \"platform\": \"web\" });\n      this.data = result.data.data[0];\n\n      console.log(this.data);\n\n      //this.$root.getBrowsePage();\n    },\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/home.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-home\">\n    <div class=\"content-inner home-page\">\n        <div v-if=\"page == 'main'\">\n            <div class=\"row\">\n                <div class=\"col\">\n                    <div class=\"row\">\n                        <div class=\"col nopadding\">\n                            <h3>{{app.getLz('home.recentlyPlayed')}}</h3>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"cd-btn-seeall\" @click=\"seeAllHistory()\">{{app.getLz('term.history')}}\n                            </button>\n                            <button class=\"cd-btn-seeall\" @click=\"seeAllRecentlyPlayed()\">{{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <div class=\"well artistfeed-well\">\n                        <template v-if=\"isSectionReady('recentlyPlayed')\">\n                            <mediaitem-list-item v-for=\"item in recentlyPlayed.limit(6)\"\n                                                 :item=\"item\" v-bind:key=\"item.id\"></mediaitem-list-item>\n                        </template>\n                        <div class=\"spinner\" v-else></div>\n                    </div>\n                </div>\n                <div class=\"col\">\n                    <div class=\"row\">\n                        <div class=\"col nopadding\">\n                            <h3>{{app.getLz('home.artistsFeed')}}</h3>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"cd-btn-seeall\" @click=\"syncFavorites()\" v-if=\"!syncingFavs\">\n                                {{app.getLz('home.syncFavorites')}}\n                            </button>\n                            <div class=\"spinner\" style=\"height: 26px;\" v-else></div>\n                            <button class=\"cd-btn-seeall\" @click=\"app.appRoute('artist-feed')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <div class=\"well artistfeed-well\" style=\"margin-top:0;\">\n                        <template v-if=\"artistFeed.length > 0\">\n                            <mediaitem-list-item v-for=\"item in artistFeed.limit(6)\" :item=\"item\" v-bind:key=\"item.id\"></mediaitem-list-item>\n                        </template>\n                        <div class=\"spinner\" v-else-if=\"followedArtists.length > 0\"></div>\n                        <div class=\"no-artist\" v-else> {{app.getLz('home.artistsFeed.noArtist')}}</div>\n                    </div>\n                </div>\n            </div>\n            <!--            <div class=\"row\" v-if=\"app.isDev\">-->\n            <!--                <div class=\"col\">-->\n            <!--                    <h3>Your Favorites</h3>-->\n            <!--                    <div class=\"well\">-->\n            <!--                        <div class=\"hint-text\" v-if=\"favorites.length == 0\">Items you have added to your favorites will-->\n            <!--                            appear here.-->\n            <!--                        </div>-->\n            <!--                        <mediaitem-scroller-horizontal kind=\"small\" :items=\"favorites\"-->\n            <!--                                                       :item=\"item\"></mediaitem-scroller-horizontal>-->\n            <!--                    </div>-->\n            <!--                </div>-->\n            <!--            </div>-->\n            <div class=\"row\" v-if=\"!seenReplay\">\n                <div class=\"col\">\n                    <button class=\"md-btn md-btn-block md-btn-replay--hero\" @click=\"$root.appRoute('replay')\">\n                        {{$root.getLz('term.replay')}} {{ year }}\n                    </button>\n                </div>\n            </div>\n            <div class=\"row\">\n                <div class=\"col\">\n                    <div class=\"row\">\n                        <div class=\"col nopadding\">\n                            <h3>{{app.getLz('home.madeForYou')}}</h3>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"md-btn md-btn-replay\" v-if=\"seenReplay\" @click=\"$root.appRoute('replay')\">\n                                {{$root.getLz('term.replay')}} {{ year }}\n                            </button>\n                        </div>\n                    </div>\n                    <div class=\"well\">\n                        <mediaitem-scroller-horizontal :items=\"madeForYou\" v-if=\"isSectionReady('madeForYou')\">\n                        </mediaitem-scroller-horizontal>\n                        <div class=\"spinner\" v-else></div>\n                    </div>\n                </div>\n            </div>\n            <div class=\"row\" v-if=\"friendsListeningTo && friendsListeningTo.length > 0\">\n                <div class=\"col\">\n                    <div class=\"row\">\n                        <div class=\"col nopadding\">\n                            <h3>{{app.getLz('home.friendsListeningTo')}}</h3>\n                        </div>\n                        <div class=\"col-auto nopadding cider-flex-center\">\n                            <button class=\"cd-btn-seeall\" @click=\"app.showSocialListeningTo()\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <div class=\"well\">\n                        <mediaitem-scroller-horizontal :items=\"friendsListeningTo\"\n                                                       v-if=\"isSectionReady('friendsListeningTo')\">\n                        </mediaitem-scroller-horizontal>\n                        <div class=\"spinner\" v-else></div>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-home', {\n    template: '#cider-home',\n    data: function() {\n      return {\n        app: this.$root,\n        followedArtists: this.$root.cfg.home.followedArtists,\n        favoriteItems: this.$root.cfg.home.favoriteItems,\n        madeForYou: [],\n        recentlyPlayed: [],\n        friendsListeningTo: [],\n        replayPlaylists: [],\n        favorites: [],\n        profile: {},\n        modify: 0,\n        artistFeed: [],\n        showingArtistFeed: false,\n        page: \"main\",\n        sectionsReady: [],\n        year: new Date().getFullYear(),\n        seenReplay: localStorage.getItem('seenReplay'),\n        syncingFavs: false\n      }\n    },\n    async mounted() {\n      let self = this\n      this.getListenNowData()\n      await this.getArtistFeed()\n      await this.getFavorites()\n      await this.getRecentlyPlayed()\n      if (new Date().getMonth() == 11) {\n        this.seenReplay = false\n        localStorage.setItem('seenReplay', false)\n      }\n    },\n    methods: {\n      async syncFavorites() {\n        this.syncingFavs = true\n        await app.syncFavorites()\n        await this.getArtistFeed()\n        this.syncingFavs = false\n      },\n      async seeAllRecentlyPlayed() {\n        let hist = await app.mk.api.v3.music(`/v1/me/recent/played`, {\n          l: this.$root.mklang,\n          include: 'tracks',\n          'include[albums]': 'catalog,tracks,artists',\n          'include[songs]': 'catalog,artists',\n        })\n        app.showCollection(hist.data, app.getLz('home.recentlyPlayed'))\n      },\n      async seeAllHistory() {\n        let hist = await app.mk.api.v3.music(`/v1/me/recent/played/tracks`, {\n          l: this.$root.mklang\n        })\n        app.showCollection(hist.data, app.getLz('term.history'))\n      },\n      isSectionReady(section) {\n        return this.sectionsReady.includes(section)\n      },\n      removeFavoriteContext() {\n        let self = this\n        return {\n          name: \"Remove from Favorites\",\n          action: function(item) {\n            let index = self.favoriteItems.findIndex(x => x.id == item.id)\n            if (index > -1) {\n              self.favoriteItems.splice(index, 1)\n              self.app.cfg.home.favoriteItems = self.favoriteItems\n            }\n          }\n        }\n      },\n      async getFavorites() {\n        let self = this\n        let libraryPlaylists = []\n        let playlists = []\n        for (let item of this.favoriteItems) {\n          if (item.type == \"library-playlists\") {\n            libraryPlaylists.push(item.id)\n          } else if (item.type == \"playlists\") {\n            playlists.push(item.id)\n          }\n        }\n        if (playlists.length != 0) {\n          this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/playlists/${playlists.toString()}`, {\n            l: this.$root.mklang\n          }).then(playlistsData => {\n            self.favorites.push(...playlistsData.data)\n          })\n        }\n        if (libraryPlaylists.length != 0) {\n          this.app.mk.api.v3.music(`v1/me/library/playlists/${playlists.toString()}`, {\n            l: this.$root.mklang\n          }).then(playlistsData => {\n            self.favorites.push(...playlistsData.data)\n          })\n        }\n      },\n      async getArtistFeed() {\n        let artists = this.followedArtists\n        let self = this\n        this.artistFeed = []\n        let chunks = []\n        for (let artistIdx = 0; artistIdx < artists.length; artistIdx += 50) {\n          chunks.push(artists.slice(artistIdx, artistIdx + 50));\n        }\n        try {\n          const chunkArtistData = await Promise.all(chunks.map(chunk =>\n            this.app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists?ids=${chunk.toString()}&views=latest-release&include[songs]=albums&fields[albums]=artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url,trackCount&limit[artists:top-songs]=2&art[url]=f`)))\n          chunkArtistData.forEach(chunkResult =>\n            chunkResult.data.data.forEach(item => {\n              if (item.views[\"latest-release\"].data.length != 0) {\n                self.artistFeed.push(item.views[\"latest-release\"].data[0])\n              }\n            }))\n          // sort artistFeed by attributes.releaseDate descending, date is formatted as \"YYYY-MM-DD\"\n          this.artistFeed.sort((a, b) => {\n            let dateA = new Date(a.attributes.releaseDate)\n            let dateB = new Date(b.attributes.releaseDate)\n            return dateB - dateA\n          })\n        } catch (error) {\n        }\n      },\n      async getRecentlyPlayed() {\n        let hist = await app.mk.api.v3.music(`/v1/me/recent/played`, {\n          l: this.$root.mklang,\n          include: 'tracks',\n          'include[albums]': 'catalog,tracks,artists',\n          'include[songs]': 'catalog,artists',\n        })\n        this.recentlyPlayed = hist.data.data\n      },\n      async getListenNowData() {\n        let self = this\n        this.app.mk.api.v3.music(`/v1/me/recommendations?timezone=${encodeURIComponent(app.formatTimezoneOffset())}&name=listen-now&with=friendsMix,library,social&art[social-profiles:url]=c&art[url]=c,f&omit[resource]=autos&relate[editorial-items]=contents&extend=editorialCard,editorialVideo&extend[albums]=artistUrl&extend[library-albums]=artistUrl,editorialVideo&extend[playlists]=artistNames,editorialArtwork,editorialVideo&extend[library-playlists]=artistNames,editorialArtwork,editorialVideo&extend[social-profiles]=topGenreNames&include[albums]=artists&include[songs]=artists&include[music-videos]=artists&fields[albums]=artistName,artistUrl,artwork,contentRating,editorialArtwork,editorialVideo,name,playParams,releaseDate,url&fields[artists]=name,url&extend[stations]=airDate,supportsAirTimeUpdates&meta[stations]=inflectionPoints&types=artists,albums,editorial-items,library-albums,library-playlists,music-movies,music-videos,playlists,stations,uploaded-audios,uploaded-videos,activities,apple-curators,curators,tv-shows,social-upsells&platform=web&l=${this.$root.mklang}`).then((data) => {\n          console.log(data.data.data[1])\n          try {\n            self.madeForYou = data.data.data.filter(section => {\n              if (section.meta.metrics.moduleType == \"6\") {\n                return section\n              }\n              ;\n            })[0].relationships.contents.data\n          } catch (err) {\n          }\n          self.sectionsReady.push(\"madeForYou\")\n\n          try {\n            self.friendsListeningTo = data.data.data.filter(section => {\n              if (section.meta.metrics.moduleType == \"11\") {\n                return section\n              }\n              ;\n            })[0].relationships.contents.data\n          } catch (err) {\n          }\n          self.sectionsReady.push(\"recentlyPlayed\")\n          self.sectionsReady.push(\"friendsListeningTo\")\n        });\n\n        app.mk.api.v3.music(\"/v1/me/social/profile/\").then((response) => {\n          self.profile = response.data.data[0]\n        })\n\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/installed-themes.ejs",
    "content": "//Not used for Now\n\n<!-- <script type=\"text/x-template\" id=\"installed-themes\">\n    <div class=\"installed-themes-page\">\n        <div class=\"gh-header\">\n            <div class=\"row\">\n                <div class=\"col nopadding\">\n                    <h1 class=\"header-text\">\n                        {{ $root.getLz(\"settings.option.visual.theme.manageStyles\") }}\n                    </h1>\n                </div>\n                <div class=\"col-auto nopadding flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.appRoute('themes-github')\">\n                        {{$root.getLz('settings.option.visual.theme.github.explore')}}\n                    </button>\n                </div>\n                <div class=\"col-auto  flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.checkForThemeUpdates()\">\n                        {{ $root.getLz('settings.option.visual.theme.checkForUpdates') }}\n                    </button>\n                </div>\n                <div class=\"col-auto nopadding flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"openThemesFolder()\">\n                        {{$root.getLz('settings.option.visual.theme.github.openfolder')}}\n                    </button>\n                </div>\n            </div>\n        </div>\n        <div class=\"gh-content\">\n            <div class=\"repos-list\">\n                <div class=\"repo-header\">\n                    <h4>{{$root.getLz('settings.option.visual.theme.github.available')}}</h4>\n                </div>\n                <ul class=\"list-group list-group-flush\">\n                    <template v-for=\"theme in themes\">\n                        <li @click=\"addStyle(theme.file)\"\n                        @contextmenu=\"contextMenu($event, theme)\"\n                        class=\"list-group-item list-group-item-dark\"\n                        :class=\"{'applied': $root.cfg.visual.styles.includes(theme.file)}\">\n\n                            <b-row>\n                                <b-col class=\"themeLabel\">{{theme.name}}</b-col>\n                                <template v-if=\"$root.cfg.visual.styles.includes(theme.file)\">\n                                    <b-col sm=\"auto\" v-if=\"theme.pack\">\n                                        <button class=\"themeContextMenu codicon codicon-package\"></button>\n                                    </b-col>\n                                    <b-col sm=\"auto\">\n                                        <button class=\"themeContextMenu codicon codicon-check\"></button>\n                                    </b-col>\n                                </template>\n                                <template v-else>\n                                    <b-col sm=\"auto\" v-if=\"theme.pack\">\n                                        <button class=\"themeContextMenu codicon codicon-package\"></button>\n                                    </b-col>\n                                    <b-col sm=\"auto\">\n                                        <button @click.stop=\"contextMenu($event, theme)\" class=\"themeContextMenu codicon codicon-list-unordered\"></button>\n                                    </b-col>\n                                </template>\n\n                            </b-row>\n                        </li>\n                        <li @click=\"addStyle(packEntry.file)\"\n                        @contextmenu=\"contextMenu($event, theme)\"\n                        class=\"list-group-item list-group-item-dark addon\"\n                        v-for=\"packEntry in theme.pack\"\n                        :class=\"{'applied': $root.cfg.visual.styles.includes(packEntry.file)}\"\n                        v-if=\"theme.pack\">\n\n                        <b-row>\n                            <b-col class=\"themeLabel\">{{packEntry.name}}</b-col>\n                            <template v-if=\"$root.cfg.visual.styles.includes(packEntry.file)\">\n                                <b-col sm=\"auto\">\n                                    <button class=\"themeContextMenu codicon codicon-check\"></button>\n                                </b-col>\n                            </template>\n                            <template v-else>\n                                <b-col sm=\"auto\">\n                                    <button class=\"themeContextMenu codicon codicon-diff-added\"></button>\n                                </b-col>\n                            </template>\n                        </b-row>\n                    </li>\n                    </template>\n                </ul>\n            </div>\n\n            <div class=\"style-editor-container\">\n                <div class=\"repo-header\">\n                    <h4>{{ $root.getLz(\"settings.option.visual.theme.github.applied\") }} </h4>\n                </div>\n                <stylestack-editor ref=\"stackEditor\"  v-if=\"themes.length != 0\" :themes=\"themes\"/>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n    // do not translate\n    Vue.component('stylestack-editor', {\n        /*html*/\n        template: `\n            <div class=\"stylestack-editor\" >\n                <draggable class=\"list-group\" v-model=\"$root.cfg.visual.styles\" @end=\"$root.reloadStyles()\">\n                    <b-list-group-item variant=\"dark\" v-for=\"theme in $root.cfg.visual.styles\" :key=\"theme\">\n                        <b-row>\n                            <b-col sm=\"auto\">\n                                <div class=\"handle codicon codicon-grabber\"></div>\n                            </b-col>\n                            <b-col class=\"themeLabel\">{{getThemeName(theme)}}</b-col>\n                            <b-col sm=\"auto\">\n                                <button class=\"removeItem codicon codicon-close\" @click=\"remove(theme)\"></button>\n                            </b-col>\n                        </b-row>\n                        </b-list-group-item>\n                </draggable>\n            </div>\n        `,\n        props: {\n            themes: {\n                type: Array,\n                default: [],\n                required: true\n            }\n        },\n        data: function () {\n            return {\n                selected: null,\n                newTheme: null,\n                themeList: []\n            }\n        },\n        mounted() {\n            console.log(this.themes)\n            this.themeList = [...this.themes]\n\n            this.themeList.forEach(theme => {\n                if (theme.pack) {\n                    theme.pack.forEach(packEntry => {\n                        packEntry.file = theme.file.replace('index.less', '') + packEntry.file\n                        this.themeList.push(packEntry)\n                    })\n                }\n            })\n        },\n        methods: {\n            gitHubExplore() {\n                this.$root.appRoute(\"themes-github\")\n            },\n            getThemeName(filename) {\n                try {\n                    return this.themeList.find(theme => theme.file === filename).name;\n                } catch (e) {\n                    return filename;\n                }\n            },\n            moveUp() {\n                const styles = this.$root.cfg.visual.styles\n                const index = styles.indexOf(this.selected)\n                if (index > 0) {\n                    styles.splice(index, 1)\n                    styles.splice(index - 1, 0, this.selected)\n                }\n                this.$root.reloadStyles()\n            },\n            moveDown() {\n                const styles = this.$root.cfg.visual.styles\n                const index = styles.indexOf(this.selected)\n                if (index < styles.length - 1) {\n                    styles.splice(index, 1)\n                    styles.splice(index + 1, 0, this.selected)\n                }\n                this.$root.reloadStyles()\n            },\n            remove(style) {\n                const styles = this.$root.cfg.visual.styles\n                const index = styles.indexOf(style)\n                styles.splice(index, 1)\n                this.$root.reloadStyles()\n            },\n            addStyle(style) {\n                const styles = this.$root.cfg.visual.styles\n                styles.push(style)\n                this.$root.reloadStyles()\n            }\n        }\n    })\n</script>\n\n<script>\n    Vue.component('installed-themes', {\n        template: \"#installed-themes\",\n        props: [],\n        data: function () {\n            return {\n                repos: [],\n                openRepo: {\n                    id: -1,\n                    name: '',\n                    description: '',\n                    html_url: '',\n                    stargazers_count: 0,\n                    owner: {\n                        avatar_url: ''\n                    },\n                    readme: \"\"\n                },\n                themesInstalled: [],\n                themes: []\n            }\n        },\n        mounted() {\n            this.getThemesList();\n        },\n        methods: {\n            getThemesList() {\n                let self = this\n                let themes = ipcRenderer.sendSync(\"get-themes\")\n                themes.unshift({\n                    name: \"Acrylic Grain\",\n                    file: \"grain.less\"\n                })\n                themes.unshift({\n                    name: \"Sweetener\",\n                    file: \"sweetener.less\"\n                })\n                themes.unshift({\n                    name: \"Reduce Visuals\",\n                    file: \"reduce_visuals.less\"\n                })\n                // themes.unshift({\n                //     name: \"Inline Drawer\",\n                //     file: \"inline_drawer.less\"\n                // })\n                themes.unshift({\n                    name: \"Dark\",\n                    file: \"dark.less\"\n                })\n                this.themes = themes\n            },\n            contextMenu(event, theme) {\n                let self = this\n                let menu = {\n                    items: {\n                        \"uninstall\": {\n                            name: app.getLz(\"settings.option.visual.theme.uninstall\"),\n                            disabled: true,\n                            action: () => {\n                                app.confirm(app.stringTemplateParser(app.getLz(\"settings.prompt.visual.theme.uninstallTheme\"), {\n                                    theme: theme.name ?? theme.file\n                                }), (res) => {\n                                    if (res) {\n                                        console.debug(theme)\n                                        ipcRenderer.once(\"theme-uninstalled\", (event, args) => {\n                                            console.debug(event, args)\n                                            self.getThemesList()\n                                        })\n                                        ipcRenderer.invoke(\"uninstall-theme\", theme.path)\n                                    }\n                                })\n\n                            }\n                        },\n                        \"viewInfo\": {\n                            name: app.getLz(\"settings.option.visual.theme.viewInfo\"),\n                            disabled: true,\n                            action: () => {\n\n                            }\n                        }\n                    }\n                }\n                if (theme.path) {\n                    menu.items.uninstall.disabled = false\n                }\n                this.$root.showMenuPanel(menu, event)\n            },\n            openThemesFolder() {\n                ipcRenderer.invoke(\"open-path\", \"themes\")\n            },\n            getInstalledThemes() {\n                let self = this\n                const themes = ipcRenderer.sendSync(\"get-themes\")\n                // for each theme, get the github_repo property and push it to the themesInstalled array, if not blank\n                themes.forEach(theme => {\n                    if (theme.github_repo !== \"\" && typeof theme.commit != \"\") {\n                        self.themesInstalled.push(theme.github_repo.toLowerCase())\n                    }\n                })\n            },\n            addStyle(filename) {\n                this.$refs.stackEditor.addStyle(filename)\n            },\n            showRepo(repo) {\n                const self = this\n                const readmeUrl = `https://raw.githubusercontent.com/${repo.full_name}/main/README.md`;\n                var requestOptions = {\n                    method: 'GET',\n                    redirect: 'follow'\n                };\n\n                fetch(readmeUrl, requestOptions)\n                    .then(response => response.text())\n                    .then(result => {\n                        self.openRepo = repo\n                        self.openRepo.readme = self.convertReadMe(result);\n                    })\n                    .catch(error => {\n                        self.openRepo = repo\n                        self.openRepo.readme = `This repository doesn't have a README.md file.`;\n                        console.log('error', error)\n                    });\n            },\n            convertReadMe(text) {\n                return marked.parse(text)\n            },\n            installThemeRepo(repo) {\n                let self = this\n                let msg = app.stringTemplateParser(app.getLz('settings.option.visual.theme.github.install.confirm'), {\n                    repo: repo.full_name\n                });\n                app.confirm(msg, (res) => {\n                    if (res) {\n                        ipcRenderer.once(\"theme-installed\", (event, arg) => {\n                            if (arg.success) {\n                                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                                self.getInstalledThemes()\n                                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n                            } else {\n                                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n                            }\n                        });\n                        ipcRenderer.invoke(\"get-github-theme\", repo.html_url)\n                    }\n                })\n            },\n            installThemeURL() {\n                let self = this\n                app.prompt(app.getLz('settings.prompt.visual.theme.github.URL'), (result) => {\n                    if (result) {\n                        ipcRenderer.once(\"theme-installed\", (event, arg) => {\n                            if (arg.success) {\n                                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n                            } else {\n                                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n                            }\n                        });\n                        ipcRenderer.invoke(\"get-github-theme\", result)\n                    }\n                });\n            },\n            getRepos() {\n                let self = this\n                var requestOptions = {\n                    method: 'GET',\n                    redirect: 'follow'\n                };\n\n                app._fetch(\"https://api.github.com/search/repositories?q=topic:cidermusictheme fork:true\", requestOptions)\n                    .then(response => response.text())\n                    .then(result => {\n                        let items = JSON.parse(result).items\n                        self.repos = items\n                    })\n                    .catch(error => console.log('error', error));\n            }\n        }\n    })\n</script> -->\n"
  },
  {
    "path": "src/renderer/views/pages/library-albums.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-library-albums\">\n    <div class=\"content-inner\">\n        <div class=\"row\">\n            <div class=\"col\" style=\"padding:0;\">\n                <h1 class=\"header-text\">{{$root.getLz('term.albums')}}</h1>\n            </div>\n            <div class=\"col-auto\">\n                <button v-if=\"library.albums.downloadState == 2\" @click=\"$root.getLibraryAlbumsFull(true, 1)\"\n                        class=\"reload-btn\"\n                        :aria-label=\"app.getLz('menubar.options.reload')\"><%- include('../svg/redo.svg') %></button>\n            </div>\n        </div>\n        <div class=\"album-header\">\n            <div class=\"col\" style=\"padding:0;\">\n                <div class=\"search-input-container\" style=\"width:100%;margin: 16px 0;\">\n                    <div class=\"search-input--icon\"></div>\n                    <input type=\"search\"\n                           style=\"width:100%;\"\n                           spellcheck=\"false\"\n                           :placeholder=\"$root.getLz('term.search') + '...'\"\n                           @input=\"$root.searchLibraryAlbums\"\n                           v-model=\"library.albums.search\" class=\"search-input\">\n                </div>\n            </div>\n            <div class=\"col-auto cider-flex-center\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <select class=\"md-select\" v-model=\"prefs.sort\"\n                                @change=\"library.albums.sorting[1] = prefs.sort; $root.searchLibraryAlbums(1)\">\n                            <optgroup :label=\"$root.getLz('term.sortBy')\">\n                                <option v-for=\"(sort, index) in library.albums.sortingOptions\" :value=\"index\">{{ sort\n                                    }}\n                                </option>\n                            </optgroup>\n                        </select>\n                    </div>\n                    <div class=\"col\">\n                        <select class=\"md-select\" v-model=\"prefs.sortOrder\"\n                                @change=\"library.albums.sortOrder[1] = prefs.sortOrder; $root.searchLibraryAlbums(1)\">\n                            <optgroup :label=\"$root.getLz('term.sortOrder')\">\n                                <option value=\"asc\">{{$root.getLz('term.sortOrder.ascending')}}</option>\n                                <option value=\"desc\">{{$root.getLz('term.sortOrder.descending')}}</option>\n                            </optgroup>\n                        </select>\n                    </div>\n                    <div class=\"col\">\n                        <select class=\"md-select\" v-model=\"prefs.viewAs\">\n                            <optgroup :label=\"$root.getLz('term.viewAs')\">\n                                <option value=\"covers\">{{$root.getLz('term.viewAs.coverArt')}}</option>\n                                <option value=\"list\">{{$root.getLz('term.viewAs.list')}}</option>\n                            </optgroup>\n                        </select>\n                    </div>\n                    <div class=\"col\">\n                        <select class=\"md-select\" v-model=\"prefs.scroll\">\n                            <optgroup :label=\"app.getLz('term.scroll')\">\n                                <option value=\"infinite\">{{app.getLz('term.scroll.infinite')}}</option>\n                                <option value=\"paged\">{{app.getLz('term.scroll.paged').replace(\"${songsPerPage}\",\n                                    pageSize)}}\n                                </option>\n                            </optgroup>\n                        </select>\n                    </div>\n                </div>\n            </div>\n            <pagination\n              :length=\"app.library.albums.displayListing.length\"\n              :pageSize=\"pageSize\"\n              :scroll=\"prefs.scroll\"\n              scrollSelector=\"#app-content\"\n              @onRangeChange=\"onRangeChange\"\n              style=\"margin-bottom: 0;\"\n            />\n        </div>\n        <div class=\"well\">\n            <div class=\"albums-square-container\">\n                <div>\n                    <mediaitem-square v-if=\"prefs.viewAs == 'covers'\" :size=\"'300'\" :item=\"item\"\n                                      v-for=\"item in currentSlice\">\n                    </mediaitem-square>\n                </div>\n            </div>\n            <mediaitem-list-item v-if=\"prefs.viewAs == 'list'\" :show-duration=\"false\" :show-meta-data=\"true\"\n                                 :show-library-status=\"false\" v-bind:key=\"item.id\" :item=\"item\" v-for=\"item in currentSlice\">\n            </mediaitem-list-item>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('cider-library-albums', {\n    template: '#cider-library-albums',\n    data: function() {\n      const pageSize = this.$root.cfg.libraryPrefs.pageSize;\n      return {\n        library: this.$root.library,\n        mediaItemSize: \"compact\",\n        prefs: this.$root.cfg.libraryPrefs.albums,\n        app: this.$root,\n        pageSize: pageSize,\n        start: 0,\n        end: pageSize\n      }\n    },\n    mounted() {\n      this.$root.getLibraryAlbumsFull(null, 1);\n      this.$root.getAlbumSort();\n      this.$root.searchLibraryAlbums(1);\n      this.$root.getLibrarySongsFull();\n      this.$root.searchLibraryAlbums(1);\n    },\n    computed: {\n      currentSlice: function() {\n        return this.library.albums.displayListing.slice(this.start, this.end);\n      }\n    },\n    methods: {\n      onRangeChange: function(newRange) {\n        this.start = newRange[0];\n        this.end = newRange[1];\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/library-artists.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-library-artists\">\n    <div class=\"content-inner library-artists-page\">\n        <!-- <div class=\"row\">\n            <div class=\"col\" style=\"padding:0;\">\n                <h1 class=\"header-text\">{{$root.getLz('term.artists')}}</h1>\n            </div>\n\n        </div> -->\n        <div class=\"inner-container\">\n            <div class=\"list-container\">\n                <div class=\"col\" style=\"padding:0;\">\n                    <div class=\"search-input-container\" style=\"width:calc(100%-20px);margin: 16px 10px 10px 10px;\">\n                        <div class=\"search-input--icon\"></div>\n                        <input type=\"search\" style=\"width:100%;\" spellcheck=\"false\"\n                               :placeholder=\"$root.getLz('term.search') + '...'\" @input=\"$root.searchLibraryArtists\"\n                               v-model=\"library.artists.search\" class=\"search-input\">\n                    </div>\n                </div>\n                <div class=\"podcasts-list\">\n                    <libraryartist-item :show-duration=\"false\" :show-meta-data=\"true\" :show-library-status=\"false\"\n                                        :item=\"item\" v-for=\"item in library.artists.displayListing\">\n                    </libraryartist-item>\n                </div>\n            </div>\n            <div class=\"episodes-list\">\n                <div class=\"episodes-inline-info\" v-if=\"clready\">\n                    <inline-collection-list :parentSelector=\"'.episodes-list'\" :data=\"clresponse\" :type=\"cltype\"\n                                            :title=\"cltitle\"></inline-collection-list>\n                </div>\n            </div>\n        </div>\n\n    </div>\n</script>\n<script>\n  Vue.component('cider-library-artists', {\n    template: '#cider-library-artists',\n    data: function() {\n      return {\n        library: this.$root.library,\n        app: this.$root,\n        ciderPodcasts: [],\n        podcasts: [],\n        episodes: [],\n        search: {\n          term: \"\",\n          loading: false,\n          results: [],\n          resultsLibrary: [],\n          next: \"\"\n        },\n        podcastSelected: {\n          id: -1\n        },\n        selected: {\n          id: -1\n        },\n        collectionList: {\n          response: null, title: null, type: null, requestBody: null\n        },\n        clresponse: [],\n        clready: false,\n        cltitle: '',\n        cltype: \"artists\",\n\n      }\n    },\n    mounted() {\n      let self = this;\n      this.$root.getLibraryArtistsFull(null, 0);\n      this.$root.$on('ap-inlinecollection', function(e) {\n        console.log(\"hey\", e)\n        self.clready = true;\n        self.clresponse = e.response;\n        self.cltitle = e.title ?? '';\n        self.cltype = e.type;\n\n      })\n    },\n    methods: {\n      getInlineCollection(e) {\n        console.log(\"hey\", e);\n      }\n    }\n  });\n</script>\n<script type=\"text/x-template\" id=\"libraryartist-item\">\n    <div v-observe-visibility=\"{callback: visibilityChanged}\"\n         @click=\"select\"\n         class=\"cd-mediaitem-list-item\"\n         :class=\"{'mediaitem-selected': app.select_hasMediaItem(guid)}\"\n         @contextmenu=\"contextMenu\">\n        <template v-if=\"isVisible\">\n            <div class=\"artwork\" v-if=\"showArtwork == true\">\n                <mediaitem-artwork\n                        :url=\"getArtwork()\"\n                        size=\"50\"\n                        :type=\"item.type\"></mediaitem-artwork>\n            </div>\n            <div class=\"info-rect\" :style=\"{'padding-left': (showArtwork ? '' : '16px')}\"\n                 @dblclick=\"select\">\n                <div class=\"title text-overflow-elipsis\">\n                    {{ item.attributes.name }}\n                </div>\n            </div>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component('libraryartist-item', {\n    template: '#libraryartist-item',\n    data: function() {\n      return {\n        isVisible: false,\n        addedToLibrary: false,\n        guid: this.uuidv4(),\n        app: this.$root,\n      }\n    },\n    props: {\n      'item': { type: Object, required: true },\n      'parent': { type: String, required: false },\n      'index': { type: Number, required: false, default: -1 },\n      'show-artwork': { type: Boolean, default: true },\n      'show-library-status': { type: Boolean, default: true },\n      'show-meta-data': { type: Boolean, default: false },\n      'show-duration': { type: Boolean, default: true },\n      'contextExt': { type: Object, required: false },\n    },\n    methods: {\n      uuidv4() {\n        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n        );\n      },\n      msToMinSec(ms) {\n        var minutes = Math.floor(ms / 60000);\n        var seconds = ((ms % 60000) / 1000).toFixed(0);\n        return minutes + \":\" + (seconds < 10 ? '0' : '') + seconds;\n      },\n      getDataType() {\n        return this.item.type\n      },\n      async select(e) {\n        let u = this.item\n        let u1 = await app.mk.api.v3.music(`/v1/me/library/artists/${u.id}/albums`, {\n          \"platform\": \"web\",\n          \"include[library-albums]\": \"artists,tracks\",\n          \"include[library-artists]\": \"catalog\",\n          \"fields[artists]\": \"url\",\n          \"includeOnly\": \"catalog,artists\"\n        })\n        this.showCollection({ data: Object.assign({}, u1.data.data) }, u.attributes.name ?? '', '');\n        //app.select_selectMediaItem(u.id, this.getDataType(), this.index, this.guid, true)\n      },\n      showCollection(response, title, type, requestBody = {}) {\n        this.$root.$emit('ap-inlinecollection', {\n            response: response, title: title, type: type, requestBody: {}\n          }\n        );\n      },\n      getArtwork() {\n        let u = \"\"\n        try {\n          u = this.item.relationships.catalog.data[0].attributes.artwork.url\n        } catch (e) {\n        }\n        ;\n        return u;\n      },\n      contextMenu(event) {\n\n        let self = this\n        let data_type = this.getDataType()\n\n        let item = self.item\n        item.attributes.artistName = item.attributes.name;\n\n        let useMenu = \"normal\"\n        if (app.selectedMediaItems.length <= 1) {\n          app.selectedMediaItems = []\n          app.select_selectMediaItem(this.item.id, data_type, this.index, this.guid, true)\n        } else {\n          useMenu = \"multiple\"\n        }\n\n        let menus = {\n          multiple: {\n            items: [] //\n          },\n          normal: {\n            items: [\n              {\n                \"name\": app.getLz('action.goToArtist'),\n                \"icon\": \"./assets/feather/user.svg\",\n                \"action\": function() {\n                  app.searchAndNavigate(self.item, 'artist')\n                  console.log(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/radio.svg\",\n                \"name\": app.getLz('action.startRadio'),\n                \"action\": function() {\n                  app.mk.setStationQueue({ song: self.item.attributes.playParams.id ?? self.item.id }).then(() => {\n                    app.mk.play()\n                    app.selectedMediaItems = []\n                  })\n                }\n              },\n              // Hidden for now, as it's not implemented yet\n              /*{\n                  \"icon\": \"./assets/feather/share.svg\",\n                  \"name\": app.getLz('action.share'),\n                  \"action\": function () {\n                      if (!self.item.attributes.url && self.item.relationships){\n                          if (self.item.relationships.catalog){\n                              app.mkapi(self.item.attributes.playParams.kind, false, self.item.relationships.catalog.data[0].id).then(u => {self.app.copyToClipboard((u.data.data.length && u.data.data.length > 0)? u.data.data[0].attributes.url : u.data.data.attributes.url)})\n                          }\n                      } else {\n                      self.app.copyToClipboard(self.item.attributes.url)}\n                  }\n              },*/\n            ]\n          }\n        }\n        if (this.contextExt) {\n          // if this.context-ext.normal is true append all options to the 'normal' menu which is a kvp of arrays\n          if (this.contextExt.normal) {\n            menus.normal.items = menus.normal.items.concat(this.contextExt.normal)\n          }\n          if (this.contextExt.multiple) {\n            menus.multiple.items = menus.multiple.items.concat(this.contextExt.multiple)\n          }\n        }\n        //CiderContextMenu.Create(event, menus[useMenu]); // Depreciated Context Menu\n        app.showMenuPanel(menus[useMenu], event);\n\n      },\n      visibilityChanged: function(isVisible, entry) {\n        this.isVisible = isVisible\n      },\n      addToLibrary() {\n        let item = this.item\n        if (item.attributes.playParams.id) {\n          console.log('adding to library', item.attributes.playParams.id)\n          app.addToLibrary(item.attributes.playParams.id.toString())\n          this.addedToLibrary = true\n        } else if (item.id) {\n          console.log('adding to library', item.id)\n          app.addToLibrary(item.id.toString())\n          this.addedToLibrary = true\n        }\n      },\n      async removeFromLibrary() {\n        let item = this.item\n        let params = { \"fields[songs]\": \"inLibrary\", \"fields[albums]\": \"inLibrary\", \"relate\": \"library\" }\n        let id = item.id ?? item.attributes.playParams.id\n        let res = await app.mkapi(item.attributes.playParams.kind ?? item.type, item.attributes.playParams.isLibrary ?? false, item.attributes.playParams.id ?? item.id, params);\n        if (res && res.relationships && res.relationships.library && res.relationships.library.data && res.relationships.library.data.length > 0) {\n          id = res.relationships.library.data[0].id\n        }\n        let kind = this.item.attributes.playParams.kind ?? this.data.item ?? '';\n        let truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        if (item.attributes.playParams.id) {\n          console.log('remove from library', id)\n          app.removeFromLibrary(truekind, id)\n          this.addedToLibrary = false\n        } else if (item.id) {\n          console.log('remove from library', id)\n          app.removeFromLibrary(truekind, id)\n          this.addedToLibrary = false\n        }\n      },\n      playTrack() {\n        let item = this.item\n        let parent = this.parent\n        let childIndex = this.index\n        console.log(item, parent, childIndex)\n        if (parent != null && childIndex != null) {\n          app.queueParentandplayChild(parent, childIndex, item);\n        } else {\n          app.playMediaItemById(item.attributes.playParams.id ?? item.id, item.attributes.playParams.kind ?? item.type, item.attributes.playParams.isLibrary ?? false, item.attributes.url)\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/library-recentlyadded.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-recentlyadded\">\n    <div class=\"content-inner\">\n        <h1 class=\"header-text\">{{$root.getLz('term.recentlyAdded')}}</h1>\n        <div class=\"well itemContainer collection-list-square\" v-if=\"itemSize == 'normal'\">\n            <mediaitem-square v-for=\"item in items\" :item=\"item\" v-bind:key=\"item.id\"></mediaitem-square>\n        </div>\n        <div class=\"well itemContainer collection-list-square\" v-else=\"itemSize == 'compact'\">\n            <mediaitem-list-item :show-meta-data=\"true\" :show-library-status=\"false\" v-for=\"item in items\"\n                                 :item=\"item\" v-bind:key=\"item.id\"></mediaitem-list-item>\n        </div>\n        <div class=\"well itemContainer collection-list-square\" v-show=\"loading\">\n            <div class=\"spinner\"></div>\n        </div>\n        <button v-if=\"nextUrl && !loading\" style=\"opacity:0;height: 32px;\"\n                v-observe-visibility=\"{callback: visibilityChanged}\">{{$root.getLz('term.showMore')}}\n        </button>\n    </div>\n</script>\n\n<script>\n  Vue.component(\"cider-recentlyadded\", {\n    template: \"#cider-recentlyadded\",\n    computed: {\n      items() {\n        return this.$store.state.pageState['recentlyAdded'].items;\n      },\n      nextUrl() {\n        return this.$store.state.pageState['recentlyAdded'].nextUrl;\n      },\n      itemSize() {\n        return this.$store.state.pageState['recentlyAdded'].size\n      }\n    },\n    data: function() {\n      return {\n        loading: false,\n        firstRoute: `/v1/me/library/recently-added?l=${app.mklang}&platform=web&include[library-albums]=artists&include[library-artists]=catalog&fields[artists]=url&fields%5Balbums%5D=artistName%2CartistUrl%2Cartwork%2CcontentRating%2CeditorialArtwork%2Cname%2CplayParams%2CreleaseDate%2Curl&includeOnly=catalog%2Cartists&limit=25`\n      }\n    },\n    async mounted() {\n      if (this.$store.state.pageState['recentlyAdded'].items.length !== 0) return\n\n      const firstResult = await app.mk.api.v3.music(this.firstRoute)\n      this.$store.state.pageState[\"recentlyAdded\"].items = firstResult.data.data\n      this.$store.state.pageState[\"recentlyAdded\"].nextUrl = firstResult.data.next\n    },\n    beforeDestroy() {\n      // this.$store.state.pageState[\"recently-added\"].scrollPosY = $(\"#app-content\").scrollTop()\n    },\n    methods: {\n      visibilityChanged: function(isVisible, entry) {\n        if (isVisible && !this.loading) {\n          this.getNextData();\n        }\n      },\n      async getNextData() {\n        if (this.$store.state.pageState[\"recentlyAdded\"].nextUrl) {\n          this.loading = true;\n          const nextResult = await app.mk.api.v3.music(this.$store.state.pageState[\"recentlyAdded\"].nextUrl)\n          this.$store.state.pageState[\"recentlyAdded\"].items = this.$store.state.pageState[\"recentlyAdded\"].items.concat(nextResult.data.data)\n          if (nextResult.data.next) {\n            this.$store.state.pageState[\"recentlyAdded\"].nextUrl = nextResult.data.next\n          } else {\n            this.$store.state.pageState[\"recentlyAdded\"].nextUrl = null\n          }\n          this.loading = false;\n        }\n        return\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/library-songs.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-library-songs\">\n    <div class=\"content-inner library-page\">\n        <div class=\"library-header\">\n            <div class=\"row\">\n                <div class=\"col\" style=\"padding:0;\">\n                    <div class=\"search-input-container\" style=\"width:100%;margin: 16px 0;\">\n                        <div class=\"search-input--icon\"></div>\n                        <input type=\"search\"\n                               style=\"width:100%;\"\n                               spellcheck=\"false\"\n                               :placeholder=\"app.getLz('term.search') + '...'\"\n                               @input=\"$root.searchLibrarySongs\"\n                               v-model=\"library.songs.search\" class=\"search-input\">\n                    </div>\n                </div>\n                <div class=\"col-auto cider-flex-center\">\n                    <div class=\"row\">\n                        <button class=\"col md-btn md-btn-primary  md-btn-icon\"\n                                style=\"min-width: 100px;margin-right: 3px;\"\n                                @click=\"app.mk.shuffleMode = 0; play()\"><img class=\"md-ico-play\">\n                            {{app.getLz('term.play')}}\n                        </button>\n                        <button class=\"col md-btn md-btn-primary  md-btn-icon\"\n                                style=\"min-width: 100px;margin-right: 3px;\"\n                                @click=\"app.mk.shuffleMode = 1;play()\"><img class=\"md-ico-shuffle\">\n                            {{app.getLz('term.shuffle')}}\n                        </button>\n                        <div class=\"col\">\n                            <select class=\"md-select\" v-model=\"prefs.sort\" @change=\"$root.searchLibrarySongs()\">\n                                <optgroup :label=\"app.getLz('term.sortBy')\">\n                                    <option v-for=\"(sort, index) in library.songs.sortingOptions\" :value=\"index\">{{ sort\n                                        }}\n                                    </option>\n                                </optgroup>\n                            </select>\n                        </div>\n                        <div class=\"col\">\n                            <select class=\"md-select\" v-model=\"prefs.sortOrder\" @change=\"$root.searchLibrarySongs()\">\n                                <optgroup :label=\"app.getLz('term.sortOrder')\">\n                                    <option value=\"asc\">{{app.getLz('term.sortOrder.ascending')}}</option>\n                                    <option value=\"desc\">{{app.getLz('term.sortOrder.descending')}}</option>\n                                </optgroup>\n                            </select>\n                        </div>\n                        <div class=\"col\">\n                            <select class=\"md-select\" v-model=\"prefs.size\" @change=\"$root.searchLibrarySongs()\">\n                                <optgroup :label=\"app.getLz('term.size')\">\n                                    <option value=\"normal\">{{app.getLz('term.size.normal')}}</option>\n                                    <option value=\"compact\">{{app.getLz('term.size.compact')}}</option>\n                                </optgroup>\n                            </select>\n                        </div>\n                        <div class=\"col\">\n                            <select class=\"md-select\" v-model=\"prefs.scroll\">\n                                <optgroup :label=\"app.getLz('term.scroll')\">\n                                    <option value=\"infinite\">{{app.getLz('term.scroll.infinite')}}</option>\n                                    <option value=\"paged\">{{app.getLz('term.scroll.paged').replace(\"${songsPerPage}\",\n                                        pageSize)}}\n                                    </option>\n                                </optgroup>\n                            </select>\n                        </div>\n                    </div>\n                </div>\n                <div class=\"col-auto cider-flex-center\">\n                    <button v-if=\"library.songs.downloadState == 2\" @click=\"$root.getLibrarySongsFull(true)\"\n                            class=\"reload-btn\"\n                            :aria-label=\"app.getLz('menubar.options.reload')\"><%- include('../svg/redo.svg') %></button>\n                    <button v-else class=\"reload-btn\" style=\"opacity: 0.8;pointer-events: none\"\n                            :aria-label=\"app.getLz('menubar.options.reload')\">\n                        <div class=\"spinner\"></div>\n                    </button>\n                </div>\n            </div>\n            <pagination\n                    :length=\"library.songs.displayListing.length\"\n                    :pageSize=\"pageSize\"\n                    :scroll=\"prefs.scroll\"\n                    scrollSelector=\"#app-content\"\n                    @onRangeChange=\"onRangeChange\"\n            />\n        </div>\n\n        <div v-if=\"library.songs.downloadState == 3\">Library contains no songs.</div>\n        <div class=\"well\" :key=\"1\" v-if=\"prefs.size == 'compact'\">\n            <mediaitem-list-item class-list=\"compact\" :item=\"item\" :parent=\"'librarysongs'\" :index=\"index\"\n                                 :show-meta-data=\"true\" :show-library-status=\"false\" v-bind:key=\"item.id\"\n                                 v-for=\"(item, index) in currentSlice\"></mediaitem-list-item>\n        </div>\n        <div class=\"well\" :key=\"2\" v-else>\n            <mediaitem-list-item :item=\"item\" :parent=\"'librarysongs'\" :index=\"index\" :show-meta-data=\"true\"\n                                 :show-library-status=\"false\" v-bind:key=\"item.id\"\n                                 v-for=\"(item, index) in currentSlice\"></mediaitem-list-item>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-library-songs', {\n    template: '#cider-library-songs',\n    data: function() {\n      const pageSize = this.$root.cfg.libraryPrefs.pageSize;\n      return {\n        // currentPage is oneIndexed\n        library: this.$root.library,\n        mediaItemSize: \"compact\",\n        prefs: this.$root.cfg.libraryPrefs.songs,\n        app: this.$root,\n        pageSize: pageSize,\n        start: 0,\n        end: pageSize\n      }\n    },\n    mounted() {\n      this.$root.getLibrarySongsFull()\n    },\n    computed: {\n      currentSlice: function() {\n        return this.library.songs.displayListing.slice(this.start, this.end);\n      }\n    },\n    methods: {\n      onRangeChange: function(newRange) {\n        this.start = newRange[0];\n        this.end = newRange[1];\n      },\n      play: function() {\n        function shuffleArray(array) {\n          for (var i = array.length - 1; i > 0; i--) {\n            var j = Math.floor(Math.random() * (i + 1));\n            var temp = array[i];\n            array[i] = array[j];\n            array[j] = temp;\n          }\n        }\n\n        let query = this.app.library.songs.displayListing.map(item => new MusicKit.MediaItem(item));\n        if (!app.mk.queue.isEmpty)\n          app.mk.queue.splice(0, app.mk.queue._itemIDs.length);\n        app.mk.stop().then(() => {\n          if (app.mk.shuffleMode == 1) {\n            shuffleArray(query)\n          }\n          app.mk.queue.append(query)\n          app.mk.changeToMediaAtIndex(0)\n        });\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/library-videos.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-library-videos\">\n    <div class=\"content-inner\">\n        <div class=\"row\">\n            <div class=\"col\" style=\"padding:0\">\n                <h1 class=\"header-text\">{{$root.getLz('term.videos')}}</h1>\n            </div>\n        </div>\n        <div class=\"madeforyou-body\">\n            <template v-if=\"videos.length > 0\">\n                <mediaitem-square :size=\"300\" :item=\"item\" v-for=\"item in videos\">\n                </mediaitem-square>\n            </template>\n            <template v-else-if=\"loaded == true\">\n                <div>{{$root.getLz('term.noVideos')}}</div>\n            </template>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-library-videos', {\n    template: \"#cider-library-videos\",\n    props: [\"data\"],\n    data: function() {\n      return {\n        videos: [],\n        loaded: false\n      }\n    },\n    mounted() {\n      this.$nextTick(async function() {\n        if (this.$data.videos == null || this.$data.videos.length == 0)\n          this.$data.videos = (await this.$root.mk.api.v3.music('/v1/me/library/music-videos')).data?.data ?? []\n        this.$data.loaded = true\n      })\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/listen_now.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-listen-now\">\n    <div class=\"content-inner\">\n        <h1 class=\"header-text\">{{app.getLz('term.listenNow')}}</h1>\n        <template v-for=\"(recom,index) in data.data\">\n            <listennow-child :recom=\"recom\" :index=\"index\"></listennow-child>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-listen-now', {\n    template: \"#cider-listen-now\",\n    props: [\"data\"],\n    data: function() {\n      return {\n        app: this.$root\n      }\n    },\n    mounted() {\n      this.$root.getListenNow()\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/madeforyou.ejs",
    "content": "<div class=\"content-inner\">\n    <div class=\"row\">\n        <div class=\"col\" style=\"padding:0\">\n            <h1 class=\"header-text\">{{$root.getLz('home.madeForYou')}}</h1>\n        </div>\n    </div>\n    <div class=\"madeforyou-body\">\n        <mediaitem-square :item=\"item\" v-for=\"item in madeforyou.data\" v-bind:key=\"item.id\">\n        </mediaitem-square>\n    </div>\n</div>\n"
  },
  {
    "path": "src/renderer/views/pages/oobe.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-oobe\">\n    <div class=\"content-inner oobe\">\n        <!--        before_we_start-->\n        <!-- <transition name=\"\"> -->\n        <div class=\"oobe-view\" v-if=\"screen == 'before_we_start'\">\n            <div class=\"oobe-header\">\n                {{ getLz(\"oobe.amupsell.title\") }}\n            </div>\n            <div class=\"oobe-body text\">{{ getLz(\"oobe.amupsell.text\") }}\n\n              <div class=\"md-option-line\">\n                <div class=\"md-option-segment\">\n                    {{$root.getLz('term.language')}}\n                </div>\n                <div class=\"md-option-segment md-option-segment_auto\">\n                    <label>\n                        <select class=\"md-select\" @change=\"$root.setLz('');$root.setLzManual()\"\n                                v-model=\"$root.cfg.general.language\">\n                            <optgroup :label=\"index\" v-for=\"(categories, index) in getLanguages()\">\n                                <option v-for=\"lang in categories\" :value=\"lang.code\">\n                                    {{lang.nameNative}}\n                                    ({{\n                                    lang.nameEnglish }})\n                                </option>\n                            </optgroup>\n                        </select>\n                    </label>\n                </div>\n              </div>\n\n            </div>\n            <div class=\"oobe-footer\">\n                <div class=\"btn-group\">\n                    <div class=\"md-btn md-btn-primary\" @click=\"screen = 'welcome'\">{{ getLz(\"oobe.next\") }}</div>\n                </div>\n            </div>\n        </div>\n        <!-- </transition> -->\n\n        <!--     Welcome   -->\n        <!-- <transition name=\"\"> -->\n        <div class=\"oobe-view\" v-if=\"screen == 'welcome'\">\n            <div class=\"oobe-header\">\n                {{ getLz(\"oobe.intro.title\") }}\n            </div>\n            <div class=\"oobe-body text\">{{ getLz(\"oobe.intro.text\") }}</div>\n            <div class=\"oobe-footer\">\n                <div class=\"btn-group\">\n                    <div class=\"md-btn\" @click=\"screen = 'before_we_start'\">{{ getLz(\"oobe.previous\") }}</div>\n                    <div class=\"md-btn md-btn-primary\" @click=\"screen = 'visual'\">{{ getLz(\"oobe.next\") }}</div>\n                </div>\n            </div>\n        </div>\n        <!-- </transition> -->\n\n        <!--     General   -->\n        <!-- <transition name=\"\"> -->\n        <div class=\"oobe-view\" v-if=\"screen == 'general'\">\n            <div class=\"oobe-header\">\n                {{ getLz(\"oobe.general.title\") }}\n            </div>\n            <div class=\"oobe-body text\"></div>\n            <div class=\"oobe-footer\">\n                <div class=\"btn-group\">\n                    <div class=\"md-btn\" @click=\"screen = 'welcome'\">{{ getLz(\"oobe.previous\") }}</div>\n                    <div class=\"md-btn md-btn-primary\" @click=\"screen = 'visual'\">{{ getLz(\"oobe.next\") }}</div>\n                </div>\n            </div>\n        </div>\n        <!-- </transition> -->\n\n        <!--     Visual   -->\n        <!-- <transition name=\"\"> -->\n        <div class=\"oobe-view\" v-if=\"screen == 'visual'\">\n            <div class=\"oobe-header\">\n                {{ getLz(\"oobe.visual.title\") }}\n            </div>\n            <div class=\"oobe-body visual\">\n                <b-row>\n                    <b-col>\n                        <div class=\"card bg-dark text-white stylePicker\"\n                             @click=\"$root.cfg.visual.directives.windowLayout = 'twopanel'\"\n                             :class=\"{'style-active': ($root.cfg.visual.directives.windowLayout == 'twopanel')}\">\n                            <div class=\"card-body\">\n                                <img class=\"visualPreview\" src=\"./assets/oobe/mojave.png\" alt=\"TEMP\">\n                            </div>\n                            <div class=\"card-footer\">\n                                Mojave\n                            </div>\n                        </div>\n                    </b-col>\n                    <b-col>\n                        <div class=\"card bg-dark text-white stylePicker\"\n                             @click=\"$root.cfg.visual.directives.windowLayout = 'default'\"\n                             :class=\"{'style-active': ($root.cfg.visual.directives.windowLayout == 'default')}\">\n                            <div class=\"card-body\">\n                                <img class=\"visualPreview\" src=\"./assets/oobe/maverick.png\" alt=\"TEMP\">\n                            </div>\n                            <div class=\"card-footer\">\n                                Maverick\n                            </div>\n                        </div>\n                    </b-col>\n                </b-row>\n                <div class=\"blurb\">{{getLz(\"oobe.visual.layout.text\")}}</div>\n            </div>\n            <div class=\"oobe-footer\">\n                <div class=\"btn-group\">\n                    <div class=\"md-btn\" @click=\"screen = 'welcome'\">{{ getLz(\"oobe.previous\") }}</div>\n                    <div class=\"md-btn md-btn-primary\" @click=\"screen = 'audio'\">{{ getLz(\"oobe.next\") }}</div>\n                </div>\n            </div>\n        </div>\n        <!-- </transition> -->\n\n        <!--     Audio   -->\n        <!-- <transition name=\"\"> -->\n        <div class=\"oobe-view\" v-if=\"screen == 'audio'\">\n            <div class=\"oobe-header\">\n                {{ getLz(\"oobe.audio.title\") }}\n            </div>\n            <div class=\"oobe-body\">\n                <div class=\"blurb\">{{ getLz(\"oobe.audio.text\") }}</div>\n                <div class=\"md-option-container\">\n                    <div class=\"settings-option-body\">\n                        <div class=\"md-option-line\">\n                            <div class=\"md-option-segment\">\n                                {{$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPE')}}\n                                <br>\n                                <small>{{$root.getLz('settings.option.audio.enableAdvancedFunctionality.ciderPPE.description')}}</small>\n                            </div>\n                            <div class=\"md-option-segment md-option-segment_auto\">\n                                <input type=\"checkbox\" v-model=\"$root.cfg.audio.maikiwiAudio.ciderPPE\"\n                                       switch />\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            <div class=\"oobe-footer\">\n                <div class=\"btn-group\">\n                    <div class=\"md-btn\" @click=\"screen = 'visual'\">{{ getLz(\"oobe.previous\") }}</div>\n                    <div class=\"md-btn md-btn-primary\" @click=\"signIn()\">{{ getLz(\"oobe.next\") }}</div>\n                </div>\n            </div>\n        </div>\n        <!-- </transition> -->\n        <div class=\"oobe-view\" v-if=\"screen == 'signin'\">\n            <div class=\"oobe-header\">\n                Sign in with Apple Music\n            </div>\n            <div class=\"oobe-body\">\n                <div class=\"blurb\"></div>\n            </div>\n            <div class=\"oobe-footer\">\n                <div class=\"btn-group\">\n                    <div class=\"md-btn\" @click=\"app.appMode ='player'\">{{ getLz(\"oobe.done\") }}</div>\n                </div>\n            </div>\n        </div>\n        <div class=\"oobe-titlebar\">\n            <div class=\"button-group\" v-if=\"$root.platform !== 'darwin'\">\n                <button class=\"min\" @click=\"$root.ipcRenderer.send('minimize')\"></button>\n                <button class=\"close\" @click=\"$root.ipcRenderer.send('close')\"></button>\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('cider-oobe', {\n    template: '#cider-oobe',\n    data: function() {\n      return {\n        screen: \"before_we_start\"\n      }\n    },\n    async mounted() {\n\n    },\n    methods: {\n      signIn() {\n        if (localStorage.getItem(\"music.ampwebplay.media-user-token\")) {\n          localStorage.setItem(\"seenOOBE\", 1)\n          window.location.reload()\n        }\n        this.screen = \"signin\";\n        capiInit();\n\n      },\n      getLz() {\n        return this.$root.getLz.apply(this.$root, arguments);\n      },\n      getLanguages: function() {\n        let langs = this.$root.lzListing\n        let categories = {\n          \"main\": [],\n          \"fun\": [],\n          \"unsorted\": []\n        }\n        // sort by category if category is undefined or empty put it in \"unsorted\"\n        for (let i = 0; i < langs.length; i++) {\n          if (langs[i].category === undefined || langs[i].category === \"\") {\n            categories.unsorted.push(langs[i])\n          } else {\n            categories[langs[i].category].push(langs[i])\n          }\n        }\n        // return\n        return categories\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/playlist-inline.ejs",
    "content": "<script type=\"text/x-template\" id=\"playlist-inline\">\n    <div class=\"content-inner playlist-page inline-playlist\" @click.self=\"$root.resetState()\">\n        <div class=\"playlist-inner\" v-if=\"data != [] && data.attributes != null\">\n            <div class=\"close-btn\" title=\"Close\" @click=\"$root.resetState()\">\n                <svg fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\" width=\"21\" height=\"21\" viewBox=\"0 0 21 21\"\n                     aria-role=\"presentation\" focusable=\"false\">\n                    <path\n                            d=\"M10.5 21C4.724 21 0 16.275 0 10.5S4.724 0 10.5 0 21 4.725 21 10.5 16.276 21 10.5 21zm-3.543-5.967a.96.96 0 00.693-.295l2.837-2.842 2.85 2.842c.167.167.41.295.693.295.552 0 1.001-.461 1.001-1.012 0-.281-.115-.512-.295-.704L11.899 10.5l2.85-2.855a.875.875 0 00.295-.68c0-.55-.45-.998-1.001-.998a.871.871 0 00-.668.295l-2.888 2.855-2.862-2.843a.891.891 0 00-.668-.281.99.99 0 00-1.001.986c0 .269.116.512.295.678L9.088 10.5l-2.837 2.843a.926.926 0 00-.295.678c0 .551.45 1.012 1.001 1.012z\"\n                            fill-rule=\"nonzero\" />\n                </svg>\n            </div>\n            <template v-if=\"app.playlists.loadingState == 0\">\n                <div class=\"content-inner centered\">\n                    <div class=\"spinner\"></div>\n                </div>\n            </template>\n            <template v-if=\"app.playlists.loadingState == 1\">\n                <div class=\"playlist-display\"\n                     :style=\"{\n                '--bgColor': (data.attributes.artwork != null && data.attributes.artwork['bgColor'] != null) ? ('#' + data.attributes.artwork.bgColor) : '',\n                '--textColor': (data.attributes.artwork != null && data.attributes.artwork['textColor1'] != null) ? ('#' + data.attributes.artwork.textColor1) : ''\n            }\">\n                    <div class=\"playlistInfo\">\n                        <div class=\"row\">\n                            <div class=\"col-auto cider-flex-center\">\n                                <div style=\"width: 260px;height:260px;\">\n                                    <mediaitem-artwork\n                                            shadow=\"large\"\n                                            :video-priority=\"true\"\n                                            :url=\"(data.attributes != null && data.attributes.artwork != null) ? data.attributes.artwork.url : ((data.relationships != null && data.relationships.tracks.data.length > 0 && data.relationships.tracks.data[0].attributes != null) ? ((data.relationships.tracks.data[0].attributes.artwork != null)? data.relationships.tracks.data[0].attributes.artwork.url : ''):'')\"\n                                            :video=\"(data.attributes != null && data.attributes.editorialVideo != null) ? (data.attributes.editorialVideo.motionDetailSquare ? data.attributes.editorialVideo.motionDetailSquare.video : (data.attributes.editorialVideo.motionSquareVideo1x1 ? data.attributes.editorialVideo.motionSquareVideo1x1.video : '')) : '' \"\n                                            size=\"260\"\n                                    ></mediaitem-artwork>\n                                </div>\n                            </div>\n                            <div class=\"col playlist-info\">\n                                <template v-if=\"!editorialNotesExpanded\">\n                                    <div>\n                                        <div class=\"playlist-name\" @click=\"editPlaylistName()\" v-show=\"!nameEditing\">\n                                            {{data.attributes ? (data.attributes.name ??\n                                            (data.attributes.title ?? '') ?? '') : ''}}\n                                        </div>\n                                        <div class=\"playlist-name\" v-show=\"nameEditing\"><input type=\"text\"\n                                                                                               spellcheck=\"false\"\n                                                                                               class=\"nameEdit\"\n                                                                                               v-model=\"data.attributes.name\"\n                                                                                               @blur=\"editPlaylist\"\n                                                                                               @change=\"editPlaylist\"\n                                                                                               @keydown.enter=\"editPlaylist\" />\n                                        </div>\n                                        <div class=\"playlist-time genre\" style=\"margin: 0px;\">{{getAlbumGenre()}}</div>\n                                        <div class=\"playlist-artist item-navigate\"\n                                             v-if=\"getArtistName(data) != '' && !useArtistChip\"\n                                             @click=\"data.attributes && data.attributes.artistName ? app.searchAndNavigate(data,'artist') : ''\">\n                                            {{getArtistName(data)}}\n                                        </div>\n                                        <template v-if=\"useArtistChip\">\n                                            <artist-chip v-for=\"artist in data.relationships.artists?.data\"\n                                                         :item=\"artist\"></artist-chip>\n                                        </template>\n                                        <div class=\"playlist-desc\"\n                                             v-if=\"(data.attributes.description && (data.attributes.description.standard || data.attributes.description.short)) || (data.attributes.editorialNotes && (data.attributes.editorialNotes.standard || data.attributes.editorialNotes.short))\">\n                                            <div v-if=\"(data.attributes.description?.short ?? data.attributes.editorialNotes?.short) != null\"\n                                                 class=\"content\"\n                                                 v-html=\"data.attributes.description?.short ?? data.attributes.editorialNotes?.short\"\n                                                 @click=\"openInfoModal()\"></div>\n                                            <div v-else-if=\"(data.attributes.description?.standard ?? data.attributes.editorialNotes?.standard) != null\"\n                                                 class=\"content\"\n                                                 v-html=\"data.attributes.description?.standard ?? data.attributes.editorialNotes?.standard\"></div>\n                                            <!-- <button v-if=\"(data.attributes.description?.short ?? data.attributes.editorialNotes?.short ) != null\" class=\"more-btn\"\n                                                    @click=\"openInfoModal()\">\n                                                {{app.getLz('term.showMore')}}\n                                            </button> -->\n                                        </div>\n                                    </div>\n                                </template>\n                                <template v-if=\"editorialNotesExpanded\">\n                                    <div class=\"playlist-desc-expanded\">\n                                        <div class=\"content\"\n                                             v-html=\"((data.attributes.editorialNotes) ? (data.attributes.editorialNotes.standard ?? (data.attributes.editorialNotes.short ?? '') ) : (data.attributes.description ? (data.attributes.description.standard ?? (data.attributes.description.short ?? '')) : ''))\"></div>\n                                        <button class=\"more-btn\"\n                                                @click=\"editorialNotesExpanded = !editorialNotesExpanded\">\n                                            {{app.getLz('term.showLess')}}\n                                        </button>\n                                    </div>\n                                </template>\n                                <div class=\"playlist-controls\" v-observe-visibility=\"{callback: isHeaderVisible}\">\n                                    <button class=\"md-btn md-btn-primary md-btn-icon\" style=\"min-width: 100px;\"\n                                            @click=\"app.mk.shuffleMode = 0; play()\"><img class=\"md-ico-play\">\n                                        {{app.getLz('term.play')}}\n                                    </button>\n                                    <button class=\"md-btn md-btn-primary md-btn-icon\" style=\"min-width: 100px;\"\n                                            @click=\"app.mk.shuffleMode = 1;play()\"><img class=\"md-ico-shuffle\">\n                                        {{app.getLz('term.shuffle')}}\n                                    </button>\n                                    <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\"\n                                            v-if=\"inLibrary!=null && confirm!=true\"\n                                            @click=\"confirmButton()\"><img\n                                                :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                        {{ (!inLibrary) ? app.getLz('action.addToLibrary') :\n                                        app.getLz(\"action.removeFromLibrary\") }}\n                                    </button>\n                                    <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\" v-if=\"confirm==true\"\n                                            @click=\"(!inLibrary) ? addToLibrary(data.attributes.playParams.id.toString()) : removeFromLibrary(data.attributes.playParams.id.toString()) \">\n                                        <img :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                        {{app.getLz('term.confirm')}}\n                                    </button>\n                                    <button class=\"more-btn-round\" style=\"float:right;\" @click=\"menu\"\n                                            :aria-label=\"app.getLz('term.more')\">\n                                        <div class=\"svg-icon\"></div>\n                                    </button>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                    <div class=\"artworkContainer\" v-if=\"data.attributes.artwork != null\">\n                        <artwork-material :url=\"data.attributes.artwork.url\" size=\"260\" images=\"1\"></artwork-material>\n                    </div>\n\n                </div>\n                <div class=\"floating-header\"\n                     :style=\"{opacity: (headerVisible ? 0 : 1),'pointer-events': (headerVisible ? 'none' : '')}\">\n                    <div class=\"row\">\n                        <div class=\"col\">\n                            <h3>{{data.attributes ? (data.attributes.name ??\n                                (data.attributes.title ?? '') ?? '') : ''}}</h3>\n                        </div>\n                        <div class=\"col-auto cider-flex-center\">\n                            <div>\n                                <button class=\"md-btn md-btn-primary  md-btn-icon\" style=\"min-width: 100px;\"\n                                        @click=\"app.mk.shuffleMode = 0; play()\"><img class=\"md-ico-play\">\n                                    {{app.getLz('term.play')}}\n                                </button>\n                                <button class=\"md-btn md-btn-primary  md-btn-icon\" style=\"min-width: 100px;\"\n                                        @click=\"app.mk.shuffleMode = 1;play()\"><img class=\"md-ico-shuffle\">\n                                    {{app.getLz('term.shuffle')}}\n                                </button>\n                                <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\"\n                                        v-if=\"inLibrary!=null && confirm!=true\"\n                                        @click=\"confirmButton()\"><img\n                                            :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                    {{ (!inLibrary) ? app.getLz('action.addToLibrary') :\n                                    app.getLz(\"action.removeFromLibrary\") }}\n                                </button>\n                                <button class=\"md-btn md-btn-icon\" style=\"min-width: 180px;\" v-if=\"confirm==true\"\n                                        @click=\"(!inLibrary) ? addToLibrary(data.attributes.playParams.id.toString()) : removeFromLibrary(data.attributes.playParams.id.toString()) \">\n                                    <img :class=\"(!inLibrary) ? 'md-ico-add' : 'md-ico-remove'\">\n                                    {{app.getLz('term.confirm')}}\n                                </button>\n                            </div>\n                        </div>\n                        <div class=\"col-auto cider-flex-center\">\n                            <button class=\"more-btn-round\" style=\"float:right;\" @click=\"menu\" :aria-label=\"term.more\">\n                                <div class=\"svg-icon\"></div>\n                            </button>\n                        </div>\n                    </div>\n                </div>\n                <div class=\"playlist-body scrollbody\">\n\n                    <b-tabs pills align=\"center\" content-class=\"mt-3\">\n                        <b-tab title=\"Tracks\">\n                            <div class=\"\">\n                                <div style=\"width:100%\">\n                                    <draggable :sort=\"data.attributes.canEdit && data.type == 'library-playlists'\"\n                                               v-model=\"data.relationships.tracks.data\" @start=\"drag=true\"\n                                               @end=\"drag=false;put()\">\n                                        <template v-if=\"nestedPlaylist == [] || nestedPlaylist.length <= 1\">\n                                            <mediaitem-list-item :item=\"item\" :parent=\"getItemParent(data)\"\n                                                                 :index=\"index\"\n                                                                 :showIndex=\"true\"\n                                                                 :showIndexPlaylist=\"(data.attributes.playParams.kind ?? data.type ?? '').includes('playlist')\"\n                                                                 :context-ext=\"buildContextMenu()\"\n                                                                 v-bind:key=\"item.id\"\n                                                                 v-for=\"(item,index) in data.relationships.tracks.data\"></mediaitem-list-item>\n                                        </template>\n                                        <template v-else>\n                                            <div v-for=\"disc in nestedPlaylist\">\n                                                <div class=\"playlist-time\">{{($root.getLz(\"term.discNumber\") ??\n                                                    \"\").replace(\"${discNumber}\",disc.disc)}}\n                                                </div>\n                                                <mediaitem-list-item :item=\"item\" :parent=\"getItemParent(data)\"\n                                                                     :index=\"index\"\n                                                                     :showIndex=\"true\"\n                                                                     :showIndexPlaylist=\"(data.attributes.playParams.kind ?? data.type ?? '').includes('playlist')\"\n                                                                     :context-ext=\"buildContextMenu()\"\n                                                                     v-bind:key=\"item.id\"\n                                                                     v-for=\"(item,index) in disc.tracks\"></mediaitem-list-item>\n                                            </div>\n\n                                        </template>\n                                    </draggable>\n\n                                </div>\n\n                            </div>\n                            <div class=\"friends-info\" v-if=\"itemBadges.length != 0\">\n                                <div class=\"well\">\n                                    <div class=\"badge-container\">\n                                        <div class=\"socialBadge\"\n                                             :title=\"`${badge.attributes.name} - @${badge.attributes.handle}`\"\n                                             v-bind:key=\"badge.id\"\n                                             v-for=\"badge in itemBadges\">\n                                            <mediaitem-artwork\n                                                    :url=\"badge.attributes.artwork.url\"\n                                                    :size=\"60\"></mediaitem-artwork>\n                                        </div>\n                                    </div>\n                                </div>\n                            </div>\n                            <div class=\"playlist-time\">\n                                {{getFormattedDate()}}\n                            </div>\n                            <div class=\"playlist-time total\">{{app.getTotalTime()}}</div>\n                            <div class=\"playlist-time item-navigate\" @click=\"app.searchAndNavigate(data,'recordLabel') \"\n                                 style=\"width: 50%;\">\n                                {{data.attributes.copyright}}\n                            </div>\n                            <template\n                                    v-if=\"(data.attributes?.playParams?.kind ?? data.type ?? '').includes('album') &&  data.relationships.catalog != null && data.relationships.catalog != null && data.relationships.catalog.data.length > 0\">\n                                <div class=\"playlist-time showExtended item-navigate\"\n                                     style=\"color:#fa586a; font-weight: bold\"\n                                     @click=\"app.routeView(data.relationships.catalog.data[0])\">\n                                    {{$root.getLz(\"action.showAlbum\")}}\n                                </div>\n                            </template>\n                            <hr>\n                        </b-tab>\n                        <template v-if=\"typeof data.views != 'undefined'\">\n                            <b-tab lazy :title=\"data.views[view].attributes.title\" v-for=\"view in data.meta.views.order\"\n                                   v-if=\"data.views[view].data.length != 0\">\n                                <div>\n                                    <div class=\"row\">\n                                        <div class=\"col\">\n                                            <h3>{{ data.views[view].attributes.title }}</h3>\n                                        </div>\n                                    </div>\n                                    <div class=\"row\">\n                                        <div class=\"col\">\n                                            <mediaitem-scroller-horizontal\n                                                    :items=\"data.views[view].data\"></mediaitem-scroller-horizontal>\n                                        </div>\n                                    </div>\n                                </div>\n                            </b-tab>\n                        </template>\n\n                    </b-tabs>\n                </div>\n            </template>\n        </div>\n        <div class=\"playlist-inner\" v-else>\n            <div class=\"close-btn\" title=\"Close\" @click=\"$root.resetState()\">\n                <svg fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\" width=\"21\" height=\"21\" viewBox=\"0 0 21 21\"\n                     aria-role=\"presentation\" focusable=\"false\">\n                    <path\n                            d=\"M10.5 21C4.724 21 0 16.275 0 10.5S4.724 0 10.5 0 21 4.725 21 10.5 16.276 21 10.5 21zm-3.543-5.967a.96.96 0 00.693-.295l2.837-2.842 2.85 2.842c.167.167.41.295.693.295.552 0 1.001-.461 1.001-1.012 0-.281-.115-.512-.295-.704L11.899 10.5l2.85-2.855a.875.875 0 00.295-.68c0-.55-.45-.998-1.001-.998a.871.871 0 00-.668.295l-2.888 2.855-2.862-2.843a.891.891 0 00-.668-.281.99.99 0 00-1.001.986c0 .269.116.512.295.678L9.088 10.5l-2.837 2.843a.926.926 0 00-.295.678c0 .551.45 1.012 1.001 1.012z\"\n                            fill-rule=\"nonzero\" />\n                </svg>\n            </div>\n            <template v-if=\"app.playlists.loadingState == 0\">\n                <div class=\"content-inner centered\">\n                    <div class=\"spinner\"></div>\n                </div>\n            </template>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('playlist-inline', {\n    template: \"#playlist-inline\",\n    props: [\"data\"],\n\n    data: function() {\n      return {\n        editorialNotesExpanded: false,\n        drag: false,\n        nameEditing: false,\n        inLibrary: null,\n        confirm: false,\n        app: this.$root,\n        itemBadges: [],\n        badgesRequested: false,\n        headerVisible: true,\n        useArtistChip: false,\n        nestedPlaylist: [],\n      }\n    },\n    mounted: function() {\n      this.$nextTick(function() {\n        this.isInLibrary()\n      })\n    },\n    watch: {\n      data: function() {\n        this.nestedPlaylist = [];\n        this.isInLibrary()\n        this.getBadges()\n        this.generateNestedPlaylist()\n      }\n    },\n    methods: {\n      openInfoModal() {\n        app.moreinfodata = [];\n        app.moreinfodata = {\n          title: this.data?.attributes ? (this.data?.attributes?.name ??\n            (this.data?.attributes?.title ?? '') ?? '') : '',\n          subtitle: this.data?.attributes?.artistName ?? '',\n          content: ((this.data?.attributes?.editorialNotes != null) ? (this.data?.attributes?.editorialNotes?.standard ?? (this.data?.attributes?.editorialNotes?.short ?? '')) : (data.attributes?.description ? (this.data.attributes?.description?.standard ?? (this.data?.attributes?.description?.short ?? '')) : ''))\n        }\n        app.modals.moreInfo = true;\n      },\n      generateNestedPlaylist() {\n        this.nestedPlaylist = [];\n        if (this.data?.type?.includes(\"album\")) {\n          console.log(this.data.relationships.tracks.data)\n          let songlists = this.data.relationships.tracks.data;\n          let discs = songlists.map(x => {\n            return x.attributes.discNumber\n          }).filter((item, i, ar) => ar.indexOf(item) === i);\n          if (discs && discs.length > 1) {\n            for (disc of discs) {\n              let songs = songlists.filter(x => x.attributes.discNumber == disc);\n              this.nestedPlaylist.push({ disc: disc, tracks: songs })\n            }\n          }\n          console.log(this.nestedPlaylist)\n\n        }\n      },\n      isHeaderVisible(visible) {\n        this.headerVisible = visible\n      },\n      getBadges() {\n        return\n        if (this.badgesRequested) {\n          return\n        }\n        this.badgesRequested = true\n        this.itemBadges = []\n        let self = this\n        var id = 0\n        try {\n          id = this.data.attributes.playParams.id\n        } catch (e) {\n          id = this.data.id\n        }\n        this.$root.getSocialBadges((badges) => {\n          let friends = badges[id]\n          if (friends) {\n            friends.forEach(function(friend) {\n              self.app.mk.api.v3.music(`/v1/social/${app.mk.storefrontId}/social-profiles/${friend}`).then(data => {\n                self.itemBadges.push(data.data.data[0])\n              })\n            })\n          }\n        })\n      },\n      confirmButton() {\n        // Return button to normal state after 3 seconds\n\n        this.confirm = true\n        setTimeout(() => this.confirm = false, 3000);\n      },\n      getArtistName(data) {\n        if (data.attributes.artistName) {\n          this.useArtistChip = true\n          return data.attributes.artistName\n        } else if (data.attributes.artist) {\n          this.useArtistChip = true\n          return data.attributes.artist.attributes.name\n        } else if (data.attributes.curatorName) {\n          return data.attributes.curatorName\n        } else {\n          return \"\"\n        }\n      },\n      getAlbumGenre: function() {\n        if (this.data.type.includes('albums')) {\n          let date = this.data.attributes.releaseDate;\n          if (date == null || date === \"\") return \"\";\n          return `${this.data.relationships.tracks.data[0].attributes.genreNames[0]} · ${new Date(date).getFullYear()}`\n        }\n      },\n      async isInLibrary() {\n        if (this.data.type && !this.data.type.includes(\"library\")) {\n          // please keep using vars here\n          const params = {\n            \"fields[playlists]\": \"inLibrary\",\n            \"fields[albums]\": \"inLibrary\",\n            \"relate\": \"library\"\n          };\n          const res = await app.mkapi(this.data.attributes.playParams.kind ?? this.data.type, this.data.attributes.playParams.isLibrary ?? false, this.data.attributes.playParams.id ?? this.data.id, params);\n          this.inLibrary = (res.data.data[0] && res.data.data[0].attributes && res.data.data[0].attributes.inLibrary) ? res.data.data[0].attributes.inLibrary : false\n          console.log(res)\n        } else {\n          this.inLibrary = true\n        }\n      },\n      editPlaylist() {\n        this.app.editPlaylist(this.data.id, this.data.attributes.name);\n        this.app.playlists.listing.forEach(playlist => {\n          if (playlist.id === this.data.id) {\n            playlist.attributes.name = this.data.attributes.name\n          }\n        })\n        this.nameEditing = false\n      },\n      addToLibrary(id) {\n        app.mk.addToLibrary(id)\n        this.inLibrary = true\n        this.confirm = false\n      },\n      async removeFromLibrary(id) {\n        const params = { \"fields[songs]\": \"inLibrary\", \"fields[albums]\": \"inLibrary\", \"relate\": \"library\" };\n        var id = this.data.id ?? this.data.attributes.playParams.id\n        const res = await app.mkapi(this.data.attributes.playParams.kind ?? this.data.type, this.data.attributes.playParams.isLibrary ?? false, this.data.attributes.playParams.id ?? this.data.id, params);\n        if (res.data.data[0] && res.data.data[0].relationships && res.data.data[0].relationships.library && res.data.data[0].relationships.library.data && res.data.data[0].relationships.library.data.length > 0) {\n          id = res.data.data[0].relationships.library.data[0].id\n        }\n        let kind = this.data.attributes.playParams.kind ?? this.data.type ?? '';\n        const truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        app.mk.api.v3.music(`v1/me/library/${truekind}/${id.toString()}`, {},\n          {\n            fetchOptions: {\n              method: \"DELETE\"\n            }\n          })\n        this.inLibrary = false\n        this.confirm = false\n      },\n      editPlaylistName() {\n        if (this.data.attributes.canEdit && this.data.type === \"library-playlists\") {\n          this.nameEditing = true\n          setTimeout(() => {\n            document.querySelector(\".nameEdit\").focus()\n          }, 100)\n        }\n      },\n      buildContextMenu(index) {\n        let self = this\n        if (!this.data.attributes.canEdit) {\n          return\n        }\n        return {\n          normal: [\n            {\n              icon: \"./assets/feather/x-circle.svg\",\n              name: app.getLz('action.removeFromPlaylist'),\n              action: () => {\n                self.remove()\n              }\n            },\n          ],\n          multiple: [\n            {\n              icon: \"./assets/feather/x-circle.svg\",\n              name: app.getLz('action.removeFromPlaylist'),\n              action: () => {\n                self.remove()\n              }\n            },\n          ]\n        }\n      },\n      async put() {\n        if (!this.data.attributes.canEdit) {\n          return\n        }\n        console.log('sds', this.convert())\n        await app.mk.api.v3.music(\n          `/v1/me/library/playlists/${this.data.attributes.playParams.id}/tracks`,\n          {},\n          {\n            fetchOptions: {\n              method: \"PUT\",\n              body: JSON.stringify({\n                data: this.convert()\n              })\n            }\n          }\n        )\n      },\n      async remove() {\n        if (!this.data.attributes.canEdit) {\n          return\n        }\n        // for each app.selectedMediaItems splice the items from the playlist\n        for (let i = 0; i < app.selectedMediaItems.length; i++) {\n          let item = app.selectedMediaItems[i]\n          let index = this.data.relationships.tracks.data.findIndex(x => x.id == item.id)\n          if (index > -1) {\n            this.data.relationships.tracks.data.splice(index, 1)\n          }\n        }\n        await this.put()\n      },\n      convert() {\n        let pl_tracks = []\n        for (let i = 0; i < this.data.relationships.tracks.data.length; i++) {\n          pl_tracks.push({\n            id: this.data.relationships.tracks.data[i].id,\n            type: this.data.relationships.tracks.data[i].type\n          })\n        }\n        return pl_tracks\n      },\n      getRecursive(url) {\n        app.apiCall(app.musicBaseUrl + \"/v1/me/library/playlists/p.V7VYlrDso6kkYY/tracks?offset=100\", res => {\n          this.data.relationships.tracks.data = this.data.relationships.tracks.data.concat(res.data.data)\n          if (res.data.next) {\n            this.getRecursive(res.data.next)\n          }\n        })\n      },\n      menu(event) {\n        let self = this\n        let artistId = null\n\n        if (typeof this.data.relationships.artists != \"undefined\") {\n          artistId = this.data.relationships.artists.data[0].id\n          if (this.data.relationships.artists.data[0].type == \"library-artists\") {\n            artistId = this.data.relationships.artists.data[0].relationships.catalog.data[0].id\n          }\n        }\n\n        let menuItems = {\n          items: {\n            \"share\": {\n              name: app.getLz('term.share'),\n              icon: \"./assets/feather/share.svg\",\n              action: () => {\n                let route = \"\"\n                switch (this.data.type) {\n                  case 'albums':\n                    route = `/v1/catalog/${app.mk.storefrontId}/albums/${this.data.id}`\n                    break;\n                  case 'playlists':\n                    route = `/v1/catalog/${app.mk.storefrontId}/playlists/${this.data.id}`\n                    break;\n                  case \"library-playlists\":\n                    route = `/v1/me/library/playlists/${this.data.id}/catalog`\n                    break\n                  case \"library-albums\":\n                    route = `/v1/me/library/albums/${this.data.id}/catalog`\n                    break\n                }\n                if (route === '') {\n                  return\n                }\n                app.mk.api.v3.music(route).then(res => {\n                  console.log(res.data.data[0].attributes.url)\n                  app.copyToClipboard(res.data.data[0].attributes.url)\n                })\n              }\n            },\n            \"follow\": {\n              name: app.getLz('action.follow'),\n              icon: \"./assets/feather/plus-circle.svg\",\n              hidden: false,\n              action: () => {\n                app.setArtistFavorite(artistId, true)\n              }\n            },\n            \"unfollow\": {\n              name: app.getLz('action.unfollow'),\n              icon: \"./assets/feather/x-circle.svg\",\n              hidden: true,\n              action: () => {\n                app.setArtistFavorite(artistId, false)\n              }\n            },\n          }\n        }\n\n        if (artistId != null) {\n          if (app.followingArtist(artistId)) {\n            menuItems.items.follow.hidden = true\n            menuItems.items.unfollow.hidden = false\n          } else {\n            menuItems.items.follow.hidden = false\n            menuItems.items.unfollow.hidden = true\n          }\n        } else {\n          menuItems.items.follow.hidden = true\n          menuItems.items.unfollow.hidden = true\n        }\n\n\n        app.showMenuPanel(menuItems, event)\n\n      },\n      getItemParent: function(data) {\n        kind = data.attributes.playParams.kind;\n        id = data.attributes.playParams.id;\n        return `${kind}:${id}`\n      },\n      getFormattedDate: function() {\n        let date = (this.data.attributes.releaseDate ?? (this.data.attributes.lastModifiedDate ?? (this.data.attributes.dateAdded ?? '')))\n        let prefix = '';\n        if (date == null || date === \"\") return \"\";\n        switch (date) {\n          case this.data.attributes.releaseDate:\n            prefix = this.app.getLz('term.time.released') + ' '\n            break;\n          case this.data.attributes.lastModifiedDate:\n            prefix = this.app.getLz('term.time.updated') + ' '\n            break;\n          case this.data.attributes.dateAdded:\n            prefix = this.app.getLz('term.time.added') + ' '\n            break;\n        }\n        let month, year;\n        try {\n          const releaseDate = new Date(date);\n          // month = new Intl.DateTimeFormat(this.app.cfg.general.language.replace('_','-'), {month: 'long'}).format(releaseDate);\n          // date = releaseDate.getDate();\n          // year = releaseDate.getFullYear();\n          let formatted = ''\n          try {\n            formatted = new Intl.DateTimeFormat(this.app.cfg.general.language?.replace('_', '-') ?? 'en-US', {\n              day: 'numeric',\n              month: 'long',\n              year: 'numeric'\n            }).format(releaseDate);\n          } catch (e) {\n            // use the format in json instead\n            if (this.app.getLz('date.format') != null) {\n              formatted = new this.app.getLz('date.format').replace(\"${d}\", releaseDate.getDate()).replace(\"${m}\", releaseDate.getMonth()).replace(\"${y}\", releaseDate.getFullYear());\n            } else {\n              formatted = new Intl.DateTimeFormat('en-US', {\n                day: 'numeric',\n                month: 'long',\n                year: 'numeric'\n              }).format(releaseDate);\n            }\n          }\n          return prefix + formatted\n        } catch (e) {\n          return \"\"\n        }\n      },\n      play() {\n        function shuffleArray(array) {\n          for (var i = array.length - 1; i > 0; i--) {\n            var j = Math.floor(Math.random() * (i + 1));\n            var temp = array[i];\n            array[i] = array[j];\n            array[j] = temp;\n          }\n        }\n\n        const id = this.data.attributes.playParams.id ?? this.data.id;\n        //console.log(\"1\")\n        const kind = this.data.attributes.playParams.kind ?? this.data.type ?? '';\n        //console.log(\"1\")\n        const truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n\n        let query = (this.data ?? app.showingPlaylist).relationships.tracks.data.map(item => new MusicKit.MediaItem(item));\n        app.mk.stop().then(function() {\n          app.mk.setQueue({ [truekind]: [id], parameters: { l: app.mklang } }).then(function() {\n            app.mk.play().then(function() {\n              if (query.length > 100) {\n                let u = query.slice(100);\n                if (app.mk.shuffleMode == 1) {\n                  shuffleArray(u)\n                }\n                app.mk.queue.append(u)\n              }\n            })\n          })\n        })\n\n\n      }\n\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/plugin-renderer.ejs",
    "content": "<script>\n  Vue.component('plugin-renderer', {\n      /*html*/\n      template: `\n            <component :is=\"getPage()\"></component>\n        `,\n      data: function() {\n        return {\n          app: this.$root,\n        }\n      },\n      props: {},\n      mounted() {\n      },\n      methods: {\n        getPage() {\n          return this.$root.pluginPages.page\n        }\n      },\n    }\n  );\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/podcasts.ejs",
    "content": "<script type=\"text/x-template\" id=\"apple-podcasts\">\n    <div class=\"content-inner podcasts-page\">\n        <div class=\"podcasts-list\">\n            <div class=\"podcasts-search\">\n                <div class=\"search-input-container\" style=\"width:100%;\">\n                    <div class=\"search-input--icon\"></div>\n                    <input type=\"search\"\n                           style=\"width:100%;\"\n                           spellcheck=\"false\"\n                           :placeholder=\"$root.getLz('term.search') + '...'\"\n                           @change=\"searchPodcasts();librarySearch()\"\n                           v-model=\"search.term\" class=\"search-input\">\n                </div>\n            </div>\n            <div v-if=\"search.term == ''\">\n                <div class=\"podcast-list-header\" v-if=\"ciderPodcasts.length != 0\">\n                    {{$root.getLz('podcast.followedOnCider')}}\n                </div>\n                <div class=\"podcast-list-header\" v-if=\"podcasts.length != 0\">\n                    {{$root.getLz('podcast.subscribedOnItunes')}}\n                </div>\n                <podcast-tab :isselected=\"podcastSelected.id == podcast.id\" @click.native=\"selectPodcast(podcast)\"\n                             v-for=\"podcast in podcasts\" :item=\"podcast\"></podcast-tab>\n            </div>\n            <div v-else>\n                <div class=\"podcast-list-header\" v-if=\"podcasts.length != 0\">\n                    {{$root.getLz('term.library')}}\n                </div>\n                <podcast-tab :isselected=\"podcastSelected.id == podcast.id\" @click.native=\"selectPodcast(podcast)\"\n                             v-for=\"podcast in search.resultsLibrary\" :item=\"podcast\"></podcast-tab>\n                <div class=\"podcast-list-header\" v-if=\"podcasts.length != 0\">\n                    {{$root.getLz('podcast.itunesStore')}}\n                </div>\n                <podcast-tab :isselected=\"podcastSelected.id == podcast.id\" @click.native=\"selectPodcast(podcast)\"\n                             v-for=\"podcast in search.results\" :item=\"podcast\"></podcast-tab>\n            </div>\n        </div>\n        <div class=\"episodes-list\">\n            <div v-if=\"podcastSelected.id != -1\" class=\"episodes-inline-info\">\n                <div class=\"row\">\n                    <div class=\"col-auto cider-flex-center\">\n                        <div class=\"podcast-artwork\">\n                            <mediaitem-artwork shadow=\"large\" :url=\"podcastSelected.attributes.artwork.url\"\n                                               size=\"300\"></mediaitem-artwork>\n                        </div>\n                    </div>\n                    <div class=\"col podcast-show-info\">\n                        <h1>{{ podcastSelected.attributes.name }}</h1>\n                        <small>{{ podcastSelected.attributes.releaseFrequency }}</small>\n                        <small>Created: {{ new Date(podcastSelected.attributes.createdDate).toLocaleDateString()\n                            }}</small>\n                    </div>\n                </div>\n\n                <div class=\"well podcast-show-description\">{{ podcastSelected.attributes.description.standard }}</div>\n                <div class=\"row\" v-if=\"!isSubscribed(podcastSelected.id)\">\n                    <div class=\"col\">\n                        <button class=\"md-btn md-btn-block\">{{$root.getLz('podcast.followOnCider')}}</button>\n                    </div>\n                    <div class=\"col\">\n                        <button class=\"md-btn md-btn-block\">{{$root.getLz('podcast.subscribeOnItunes')}}</button>\n                    </div>\n                </div>\n                <h3>{{$root.getLz('podcast.episodes')}}</h3>\n            </div>\n            <div v-if=\"this.search.results.length == 0 && podcastSelected.id == -1\" class=\"podcast-no-search-results\">\n                <h3>{{$root.getLz('error.noResults')}}</h3>\n                <p>{{$root.getLz('error.noResults.description')}}</p>\n            </div>\n            <podcast-episode :isselected=\"selected.id == episode.id\" @dblclick.native=\"playEpisode(episode)\"\n                             @click.native=\"selectEpisode(episode)\" :item=\"episode\"\n                             v-for=\"episode in episodes\"></podcast-episode>\n        </div>\n        <transition name=\"wpfade\">\n            <div class=\"podcasts-details\" v-if=\"selected.id != -1\">\n                <div class=\"podcasts-details-header\">\n                    <button class=\"close-btn\" @click=\"selected.id = -1\"\n                            :aria-label=\"$root.getLz('action.close')\"></button>\n                </div>\n                <div class=\"podcast-artwork\">\n                    <mediaitem-artwork shadow=\"large\" :url=\"selected.attributes.artwork.url\"\n                                       size=\"300\"></mediaitem-artwork>\n                </div>\n                <h3 class=\"podcast-header\">{{ selected.attributes.name }}</h3>\n                <button @click=\"playEpisode(selected)\" class=\"md-btn podcast-play-btn\">\n                    {{$root.getLz('podcast.playEpisode')}}\n                </button>\n                <div class=\"podcast-genre\">\n                    {{ selected.attributes.genreNames[0] }}\n                </div>\n                <div class=\"podcast-metainfo\">\n                    {{ msToMinSec(selected.attributes.durationInMilliseconds) }} • {{ new\n                    Date(selected.attributes.releaseDateTime).toLocaleString() }}\n                </div>\n                <div class=\"well podcast-description\" v-if=\"selected.attributes.description.standard\">{{\n                    selected.attributes.description.standard }}\n                </div>\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <button class=\"md-btn md-btn-block meta-btn\" @click=\"openUrl(selected.attributes.websiteUrl)\">\n                            {{$root.getLz('podcast.website')}}\n                        </button>\n                    </div>\n                    <div class=\"col\">\n                        <button class=\"md-btn md-btn-block meta-btn\"\n                                @click=\"$root.share(selected.attributes.websiteUrl)\">{{$root.getLz('action.share')}}\n                        </button>\n                    </div>\n                </div>\n            </div>\n        </transition>\n\n    </div>\n</script>\n<script type=\"text/x-template\" id=\"podcast-tab\">\n    <div class=\"cd-mediaitem-list-item list-flat\" :class=\"{'mediaitem-selected': isselected}\">\n        <div class=\"artwork\">\n            <mediaitem-artwork\n                    :url=\"item.attributes.artwork.url\"\n                    size=\"50\"\n                    type=\"podcast\"></mediaitem-artwork>\n        </div>\n        <div class=\"info-rect\">\n            <div class=\"title text-overflow-elipsis\">\n                {{ item.attributes.name }}\n            </div>\n        </div>\n    </div>\n</script>\n<script type=\"text/x-template\" id=\"podcast-episode\">\n    <div class=\"cd-mediaitem-list-item list-flat\" :class=\"{'mediaitem-selected': isselected}\">\n        <div class=\"info-rect\" :style=\"{'padding-left':'16px'}\">\n            <div class=\"title text-overflow-elipsis\">\n                {{ item.attributes.name }}\n            </div>\n            <div class=\"subtitle text-overflow-elipsis\">\n                {{ item.attributes.description.standard }}\n            </div>\n            <div class=\"subtitle text-overflow-elipsis\">\n                {{ msToMinSec(item.attributes.durationInMilliseconds) }} • {{ new\n                Date(item.attributes.releaseDateTime).toLocaleString() }}\n            </div>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('podcast-episode', {\n    template: '#podcast-episode',\n    props: ['item', 'isselected'],\n    methods: {\n      msToMinSec(ms) {\n        var minutes = Math.floor(ms / 60000);\n        var seconds = ((ms % 60000) / 1000).toFixed(0);\n        return minutes + \":\" + (seconds < 10 ? '0' : '') + seconds;\n      }\n    }\n  });\n  Vue.component('podcast-tab', {\n    template: '#podcast-tab',\n    props: ['item', 'isselected'],\n    methods: {}\n  });\n  Vue.component('apple-podcasts', {\n    template: '#apple-podcasts',\n    data: function() {\n      return {\n        ciderPodcasts: [],\n        podcasts: [],\n        episodes: [],\n        search: {\n          term: \"\",\n          loading: false,\n          results: [],\n          resultsLibrary: [],\n          next: \"\"\n        },\n        podcastSelected: {\n          id: -1\n        },\n        selected: {\n          id: -1\n        }\n      }\n    },\n    async mounted() {\n      let podcastShow = await app.mk.api.v3.podcasts(`/v1/me/library/podcasts?include=episodes`)\n      this.podcasts = podcastShow.data.data\n      if (podcastShow.data.next) {\n        await this.getNext(podcastShow.data.next)\n      }\n      // this.episodes = podcastShow.data.data[0].relationships.episodes.data\n    },\n    methods: {\n      searchTriggerVis(visible) {\n\n      },\n      librarySearch() {\n        this.search.resultsLibrary = []\n        if (this.search.term.length > 2) {\n          this.search.resultsLibrary = this.podcasts.filter(podcast => podcast.attributes.name.toLowerCase().includes(this.search.term.toLowerCase()))\n        }\n      },\n      isSubscribed(id) {\n        return this.podcasts.filter(podcast => podcast.id == id).length > 0\n      },\n      searchPodcasts() {\n        let self = this\n        if (this.search.term == \"\") {\n          return\n        }\n        app.mk.api.v3.podcasts(`/v1/catalog/${app.mk.storefrontId}/search`, {\n          term: this.search.term,\n          types: [\"podcasts\"],\n          limit: 25\n        }).then(response => {\n          console.log(response)\n          self.search.results = response.data.results.podcasts.data\n        })\n      },\n      openUrl(url) {\n        window.open(url)\n      },\n      msToMinSec(ms) {\n        var minutes = Math.floor(ms / 60000);\n        var seconds = ((ms % 60000) / 1000).toFixed(0);\n        return minutes + \":\" + (seconds < 10 ? '0' : '') + seconds;\n      },\n      playEpisode(episode) {\n        app.mk.setQueue({ 'episode': episode.id, parameters: { l: app.mklang } }).then(() => {\n          app.mk.play()\n        })\n      },\n      selectPodcast(podcast) {\n        this.podcastSelected = podcast\n        this.getEpisodes(podcast)\n      },\n      selectEpisode(episode) {\n        this.selected = Clone(episode)\n      },\n      async getEpisodes(podcast) {\n        this.episodes = []\n        let eps = await app.mk.api.v3.podcasts(`/v1/catalog/${app.mk.storefrontId}/podcasts/${podcast.id}?include=episodes`)\n\n        eps.data.data[0].relationships.episodes.data.forEach(ep => {\n          this.episodes.push(ep)\n        })\n        if (eps.data.data[0].relationships.episodes.next) {\n          await this.getNextEpisodes(eps.data.data[0].relationships.episodes.next, podcast.id)\n        }\n      },\n      async getNextEpisodes(next, podcastId) {\n\n        let podcastShow = await app.mk.api.v3.podcasts(next)\n        if (podcastId != this.podcastSelected.id) {\n          return\n        }\n        podcastShow.data.data.forEach(ep => {\n          this.episodes.push(ep)\n        })\n        if (podcastShow.data.next) {\n          await this.getNextEpisodes(podcastShow.data.next, podcastId)\n        }\n      },\n      async getNext(next) {\n        let podcastShow = await app.mk.api.v3.podcasts(next)\n        this.podcasts = this.podcasts.concat(podcastShow.data.data)\n        if (podcastShow.data.next) {\n          await this.getNext(podcastShow.data.next)\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/radio.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-radio\">\n    <div class=\"content-inner\">\n        <h1 class=\"header-text\">{{$root.getLz(\"term.radio\")}}</h1>\n        <template v-if=\"data.relationships && data.relationships.tabs\">\n            <template v-for=\"(recom,index) in data.relationships.tabs.data[0].relationships.children.data\">\n                <div class=\"row\">\n                    <div class=\"col\" v-if=\"recom.attributes.name != 'Chart Set'\">\n                        <h3>{{ recom.attributes.name ?? \"\"}}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\">\n                        <button class=\"cd-btn-seeall\" v-if=\"recom.attributes.name == 'Recently Played' && recent.length > 10\"\n                                @click=\"app.showCollection({ data: recent }, recom.attributes.name ?? '', 'listen_now')\">\n                            {{app.getLz('term.seeAll')}}\n                        </button>\n                        <template v-if=\"index != 0 && recom.relationships && ((recom.relationships.children &&  recom.relationships.children.data.length > 10) || (recom.relationships.contents && recom.relationships.contents.data.length > 10))\">\n                            <button class=\"cd-btn-seeall\" v-if=\"recom.relationships.room\"\n                                    @click=\"app.showRoom(recom.relationships.room?.data[0].href)\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                            <button class=\"cd-btn-seeall\" v-else\n                                    @click=\"app.showCollection(recom.relationships.children ? recom.relationships.children : recom.relationships.contents, recom.attributes.name ?? '', 'listen_now')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </template>\n                    </div>\n                </div>\n\n                <div v-if=\"recom.attributes.name == 'Recently Played'\">\n                    <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                          :browsesp=\"index == 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\"\n                                                          :kind=\"recom.attributes.editorialElementKind\"\n                                                          :items=\"recent.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                </div>\n                <template v-else-if=\"(recom.relationships != null && ((recom.relationships.children && recom.relationships.children.data) || (recom.relationships.contents && recom.relationships.contents.data)))\">\n                    <template v-if=\"index === 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\">\n                        <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                              :browsesp=\"index == 0|| (data.relationships.tabs.data[0].relationships.children.data[0].relationships == null && index === 1)\"\n                                                              :kind=\"recom.attributes.editorialElementKind\"\n                                                              :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                    </template>\n                    <template v-else-if=\"(['327']).includes(recom.attributes.editorialElementKind)\">\n                        <div class=\"mediaitem-list-item__grid\">\n                            <listitem-horizontal :items=\"recom.relationships.contents.data.limit(20)\">\n                            </listitem-horizontal>\n                        </div>\n                    </template>\n                    <template v-else-if=\"(['385']).includes(recom.attributes.editorialElementKind)\">\n                        <mediaitem-scroller-horizontal-mvview :imagesize=\"800\"\n                                                              :kind=\"recom.attributes.editorialElementKind\"\n                                                              :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                    </template>\n                    <template v-else-if=\"recom.attributes.name == 'Chart Set'\">\n                        <!-- ignored -->\n                    </template>\n                    <template v-else-if=\"(['488']).includes(recom.attributes.editorialElementKind)\">\n                        <!-- ignored -->\n                    </template>\n                    <template v-else>\n                        <mediaitem-scroller-horizontal-large\n                                :items=\"recom.relationships.children ? recom.relationships.children.data.limit(10) : recom.relationships.contents.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                    </template>\n                </template>\n                <template v-else>\n                    <template v-if=\"recom.attributes.links && recom.attributes.editorialElementKind.includes('391')\">\n                        <div class=\"grouping-container\">\n                            <button class=\"grouping-btn\" @click=\"$root.goToGrouping(link.url)\"\n                                    v-for=\"link in recom.attributes.links\">{{ link.label }}\n                            </button>\n                        </div>\n                    </template>\n                </template>\n            </template>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-radio', {\n    template: \"#cider-radio\",\n    props: [\"data\"],\n    data: function() {\n      return {\n        app: this.$root,\n        recent: []\n      };\n    },\n    mounted() {\n      this.$root.getRadioPage();\n    //   debugger\n      this.getRecentlyPlayed();\n    //   debugger\n    },\n    methods: {\n      getRecentlyPlayed: async function (next = null) {\n        const recent = await app.mk.api.v3.music(`${next ?? \"/v1/me/recent/radio-stations\"}`, {\n          \"platform\": \"web\",\n          \"art[url]\": \"f\",\n          l: app.mklang\n        })\n\n        console.debug(recent.data.data)\n        this.recent = this.recent.concat(recent.data.data);\n\n        if (recent.data.next) {\n            this.getRecentlyPlayed(recent.data.next);\n        }\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/recordLabel.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-recordlabel\">\n    <div class=\"content-inner artist-page\">\n        <div class=\"artist-header\" :style=\"getArtistPalette(data)\">\n            <div class=\"row\">\n                <div class=\"col-sm\" style=\"width: auto;\">\n                    <div class=\"artist-image\">\n                        <mediaitem-artwork\n                                shadow=\"large\"\n                                :url=\"data.attributes.artwork ? data.attributes.artwork.url : ''\"\n                                size=\"220\" type=\"artists\"></mediaitem-artwork>\n                    </div>\n                </div>\n                <div class=\"col cider-flex-center\">\n                    <h1>{{ data.attributes.name }}</h1>\n                </div>\n\n            </div>\n        </div>\n        <div class=\"artist-body\">\n            <div v-if=\"$root.showingPlaylist.attributes.description\">\n                <div class=\"row\">\n                    <h3>{{ $root.getLz(\"term.about\") }}</h3>\n                </div>\n                <div class=\"row\">\n                    <div>{{ $root.showingPlaylist.attributes.description.standard }}</div>\n                </div>\n\n            </div>\n            <template v-if=\"data.views && data.views['latest-releases']\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3>{{ data.views[\"latest-releases\"].attributes.title ?? \"\"}}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\" v-if=\"data.views['latest-releases'].data.length >= 10\">\n                        <button class=\"cd-btn-seeall\"\n                                @click=\"$root.showRecordLabelView(data.id, data.attributes.name + ' -  Latest Releases', 'latest-releases')\">\n                            {{ $root.getLz('term.seeAll') }}\n                        </button>\n                    </div>\n                </div>\n                <mediaitem-square :item=\"item\" v-for=\"item in data.views['latest-releases'].data\">\n                </mediaitem-square>\n            </template>\n            <template v-if=\"data.views && data.views['top-releases']\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3>{{ data.views[\"top-releases\"].attributes.title ?? \"\" }}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\" v-if=\"data.views['top-releases'].data.length >= 10\">\n                        <button class=\"cd-btn-seeall\"\n                                @click=\"$root.showRecordLabelView(data.id, data.attributes.name + ' -  Top Releases', 'top-releases')\">\n                            {{ $root.getLz('term.seeAll') }}\n                        </button>\n                    </div>\n                </div>\n                <mediaitem-square :item=\"item\" v-for=\"item in data.views['top-releases'].data\">\n                </mediaitem-square>\n            </template>\n            <template\n                    v-if=\"data.relationships && data.relationships.playlists && data.relationships.playlists.data.length > 0\">\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h3>{{ $root.getLz('term.playlists') }}</h3>\n                    </div>\n                    <div class=\"col-auto cider-flex-center\" v-if=\"data.relationships.playlists.data.length >= 5\">\n                        <button class=\"cd-btn-seeall\"\n                                @click=\"$root.showCollection(data.relationships.playlists, data.attributes.name + ' -  Playlists', 'curator')\">\n                            {{ $root.getLz('term.seeAll') }}\n                        </button>\n                    </div>\n                </div>\n                <mediaitem-square :item=\"item\" v-for=\"item in data.relationships.playlists.data.limit(5)\">\n                </mediaitem-square>\n            </template>\n        </div>\n    </div>\n</script>\n<script>\n  Vue.component('cider-recordlabel', {\n    template: \"#cider-recordlabel\",\n    props: ['data'],\n    data: function() {\n      return {\n        topSongsExpanded: false,\n        $root: this.$root\n      }\n    },\n    methods: {\n      getArtistPalette(artist) {\n        if (artist?.attributes?.artwork != null) {\n          return {\n            \"background\": \"#\" + artist[\"attributes\"][\"artwork\"][\"bgColor\"],\n            \"color\": \"#\" + artist[\"attributes\"][\"artwork\"][\"textColor1\"],\n          }\n        } else {\n          return {\n            \"background\": \"#000000\",\n            \"color\": \"#ffffff\",\n          }\n        }\n      },\n      getTopResult() {\n        if (this.search.results[\"meta\"]) {\n          return this.search.results[this.search.results.meta.results.order[0]][\"data\"][0]\n        } else {\n          return false;\n        }\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/remote-pair.ejs",
    "content": "<script type=\"text/x-template\" id=\"remote-pair\">\n    <div style=\"display:flex;width:100%;height:100%;padding-top: var(--navigationBarHeight);position:absolute;top:0;left:0;\">\n        <webview id=\"foo\" src=\"https://cider.sh\" style=\"display:inline-flex; width:100%;\"></webview>\n    </div>\n</script>\n<script>\n  Vue.component('remote-pair', {\n    template: '#remote-pair',\n    async mounted() {\n      ipcRenderer.send('get-remote-pair-url')\n      ipcRenderer.on('send-remote-pair-url', (event, url) => {\n        this.url = url\n        app.webview.src = url\n        document.getElementById('foo').src = url;\n      })\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/replay.ejs",
    "content": "<script type=\"text/x-template\" id=\"replay-page\">\n    <div class=\"content-inner replay-page\">\n        <vue-horizontal style=\"height: 300px;\">\n            <div class=\"replay-period\" v-for=\"year in years\" @click=\"getReplayYear(year.attributes.year)\">\n                <div class=\"artwork-container\">\n                    <mediaitem-artwork :size=\"200\"\n                                       :url=\"year.relationships.playlist.data[0].attributes.artwork.url\"></mediaitem-artwork>\n                </div>\n                {{ year.attributes.year }}\n            </div>\n        </vue-horizontal>\n        <hr>\n        <transition name=\"replaycard\">\n            <div class=\"replay-viewport\" v-if=\"loaded.id != -1\">\n                <!-- Stats -->\n                <div class=\"replay-video\" v-if=\"false\">\n                    <mediaitem-artwork\n                            :url=\"loaded.playlist.attributes.editorialVideo.motionWideVideo21x9.previewFrame.url\"\n                            :video=\"loaded.playlist.attributes.editorialVideo.motionWideVideo21x9.video\"\n                            :video-priority=\"true\"></mediaitem-artwork>\n                </div>\n                <h1 class=\"replay-header\">{{ loaded.attributes.year }} {{$root.getLz('term.replay')}}</h1>\n                <hr>\n                <div class=\"row\">\n                    <div class=\"col\">\n                        <h4 @click=\"hourshow = !hourshow\">{{convertToHours(loaded.attributes.listenTimeInMinutes)}}\n                            {{$root.getLz('term.time.hours')}} \n                            {{hourshow ? \"\" : (loaded.attributes.listenTimeInMinutes % 60) }}\n                            {{hourshow ? \"\" : $root.getLz('term.time.minutes')}}</h4>\n                        <h4>{{ loaded.attributes.uniqueAlbumCount }} {{$root.getLz('term.uniqueAlbums')}}</h4>\n                        <h4>{{ loaded.attributes.uniqueArtistCount }} {{$root.getLz('term.uniqueArtists')}}</h4>\n                        <h4>{{ loaded.attributes.uniqueSongCount }} {{$root.getLz('term.uniqueSongs')}}</h4>\n                    </div>\n                    <div class=\"col-auto replay-playlist-container\">\n                        <mediaitem-square kind=\"card\" :no-scale=\"true\" :force-video=\"true\"\n                                          :item=\"loaded.playlist\"></mediaitem-square>\n                    </div>\n                </div>\n                <!--            Top Artists-->\n                <h3>{{$root.getLz('term.topArtists')}}</h3>\n                <div class=\"well\">\n                    <mediaitem-scroller-horizontal>\n                        <div class=\"card replay-card\" v-for=\"artistData in loaded.views['top-artists'].data\">\n                            <div class=\"card-body\">\n                                <mediaitem-square :item=\"artistData.relationships.artist.data[0]\"></mediaitem-square>\n                            </div>\n                            <div class=\"card-footer\">\n                                {{ convertToHours(artistData.attributes.listenTimeInMinutes) }}\n                                {{$root.getLz('term.time.hours', {'count':\n                                convertToHours(artistData.attributes.listenTimeInMinutes) })}}<br>\n                                {{$root.getLz('term.listenedTo')}} {{ artistData.attributes.playCount }}\n                                {{$root.getLz('term.times')}}\n                            </div>\n                        </div>\n                    </mediaitem-scroller-horizontal>\n                </div>\n                <!--            Top Albums-->\n                <h3>{{$root.getLz('term.topAlbums')}}</h3>\n                <div class=\"well\">\n                    <mediaitem-scroller-horizontal>\n                        <div class=\"card replay-card\" v-for=\"albumData in loaded.views['top-albums'].data\">\n                            <div class=\"card-body\">\n                                <mediaitem-square :item=\"albumData.relationships.album.data[0]\"></mediaitem-square>\n                            </div>\n                            <div class=\"card-footer\">\n                                {{ convertToHours(albumData.attributes.listenTimeInMinutes) }}\n                                {{$root.getLz('term.time.hours', {'count':\n                                convertToHours(albumData.attributes.listenTimeInMinutes)})}}<br>\n                                {{ albumData.attributes.playCount }} {{$root.getLz('term.plays')}}\n                            </div>\n                        </div>\n                    </mediaitem-scroller-horizontal>\n                </div>\n                <!--            Top Songs-->\n                <h3>{{$root.getLz('term.topSongs')}}</h3>\n                <div class=\"well\">\n                    <listitem-horizontal :show-library-status=\"false\"\n                                         :items=\"songsToArray(loaded.views['top-songs'].data)\"></listitem-horizontal>\n                </div>\n                <h3>{{$root.getLz('term.topGenres')}}</h3>\n                <div class=\"top-genres-container\">\n                    <div v-for=\"genre in loaded.topGenres\" class=\"replay-genre-display\">\n                        <div class=\"genre-name\">\n                            {{ genre.genre }}\n                        </div>\n                        <div class=\"genre-count\">\n                            <div class=\"genre-count-bar\" :style=\"{'width': genre.count + '%'}\">\n                                {{ genre.count }}%\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </transition>\n    </div>\n</script>\n<script>\n  Vue.component('replay-page', {\n    template: '#replay-page',\n    data: function() {\n      return {\n        years: [],\n        loaded: {\n          id: -1\n        },\n        hourshow: true,\n        musicTypeGenre: \"\"\n      }\n    },\n    async mounted() {\n      // Get available years\n      let year = await app.mk.api.v3.music(\"/v1/me/music-summaries/search?extend=inLibrary&period=year&fields[music-summaries]=period%2Cyear&include[music-summaries]=playlist\")\n      this.years = year.data.data\n      this.years.reverse()\n      localStorage.setItem(\"seenReplay\", true)\n      this.getReplayYear();\n      const musicGenre = await app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/genres/34`)\n      this.musicTypeGenre = musicGenre.data.data[0].attributes.name\n    },\n    methods: {\n      songsToArray(songsData) {\n        let self = this\n        let songs = []\n        let topGenres = {}\n        let genrePlayCount = 0;\n        songsData.forEach(function(songData) {\n          let song = songData.relationships.song.data[0]\n          song.attributes.playCount = songData.attributes.playCount\n          songs.push(song)\n          genrePlayCount += song.attributes.playCount\n          song.attributes.genreNames.forEach(function(genre) {\n            if (genre != self.musicTypeGenre) {\n              if (topGenres[genre] == undefined) {\n                topGenres[genre] = song.attributes.playCount\n              } else {\n                topGenres[genre] += song.attributes.playCount\n              }\n            }\n          })\n        })\n        let topGenresArray = []\n        for (let genre in topGenres) {\n          topGenresArray.push({\n            genre: genre,\n            count: topGenres[genre]\n          })\n        }\n        topGenresArray.sort(function(a, b) {\n          return b.count - a.count\n        })\n        topGenresArray.forEach(function(genre) {\n          genre.count = Math.round(genre.count / genrePlayCount * 100)\n        })\n        this.loaded.topGenres = topGenresArray\n\n        return songs\n      },\n      async getReplayYear(year = new Date().getFullYear()) {\n        this.loaded.id = -1\n        let response = await app.mk.api.v3.music(`/v1/me/music-summaries/year-${year}?extend=inLibrary&views=top-artists%2Ctop-albums%2Ctop-songs&include[music-summaries]=playlist&include[playlists]=tracks&includeOnly=playlist%2Ctracks%2Csong%2Cartist%2Calbum`)\n        let replayData = response.data.data[0]\n        // extended playlist\n        let playlist = await app.mk.api.v3.music(replayData.relationships.playlist.data[0].href, { extend: \"editorialArtwork,editorialVideo\" })\n        replayData.playlist = playlist.data.data[0]\n        this.loaded = replayData\n      },\n      convertToHours(minutes) {\n        return Math.floor(minutes / 60)\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/search.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-search\">\n    <div class=\"content-inner search-page\">\n        <div class=\"search-input-container fs-search\" v-if=\"$root.appMode == 'fullscreen'\">\n            <div class=\"search-input--icon\"></div>\n            <input type=\"search\" spellcheck=\"false\" @focus=\"$root.search.showHints = true\"\n                    @blur=\"$root.setTimeout(()=>{if($root.hintscontext != true){$root.search.showHints = false} }, 300)\"\n                   v-on:keyup.enter=\"$root.searchQuery($root.search.hints[$root.search.cursor]?.content ?? $root.search.hints[$root.search.cursor]?.searchTerm ?? $root.search.term);$root.search.showHints = false; $root.search.showSearchView = true\" @input=\"$root.getSearchHints()\"\n                   :placeholder=\"$root.getLz('term.search') + '...'\" v-model=\"$root.search.term\"\n                   class=\"search-input\" />\n\n            <div class=\"search-hints-container\" v-if=\"$root.search.showHints && $root.search.hints.length != 0\">\n                <div class=\"search-hints\">\n                    <button class=\"search-hint text-overflow-elipsis\" v-for=\"(hint, index) in $root.search.hints.filter((a) => {return a.content == null})\" :class=\"{active: ($root.search.cursor == index)}\"\n                            @click=\"$root.search.term = hint.searchTerm;$root.search.showHints = false;$root.searchQuery(hint.searchTerm)\">\n                        {{ hint.displayTerm }}\n                    </button>\n                    <template v-for=\"(item, position) in $root.search.hints.filter((a) => {return a.content != null})\">\n                        <mediaitem-smarthints :item=\"item.content\" :position=\"position\"> </mediaitem-smarthints>\n                    </template>\n                </div>\n\n            </div>\n        </div>\n        <div class=\"btn-group searchToggle\">\n            <button\n                    @click=\"searchType = 'catalog'\"\n                    class=\"md-btn md-btn-small\" :class=\"{'md-btn-primary': searchType == 'catalog'}\">{{\n                $root.getLz(\"term.appleMusic\") }}\n            </button>\n            <button\n                    @click=\"searchType = 'library';\"\n                    class=\"md-btn md-btn-small\" :class=\"{'md-btn-primary': searchType == 'library'}\">{{\n                $root.getLz(\"term.library\") }}\n            </button>\n        </div>\n        <div v-if=\"search != null && search != [] && search.term != '' && $root.search.showSearchView\">\n            <template v-if=\"searchType == 'catalog'\">\n                <h3>{{app.getLz('term.topResult')}}</h3>\n                <mediaitem-scroller-horizontal\n                        :items=\"search?.results[search?.results?.meta?.results?.order[0]]?.data\"></mediaitem-scroller-horizontal>\n                <div class=\"row\">\n                    <div class=\"col\" v-if=\"search.results.song\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                <h3>{{app.getLz('term.songs')}}</h3>\n                            </div>\n                            <div class=\"col-auto cider-flex-center\"\n                                 @click=\"app.showSearchView(app.search.term, 'song', app.friendlyTypes('song'))\"\n                                 v-if=\"search.results.song.data.length >= 12\">\n                                <button class=\"cd-btn-seeall\">{{app.getLz('term.seeAll')}}</button>\n                            </div>\n                        </div>\n                        <div class=\"mediaitem-list-item__grid\">\n                            <listitem-horizontal :items=\"search.results.song.data.limit(12)\">\n                            </listitem-horizontal>\n                        </div>\n                    </div>\n                    <div v-else style=\"text-align: center\">\n                        <h3>{{app.getLz('error.noResults')}}</h3>\n                        <p>{{app.getLz('error.noResults.description')}}</p>\n                    </div>\n                </div>\n\n                <template v-if=\"search.results['meta'] != null\">\n                    <template\n                            v-for=\"section in search.results.meta.results.order\"\n                            v-if=\"section != 'song' && section != 'top'\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                <h3>{{ app.friendlyTypes(section) }}</h3>\n                            </div>\n                            <div class=\"col-auto cider-flex-center\" v-if=\"search.results[section].data.length >= 10\">\n                                <button class=\"cd-btn-seeall\"\n                                        @click=\"app.showSearchView(app.search.term, section, app.friendlyTypes(section))\">\n                                    {{app.getLz('term.seeAll')}}\n                                </button>\n                            </div>\n                        </div>\n                        <template v-if=\"!app.friendlyTypes(section).includes('Video')\">\n                            <mediaitem-scroller-horizontal-large\n                                    :items=\"search.results[section].data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                        </template>\n                        <template v-else>\n                            <mediaitem-scroller-horizontal-mvview\n                                    :items=\"search.results[section].data.limit(10)\"></mediaitem-scroller-horizontal-mvview>\n                        </template>\n                    </template>\n                </template>\n                <template v-if=\"search.resultsSocial.playlist\">\n                    <div class=\"row\">\n                        <div class=\"col\">\n                            <h3>{{app.getLz('term.sharedPlaylists')}}</h3>\n                        </div>\n                        <div class=\"col-auto cider-flex-center\" v-if=\"search.resultsSocial.playlist.data.length >= 10\">\n                            <button class=\"cd-btn-seeall\"\n                                    @click=\"app.showCollection(search.resultsSocial.playlist, 'Shared Playlists', 'default')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <mediaitem-scroller-horizontal-large\n                            :items=\"search.resultsSocial.playlist.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                </template>\n                <template v-if=\"search.resultsSocial.profile\">\n                    <div class=\"row\">\n                        <div class=\"col\">\n                            <h3>{{app.getLz('term.people')}}</h3>\n                        </div>\n                        <div class=\"col-auto cider-flex-center\" v-if=\"search.resultsSocial.profile.data.length >= 10\">\n                            <button class=\"cd-btn-seeall\"\n                                    @click=\"app.showCollection(search.resultsSocial.profile, 'People', 'default')\">\n                                {{app.getLz('term.seeAll')}}\n                            </button>\n                        </div>\n                    </div>\n                    <mediaitem-scroller-horizontal-large\n                            :items=\"search.resultsSocial.profile.data.limit(10)\"></mediaitem-scroller-horizontal-large>\n                </template>\n            </template>\n            <template v-else>\n                <h1>{{ $root.getLz(\"term.library\") }}</h1>\n                <div v-for=\"(section, key) in $root.search.resultsLibrary\">\n                    <h3>{{app.friendlyTypes(key)}}</h3>\n                    <div class=\"mediaitem-list-item__grid\" v-if=\"key.includes('songs')\">\n                        <listitem-horizontal :items=\"section.data\"></listitem-horizontal>\n                    </div>\n                    <div class=\"well\" v-else>\n                        <mediaitem-scroller-horizontal-large\n                                :items=\"section.data\"></mediaitem-scroller-horizontal-large>\n                    </div>\n                </div>\n            </template>\n        </div>\n        <div v-else>\n            <div v-if=\"categoriesReady || getCategories()\">\n                <div>\n                    <div class=\"col\"\n                         v-if=\"categoriesView != null && categoriesView != [] && categoriesView[0]?.attributes != null && categoriesView[0]?.attributes.title != null\">\n                        <h3>{{$root.getLz('home.recentlyPlayed')}}</h3>\n                        <div class=\"mediaitem-list-item__grid\">\n                            <listitem-horizontal :items=\"recentlyPlayed.limit(10)\">\n                            </listitem-horizontal>\n                        </div>\n                        <!-- <mediaitem-square :kind=\"'385'\" size=\"600\" v-for=\"item in recentlyPlayed.limit(10)\" :item=\"item\" :imagesize=\"800\"></mediaitem-square>-->\n                        <h3>{{categoriesView[0]?.attributes?.title?.stringForDisplay ?? \"\"}}</h3>\n                    </div>\n                </div>\n                <div class=\"categories\">\n                    <mediaitem-square :kind=\"'385'\" :imageformat=\"'bb'\" size=\"600\" :removeamtext=\"true\"\n                                      :item=\"item ? (item.attributes.kind ? item : ((item.relationships && item.relationships.contents ) ? item.relationships.contents.data[0] : item)) : []\"\n                                      :imagesize=\"800\"\n                                      v-for=\"item of getFlattenedCategories()\"/>\n                </div>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script>\n  Vue.component('cider-search', {\n    template: \"#cider-search\",\n    props: ['search'],\n    data: function() {\n      return {\n        app: this.$root,\n        recentlyPlayed: [],\n        categoriesView: [],\n        categoriesReady: false,\n        searchType: \"catalog\",\n      }\n    },\n    methods: {\n      getTopResult() {\n        try {\n          return this.search.results[this.search.results.meta.results.order[0]][\"data\"][0]\n        } catch (error) {\n          return false\n        }\n      },\n      async seeAllHistory() {\n        let hist = await app.mk.api.v3.music(`/v1/me/recent/played/tracks`, {\n          l: this.$root.mklang\n        })\n        this.recentlyPlayed = hist.data.data\n      },\n      async getCategories() {\n        if (this.categoriesView != [] && this.categoriesView.length > 0) {\n          this.categoriesReady = true;\n          return await true;\n        } else {\n          await this.seeAllHistory()\n          let response = await this.app.mk.api.v3.music(`/v1/recommendations/${this.app.mk.storefrontId}?timezone=${encodeURIComponent(this.app.formatTimezoneOffset())}&name=search-landing&platform=web&extend=editorialArtwork&art%5Burl%5D=f%2Cc&types=editorial-items%2Capple-curators%2Cactivities&l=${this.$root.mklang}`);\n          this.categoriesView = response.data.data;\n          console.log(this.categoriesView)\n          this.categoriesReady = true;\n          return await true;\n        }\n      },\n      getFlattenedCategories() {\n        let flattened = [];\n        for (let i = 0; i < this.categoriesView.length; i++) {\n          if (this.categoriesView[i].relationships && this.categoriesView[i].relationships.contents && this.categoriesView[i].relationships.contents.data) {\n            for (let j = 0; j < this.categoriesView[i].relationships.contents.data.length; j++) {\n              if (this.categoriesView[i].relationships.contents.data[j].type != 'editorial-items')\n                flattened.push(this.categoriesView[i].relationships.contents.data[j])\n            }\n          }\n        }\n        return flattened;\n      }\n    }\n  })\n</script>\n"
  },
  {
    "path": "src/renderer/views/pages/themes-github.ejs",
    "content": "//Not used for Now\n\n<!-- <script type=\"text/x-template\" id=\"themes-github\">\n    <div class=\"github-themes-page\">\n        <div class=\"gh-header\">\n            <div class=\"row\">\n                <div class=\"col nopadding\">\n                    <h1 class=\"header-text\">{{$root.getLz('settings.header.visual.theme.github.page')}}</h1>\n                </div>\n                <div class=\"col-auto nopadding flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.appRoute('installed-themes')\">\n                        {{$root.getLz('settings.option.visual.theme.manageStyles')}}\n                    </button>\n                </div>\n                <div class=\"col-auto flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"$root.checkForThemeUpdates()\">\n                        {{ $root.getLz('settings.option.visual.theme.checkForUpdates') }}\n                    </button>\n                </div>\n                <div class=\"col-auto nopadding flex-center\">\n                    <button class=\"md-btn md-btn-small md-btn-block\" @click=\"installThemeURL()\">\n                        {{$root.getLz('settings.option.visual.theme.github.download')}}\n                    </button>\n                </div>\n            </div>\n        </div>\n        <div class=\"gh-content\">\n            <div class=\"repos-list\">\n                <ul class=\"list-group list-group-flush\">\n                    <li @click=\"showRepo(repo)\" class=\"list-group-item list-group-item-dark\"\n                        :style=\"{'background': (repo.id == openRepo.id) ? 'var(--keyColor)' : ''}\"\n                        v-for=\"repo in repos\">\n                        <div class=\"row\">\n                            <div class=\"col flex-center\">\n                                <div>\n                                    <h4 class=\"repo-name\">{{ (repo.description != null) ? repo.description :\n                                        repo.full_name }}</h4>\n                                    <div>⭐ {{ repo.stargazers_count }}</div>\n                                </div>\n                            </div>\n                            <div class=\"col-auto\">\n                                <span v-if=\"themesInstalled.includes(repo.full_name.toLowerCase())\"\n                                      class=\"codicon codicon-cloud-download\"></span>\n                            </div>\n                        </div>\n                    </li>\n                </ul>\n            </div>\n\n            <div class=\"github-preview\" v-if=\"openRepo.full_name\">\n                <div class=\"gh-preview-header\">\n                    <div class=\"row nopadding\">\n                        <div class=\"col nopadding flex-center\">\n                            <div>\n                                <h3 class=\"repo-preview-name\">{{ openRepo.description }}</h3>\n                                <div>\n                                    <div class=\"svg-icon inline\"\n                                         :style=\"{'--url': 'url(\\'./assets/github.svg\\')'}\"></div>\n                                    <a class=\"repo-url\" target=\"_blank\" :href=\"openRepo.html_url\">{{ openRepo.full_name\n                                        }}</a></div>\n                                <div>⭐ {{ openRepo.stargazers_count }}</div>\n                            </div>\n                        </div>\n                        <div class=\"col-auto nopadding flex-center\">\n                            <button class=\"md-btn md-btn-primary\" @click=\"installThemeRepo(openRepo)\">\n                                <span v-if=\"!themesInstalled.includes(openRepo.full_name.toLowerCase())\">{{$root.getLz('action.install')}}</span>\n                                <span v-else>{{$root.getLz('action.update')}}</span>\n                            </button>\n                        </div>\n                    </div>\n                </div>\n                <hr>\n                <div v-html=\"openRepo.readme\" class=\"github-content\"></div>\n            </div>\n            <div class=\"github-preview\" v-else>\n\n            </div>\n            </transition>\n        </div>\n    </div>\n</script>\n<script>\n    Vue.component('themes-github', {\n        template: \"#themes-github\",\n        props: [],\n        data: function () {\n            return {\n                repos: [],\n                openRepo: {\n                    id: -1,\n                    name: '',\n                    description: '',\n                    html_url: '',\n                    stargazers_count: 0,\n                    owner: {\n                        avatar_url: ''\n                    },\n                    readme: \"\"\n                },\n                themesInstalled: [],\n                themes: []\n            }\n        },\n        mounted() {\n            this.themes = ipcRenderer.sendSync(\"get-themes\")\n            this.getRepos();\n            this.getInstalledThemes();\n        },\n        methods: {\n            openThemesFolder() {\n                ipcRenderer.invoke(\"open-path\", \"themes\")\n            },\n            getInstalledThemes() {\n                let self = this\n                const themes = ipcRenderer.sendSync(\"get-themes\")\n                // for each theme, get the github_repo property and push it to the themesInstalled array, if not blank\n                themes.forEach(theme => {\n                    if (theme.github_repo !== \"\" && typeof theme.commit != \"\") {\n                        self.themesInstalled.push(theme.github_repo.toLowerCase())\n                    }\n                })\n            },\n            showRepo(repo) {\n                const self = this\n                const readmeUrl = `https://raw.githubusercontent.com/${repo.full_name}/main/README.md`;\n                var requestOptions = {\n                    method: 'GET',\n                    redirect: 'follow'\n                };\n\n                fetch(readmeUrl, requestOptions)\n                    .then(response => response.text())\n                    .then(result => {\n                        self.openRepo = repo\n                        self.openRepo.readme = self.convertReadMe(result);\n                    })\n                    .catch(error => {\n                        self.openRepo = repo\n                        self.openRepo.readme = `This repository doesn't have a README.md file.`;\n                        console.log('error', error)\n                    });\n            },\n            convertReadMe(text) {\n                return marked.parse(text)\n            },\n            installThemeRepo(repo) {\n                let self = this\n                let msg = app.stringTemplateParser(app.getLz('settings.option.visual.theme.github.install.confirm'), {\n                    repo: repo.full_name\n                });\n                app.confirm(msg, (res) => {\n                    if (res) {\n                        ipcRenderer.once(\"theme-installed\", (event, arg) => {\n                            if (arg.success) {\n                                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                                self.getInstalledThemes()\n                                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n                            } else {\n                                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n                            }\n                        });\n                        ipcRenderer.invoke(\"get-github-theme\", repo.html_url)\n                    }\n                })\n            },\n            installThemeURL() {\n                let self = this\n                app.prompt(app.getLz('settings.prompt.visual.theme.github.URL'), (result) => {\n                    if (result) {\n                        ipcRenderer.once(\"theme-installed\", (event, arg) => {\n                            if (arg.success) {\n                                self.themes = ipcRenderer.sendSync(\"get-themes\")\n                                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));\n                            } else {\n                                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));\n                            }\n                        });\n                        ipcRenderer.invoke(\"get-github-theme\", result)\n                    }\n                });\n            },\n            getRepos() {\n                let self = this\n                var requestOptions = {\n                    method: 'GET',\n                    redirect: 'follow'\n                };\n\n                app._fetch(\"https://api.github.com/search/repositories?q=topic:cidermusictheme fork:true&per_page=100\", requestOptions)\n                    .then(response => response.text())\n                    .then(result => {\n                        let items = JSON.parse(result).items\n                        self.repos = items\n                    })\n                    .catch(error => console.log('error', error));\n            }\n        }\n    })\n</script>\n -->\n"
  },
  {
    "path": "src/renderer/views/pages/webview.ejs",
    "content": "<template v-if=\"page == 'webview'\">\n    <div style=\"display:flex;width:100%;height:100%\">\n        <webview id=\"foo\" :src=\"webview.url\" nodeintegration=\"true\" style=\"display:inline-flex; width:100%;\"></webview>\n    </div>\n</template>\n"
  },
  {
    "path": "src/renderer/views/pages/zoo.ejs",
    "content": "<script type=\"text/x-template\" id=\"cider-zoo\">\n    <div class=\"content-inner\">\n        <svg-icon />\n        <h3>Welcome to element park. *BERR NERR NERR NERR NERRRRR BERR NER NER NER NERRR BERRR NR NR NRRRR*</h3>\n        <button @click=\"app.playMediaItemById('1592151778', 'album')\">Play Test Album</button>\n        {{ $store.state.test }}\n        <div class=\"spinner\"></div>\n        <button class=\"md-btn\">Cider Button</button>\n        <artist-chip\n                v-if=\"artistLoaded\"\n                :item=\"artist\"\n        ></artist-chip>\n\n        <amp-chrome-player />\n        <!-- <amp-footer-player/> -->\n        <hr>\n        <amp-lcd-progress />\n        <hr>\n        <amp-playback-controls-shuffle />\n        <apple-music-playback-controls theme=\"dark\" />\n        <apple-music-progress theme=\"dark\"></apple-music-progress>\n        <apple-music-volume theme=\"dark\"></apple-music-volume>\n        <amp-user-menu />\n        <amp-tv-overlay />\n        <amp-podcast-playback-controls />\n        <amp-lcd />\n    </div>\n</script>\n<script>\n  Vue.component('cider-zoo', {\n    template: '#cider-zoo',\n    data: function() {\n      return {\n        artistLoaded: false,\n        artist: {}\n      }\n    },\n    async mounted() {\n      app.mk.api.v3.music(`/v1/catalog/${app.mk.storefrontId}/artists/669831761`).then(response => {\n        this.artist = response.data.data[0];\n        this.artistLoaded = true;\n      });\n    },\n    methods: {}\n  });\n</script>\n"
  },
  {
    "path": "src/renderer/workbox-962786f2.js",
    "content": "define([\"exports\"], function (t) {\n  \"use strict\";\n  try {\n    self[\"workbox:core:6.4.1\"] && _();\n  } catch (t) {}\n  const e = (t, ...e) => {\n    let s = t;\n    return e.length > 0 && (s += ` :: ${JSON.stringify(e)}`), s;\n  };\n  class s extends Error {\n    constructor(t, s) {\n      super(e(t, s)), (this.name = t), (this.details = s);\n    }\n  }\n  try {\n    self[\"workbox:routing:6.4.1\"] && _();\n  } catch (t) {}\n  const n = (t) => (t && \"object\" == typeof t ? t : { handle: t });\n  class r {\n    constructor(t, e, s = \"GET\") {\n      (this.handler = n(e)), (this.match = t), (this.method = s);\n    }\n    setCatchHandler(t) {\n      this.catchHandler = n(t);\n    }\n  }\n  class i extends r {\n    constructor(t, e, s) {\n      super(\n        ({ url: e }) => {\n          const s = t.exec(e.href);\n          if (s && (e.origin === location.origin || 0 === s.index)) return s.slice(1);\n        },\n        e,\n        s,\n      );\n    }\n  }\n  class o {\n    constructor() {\n      (this.t = new Map()), (this.i = new Map());\n    }\n    get routes() {\n      return this.t;\n    }\n    addFetchListener() {\n      self.addEventListener(\"fetch\", (t) => {\n        const { request: e } = t,\n          s = this.handleRequest({ request: e, event: t });\n        s && t.respondWith(s);\n      });\n    }\n    addCacheListener() {\n      self.addEventListener(\"message\", (t) => {\n        if (t.data && \"CACHE_URLS\" === t.data.type) {\n          const { payload: e } = t.data,\n            s = Promise.all(\n              e.urlsToCache.map((e) => {\n                \"string\" == typeof e && (e = [e]);\n                const s = new Request(...e);\n                return this.handleRequest({ request: s, event: t });\n              }),\n            );\n          t.waitUntil(s), t.ports && t.ports[0] && s.then(() => t.ports[0].postMessage(!0));\n        }\n      });\n    }\n    handleRequest({ request: t, event: e }) {\n      const s = new URL(t.url, location.href);\n      if (!s.protocol.startsWith(\"http\")) return;\n      const n = s.origin === location.origin,\n        { params: r, route: i } = this.findMatchingRoute({\n          event: e,\n          request: t,\n          sameOrigin: n,\n          url: s,\n        });\n      let o = i && i.handler;\n      const a = t.method;\n      if ((!o && this.i.has(a) && (o = this.i.get(a)), !o)) return;\n      let c;\n      try {\n        c = o.handle({ url: s, request: t, event: e, params: r });\n      } catch (t) {\n        c = Promise.reject(t);\n      }\n      const h = i && i.catchHandler;\n      return (\n        c instanceof Promise &&\n          (this.o || h) &&\n          (c = c.catch(async (n) => {\n            if (h)\n              try {\n                return await h.handle({\n                  url: s,\n                  request: t,\n                  event: e,\n                  params: r,\n                });\n              } catch (t) {\n                t instanceof Error && (n = t);\n              }\n            if (this.o) return this.o.handle({ url: s, request: t, event: e });\n            throw n;\n          })),\n        c\n      );\n    }\n    findMatchingRoute({ url: t, sameOrigin: e, request: s, event: n }) {\n      const r = this.t.get(s.method) || [];\n      for (const i of r) {\n        let r;\n        const o = i.match({ url: t, sameOrigin: e, request: s, event: n });\n        if (o) return (r = o), ((Array.isArray(r) && 0 === r.length) || (o.constructor === Object && 0 === Object.keys(o).length) || \"boolean\" == typeof o) && (r = void 0), { route: i, params: r };\n      }\n      return {};\n    }\n    setDefaultHandler(t, e = \"GET\") {\n      this.i.set(e, n(t));\n    }\n    setCatchHandler(t) {\n      this.o = n(t);\n    }\n    registerRoute(t) {\n      this.t.has(t.method) || this.t.set(t.method, []), this.t.get(t.method).push(t);\n    }\n    unregisterRoute(t) {\n      if (!this.t.has(t.method))\n        throw new s(\"unregister-route-but-not-found-with-method\", {\n          method: t.method,\n        });\n      const e = this.t.get(t.method).indexOf(t);\n      if (!(e > -1)) throw new s(\"unregister-route-route-not-registered\");\n      this.t.get(t.method).splice(e, 1);\n    }\n  }\n  let a;\n  const c = () => (a || ((a = new o()), a.addFetchListener(), a.addCacheListener()), a);\n  function h(t, e, n) {\n    let o;\n    if (\"string\" == typeof t) {\n      const s = new URL(t, location.href);\n      o = new r(({ url: t }) => t.href === s.href, e, n);\n    } else if (t instanceof RegExp) o = new i(t, e, n);\n    else if (\"function\" == typeof t) o = new r(t, e, n);\n    else {\n      if (!(t instanceof r))\n        throw new s(\"unsupported-route-type\", {\n          moduleName: \"workbox-routing\",\n          funcName: \"registerRoute\",\n          paramName: \"capture\",\n        });\n      o = t;\n    }\n    return c().registerRoute(o), o;\n  }\n  const u = {\n      googleAnalytics: \"googleAnalytics\",\n      precache: \"precache-v2\",\n      prefix: \"workbox\",\n      runtime: \"runtime\",\n      suffix: \"undefined\" != typeof registration ? registration.scope : \"\",\n    },\n    l = (t) => [u.prefix, t, u.suffix].filter((t) => t && t.length > 0).join(\"-\"),\n    f = (t) => t || l(u.precache),\n    w = (t) => t || l(u.runtime);\n  function d(t, e) {\n    const s = new URL(t);\n    for (const t of e) s.searchParams.delete(t);\n    return s.href;\n  }\n  class p {\n    constructor() {\n      this.promise = new Promise((t, e) => {\n        (this.resolve = t), (this.reject = e);\n      });\n    }\n  }\n  const y = new Set();\n  try {\n    self[\"workbox:strategies:6.4.1\"] && _();\n  } catch (t) {}\n  function g(t) {\n    return \"string\" == typeof t ? new Request(t) : t;\n  }\n  class R {\n    constructor(t, e) {\n      (this.h = {}), Object.assign(this, e), (this.event = e.event), (this.u = t), (this.l = new p()), (this.p = []), (this.g = [...t.plugins]), (this.R = new Map());\n      for (const t of this.g) this.R.set(t, {});\n      this.event.waitUntil(this.l.promise);\n    }\n    async fetch(t) {\n      const { event: e } = this;\n      let n = g(t);\n      if (\"navigate\" === n.mode && e instanceof FetchEvent && e.preloadResponse) {\n        const t = await e.preloadResponse;\n        if (t) return t;\n      }\n      const r = this.hasCallback(\"fetchDidFail\") ? n.clone() : null;\n      try {\n        for (const t of this.iterateCallbacks(\"requestWillFetch\")) n = await t({ request: n.clone(), event: e });\n      } catch (t) {\n        if (t instanceof Error)\n          throw new s(\"plugin-error-request-will-fetch\", {\n            thrownErrorMessage: t.message,\n          });\n      }\n      const i = n.clone();\n      try {\n        let t;\n        t = await fetch(n, \"navigate\" === n.mode ? void 0 : this.u.fetchOptions);\n        for (const s of this.iterateCallbacks(\"fetchDidSucceed\")) t = await s({ event: e, request: i, response: t });\n        return t;\n      } catch (t) {\n        throw (\n          (r &&\n            (await this.runCallbacks(\"fetchDidFail\", {\n              error: t,\n              event: e,\n              originalRequest: r.clone(),\n              request: i.clone(),\n            })),\n          t)\n        );\n      }\n    }\n    async fetchAndCachePut(t) {\n      const e = await this.fetch(t),\n        s = e.clone();\n      return this.waitUntil(this.cachePut(t, s)), e;\n    }\n    async cacheMatch(t) {\n      const e = g(t);\n      let s;\n      const { cacheName: n, matchOptions: r } = this.u,\n        i = await this.getCacheKey(e, \"read\"),\n        o = Object.assign(Object.assign({}, r), { cacheName: n });\n      s = await caches.match(i, o);\n      for (const t of this.iterateCallbacks(\"cachedResponseWillBeUsed\"))\n        s =\n          (await t({\n            cacheName: n,\n            matchOptions: r,\n            cachedResponse: s,\n            request: i,\n            event: this.event,\n          })) || void 0;\n      return s;\n    }\n    async cachePut(t, e) {\n      const n = g(t);\n      var r;\n      await ((r = 0), new Promise((t) => setTimeout(t, r)));\n      const i = await this.getCacheKey(n, \"write\");\n      if (!e)\n        throw new s(\"cache-put-with-no-response\", {\n          url: ((o = i.url), new URL(String(o), location.href).href.replace(new RegExp(`^${location.origin}`), \"\")),\n        });\n      var o;\n      const a = await this.m(e);\n      if (!a) return !1;\n      const { cacheName: c, matchOptions: h } = this.u,\n        u = await self.caches.open(c),\n        l = this.hasCallback(\"cacheDidUpdate\"),\n        f = l\n          ? await (async function (t, e, s, n) {\n              const r = d(e.url, s);\n              if (e.url === r) return t.match(e, n);\n              const i = Object.assign(Object.assign({}, n), {\n                  ignoreSearch: !0,\n                }),\n                o = await t.keys(e, i);\n              for (const e of o) if (r === d(e.url, s)) return t.match(e, n);\n            })(u, i.clone(), [\"__WB_REVISION__\"], h)\n          : null;\n      try {\n        await u.put(i, l ? a.clone() : a);\n      } catch (t) {\n        if (t instanceof Error)\n          throw (\n            (\"QuotaExceededError\" === t.name &&\n              (await (async function () {\n                for (const t of y) await t();\n              })()),\n            t)\n          );\n      }\n      for (const t of this.iterateCallbacks(\"cacheDidUpdate\"))\n        await t({\n          cacheName: c,\n          oldResponse: f,\n          newResponse: a.clone(),\n          request: i,\n          event: this.event,\n        });\n      return !0;\n    }\n    async getCacheKey(t, e) {\n      const s = `${t.url} | ${e}`;\n      if (!this.h[s]) {\n        let n = t;\n        for (const t of this.iterateCallbacks(\"cacheKeyWillBeUsed\"))\n          n = g(\n            await t({\n              mode: e,\n              request: n,\n              event: this.event,\n              params: this.params,\n            }),\n          );\n        this.h[s] = n;\n      }\n      return this.h[s];\n    }\n    hasCallback(t) {\n      for (const e of this.u.plugins) if (t in e) return !0;\n      return !1;\n    }\n    async runCallbacks(t, e) {\n      for (const s of this.iterateCallbacks(t)) await s(e);\n    }\n    *iterateCallbacks(t) {\n      for (const e of this.u.plugins)\n        if (\"function\" == typeof e[t]) {\n          const s = this.R.get(e),\n            n = (n) => {\n              const r = Object.assign(Object.assign({}, n), { state: s });\n              return e[t](r);\n            };\n          yield n;\n        }\n    }\n    waitUntil(t) {\n      return this.p.push(t), t;\n    }\n    async doneWaiting() {\n      let t;\n      for (; (t = this.p.shift()); ) await t;\n    }\n    destroy() {\n      this.l.resolve(null);\n    }\n    async m(t) {\n      let e = t,\n        s = !1;\n      for (const t of this.iterateCallbacks(\"cacheWillUpdate\"))\n        if (\n          ((e =\n            (await t({\n              request: this.request,\n              response: e,\n              event: this.event,\n            })) || void 0),\n          (s = !0),\n          !e)\n        )\n          break;\n      return s || (e && 200 !== e.status && (e = void 0)), e;\n    }\n  }\n  class m {\n    constructor(t = {}) {\n      (this.cacheName = w(t.cacheName)), (this.plugins = t.plugins || []), (this.fetchOptions = t.fetchOptions), (this.matchOptions = t.matchOptions);\n    }\n    handle(t) {\n      const [e] = this.handleAll(t);\n      return e;\n    }\n    handleAll(t) {\n      t instanceof FetchEvent && (t = { event: t, request: t.request });\n      const e = t.event,\n        s = \"string\" == typeof t.request ? new Request(t.request) : t.request,\n        n = \"params\" in t ? t.params : void 0,\n        r = new R(this, { event: e, request: s, params: n }),\n        i = this.v(r, s, e);\n      return [i, this.q(i, r, s, e)];\n    }\n    async v(t, e, n) {\n      let r;\n      await t.runCallbacks(\"handlerWillStart\", { event: n, request: e });\n      try {\n        if (((r = await this.U(e, t)), !r || \"error\" === r.type)) throw new s(\"no-response\", { url: e.url });\n      } catch (s) {\n        if (s instanceof Error) for (const i of t.iterateCallbacks(\"handlerDidError\")) if (((r = await i({ error: s, event: n, request: e })), r)) break;\n        if (!r) throw s;\n      }\n      for (const s of t.iterateCallbacks(\"handlerWillRespond\")) r = await s({ event: n, request: e, response: r });\n      return r;\n    }\n    async q(t, e, s, n) {\n      let r, i;\n      try {\n        r = await t;\n      } catch (i) {}\n      try {\n        await e.runCallbacks(\"handlerDidRespond\", {\n          event: n,\n          request: s,\n          response: r,\n        }),\n          await e.doneWaiting();\n      } catch (t) {\n        t instanceof Error && (i = t);\n      }\n      if (\n        (await e.runCallbacks(\"handlerDidComplete\", {\n          event: n,\n          request: s,\n          response: r,\n          error: i,\n        }),\n        e.destroy(),\n        i)\n      )\n        throw i;\n    }\n  }\n  function v(t, e) {\n    const s = e();\n    return t.waitUntil(s), s;\n  }\n  try {\n    self[\"workbox:precaching:6.4.1\"] && _();\n  } catch (t) {}\n  function q(t) {\n    if (!t) throw new s(\"add-to-cache-list-unexpected-type\", { entry: t });\n    if (\"string\" == typeof t) {\n      const e = new URL(t, location.href);\n      return { cacheKey: e.href, url: e.href };\n    }\n    const { revision: e, url: n } = t;\n    if (!n) throw new s(\"add-to-cache-list-unexpected-type\", { entry: t });\n    if (!e) {\n      const t = new URL(n, location.href);\n      return { cacheKey: t.href, url: t.href };\n    }\n    const r = new URL(n, location.href),\n      i = new URL(n, location.href);\n    return r.searchParams.set(\"__WB_REVISION__\", e), { cacheKey: r.href, url: i.href };\n  }\n  class U {\n    constructor() {\n      (this.updatedURLs = []),\n        (this.notUpdatedURLs = []),\n        (this.handlerWillStart = async ({ request: t, state: e }) => {\n          e && (e.originalRequest = t);\n        }),\n        (this.cachedResponseWillBeUsed = async ({ event: t, state: e, cachedResponse: s }) => {\n          if (\"install\" === t.type && e && e.originalRequest && e.originalRequest instanceof Request) {\n            const t = e.originalRequest.url;\n            s ? this.notUpdatedURLs.push(t) : this.updatedURLs.push(t);\n          }\n          return s;\n        });\n    }\n  }\n  class L {\n    constructor({ precacheController: t }) {\n      (this.cacheKeyWillBeUsed = async ({ request: t, params: e }) => {\n        const s = (null == e ? void 0 : e.cacheKey) || this.L.getCacheKeyForURL(t.url);\n        return s ? new Request(s, { headers: t.headers }) : t;\n      }),\n        (this.L = t);\n    }\n  }\n  let b, E;\n  async function C(t, e) {\n    let n = null;\n    if (t.url) {\n      n = new URL(t.url).origin;\n    }\n    if (n !== self.location.origin) throw new s(\"cross-origin-copy-response\", { origin: n });\n    const r = t.clone(),\n      i = {\n        headers: new Headers(r.headers),\n        status: r.status,\n        statusText: r.statusText,\n      },\n      o = e ? e(i) : i,\n      a = (function () {\n        if (void 0 === b) {\n          const t = new Response(\"\");\n          if (\"body\" in t)\n            try {\n              new Response(t.body), (b = !0);\n            } catch (t) {\n              b = !1;\n            }\n          b = !1;\n        }\n        return b;\n      })()\n        ? r.body\n        : await r.blob();\n    return new Response(a, o);\n  }\n  class O extends m {\n    constructor(t = {}) {\n      (t.cacheName = f(t.cacheName)), super(t), (this._ = !1 !== t.fallbackToNetwork), this.plugins.push(O.copyRedirectedCacheableResponsesPlugin);\n    }\n    async U(t, e) {\n      const s = await e.cacheMatch(t);\n      return s || (e.event && \"install\" === e.event.type ? await this.C(t, e) : await this.O(t, e));\n    }\n    async O(t, e) {\n      let n;\n      const r = e.params || {};\n      if (!this._)\n        throw new s(\"missing-precache-entry\", {\n          cacheName: this.cacheName,\n          url: t.url,\n        });\n      {\n        const s = r.integrity,\n          i = t.integrity,\n          o = !i || i === s;\n        (n = await e.fetch(new Request(t, { integrity: i || s }))), s && o && (this.N(), await e.cachePut(t, n.clone()));\n      }\n      return n;\n    }\n    async C(t, e) {\n      this.N();\n      const n = await e.fetch(t);\n      if (!(await e.cachePut(t, n.clone())))\n        throw new s(\"bad-precaching-response\", {\n          url: t.url,\n          status: n.status,\n        });\n      return n;\n    }\n    N() {\n      let t = null,\n        e = 0;\n      for (const [s, n] of this.plugins.entries()) n !== O.copyRedirectedCacheableResponsesPlugin && (n === O.defaultPrecacheCacheabilityPlugin && (t = s), n.cacheWillUpdate && e++);\n      0 === e ? this.plugins.push(O.defaultPrecacheCacheabilityPlugin) : e > 1 && null !== t && this.plugins.splice(t, 1);\n    }\n  }\n  (O.defaultPrecacheCacheabilityPlugin = {\n    cacheWillUpdate: async ({ response: t }) => (!t || t.status >= 400 ? null : t),\n  }),\n    (O.copyRedirectedCacheableResponsesPlugin = {\n      cacheWillUpdate: async ({ response: t }) => (t.redirected ? await C(t) : t),\n    });\n  class x {\n    constructor({ cacheName: t, plugins: e = [], fallbackToNetwork: s = !0 } = {}) {\n      (this.k = new Map()),\n        (this.K = new Map()),\n        (this.T = new Map()),\n        (this.u = new O({\n          cacheName: f(t),\n          plugins: [...e, new L({ precacheController: this })],\n          fallbackToNetwork: s,\n        })),\n        (this.install = this.install.bind(this)),\n        (this.activate = this.activate.bind(this));\n    }\n    get strategy() {\n      return this.u;\n    }\n    precache(t) {\n      this.addToCacheList(t), this.W || (self.addEventListener(\"install\", this.install), self.addEventListener(\"activate\", this.activate), (this.W = !0));\n    }\n    addToCacheList(t) {\n      const e = [];\n      for (const n of t) {\n        \"string\" == typeof n ? e.push(n) : n && void 0 === n.revision && e.push(n.url);\n        const { cacheKey: t, url: r } = q(n),\n          i = \"string\" != typeof n && n.revision ? \"reload\" : \"default\";\n        if (this.k.has(r) && this.k.get(r) !== t)\n          throw new s(\"add-to-cache-list-conflicting-entries\", {\n            firstEntry: this.k.get(r),\n            secondEntry: t,\n          });\n        if (\"string\" != typeof n && n.integrity) {\n          if (this.T.has(t) && this.T.get(t) !== n.integrity)\n            throw new s(\"add-to-cache-list-conflicting-integrities\", {\n              url: r,\n            });\n          this.T.set(t, n.integrity);\n        }\n        if ((this.k.set(r, t), this.K.set(r, i), e.length > 0)) {\n          const t = `Workbox is precaching URLs without revision info: ${e.join(\", \")}\\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;\n          console.warn(t);\n        }\n      }\n    }\n    install(t) {\n      return v(t, async () => {\n        const e = new U();\n        this.strategy.plugins.push(e);\n        for (const [e, s] of this.k) {\n          const n = this.T.get(s),\n            r = this.K.get(e),\n            i = new Request(e, {\n              integrity: n,\n              cache: r,\n              credentials: \"same-origin\",\n            });\n          await Promise.all(\n            this.strategy.handleAll({\n              params: { cacheKey: s },\n              request: i,\n              event: t,\n            }),\n          );\n        }\n        const { updatedURLs: s, notUpdatedURLs: n } = e;\n        return { updatedURLs: s, notUpdatedURLs: n };\n      });\n    }\n    activate(t) {\n      return v(t, async () => {\n        const t = await self.caches.open(this.strategy.cacheName),\n          e = await t.keys(),\n          s = new Set(this.k.values()),\n          n = [];\n        for (const r of e) s.has(r.url) || (await t.delete(r), n.push(r.url));\n        return { deletedURLs: n };\n      });\n    }\n    getURLsToCacheKeys() {\n      return this.k;\n    }\n    getCachedURLs() {\n      return [...this.k.keys()];\n    }\n    getCacheKeyForURL(t) {\n      const e = new URL(t, location.href);\n      return this.k.get(e.href);\n    }\n    getIntegrityForCacheKey(t) {\n      return this.T.get(t);\n    }\n    async matchPrecache(t) {\n      const e = t instanceof Request ? t.url : t,\n        s = this.getCacheKeyForURL(e);\n      if (s) {\n        return (await self.caches.open(this.strategy.cacheName)).match(s);\n      }\n    }\n    createHandlerBoundToURL(t) {\n      const e = this.getCacheKeyForURL(t);\n      if (!e) throw new s(\"non-precached-url\", { url: t });\n      return (s) => ((s.request = new Request(t)), (s.params = Object.assign({ cacheKey: e }, s.params)), this.strategy.handle(s));\n    }\n  }\n  const N = () => (E || (E = new x()), E);\n  class k extends r {\n    constructor(t, e) {\n      super(({ request: s }) => {\n        const n = t.getURLsToCacheKeys();\n        for (const r of (function* (t, { ignoreURLParametersMatching: e = [/^utm_/, /^fbclid$/], directoryIndex: s = \"index.html\", cleanURLs: n = !0, urlManipulation: r } = {}) {\n          const i = new URL(t, location.href);\n          (i.hash = \"\"), yield i.href;\n          const o = (function (t, e = []) {\n            for (const s of [...t.searchParams.keys()]) e.some((t) => t.test(s)) && t.searchParams.delete(s);\n            return t;\n          })(i, e);\n          if ((yield o.href, s && o.pathname.endsWith(\"/\"))) {\n            const t = new URL(o.href);\n            (t.pathname += s), yield t.href;\n          }\n          if (n) {\n            const t = new URL(o.href);\n            (t.pathname += \".html\"), yield t.href;\n          }\n          if (r) {\n            const t = r({ url: i });\n            for (const e of t) yield e.href;\n          }\n        })(s.url, e)) {\n          const e = n.get(r);\n          if (e) {\n            return { cacheKey: e, integrity: t.getIntegrityForCacheKey(e) };\n          }\n        }\n      }, t.strategy);\n    }\n  }\n  (t.CacheFirst = class extends m {\n    async U(t, e) {\n      let n,\n        r = await e.cacheMatch(t);\n      if (!r)\n        try {\n          r = await e.fetchAndCachePut(t);\n        } catch (t) {\n          t instanceof Error && (n = t);\n        }\n      if (!r) throw new s(\"no-response\", { url: t.url, error: n });\n      return r;\n    }\n  }),\n    (t.precacheAndRoute = function (t, e) {\n      !(function (t) {\n        N().precache(t);\n      })(t),\n        (function (t) {\n          const e = N();\n          h(new k(e, t));\n        })(e);\n    }),\n    (t.registerRoute = h);\n});\n//# sourceMappingURL=workbox-962786f2.js.map\n"
  },
  {
    "path": "src/web-remote/ciderframework.css",
    "content": "/* Simple CSS framework for Cider */\n\n.md-labeltext {\n  font-size: 14px;\n  text-transform: uppercase;\n  opacity: 0.75;\n  font-weight: 500;\n}\n\n.md-option-container {\n  border-radius: 10px;\n  overflow: hidden;\n}\n\n.md-option-line {\n  display: flex;\n  width: 100%;\n  padding: 14px;\n  background: var(--opaquePageBGColor);\n  font-size: 0.85em;\n}\n\n.md-option-segment.md-option-segment_auto {\n  width: auto;\n  white-space: nowrap;\n}\n\n.md-option-container .md-option-line:not(:last-child) {\n  border-bottom: 1px solid rgb(0 0 0 / 15%);\n}\n\ninput[type=\"range\"].md-slider {\n  -webkit-appearance: none;\n  height: 7px;\n  background: rgba(255, 255, 255, 0.6);\n  border-radius: 5px;\n  background-size: 70% 100%;\n  background-repeat: no-repeat;\n}\n\ninput[type=\"range\"].md-slider::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  height: 20px;\n  width: 20px;\n  border-radius: 50%;\n  background: rgb(255 255 255);\n  cursor: ew-resize;\n  box-shadow: 0 0 2px 0 #555;\n}\n\ninput[type=\"range\"].md-slider::-webkit-slider-runnable-track {\n  -webkit-appearance: none;\n  box-shadow: none;\n  border: none;\n  background: transparent;\n}\n\n.md-option-segment {\n  width: 100%;\n  display: flex;\n  justify-content: center;\n  flex-direction: column;\n}\n\n.md-h1 {\n  font-size: 3em;\n  text-align: center;\n}\n\n.md-header {\n  padding: 16px;\n}\n\n.md-header-title {\n  padding: 18px;\n  font-weight: 600;\n  font-size: 16px;\n  height: 55px;\n  background: var(--opaquePageBGColor);\n  border-bottom: 1px solid rgb(0 0 0 / 15%);\n}\n\n.md-footer {\n  padding: 16px;\n  text-align: center;\n}\n\n.md-close-btn {\n  -webkit-mask-image: url(\"ameres://icons/webui/close.svg\");\n  -webkit-mask-repeat: no-repeat;\n  -webkit-mask-position: center;\n  background-color: white;\n  opacity: 0.75;\n  -webkit-mask-size: contain;\n  height: 18px;\n  width: 18px;\n}\n\n.md-btn {\n  background: rgba(100, 100, 100, 0.5);\n  padding: 8px 16px;\n  border-radius: 4px;\n  font-size: 15px;\n  border: 1px solid rgb(100 100 100 / 35%);\n  box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.4);\n  white-space: nowrap;\n}\n\n.md-btn.md-btn-block {\n  display: block;\n}\n\n.md-btn:active {\n  filter: brightness(75%);\n}\n\n.md-select {\n  padding: 5px 10px;\n  font-size: 1em;\n  font-family: inherit;\n  border-radius: 4px;\n  border: 1px solid rgb(100 100 100 / 35%);\n  box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.4);\n}\n\n.md-select:focus {\n  outline: none;\n}\n\n.md-select > option {\n  font-size: 1em;\n  font-family: inherit;\n  padding: 8px 16px;\n}\n\n.md-btn.md-btn-primary {\n  background: var(--keyColor);\n  color: white;\n}\n\n.md-transparent {\n  background: transparent;\n}\n\n.md-container {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  position: absolute;\n  top: 0px;\n  left: 0px;\n  width: 100%;\n  padding: 32px;\n}\n\n.md-container_panel {\n  padding: 0px;\n}\n\n.md-body {\n  height: 100%;\n  padding: 16px;\n  font-size: 1.25em;\n}\n\n@media (prefers-color-scheme: light) {\n  .md-btn {\n    background: rgb(255 255 255);\n    box-shadow: rgb(0 0 0 / 10%) 0px 0px 1px, rgb(0 0 0 / 20%) 0px 1px 1px;\n    border: 1px solid rgb(0 0 0 / 15%);\n  }\n  .md-close-btn {\n    background-color: #000;\n  }\n}\n\n/* Vue transitions */\n\n.fade_simple-enter-active,\n.fade_simple-leave-active {\n  transition: all 0.5s;\n}\n\n.fade_simple-enter,\n.fade_simple-leave-to {\n  opacity: 0;\n}\n\n.fade-enter-active,\n.fade-leave-active {\n  transition: all 0.5s;\n}\n\n.fade-enter,\n.fade-leave-to {\n  opacity: 0;\n  transform: scale(0.95);\n}\n\n/* CSS Grids */\n\n.container,\n.container-fluid,\n.container-xxl,\n.container-xl,\n.container-lg,\n.container-md,\n.container-sm {\n  width: 100%;\n  padding-right: var(--bs-gutter-x, 0.75rem);\n  padding-left: var(--bs-gutter-x, 0.75rem);\n  margin-right: auto;\n  margin-left: auto;\n}\n\n.row {\n  --bs-gutter-x: 1.5rem;\n  --bs-gutter-y: 0;\n  display: flex;\n  flex-wrap: wrap;\n  margin-top: calc(-1 * var(--bs-gutter-y));\n  margin-right: calc(-0.5 * var(--bs-gutter-x));\n  margin-left: calc(-0.5 * var(--bs-gutter-x));\n}\n\n.row > * {\n  box-sizing: border-box;\n  flex-shrink: 0;\n  width: 100%;\n  max-width: 100%;\n  padding-right: calc(var(--bs-gutter-x) * 0.5);\n  padding-left: calc(var(--bs-gutter-x) * 0.5);\n  margin-top: var(--bs-gutter-y);\n}\n\n.col {\n  flex: 1 0 0%;\n}\n\n.row-cols-auto > * {\n  flex: 0 0 auto;\n  width: auto;\n}\n\n.row-cols-1 > * {\n  flex: 0 0 auto;\n  width: 100%;\n}\n\n.row-cols-2 > * {\n  flex: 0 0 auto;\n  width: 50%;\n}\n\n.row-cols-3 > * {\n  flex: 0 0 auto;\n  width: 33.3333333333%;\n}\n\n.row-cols-4 > * {\n  flex: 0 0 auto;\n  width: 25%;\n}\n\n.row-cols-5 > * {\n  flex: 0 0 auto;\n  width: 20%;\n}\n\n.row-cols-6 > * {\n  flex: 0 0 auto;\n  width: 16.6666666667%;\n}\n\n.col-auto {\n  flex: 0 0 auto;\n  width: auto;\n}\n\n@media only screen and (min-width: 1133px) and (max-width: 1233px) {\n  .about-page {\n    .row .col-auto {\n      display: none !important;\n    }\n  }\n}\n\n.col-1 {\n  flex: 0 0 auto;\n  width: 8.33333333%;\n}\n\n.col-2 {\n  flex: 0 0 auto;\n  width: 16.66666667%;\n}\n\n.col-3 {\n  flex: 0 0 auto;\n  width: 25%;\n}\n\n.col-4 {\n  flex: 0 0 auto;\n  width: 33.33333333%;\n}\n\n.col-5 {\n  flex: 0 0 auto;\n  width: 41.66666667%;\n}\n\n.col-6 {\n  flex: 0 0 auto;\n  width: 50%;\n}\n\n.col-7 {\n  flex: 0 0 auto;\n  width: 58.33333333%;\n}\n\n.col-8 {\n  flex: 0 0 auto;\n  width: 66.66666667%;\n}\n\n.col-9 {\n  flex: 0 0 auto;\n  width: 75%;\n}\n\n.col-10 {\n  flex: 0 0 auto;\n  width: 83.33333333%;\n}\n\n.col-11 {\n  flex: 0 0 auto;\n  width: 91.66666667%;\n}\n\n.col-12 {\n  flex: 0 0 auto;\n  width: 100%;\n}\n\n.offset-1 {\n  margin-left: 8.33333333%;\n}\n\n.offset-2 {\n  margin-left: 16.66666667%;\n}\n\n.offset-3 {\n  margin-left: 25%;\n}\n\n.offset-4 {\n  margin-left: 33.33333333%;\n}\n\n.offset-5 {\n  margin-left: 41.66666667%;\n}\n\n.offset-6 {\n  margin-left: 50%;\n}\n\n.offset-7 {\n  margin-left: 58.33333333%;\n}\n\n.offset-8 {\n  margin-left: 66.66666667%;\n}\n\n.offset-9 {\n  margin-left: 75%;\n}\n\n.offset-10 {\n  margin-left: 83.33333333%;\n}\n\n.offset-11 {\n  margin-left: 91.66666667%;\n}\n\n.g-0,\n.gx-0 {\n  --bs-gutter-x: 0;\n}\n\n.g-0,\n.gy-0 {\n  --bs-gutter-y: 0;\n}\n\n.g-1,\n.gx-1 {\n  --bs-gutter-x: 0.25rem;\n}\n\n.g-1,\n.gy-1 {\n  --bs-gutter-y: 0.25rem;\n}\n\n.g-2,\n.gx-2 {\n  --bs-gutter-x: 0.5rem;\n}\n\n.g-2,\n.gy-2 {\n  --bs-gutter-y: 0.5rem;\n}\n\n.g-3,\n.gx-3 {\n  --bs-gutter-x: 1rem;\n}\n\n.g-3,\n.gy-3 {\n  --bs-gutter-y: 1rem;\n}\n\n.g-4,\n.gx-4 {\n  --bs-gutter-x: 1.5rem;\n}\n\n.g-4,\n.gy-4 {\n  --bs-gutter-y: 1.5rem;\n}\n\n.g-5,\n.gx-5 {\n  --bs-gutter-x: 3rem;\n}\n\n.g-5,\n.gy-5 {\n  --bs-gutter-y: 3rem;\n}\n\n.d-inline {\n  display: inline !important;\n}\n\n.d-inline-block {\n  display: inline-block !important;\n}\n\n.d-block {\n  display: block !important;\n}\n\n.d-grid {\n  display: grid !important;\n}\n\n.d-table {\n  display: table !important;\n}\n\n.d-table-row {\n  display: table-row !important;\n}\n\n.d-table-cell {\n  display: table-cell !important;\n}\n\n.d-flex {\n  display: flex !important;\n}\n\n.d-inline-flex {\n  display: inline-flex !important;\n}\n\n.d-none {\n  display: none !important;\n}\n\n.flex-fill {\n  flex: 1 1 auto !important;\n}\n\n.flex-row {\n  flex-direction: row !important;\n}\n\n.flex-column {\n  flex-direction: column !important;\n}\n\n.flex-row-reverse {\n  flex-direction: row-reverse !important;\n}\n\n.flex-column-reverse {\n  flex-direction: column-reverse !important;\n}\n\n.flex-grow-0 {\n  flex-grow: 0 !important;\n}\n\n.flex-grow-1 {\n  flex-grow: 1 !important;\n}\n\n.flex-shrink-0 {\n  flex-shrink: 0 !important;\n}\n\n.flex-shrink-1 {\n  flex-shrink: 1 !important;\n}\n\n.flex-wrap {\n  flex-wrap: wrap !important;\n}\n\n.flex-nowrap {\n  flex-wrap: nowrap !important;\n}\n\n.flex-wrap-reverse {\n  flex-wrap: wrap-reverse !important;\n}\n\n.justify-content-start {\n  justify-content: flex-start !important;\n}\n\n.justify-content-end {\n  justify-content: flex-end !important;\n}\n\n.justify-content-center {\n  justify-content: center !important;\n}\n\n.justify-content-between {\n  justify-content: space-between !important;\n}\n\n.justify-content-around {\n  justify-content: space-around !important;\n}\n\n.justify-content-evenly {\n  justify-content: space-evenly !important;\n}\n\n.align-items-start {\n  align-items: flex-start !important;\n}\n\n.align-items-end {\n  align-items: flex-end !important;\n}\n\n.align-items-center {\n  align-items: center !important;\n}\n\n.align-items-baseline {\n  align-items: baseline !important;\n}\n\n.align-items-stretch {\n  align-items: stretch !important;\n}\n\n.align-content-start {\n  align-content: flex-start !important;\n}\n\n.align-content-end {\n  align-content: flex-end !important;\n}\n\n.align-content-center {\n  align-content: center !important;\n}\n\n.align-content-between {\n  align-content: space-between !important;\n}\n\n.align-content-around {\n  align-content: space-around !important;\n}\n\n.align-content-stretch {\n  align-content: stretch !important;\n}\n\n.align-self-auto {\n  align-self: auto !important;\n}\n\n.align-self-start {\n  align-self: flex-start !important;\n}\n\n.align-self-end {\n  align-self: flex-end !important;\n}\n\n.align-self-center {\n  align-self: center !important;\n}\n\n.align-self-baseline {\n  align-self: baseline !important;\n}\n\n.align-self-stretch {\n  align-self: stretch !important;\n}\n\n.order-first {\n  order: -1 !important;\n}\n\n.order-0 {\n  order: 0 !important;\n}\n\n.order-1 {\n  order: 1 !important;\n}\n\n.order-2 {\n  order: 2 !important;\n}\n\n.order-3 {\n  order: 3 !important;\n}\n\n.order-4 {\n  order: 4 !important;\n}\n\n.order-5 {\n  order: 5 !important;\n}\n\n.order-last {\n  order: 6 !important;\n}\n\n.m-0 {\n  margin: 0 !important;\n}\n\n.m-1 {\n  margin: 0.25rem !important;\n}\n\n.m-2 {\n  margin: 0.5rem !important;\n}\n\n.m-3 {\n  margin: 1rem !important;\n}\n\n.m-4 {\n  margin: 1.5rem !important;\n}\n\n.m-5 {\n  margin: 3rem !important;\n}\n\n.m-auto {\n  margin: auto !important;\n}\n\n.mx-0 {\n  margin-right: 0 !important;\n  margin-left: 0 !important;\n}\n\n.mx-1 {\n  margin-right: 0.25rem !important;\n  margin-left: 0.25rem !important;\n}\n\n.mx-2 {\n  margin-right: 0.5rem !important;\n  margin-left: 0.5rem !important;\n}\n\n.mx-3 {\n  margin-right: 1rem !important;\n  margin-left: 1rem !important;\n}\n\n.mx-4 {\n  margin-right: 1.5rem !important;\n  margin-left: 1.5rem !important;\n}\n\n.mx-5 {\n  margin-right: 3rem !important;\n  margin-left: 3rem !important;\n}\n\n.mx-auto {\n  margin-right: auto !important;\n  margin-left: auto !important;\n}\n\n.my-0 {\n  margin-top: 0 !important;\n  margin-bottom: 0 !important;\n}\n\n.my-1 {\n  margin-top: 0.25rem !important;\n  margin-bottom: 0.25rem !important;\n}\n\n.my-2 {\n  margin-top: 0.5rem !important;\n  margin-bottom: 0.5rem !important;\n}\n\n.my-3 {\n  margin-top: 1rem !important;\n  margin-bottom: 1rem !important;\n}\n\n.my-4 {\n  margin-top: 1.5rem !important;\n  margin-bottom: 1.5rem !important;\n}\n\n.my-5 {\n  margin-top: 3rem !important;\n  margin-bottom: 3rem !important;\n}\n\n.my-auto {\n  margin-top: auto !important;\n  margin-bottom: auto !important;\n}\n\n.mt-0 {\n  margin-top: 0 !important;\n}\n\n.mt-1 {\n  margin-top: 0.25rem !important;\n}\n\n.mt-2 {\n  margin-top: 0.5rem !important;\n}\n\n.mt-3 {\n  margin-top: 1rem !important;\n}\n\n.mt-4 {\n  margin-top: 1.5rem !important;\n}\n\n.mt-5 {\n  margin-top: 3rem !important;\n}\n\n.mt-auto {\n  margin-top: auto !important;\n}\n\n.me-0 {\n  margin-right: 0 !important;\n}\n\n.me-1 {\n  margin-right: 0.25rem !important;\n}\n\n.me-2 {\n  margin-right: 0.5rem !important;\n}\n\n.me-3 {\n  margin-right: 1rem !important;\n}\n\n.me-4 {\n  margin-right: 1.5rem !important;\n}\n\n.me-5 {\n  margin-right: 3rem !important;\n}\n\n.me-auto {\n  margin-right: auto !important;\n}\n\n.mb-0 {\n  margin-bottom: 0 !important;\n}\n\n.mb-1 {\n  margin-bottom: 0.25rem !important;\n}\n\n.mb-2 {\n  margin-bottom: 0.5rem !important;\n}\n\n.mb-3 {\n  margin-bottom: 1rem !important;\n}\n\n.mb-4 {\n  margin-bottom: 1.5rem !important;\n}\n\n.mb-5 {\n  margin-bottom: 3rem !important;\n}\n\n.mb-auto {\n  margin-bottom: auto !important;\n}\n\n.ms-0 {\n  margin-left: 0 !important;\n}\n\n.ms-1 {\n  margin-left: 0.25rem !important;\n}\n\n.ms-2 {\n  margin-left: 0.5rem !important;\n}\n\n.ms-3 {\n  margin-left: 1rem !important;\n}\n\n.ms-4 {\n  margin-left: 1.5rem !important;\n}\n\n.ms-5 {\n  margin-left: 3rem !important;\n}\n\n.ms-auto {\n  margin-left: auto !important;\n}\n\n.p-0 {\n  padding: 0 !important;\n}\n\n.p-1 {\n  padding: 0.25rem !important;\n}\n\n.p-2 {\n  padding: 0.5rem !important;\n}\n\n.p-3 {\n  padding: 1rem !important;\n}\n\n.p-4 {\n  padding: 1.5rem !important;\n}\n\n.p-5 {\n  padding: 3rem !important;\n}\n\n.px-0 {\n  padding-right: 0 !important;\n  padding-left: 0 !important;\n}\n\n.px-1 {\n  padding-right: 0.25rem !important;\n  padding-left: 0.25rem !important;\n}\n\n.px-2 {\n  padding-right: 0.5rem !important;\n  padding-left: 0.5rem !important;\n}\n\n.px-3 {\n  padding-right: 1rem !important;\n  padding-left: 1rem !important;\n}\n\n.px-4 {\n  padding-right: 1.5rem !important;\n  padding-left: 1.5rem !important;\n}\n\n.px-5 {\n  padding-right: 3rem !important;\n  padding-left: 3rem !important;\n}\n\n.py-0 {\n  padding-top: 0 !important;\n  padding-bottom: 0 !important;\n}\n\n.py-1 {\n  padding-top: 0.25rem !important;\n  padding-bottom: 0.25rem !important;\n}\n\n.py-2 {\n  padding-top: 0.5rem !important;\n  padding-bottom: 0.5rem !important;\n}\n\n.py-3 {\n  padding-top: 1rem !important;\n  padding-bottom: 1rem !important;\n}\n\n.py-4 {\n  padding-top: 1.5rem !important;\n  padding-bottom: 1.5rem !important;\n}\n\n.py-5 {\n  padding-top: 3rem !important;\n  padding-bottom: 3rem !important;\n}\n\n.pt-0 {\n  padding-top: 0 !important;\n}\n\n.pt-1 {\n  padding-top: 0.25rem !important;\n}\n\n.pt-2 {\n  padding-top: 0.5rem !important;\n}\n\n.pt-3 {\n  padding-top: 1rem !important;\n}\n\n.pt-4 {\n  padding-top: 1.5rem !important;\n}\n\n.pt-5 {\n  padding-top: 3rem !important;\n}\n\n.pe-0 {\n  padding-right: 0 !important;\n}\n\n.pe-1 {\n  padding-right: 0.25rem !important;\n}\n\n.pe-2 {\n  padding-right: 0.5rem !important;\n}\n\n.pe-3 {\n  padding-right: 1rem !important;\n}\n\n.pe-4 {\n  padding-right: 1.5rem !important;\n}\n\n.pe-5 {\n  padding-right: 3rem !important;\n}\n\n.pb-0 {\n  padding-bottom: 0 !important;\n}\n\n.pb-1 {\n  padding-bottom: 0.25rem !important;\n}\n\n.pb-2 {\n  padding-bottom: 0.5rem !important;\n}\n\n.pb-3 {\n  padding-bottom: 1rem !important;\n}\n\n.pb-4 {\n  padding-bottom: 1.5rem !important;\n}\n\n.pb-5 {\n  padding-bottom: 3rem !important;\n}\n\n.ps-0 {\n  padding-left: 0 !important;\n}\n\n.ps-1 {\n  padding-left: 0.25rem !important;\n}\n\n.ps-2 {\n  padding-left: 0.5rem !important;\n}\n\n.ps-3 {\n  padding-left: 1rem !important;\n}\n\n.ps-4 {\n  padding-left: 1.5rem !important;\n}\n\n.ps-5 {\n  padding-left: 3rem !important;\n}\n"
  },
  {
    "path": "src/web-remote/index.js",
    "content": "var socket;\n\nVue.component(\"footer-player\", {\n  template: \"#footer-player\",\n});\n\n// vue instance\nvar app = new Vue({\n  el: \"#app\",\n  data: {\n    screen: \"player\",\n    player: {\n      currentMediaItem: {},\n      songActions: false,\n      maxVolume: 1,\n      lyrics: {},\n      lyricsMediaItem: {},\n      lyricsDebug: {\n        current: 0,\n        start: 0,\n        end: 0,\n      },\n      lyricsScrollingBlocked: false,\n      queue: {},\n      lowerPanelState: \"controls\",\n      userInteraction: false,\n      status: {\n        inLibrary: false,\n        rating: 0,\n      },\n    },\n    queue: {\n      temp: [],\n    },\n    artistPage: {\n      data: {},\n      editorsNotes: false,\n    },\n    albumPage: {\n      data: {},\n      editorsNotes: false,\n    },\n    search: {\n      query: \"\",\n      results: [],\n      state: 0,\n      tab: \"all\",\n      searchType: \"applemusic\",\n      trackSelect: false,\n      selected: {},\n      queue: {},\n      lastPage: \"search\",\n      lastY: 0,\n    },\n    lastPage: \"player\",\n    connectedState: 0,\n    url: window.location.hostname,\n    mode: \"default\",\n    // url: \"localhost\",\n  },\n  methods: {\n    isElectron() {\n      // Renderer process\n      if (typeof window !== \"undefined\" && typeof window.process === \"object\" && window.process.type === \"renderer\") {\n        return true;\n      }\n      // Main process\n      if (typeof process !== \"undefined\" && typeof process.versions === \"object\" && !!process.versions.electron) {\n        return true;\n      }\n      // Detect the user agent when the `nodeIntegration` option is set to true\n      if (typeof navigator === \"object\" && typeof navigator.userAgent === \"string\" && navigator.userAgent.indexOf(\"Electron\") >= 0) {\n        return true;\n      }\n      return false;\n    },\n    searchScroll(e) {\n      this.search.lastY = e.target.scrollTop;\n    },\n    musicKitAPI(method, id, params, library = false) {\n      socket.send(\n        JSON.stringify({\n          action: \"musickit-api\",\n          method: method,\n          id: id,\n          params: params,\n          library: library,\n        }),\n      );\n    },\n    resetPlayerUI() {\n      this.player.lowerPanelState = \"controls\";\n    },\n    musicAppVariant() {\n      if (navigator.userAgent.match(/Android/i)) {\n        return \"Cider\";\n      } else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {\n        return \"Cider\";\n      } else {\n        if (navigator.userAgent.indexOf(\"Mac\") > 0) {\n          return \"Music\";\n        } else if (navigator.userAgent.indexOf(\"Win\") > 0) {\n          return \"Cider\";\n        } else {\n          return \"Cider\";\n        }\n      }\n    },\n    checkOrientation() {\n      // check orientation of device\n      if (window.innerHeight > window.innerWidth) {\n        return \"portrait\";\n      } else {\n        return \"landscape\";\n      }\n    },\n    checkPlatformMD() {\n      // check if platfom is desktop or mobile\n      if (navigator.userAgent.match(/Android/i)) {\n        return \"mobile\";\n      } else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {\n        return \"mobile\";\n      } else {\n        if (navigator.userAgent.indexOf(\"Mac\") > 0) {\n          return \"desktop\";\n        } else if (navigator.userAgent.indexOf(\"Win\") > 0) {\n          return \"desktop\";\n        } else {\n          return \"desktop\";\n        }\n      }\n    },\n    checkPlatform() {\n      if (navigator.userAgent.match(/Android/i)) {\n        return \"android\";\n      } else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {\n        return \"ios\";\n      } else {\n        if (navigator.userAgent.indexOf(\"Mac\") > 0) {\n          return \"mac\";\n        } else if (navigator.userAgent.indexOf(\"Win\") > 0) {\n          return \"win\";\n        } else {\n          return \"linux\";\n        }\n      }\n    },\n    artworkPlaying() {\n      if (this.player.currentMediaItem.status) {\n        return;\n      } else {\n        return [\"paused\"];\n      }\n    },\n    setAutoplay(value) {\n      socket.send(\n        JSON.stringify({\n          action: \"set-autoplay\",\n          autoplay: value,\n        }),\n      );\n      this.getCurrentMediaItem();\n      if (value) {\n        setTimeout(() => {\n          this.getQueue();\n        }, 1000);\n      } else {\n        this.getQueue();\n      }\n    },\n    seekTo(time, adjust = true) {\n      if (adjust) {\n        time = parseInt(time / 1000);\n      }\n      socket.send(\n        JSON.stringify({\n          action: \"seek\",\n          time: time,\n        }),\n      );\n    },\n    setVolume(volume) {\n      socket.send(\n        JSON.stringify({\n          action: \"volume\",\n          volume: volume,\n        }),\n      );\n    },\n    getVolumeMax() {\n      socket.send(\n        JSON.stringify({\n          action: \"volumeMax\",\n        }),\n      );\n    },\n    getQueue() {\n      socket.send(\n        JSON.stringify({\n          action: \"get-queue\",\n        }),\n      );\n    },\n    play() {\n      socket.send(\n        JSON.stringify({\n          action: \"play\",\n        }),\n      );\n    },\n    pause() {\n      socket.send(\n        JSON.stringify({\n          action: \"pause\",\n        }),\n      );\n    },\n    next() {\n      socket.send(\n        JSON.stringify({\n          action: \"next\",\n        }),\n      );\n    },\n    previous() {\n      socket.send(\n        JSON.stringify({\n          action: \"previous\",\n        }),\n      );\n    },\n    searchArtist() {\n      this.search.query = this.player.currentMediaItem.artistName;\n      this.screen = \"search\";\n      this.searchQuery();\n    },\n    trackSelect(song) {\n      this.search.selected = song;\n      this.search.trackSelect = true;\n    },\n    clearSelectedTrack() {\n      this.search.selected = {};\n      this.search.trackSelect = false;\n    },\n    getArtworkColor(hex) {\n      return `#${hex}`;\n    },\n    playMediaItemById(id, kind = \"song\") {\n      socket.send(\n        JSON.stringify({\n          action: \"play-mediaitem\",\n          id: id,\n          kind: kind,\n        }),\n      );\n      this.screen = \"player\";\n    },\n    playNext(type, id) {\n      socket.send(\n        JSON.stringify({\n          action: \"play-next\",\n          type: type,\n          id: id,\n        }),\n      );\n    },\n    playLater(type, id) {\n      socket.send(\n        JSON.stringify({\n          action: \"play-later\",\n          type: type,\n          id: id,\n        }),\n      );\n    },\n    getLibraryStatus(type, id) {\n      if (type !== undefined && id !== \"no-id-found\") {\n        socket.send(\n          JSON.stringify({\n            action: \"library-status\",\n            type: type,\n            id: id,\n          }),\n        );\n      } else {\n        this.player.status = {};\n      }\n    },\n    searchQuery() {\n      if (this.search.query.length == 0) {\n        this.search.state = 0;\n        return;\n      }\n      this.search.state = 1;\n      var actionType = \"search\";\n      if (this.search.searchType == \"library\") {\n        actionType = \"library-search\";\n      }\n      socket.send(\n        JSON.stringify({\n          action: actionType,\n          term: this.search.query,\n          limit: 20,\n        }),\n      );\n    },\n    quickSearch() {\n      var search = prompt(\"Search for a song\", \"\");\n      if (search == null || search == \"\") {\n        return;\n      }\n\n      socket.send(\n        JSON.stringify({\n          action: \"quick-play\",\n          term: search,\n        }),\n      );\n    },\n    parseTime(value) {\n      var minutes = Math.floor(value / 60000);\n      var seconds = ((value % 60000) / 1000).toFixed(0);\n      return minutes + \":\" + (seconds < 10 ? \"0\" : \"\") + seconds;\n    },\n    parseTimeDecimal(value) {\n      var minutes = Math.floor(value / 60000);\n      var seconds = ((value % 60000) / 1000).toFixed(0);\n      return minutes + \".\" + (seconds < 10 ? \"0\" : \"\") + seconds;\n    },\n    hmsToSecondsOnly(str) {\n      var p = str.split(\":\"),\n        s = 0,\n        m = 1;\n\n      while (p.length > 0) {\n        s += m * parseInt(p.pop(), 10);\n        m *= 60;\n      }\n\n      return s;\n    },\n    getCurrentTime() {\n      return parseFloat(this.hmsToSecondsOnly(this.parseTime(this.player.currentMediaItem.durationInMillis - this.player.currentMediaItem.remainingTime)));\n    },\n    percentage(partial, full) {\n      return (100 * partial) / full;\n    },\n    getLyricBGStyle(start, end) {\n      var currentTime = this.getCurrentTime();\n      var duration = this.player.currentMediaItem.durationInMillis;\n      var start2 = this.hmsToSecondsOnly(start);\n      var end2 = this.hmsToSecondsOnly(end);\n      var currentProgress = (100 * currentTime) / end2;\n      // check if currenttime is between start and end\n      this.player.lyricsDebug.start = start2;\n      this.player.lyricsDebug.end = end2;\n      this.player.lyricsDebug.current = currentTime;\n      if (currentTime >= start2 && currentTime <= end2) {\n        return {\n          \"--bgSpeed\": `${end2 - start2}s`,\n        };\n      } else {\n        return {};\n      }\n    },\n    blockLyricsScrolling() {\n      this.lyricsScrollingBlocked = true;\n      setTimeout(() => {\n        this.lyricsScrollingBlocked = false;\n      }, 100);\n    },\n    getLyricClass(start, end) {\n      var currentTime = this.getCurrentTime();\n      // check if currenttime is between start and end\n      if (currentTime >= start && currentTime <= end) {\n        setTimeout(() => {\n          if (document.querySelector(\".lyric-line.active\") && !this.lyricsScrollingBlocked) {\n            document.querySelector(\".lyric-line.active\").scrollIntoView({\n              behavior: \"smooth\",\n              block: \"center\",\n            });\n          }\n        }, 200);\n        return \"active\";\n      } else {\n        return \"\";\n      }\n    },\n    getAlbumArtUrl(size = 600) {\n      if (this.player.currentMediaItem.artwork) {\n        return `url(\"${this.player.currentMediaItem.artwork.url.replace(\"{w}\", size).replace(\"{h}\", size)}\")`;\n      } else {\n        return \"\";\n      }\n    },\n    getAlbumArtUrlList(url, size = 64) {\n      return `url(\"${url.replace(\"{w}\", size).replace(\"{h}\", size)}\")`;\n    },\n    searchTabClass(tab) {\n      if (tab == this.search.tab) {\n        return \"active\";\n      }\n    },\n    searchTypeClass(type) {\n      if (type == this.search.searchType) {\n        return \"active\";\n      }\n    },\n    getQueuePositionClass(position) {\n      if (this.player.queue[\"_position\"] == position) {\n        return [\"playing\", \"passed\"];\n      } else if (this.player.queue[\"_position\"] > position) {\n        return [\"passed\"];\n      }\n    },\n    showSearch(reset = false) {\n      if (reset) {\n        this.search.lastPage = \"search\";\n      }\n      switch (this.search.lastPage) {\n        case \"search\":\n          this.screen = \"search\";\n          break;\n        case \"album\":\n          this.screen = \"album-page\";\n          break;\n        case \"artist\":\n          this.screen = \"artist-page\";\n          break;\n        case \"playlist\":\n          this.screen = \"playlist-page\";\n          break;\n      }\n    },\n    showArtistByName(name) {\n      this.musicKitAPI(\"search\", name, { types: \"artists\" });\n    },\n    showAlbum(id, library = false) {\n      this.search.lastPage = \"album\";\n      this.screen = \"album-page\";\n      this.musicKitAPI(\"album\", id, {}, library);\n    },\n    showPlaylist(id, library = false) {\n      this.search.lastPage = \"album\";\n      this.screen = \"album-page\";\n      this.musicKitAPI(\"playlist\", id, {}, library);\n    },\n    showArtist(id, library = false) {\n      this.search.lastPage = \"artist\";\n      this.screen = \"artist-page\";\n      this.musicKitAPI(\"artist\", id, { include: \"songs,playlists,albums\" }, library);\n    },\n    showQueue() {\n      this.queue.temp = this.player[\"queue\"][\"_queueItems\"];\n      this.screen = \"queue\";\n      this.getQueue();\n    },\n    queueMove(evt) {\n      // console.log(evt)\n      // console.log(`new: ${evt.moved.newIndex} old: ${evt.moved.oldIndex}`)\n      this.queue.temp.splice(evt.moved.newIndex, 0, this.queue.temp.splice(evt.moved.oldIndex, 1)[0]);\n      socket.send(\n        JSON.stringify({\n          action: \"queue-move\",\n          from: evt.moved.oldIndex,\n          to: evt.moved.newIndex,\n        }),\n      );\n      this.getQueue();\n      return true;\n    },\n    repeat() {\n      socket.send(\n        JSON.stringify({\n          action: \"repeat\",\n        }),\n      );\n      this.getCurrentMediaItem();\n    },\n    shuffle() {\n      socket.send(\n        JSON.stringify({\n          action: \"shuffle\",\n        }),\n      );\n      this.getCurrentMediaItem();\n    },\n    setShuffle(val) {\n      socket.send(\n        JSON.stringify({\n          action: \"set-shuffle\",\n          shuffle: val,\n        }),\n      );\n      this.getCurrentMediaItem();\n    },\n    getMediaPalette(data) {\n      if (data != null && data[\"artwork\"] != null) {\n        var palette = {\n          \"--bgColor\": `#${data[\"artwork\"][\"bgColor\"] ?? \"000000\"}`,\n          \"--textColor1\": `#${data[\"artwork\"][\"textColor1\"] ?? \"ffffff\"}`,\n          \"--textColor2\": `#${data[\"artwork\"][\"textColor2\"] ?? \"ffffff\"}`,\n          \"--textColor3\": `#${data[\"artwork\"][\"textColor3\"] ?? \"ffffff\"}`,\n          \"--textColor4\": `#${data[\"artwork\"][\"textColor4\"] ?? \"ffffff\"}`,\n        };\n        return palette;\n      } else {\n        let u = {\n          \"--bgColor\": `#${\"000000\"}`,\n          \"--textColor1\": `#${\"ffffff\"}`,\n          \"--textColor2\": `#${\"ffffff\"}`,\n          \"--textColor3\": `#${\"ffffff\"}`,\n          \"--textColor4\": `#${\"ffffff\"}`,\n        };\n        return u;\n      }\n    },\n    playAlbum(id, shuffle = false) {\n      if (shuffle) {\n        this.setShuffle(true);\n      } else {\n        this.setShuffle(false);\n      }\n      this.playMediaItemById(id, \"album\");\n    },\n    playCustom(id, kind, shuffle = false) {\n      if (shuffle) {\n        this.setShuffle(true);\n      } else {\n        this.setShuffle(false);\n      }\n      this.playMediaItemById(id, kind);\n    },\n    getLyrics() {\n      socket.send(\n        JSON.stringify({\n          action: \"get-lyrics\",\n        }),\n      );\n    },\n    showLyrics() {\n      this.getLyrics();\n      this.screen = \"lyrics\";\n    },\n    showLyricsInline() {\n      this.getLyrics();\n      this.player.lowerPanelState = \"lyrics\";\n    },\n    parseLyrics() {\n      var xml = this.stringToXml(this.player.lyricsMediaItem.ttml);\n      var json = xmlToJson(xml);\n      this.player.lyrics = json;\n    },\n    stringToXml(st) {\n      // string to xml\n      var xml = new DOMParser().parseFromString(st, \"text/xml\");\n      return xml;\n    },\n    canShowSearchTab(tab) {\n      if (tab == this.search.tab || this.search.tab == \"all\") {\n        return true;\n      } else {\n        return false;\n      }\n    },\n    getCurrentMediaItem() {\n      socket.send(\n        JSON.stringify({\n          action: \"get-currentmediaitem\",\n        }),\n      );\n    },\n    setStreamerOverlay() {\n      document.body.classList.add(\"streamer-overlay\");\n    },\n    setMode(mode) {\n      switch (mode) {\n        default:\n          this.screen = \"player\";\n          break;\n        case \"miniplayer\":\n          this.screen = \"miniplayer\";\n          break;\n      }\n    },\n    connect() {\n      let self = this;\n      this.connectedState = 0;\n      if (this.url === \"\") {\n        this.url = prompt(\"Host IP\", \"localhost\");\n      }\n      socket = new WebSocket(`ws://${this.url}:26369`);\n      socket.onopen = (e) => {\n        console.log(e);\n        console.log(\"connected\");\n        app.connectedState = 1;\n        if (getParameterByName(\"mode\")) {\n          self.setMode(getParameterByName(\"mode\"));\n        } else {\n          self.setMode(\"default\");\n        }\n        self.clearSelectedTrack();\n      };\n\n      socket.onclose = (e) => {\n        console.log(e);\n        console.log(\"disconnected\");\n        app.connectedState = 2;\n      };\n\n      socket.onerror = (e) => {\n        console.log(e);\n        console.log(\"error\");\n        app.connectedState = 2;\n      };\n\n      socket.onmessage = (e) => {\n        const response = JSON.parse(e.data);\n        switch (response.type) {\n          default:\n            break;\n          case \"musickitapi.search\":\n            self.showArtist(response.data[\"artists\"][0][\"id\"]);\n            break;\n          case \"musickitapi.playlist\":\n          case \"musickitapi.album\":\n            if (self.screen == \"album-page\") {\n              self.albumPage.data = response.data;\n            }\n            break;\n          case \"musickitapi.artist\":\n            if (self.screen == \"artist-page\") {\n              self.artistPage.data = response.data;\n            }\n            break;\n          case \"queue\":\n            // console.log(response.data);\n            self.player.queue = response.data;\n            self.queue.temp = response.data[\"_queueItems\"];\n            self.$forceUpdate();\n            break;\n          case \"lyrics\":\n            self.player.lyrics = response.data;\n            self.$forceUpdate();\n            break;\n          case \"searchResultsLibrary\":\n            self.search.results = response.data;\n            self.search.state = 2;\n            break;\n          case \"searchResults\":\n            self.search.results = response.data;\n            self.search.state = 2;\n            break;\n          case \"playbackStateUpdate\":\n            if (!self.player.userInteraction) {\n              self.updatePlaybackState(response.data);\n            }\n            break;\n          case \"maxVolume\":\n            this.player.maxVolume = response.data;\n            break;\n          case \"libraryStatus\":\n            this.player.status = response.data;\n            break;\n          case \"rate\":\n            var params = this.player.currentMediaItem.playParams;\n            if (params && params.id === response.data.id && params.kind === response.data.kind) {\n              this.player.status = {\n                rating: response.data.rating,\n                inLibrary: this.player.status.inLibrary,\n              };\n            }\n            break;\n          case \"change-library\":\n            var params = this.player.currentMediaItem.playParams;\n            if (params && params.id === response.data.id && params.kind === response.data.kind) {\n              this.player.status = {\n                rating: this.player.status.rating,\n                inLibrary: response.data.add,\n              };\n            }\n            break;\n        }\n        // console.log(e.data);\n      };\n    },\n    updatePlaybackState(mediaitem) {\n      var lyricsDisplayed = this.screen == \"lyrics\" || this.player.lowerPanelState == \"lyrics\";\n      if (this.player.currentMediaItem[\"isrc\"] != mediaitem[\"isrc\"]) {\n        this.getLibraryStatus(mediaitem.playParams.kind, mediaitem.playParams.id);\n\n        if (lyricsDisplayed) {\n          this.getLyrics();\n        }\n        if (this.screen == \"queue\") {\n          this.getQueue();\n        }\n      }\n      this.player.currentMediaItem = mediaitem;\n    },\n    openSongMenu() {\n      const params = this.player.currentMediaItem.playParams;\n\n      if (params) {\n        this.getLibraryStatus(params.kind, params.id);\n      }\n\n      this.player.songActions = true;\n    },\n    rate(rating) {\n      const params = this.player.currentMediaItem.playParams;\n\n      if (params && params.kind !== undefined && params.id !== \"no-id-found\") {\n        socket.send(\n          JSON.stringify({\n            action: \"rating\",\n            type: params.kind,\n            id: params.id,\n            rating: rating,\n          }),\n        );\n      }\n    },\n    toLibrary(shouldAdd) {\n      const params = this.player.currentMediaItem.playParams;\n\n      if (params && params.kind !== undefined && params.id !== \"no-id-found\") {\n        socket.send(\n          JSON.stringify({\n            action: \"change-library\",\n            type: params.kind,\n            id: params.id,\n            add: shouldAdd,\n          }),\n        );\n      }\n    },\n    quit() {\n      socket.send(\n        JSON.stringify({\n          action: \"quit\",\n        }),\n      );\n    },\n  },\n});\n\nfunction getParameterByName(name, url) {\n  if (!url) url = window.location.href;\n  name = name.replace(/[\\[\\]]/g, \"\\\\$&\");\n  var regex = new RegExp(\"[?&]\" + name + \"(=([^&#]*)|&|#|$)\"),\n    results = regex.exec(url);\n  if (!results) return null;\n  if (!results[2]) return \"\";\n  return decodeURIComponent(results[2].replace(/\\+/g, \" \"));\n}\n\nfunction xmlToJson(xml) {\n  // Create the return object\n  var obj = {};\n\n  if (xml.nodeType == 1) {\n    // element\n    // do attributes\n    if (xml.attributes.length > 0) {\n      obj[\"@attributes\"] = {};\n      for (var j = 0; j < xml.attributes.length; j++) {\n        var attribute = xml.attributes.item(j);\n        obj[\"@attributes\"][attribute.nodeName] = attribute.nodeValue;\n      }\n    }\n  } else if (xml.nodeType == 3) {\n    // text\n    obj = xml.nodeValue;\n  }\n\n  // do children\n  if (xml.hasChildNodes()) {\n    for (var i = 0; i < xml.childNodes.length; i++) {\n      var item = xml.childNodes.item(i);\n      var nodeName = item.nodeName;\n      if (typeof obj[nodeName] == \"undefined\") {\n        obj[nodeName] = xmlToJson(item);\n      } else {\n        if (typeof obj[nodeName].push == \"undefined\") {\n          var old = obj[nodeName];\n          obj[nodeName] = [];\n          obj[nodeName].push(old);\n        }\n        obj[nodeName].push(xmlToJson(item));\n      }\n    }\n  }\n  return obj;\n}\n\nwindow.onresize = function () {\n  app.resetPlayerUI();\n};\n\napp.connect();\n"
  },
  {
    "path": "src/web-remote/manifest.json",
    "content": "{\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#000000\",\n  \"display\": \"standalone\",\n  \"scope\": \"/\",\n  \"start_url\": \"/\",\n  \"name\": \"Cider Remote\",\n  \"short_name\": \"Cider Remote\",\n  \"description\": \"Cider Remote\",\n  \"developer\": {\n    \"name\": \"Cider Collective\",\n    \"url\": \"https://cider.sh?utm-source=manifest\"\n  },\n  \"homepage_url\": \"https://cider.sh?utm-source=manifest\",\n  \"icons\": [\n    {\n      \"src\": \"/icon-192x192.png\",\n      \"sizes\": \"192x192\",\n      \"type\": \"image/png\"\n    },\n    {\n      \"src\": \"/icon-256x256.png\",\n      \"sizes\": \"256x256\",\n      \"type\": \"image/png\"\n    },\n    {\n      \"src\": \"/icon-384x384.png\",\n      \"sizes\": \"384x384\",\n      \"type\": \"image/png\"\n    },\n    {\n      \"src\": \"/icon-512x512.png\",\n      \"sizes\": \"512x512\",\n      \"type\": \"image/png\"\n    }\n  ],\n  \"protocol_handlers\": [\n    {\n      \"protocol\": \"ext+cider\",\n      \"name\": \"Cider\",\n      \"uriTemplate\": \"/?url=%s\"\n    }\n  ]\n}\n"
  },
  {
    "path": "src/web-remote/style.css",
    "content": "@import url(\"ciderframework.css\");\n:root {\n  --appleEase: cubic-bezier(0.42, 0, 0.58, 1);\n  --mediaItemShadow: inset 0px 0px 0px 1px rgb(200 200 200 / 16%), 0 8px 40px rgb(0 0 0 / 0.55);\n  --keyColor: #fa586a;\n  --keyColor-rgb: 250, 88, 106;\n  --keyColor-rollover: #ff8a9c;\n  --keyColor-rollover-rgb: 255, 138, 156;\n  --keyColor-pressed: #ff7183;\n  --keyColor-pressed-rgb: 255, 113, 131;\n  --keyColor-deepPressed: #ff8a9c;\n  --keyColor-deepPressed-rgb: 255, 138, 156;\n  --keyColor-disabled: rgba(250, 88, 106, 0.35);\n}\n\nhtml,\nbody {\n  margin: 0;\n  padding: 0;\n  overflow: hidden;\n  width: 100%;\n  height: 100%;\n  box-sizing: border-box;\n}\n\n*,\n*:before,\n*:after {\n  box-sizing: inherit;\n}\n\n/* Modern style overlay scrollbars */\n\n::-webkit-scrollbar {\n  width: 16px;\n  height: 24px;\n}\n\n::-webkit-scrollbar-button {\n  display: none;\n}\n\n::-webkit-scrollbar-track-piece {\n  background: transparent;\n}\n\n::-webkit-scrollbar-thumb {\n  background: transparent;\n  border: 6px solid transparent;\n  box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 50%);\n  border-radius: 16px;\n  min-height: 64px;\n  transition: border 1s;\n}\n\n::-webkit-scrollbar-thumb:hover {\n  border: 5px solid transparent;\n  box-shadow: inset 0px 0px 10px 10px rgb(200 200 200 / 80%);\n}\n\n#app {\n  --artwork: url();\n  max-width: 600px;\n  width: 100%;\n  height: 100%;\n  background: rgb(20 20 20);\n  color: white;\n  user-select: none;\n  margin: 0 auto;\n  position: relative;\n  overflow: hidden;\n  padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);\n}\n\n#app:before {\n  content: \"\";\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background-image: var(--artwork);\n  background-position: center;\n  background-size: cover;\n  opacity: 0.25;\n  filter: blur(32px) saturate(180%);\n}\n\nbody.streamer-overlay {\n  background: transparent;\n}\n\nbody.streamer-overlay #app {\n  background: transparent;\n}\n\nbody.streamer-overlay #app:before {\n  display: none;\n}\n\nbody {\n  background: #111;\n  font-family: \"Segoe UI Variable Display\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Open Sans\", \"Helvetica Neue\", sans-serif;\n}\n\ninput[type=\"range\"].web-slider {\n  -webkit-appearance: none;\n  height: 4px;\n  background: rgba(255, 255, 255, 0.6);\n  border-radius: 5px;\n  background-size: 70% 100%;\n  background-repeat: no-repeat;\n}\n\ninput[type=\"range\"].web-slider::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  height: 20px;\n  width: 20px;\n  border-radius: 50%;\n  background: rgb(255 255 255);\n  cursor: ew-resize;\n  box-shadow: 0 0 2px 0 #555;\n}\n\ninput[type=\"range\"].web-slider::-webkit-slider-runnable-track {\n  -webkit-appearance: none;\n  box-shadow: none;\n  border: none;\n  background: transparent;\n}\n\n.nopadding {\n  padding: 0px;\n}\n\n.md-btn {\n  font-family: inherit;\n}\n\n.wr-btn {\n  font-family: inherit;\n  appearance: none;\n  border: 0px;\n  border-radius: 6px;\n  padding: 8px;\n  font-weight: 600;\n  background: rgb(80 80 80 / 70%);\n  color: white;\n}\n\n.footer-player {\n  padding: 6px;\n  display: flex;\n  border-top: 1px solid rgb(200 200 200 / 15%);\n  background: rgb(200 200 200 / 10%);\n}\n\n.player-duration-time {\n  opacity: 0.5;\n}\n\n.player-artwork-container {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.player-duration-container {\n  font-size: 0.85em;\n  font-weight: 500;\n}\n\n.media-artwork {\n  --artwork: url(\"\");\n  width: 80vw;\n  height: 80vw;\n  max-height: 500px;\n  max-width: 500px;\n  background: black;\n  background-image: var(--artwork);\n  background-size: cover;\n  background-position: center;\n  background-repeat: no-repeat;\n  border-radius: 8px;\n  box-shadow: var(--mediaItemShadow);\n  transition: transform 0.1s var(--appleEase);\n}\n\n.media-artwork.paused {\n  transition: transform 0.35s var(--appleEase);\n  transform: scale(0.85);\n}\n\n.lossless-badge {\n  background-image: url(\"./assets/lossless.svg\");\n  background: rgb(150 150 150);\n  border-radius: 6px;\n  padding: 0px 6px;\n  color: rgb(30 30 30);\n  font-weight: 600;\n}\n\n.playback-slider {\n  width: 90%;\n}\n\n.volume-slider {\n  width: 100%;\n}\n\n.volume-slider-container {\n  width: 90%;\n  margin: 0 auto;\n  padding: 0px;\n}\n\n.volume-slider-container .col-auto,\n.volume-slider-container .col {\n  display: flex;\n  align-items: center;\n  justify-self: center;\n  padding: 0px;\n  margin: 0px;\n}\n\n.playback-button {\n  font-size: 2em;\n  width: 64px;\n  height: 64px;\n  padding: 0px;\n  background: transparent;\n  border: 0px;\n  border-radius: 0px;\n  box-shadow: unset;\n  background-size: 24px;\n  background-position: center;\n  background-repeat: no-repeat;\n}\n\n.playback-button:active {\n  transform: scale(0.95);\n}\n\n.playback-button--small {\n  font-size: 1em;\n  color: inherit;\n  background-size: 18px;\n  background-repeat: no-repeat;\n  background-position: center;\n  background-color: transparent;\n  width: 64px;\n  height: 32px;\n  border: 0px;\n  box-shadow: unset;\n}\n\n.playback-button--small.active {\n  background-color: rgb(200 200 200 / 25%);\n}\n\n.playback-button--small.activeColor {\n  background-color: var(--keyColor);\n}\n\n.playback-button--small.search {\n  background-image: url(\"./assets/search.svg\");\n}\n\n.playback-button--small.queue {\n  background-image: url(\"./assets/list.svg\");\n}\n\n.playback-button--small.lyrics {\n  background-image: url(\"./assets/quote-right.svg\");\n}\n\n.playback-button--small.autoplay {\n  background-image: url(\"./assets/infinity.svg\");\n}\n\n.playback-button--small.shuffle {\n  background-image: url(\"./assets/shuffle.svg\");\n}\n\n.playback-button--small.repeat {\n  background-image: url(\"./assets/repeat.svg\");\n}\n\n.playback-button--small.repeat.repeatOne {\n  background-color: rgb(200 200 200 / 25%);\n  background-image: url(\"./assets/repeatOne.svg\");\n}\n\n.playback-button.pause {\n  background-image: url(\"./assets/pause.svg\");\n}\n\n.playback-button.play {\n  background-image: url(\"./assets/play.svg\");\n}\n\n.playback-button.next {\n  background-image: url(\"./assets/forward.svg\");\n}\n\n.playback-button.previous {\n  background-image: url(\"./assets/backward.svg\");\n}\n\n.playback-button.quit {\n  background-image: url(\"./assets/x.svg\");\n}\n\n.quit-button-container {\n  position: absolute;\n  top: 0px;\n  right: 60px;\n  width: 10px;\n  height: 10px;\n  z-index: 10;\n}\n\n.popup-confirm {\n  margin: 0 auto;\n  width: 100%;\n  height: 100%;\n  position: relative;\n}\n\n.overlay {\n  position: absolute;\n  background: rgba(71, 71, 71, 0.35);\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n}\n\n.popup {\n  position: absolute;\n  top: 40%;\n  left: 15%;\n  width: 70%;\n  margin: 0px;\n  z-index: 10px;\n  background: rgba(255, 255, 255, 0.85);\n  border-radius: 8px;\n  text-align: center;\n  box-sizing: border-box;\n}\n\n.popup h3 {\n  color: rgb(0, 0, 0);\n  margin: 20px 0 0 0;\n  padding: 0;\n}\n\n.popup p {\n  color: rgb(0, 0, 0);\n  font-weight: 10px;\n  margin: 15px;\n  padding: 0;\n}\n\n.popup .button-holder a {\n  color: #007aff;\n  text-decoration: none;\n  line-height: 45px;\n  font-weight: bold;\n  display: block;\n  border-top: 1px solid #bababa;\n}\n\n.popup .two-button a {\n  width: 50%;\n  float: left;\n  box-sizing: border-box;\n}\n\n.popup .two-button a:first-child {\n  color: #ff0000;\n  border-right: 1px solid #bababa;\n}\n\n.playback-buttons {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.player-volume-glyph {\n  width: 32px;\n  height: 16px;\n  background-repeat: no-repeat;\n  background-size: contain;\n  background-position: center;\n}\n\n.player-volume-glyph.decrease {\n  background-image: url(\"./assets/volume-down.svg\");\n  opacity: 0.5;\n}\n\n.player-volume-glyph.increase {\n  background-image: url(\"./assets/volume-up.svg\");\n  opacity: 0.5;\n}\n\n.player-track-info {\n  width: 90%;\n  margin: 0 auto;\n}\n\n.player-song-title {\n  font-size: 1.25em;\n  text-align: left;\n  margin: 0 auto;\n  font-weight: 500;\n}\n\n.player-song-artist {\n  font-size: 1em;\n  text-align: left;\n  margin: 0 auto;\n  color: var(--keyColor);\n  font-weight: 400;\n}\n\n.player-song-artist:hover {\n  cursor: pointer;\n  text-decoration: underline;\n}\n\n.player-more-container {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.player-more-button {\n  appearance: none;\n  width: 32px;\n  height: 32px;\n  border-radius: 50%;\n  border: 0px;\n  background: var(--keyColor);\n  cursor: pointer;\n  box-shadow: inset 0px 0px 0px 1px rgb(200 200 200 / 16%);\n  color: white;\n  font-weight: bold;\n  padding: 0px;\n  font-size: 16px;\n}\n\n.back-button {\n  width: 40px;\n  height: 40px;\n  background-color: transparent;\n  background-size: 16px;\n  background-position: center;\n  background-repeat: no-repeat;\n  background-image: url(\"./assets/arrow-left.svg\");\n  border: 0px;\n  border-radius: 0px;\n}\n\n.header-text {\n  height: 40px;\n  display: flex;\n  align-items: center;\n}\n\n.search-input {\n  width: 100%;\n  padding: 12px;\n  font-size: 1em;\n  font-family: inherit;\n  border-radius: 8px;\n  border: 0px;\n  background: rgb(20 20 20 / 0.85);\n  color: #eee;\n}\n\n.flex-center {\n  display: flex;\n  align-items: center;\n  flex-wrap: wrap;\n}\n\n.list-entry-header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 12px;\n  font-size: 1em;\n  font-family: inherit;\n}\n\n.list-entry {\n  display: flex;\n  align-items: center;\n  /* justify-content: space-between; */\n  padding: 12px;\n  font-size: 1em;\n  font-family: inherit;\n  border-bottom: 1px solid rgba(255 255 255 / 0.1);\n  cursor: pointer;\n}\n\n.list-entry.artist-song {\n  padding: 5px;\n  width: 100%;\n}\n\n.list-entry-image {\n  --artwork: url(\"\");\n  width: 64px;\n  height: 64px;\n  background: var(--artwork);\n  background-size: cover;\n  background-position: center;\n  background-repeat: no-repeat;\n  border-radius: 4px;\n  box-shadow: var(--mediaItemShadow);\n}\n\n.artist-song .list-entry-image {\n  width: 45px;\n  height: 45px;\n}\n\n.list-entry-image.artist {\n  border-radius: 50%;\n}\n\n.list-entry-body {\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: flex-start;\n  margin-left: 12px;\n}\n\n.list-entry-name {\n  font-size: 14px;\n  font-weight: 500;\n  overflow: hidden;\n  width: 100%;\n}\n\n.list-entry-artist {\n  font-size: 12px;\n  overflow: hidden;\n  width: 100%;\n}\n\n.list-entry .handle {\n  height: 100%;\n  width: 28px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  background-size: contain;\n  background-repeat: no-repeat;\n  background-image: url(\"./assets/Grabber.svg\");\n  cursor: grab;\n}\n\n.list-entry .handle:active {\n  cursor: grabbing;\n}\n\n.song-scroller-horizontal {\n  display: flex;\n  overflow-y: scroll;\n  overflow-x: hidden;\n  overflow-y: overlay;\n  width: 100%;\n  height: 200px;\n  /*! flex-flow: row; */\n  flex-direction: row;\n  flex-wrap: wrap;\n}\n\n.song-placeholder {\n  height: 60px;\n  width: 50%;\n  flex: 0 0 auto;\n}\n\n.mediaitem-scroller-horizontal {\n  display: flex;\n  overflow-y: hidden;\n  overflow-x: scroll;\n  overflow-x: overlay;\n  width: 100%;\n}\n\n.mediaitem-scroller-horizontal::-webkit-scrollbar {\n  display: none;\n}\n\n.album-placeholder {\n  height: 180px;\n  width: 180px;\n  flex: 0 0 auto;\n}\n\n.md-container {\n  width: 100%;\n  position: relative;\n}\n\n.search-panel {\n  background: rgb(0 0 0 / 50%);\n}\n\n.search-header {\n  position: absolute;\n  width: 100%;\n  z-index: 1;\n  backdrop-filter: blur(16px);\n  -webkit-backdrop-filter: blur(16px);\n  border-bottom: 1px solid rgb(200 200 200 / 8%);\n}\n\n.connection-error-panel {\n  background: rgb(0 0 0 / 50%);\n}\n\n.search-type-container {\n  display: flex;\n}\n\n.search-type-button {\n  background: rgb(20 20 20 / 0.85);\n  border-radius: 50px;\n  color: white;\n  border: 0px;\n  box-shadow: unset;\n  font-family: inherit;\n  padding: 8px 16px;\n  font-size: 14px;\n  font-weight: 500;\n  margin: 8px;\n  margin-top: 0px;\n  margin-bottom: 0px;\n}\n\n.search-type-button.active {\n  background: var(--keyColor);\n}\n\n.search-tab-container {\n  overflow: auto;\n  white-space: nowrap;\n  overflow-y: hidden;\n}\n\n.search-tab-container::-webkit-scrollbar {\n  display: none;\n}\n\n.search-body-container {\n  position: relative;\n  width: 100%;\n  height: 100%;\n  overflow-y: scroll;\n  overflow-y: overlay;\n}\n\n.queue-body {\n  width: 100%;\n  height: 100%;\n}\n\n.text-overflow-elipsis {\n  min-width: 0px;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n\n.album-body-container {\n  position: relative;\n  width: 100%;\n  height: 100%;\n  overflow-y: scroll;\n  overflow-y: overlay;\n  overflow-x: hidden;\n}\n\n.albumpage-artwork {\n  --artwork: url(\"\");\n  width: 30vh;\n  height: 30vh;\n  margin: 0 auto;\n  border-radius: 6px;\n  background: black;\n  margin-bottom: 18px;\n  box-shadow: var(--mediaItemShadow);\n  background-image: var(--artwork);\n  background-size: cover;\n  background-repeat: no-repeat;\n  background-position: center;\n}\n\n.albumpage-misc-info {\n  text-align: center;\n  font-size: 13px;\n  font-weight: 600;\n  opacity: 0.5;\n}\n\n.albumpage-album-notes {\n  margin: 0 auto;\n  margin-top: 16px;\n  height: 60px;\n  overflow: hidden;\n  position: relative;\n  max-width: 300px;\n}\n\n.albumpage-album-notes > .notes-preview {\n  height: 48px;\n  overflow: hidden;\n  -webkit-mask-image: -webkit-gradient(linear, left 95%, left bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0)));\n}\n\n.albumpage-album-notes > .notes-more {\n  position: absolute;\n  bottom: 0px;\n  right: 0px;\n  appearance: none;\n  background: transparent;\n  color: var(--keyColor);\n  font-weight: bold;\n  font-family: inherit;\n  text-transform: uppercase;\n  height: 100%;\n  width: 100%;\n  padding: 0px;\n  border: 0px;\n  display: flex;\n  justify-content: flex-end;\n  align-items: flex-end;\n}\n\n.album-page-fullnotes-body {\n  padding: 22px;\n  font-size: 17px;\n  overflow-y: scroll;\n  overflow-y: overlay;\n}\n\n.albumpage-album-name {\n  margin: 0 auto;\n  font-size: 17px;\n  width: 100%;\n  text-align: center;\n  font-weight: 600;\n}\n\n.albumpage-artist-name {\n  margin: 0 auto;\n  width: 100%;\n  text-align: center;\n  font-size: 18px;\n  color: var(--keyColor);\n}\n\n.albumpage-artist-name:hover {\n  text-decoration: underline;\n  cursor: pointer;\n}\n\n.artist-header {\n  /* height: 400px; */\n  width: 100%;\n  /* margin: 12px auto; */\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  /* padding: 12px; */\n  flex-direction: column;\n  background: rgb(0 0 0 / 40%);\n}\n\n.artist-header .artist-header-portrait {\n  height: 200px;\n  width: 200px;\n  background: var(--artwork);\n  background-size: contain;\n  background-repeat: no-repeat;\n  border-radius: 100%;\n  box-shadow: var(--mediaItemShadow);\n}\n\n.search-body {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  padding-top: 220px;\n}\n\n.artist-body {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n}\n\n.search-tab {\n  background: rgb(20 20 20 / 0.85);\n  border-radius: 50px;\n  color: white;\n  border: 0px;\n  box-shadow: unset;\n  font-family: inherit;\n  padding: 8px 16px;\n  font-size: 14px;\n  font-weight: 500;\n}\n\n.search-tab.active {\n  background: var(--keyColor);\n}\n\n.context-menu {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background: rgba(0, 0, 0, 0.5);\n  z-index: 100;\n}\n\n.context-menu .context-menu-item {\n  --borderRadius: 10px;\n  appearance: none;\n  width: 100%;\n  display: block;\n  font-size: 1.1em;\n  padding: 18px 20px;\n  font-family: inherit;\n  border: 0px;\n  font-weight: 600;\n  border-radius: 0px;\n  border-bottom: 1px solid rgb(200 200 200 / 15%);\n  margin: 0px;\n  background: rgb(60 60 60 / 80%);\n  backdrop-filter: blur(16px) saturate(180%);\n  -webkit-backdrop-filter: blur(16px) saturate(180%);\n  color: #ccc;\n}\n\n.context-menu .context-menu-item:hover {\n  cursor: pointer;\n}\n\n.context-menu .context-menu-item:disabled {\n  cursor: default;\n  filter: brightness(125%);\n}\n\n.context-menu .context-menu-item:active:disabled {\n  filter: brightness(125%);\n}\n\n.context-menu .context-menu-item:active {\n  filter: brightness(75%);\n}\n\n.context-menu .context-menu-item:first-child {\n  border-radius: 0px;\n  border-top-left-radius: var(--borderRadius);\n  border-top-right-radius: var(--borderRadius);\n}\n\n.context-menu .context-menu-item:last-child {\n  border-radius: 0px;\n  border-bottom-left-radius: var(--borderRadius);\n  border-bottom-right-radius: var(--borderRadius);\n  border-bottom: 0px;\n}\n\n.context-menu .context-menu-item:only-child {\n  border-radius: var(--borderRadius);\n}\n\n.context-menu .context-menu-item.context-menu-item--left {\n  text-align: left;\n}\n\n.context-menu .context-menu-body {\n  display: flex;\n  align-items: flex-end;\n  justify-content: flex-end;\n  flex-direction: column;\n}\n\n.lyric-body {\n  -webkit-mask-image: -webkit-gradient(linear, left 95%, left bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0)));\n  overflow-y: scroll;\n  overflow-x: hidden;\n  display: flex;\n  flex-flow: column;\n}\n\n.lyric-line {\n  --bgSpeed: 1s;\n  appearance: none;\n  color: white;\n  font-size: 2rem;\n  transform: scale(0.8);\n  transform-origin: left center;\n  transition: transform 0.2s var(--appleEase);\n  opacity: 0.75;\n  width: auto;\n  display: inline-block;\n  margin: 10px;\n  margin-left: 5%;\n  margin-right: 0px;\n}\n\n.lyric-line:hover {\n  cursor: pointer;\n}\n\n.lyric-line:hover::after {\n  content: \" \";\n  width: 100%;\n  height: 100%;\n  position: absolute;\n  top: 0;\n  left: 0;\n  transform: scale(1.06);\n  background: rgba(200, 200, 200, 0.1);\n  pointer-events: none;\n  border-radius: 10px;\n  -webkit-backface-visibility: hidden;\n}\n\n.lyric-line.active {\n  --bgSpeed: 1s;\n  opacity: 1;\n  transform: scale(1);\n  /*background: var(--keyColor);*/\n  transition: transform 0.2s var(--appleEase);\n}\n\n.lyric-line:not(.active) {\n  filter: blur(1px);\n}\n\n.lyricWaiting {\n  margin-top: 8px;\n  display: none;\n}\n\n.lyric-line.active .lyricWaiting {\n  display: inline-flex;\n  animation: lyricWaitingLine 6s cubic-bezier(0.42, 0, 0.58, 1) infinite;\n}\n\n.lyric-line.active .lyricWaiting > div {\n  width: 10px;\n  height: 10px;\n  background: white;\n  border-radius: 50%;\n  margin: 3px;\n}\n\n@keyframes lyricWaitingLine {\n  0% {\n    opacity: 0;\n    transform: scale(0.85);\n  }\n  50% {\n    opacity: 1;\n    transform: scale(1);\n  }\n  100% {\n    opacity: 0;\n    transform: scale(0.85);\n  }\n}\n\n.lyric-line2:before {\n  background: var(--keyColor);\n  content: \"\";\n  width: 0%;\n  height: 6px;\n  position: absolute;\n  bottom: -8px;\n  left: 0;\n  border-radius: 10px;\n  z-index: -1;\n  transition: width var(--bgSpeed);\n}\n\n.lyric-line2.active:before {\n  width: 100%;\n  transition: width var(--bgSpeed);\n}\n\n.player_top {\n  height: 100%;\n}\n\n.miniplayer-main {\n  width: 100%;\n  height: 100%;\n  position: relative;\n}\n\n.miniplayer-main .miniplayer-controls {\n  position: absolute;\n  bottom: 0px;\n  left: 0px;\n  background: rgb(0 0 0 / 50%);\n  height: 80px;\n  z-index: 2;\n  width: 100%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  backdrop-filter: blur(16px) saturate(180%);\n}\n\n.miniplayer-main .miniplayer-draggable {\n  position: absolute;\n  top: 0;\n  left: 0;\n  height: calc(100% - 80px);\n  width: 100%;\n}\n\n.miniplayer-main .miniplayer-controls .md-btn {\n  width: 40px;\n  background-size: 16px;\n}\n\n.media-artwork--miniplayer {\n  width: 100%;\n  height: 100%;\n  background: var(--artwork);\n  background-size: cover;\n  background-position: center;\n  background-repeat: no-repeat;\n}\n\n/* Small Screen */\n\n@media only screen and (max-height: 668px) {\n  #app {\n    zoom: 0.8;\n  }\n}\n\n/* Big Screen */\n\n@media only screen and (orientation: landscape) {\n  #app {\n    max-width: 100%;\n  }\n  .album-body-container {\n    display: flex;\n    flex-wrap: wrap;\n  }\n  .album-body-container > .md-header {\n    min-width: 300px;\n    flex: 0 0 auto;\n    /*! max-width: 300px; */\n    margin: 0 auto;\n  }\n  .artist-body {\n    position: relative;\n    /*! flex: 0 0 auto; */\n  }\n  .player-panel {\n    display: flex;\n    flex-direction: row;\n    justify-content: center;\n    padding: 40px;\n  }\n  .player_bottom {\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    flex-direction: column;\n    width: 100%;\n    max-width: 50vw;\n    margin: 0;\n    padding: 0 16px;\n  }\n  .media-artwork {\n    width: 45vw;\n    height: 45vw;\n    margin: 0;\n  }\n  .player-song-title {\n    font-size: 2em;\n  }\n  .player-song-artist {\n    font-size: 1.25em;\n    font-weight: 400;\n  }\n  .search-panel {\n  }\n  .md-footer {\n    width: 100%;\n  }\n}\n\n/* Transitions */\n\n.wpfade-enter-active,\n.wpfade-leave-active {\n  transition: opacity 0.1s var(--appleEase);\n}\n\n.wpfade-enter,\n.wpfade-leave-to {\n  opacity: 0;\n}\n"
  },
  {
    "path": "src/web-remote/views/components/animatedartwork-view.ejs",
    "content": "<script type=\"text/x-template\" id=\"animatedartwork-view\">\n    <div class=\"animated\" v-bind:vid=\"app.hashCode(video).toString()\" v-if=\"video\">\n        <video ref=\"video\" class=\"animated-artwork-video\" loop id=\"animated-artwork\"></video>\n    </div>\n</script>\n\n<script>\n  Vue.component('animatedartwork-view', {\n    template: '#animatedartwork-view',\n    data: function() {\n      return {\n        app: this.$root,\n        hls: null,\n      }\n    },\n    props: {\n      video: {\n        type: String,\n        required: true\n      },\n      priority: {\n        type: Boolean,\n        default: false\n      }\n    },\n    async mounted() {\n      if (!this.priority && app.cfg.visual.animated_artwork == \"limited\") {\n        return\n      } else if (app.cfg.visual.animated_artwork == \"disabled\") {\n        return\n      }\n      if (this.video) {\n        this.$nextTick(function() {\n          var config = {\n            backBufferLength: 0,\n            enableWebVTT: false,\n            enableCEA708Captions: false,\n            emeEnabled: false,\n            abrEwmaDefaultEstimate: 10000,\n            testBandwidth: false,\n          };\n          if (this.hls) {\n            this.hls.detachMedia();\n          } else {\n\n            this.hls = new CiderHls(config);\n          }\n          // bind them together\n          if (this.$refs.video) {\n            let d = \"WIDEVINE_SOFTWARE\"\n            let h = {\n              initDataTypes: [\"cenc\", \"keyids\"],\n              distinctiveIdentifier: \"optional\",\n              persistentState: \"required\"\n            }\n            let p = {\n              platformInfo: { requiresCDMAttachOnStart: !0, maxSecurityLevel: d, keySystemConfig: h },\n              appData: { serviceName: \"Apple Music\" }\n            }\n            this.hls.attachMedia(this.$refs.video);\n            this.hls.loadSource(this.video);\n            this.hls.loadLevel = parseInt(app.cfg.visual.animated_artwork_qualityLevel || 1);\n          }\n        })\n      }\n    },\n    async beforeDestroy() {\n      if (this.hls) {\n        await this.hls.destroy();\n        this.hls = null\n      }\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/web-remote/views/components/mediaitem-artwork.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-artwork\">\n    <div class=\"mediaitem-artwork\" :class=\"[{'rounded': (type == 'artists')}, classes]\" :key=\"url\"\n         v-observe-visibility=\"{callback: visibilityChanged}\">\n        <img :src=\"getMediaItemArtwork(url, size, width)\"  :style=\"{ width: size + 'px'}\"\n             decoding=\"async\" loading=\"lazy\"\n             class=\"mediaitem-artwork--img\">\n        <!-- <div v-if=\"video && isVisible && getVideoPriority()\" class=\"animatedartwork-view-box\">\n            <animatedartwork-view :priority=\"getVideoPriority()\" :video=\"video\"></animatedartwork-view>\n        </div> -->\n    </div>\n</script>\n\n<script>\n  Vue.component('mediaitem-artwork', {\n    template: '#mediaitem-artwork',\n    props: {\n      size: {\n        type: [String, Number],\n        default: '120'\n      },\n      width: {\n        type: [String, Number],\n        required: false\n      },\n      url: {\n        type: String,\n        default: ''\n      },\n      type: {\n        type: String,\n        default: ''\n      },\n      video: {\n        type: String,\n        required: false\n      },\n      videoPriority: {\n        type: Boolean,\n        required: false\n      },\n      shadow: {\n        type: String,\n        default: ''\n      }\n    },\n    data: function() {\n      return {\n        app: this.$root,\n        isVisible: false,\n        style: {\n          \"box-shadow\": \"\"\n        },\n        classes: []\n      }\n    },\n    mounted() {\n      this.getClasses()\n    },\n    methods: {\n      getVideoPriority() {\n        return false\n      },\n      getClasses() {\n        switch (this.shadow) {\n          case \"none\":\n            this.classes.push(\"no-shadow\")\n            break;\n          case \"large\":\n            this.classes.push(\"shadow\")\n            break;\n          case \"subtle\":\n            this.classes.push(\"subtle-shadow\")\n            break;\n          default:\n            break;\n        }\n        return this.classes;\n      },\n      getArtworkStyle() {\n        return {\n          width: this.size + 'px',\n          height: this.size + 'px'\n        };\n      },\n      visibilityChanged: function(isVisible, entry) {\n        this.isVisible = isVisible\n      },\n      getMediaItemArtwork(url, height = 64, width) {\n        try{\n        if (typeof url == \"undefined\" || url == \"\") {\n          return \"./assets/MissingArtwork.svg\"\n        }\n        height = parseInt(height * window.devicePixelRatio)\n        if (width) {\n          width = parseInt(width * window.devicePixelRatio)\n        }\n        let newurl = `${url.replace('{w}', width ?? height).replace('{h}', height).replace('{f}', \"webp\").replace('{c}', ((width === 900) ? \"sr\" : \"cc\"))}`;\n\n        if (newurl.includes(\"900x516\")) {\n          newurl = newurl.replace(\"900x516cc\", \"900x516sr\").replace(\"900x516bb\", \"900x516sr\");\n        }\n        return newurl} catch (e){\n          return \"./assets/MissingArtwork.svg\"\n        }\n      },\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/web-remote/views/components/mediaitem-square.ejs",
    "content": "<script type=\"text/x-template\" id=\"mediaitem-square\">\n    <div tabindex=\"0\"\n         class=\"cd-mediaitem-square\" :class=\"getClasses()\" @contextmenu=\"contextMenu\"\n         v-observe-visibility=\"{callback: visibilityChanged}\"\n         :style=\"{'--spcolor': getBgColor()}\">\n        <template v-if=\"isVisible\">\n            <div class=\"artwork-container\">\n                <div class=\"artwork\" @click='app.routeView(item)'>\n                    <mediaitem-artwork\n                            :url=\"getArtworkUrl()\"\n                            :video=\"(item.attributes != null && item.attributes.editorialVideo != null) ? (item.attributes.editorialVideo.motionDetailSquare ? item.attributes.editorialVideo.motionDetailSquare.video : (item.attributes.editorialVideo.motionSquareVideo1x1 ? item.attributes.editorialVideo.motionSquareVideo1x1.video : '')) : '' \"\n                            :size=\"size\"\n                            shadow=\"subtle\"\n                            :type=\"item.type\"></mediaitem-artwork>\n                </div>\n                <button class=\"menu-btn\" v-if=\"!nomenu.includes(item.type)\"\n                        @click=\"contextMenu\" :aria-label=\"$root.getLz('term.more')\">\n                    <%- include(\"../svg/more.svg\") %>\n                </button>\n                <button class=\"play-btn\" v-if=\"!noplay.includes(item.type)\"\n                        @click=\"app.playMediaItem(item)\" :aria-label=\"$root.getLz('term.play')\">\n                    <%- include(\"../svg/play.svg\") %>\n                </button>\n                <div class=\"badge-container\" v-if=\"itemBadges.length != 0\">\n                    <div class=\"socialBadge\" v-for=\"badge in itemBadges.limit(1)\">\n                        <mediaitem-artwork\n                                :url=\"(badge.attributes.artwork ? badge.attributes.artwork.url : '')\"\n                                :size=\"32\"></mediaitem-artwork>\n                    </div>\n                </div>\n            </div>\n            <div class=\"info-rect\" :class=\"{'info-rect-card': kind == 'card'}\"\n                 :style=\"{'--bgartwork': getArtworkUrl(size, true)}\">\n                <div class=\"title\" v-if=\"item.attributes.artistNames == null || kind!= 'card'\"\n                     @click='app.routeView(item)'>\n                    <div class=\"item-navigate text-overflow-elipsis\">{{ item.attributes.name }}</div>\n                    <div class=\"explicit-icon\" v-if=\"item.attributes && item.attributes.contentRating == 'explicit'\"\n                         style=\"background-image: url(./assets/explicit.svg);height: 12px;width: 12px;filter: contrast(0);background-repeat: no-repeat;margin-top: 2.63px;margin-left: 4px;\"></div>\n                </div>\n                <div class=\"subtitle item-navigate text-overflow-elipsis\" @click=\"getSubtitleNavigation()\"\n                     v-if=\"getSubtitle() != ''\">\n                    {{ getSubtitle() }}\n                </div>\n                <div class=\"subtitle\" v-if=\"getSubtitle() == '' && kind != 'card'\">&nbsp;</div>\n            </div>\n        </template>\n    </div>\n</script>\n\n<script>\n  Vue.component('mediaitem-square', {\n    template: '#mediaitem-square',\n    props: {\n      item: {\n        type: Object,\n        required: true\n      },\n      kind: {\n        type: String,\n        default: ''\n      },\n      size: {\n        type: String,\n        default: '190'\n      },\n      'contextExt': { type: Object, required: false },\n    },\n    data: function() {\n      return {\n        isVisible: false,\n        addedToLibrary: false,\n        guid: this.uuidv4(),\n        noplay: [\"apple-curators\"],\n        nomenu: [\"artists\", \"stations\", \"apple-curators\"],\n        app: this.$root,\n        badges: this.$root.socialBadges.badgeMap,\n        itemBadges: []\n      }\n    },\n    async mounted() {\n      await this.getBadges()\n    },\n    methods: {\n      getBgColor() {\n        let color = `#${(this.item.attributes.artwork != null && this.item.attributes.artwork.bgColor != null) ? (this.item.attributes.artwork.bgColor) : `333333`}`\n        let c = color.substring(1);      // strip #\n        var rgb = parseInt(c, 16);   // convert rrggbb to decimal\n        var r = (rgb >> 16) & 0xff;  // extract red\n        var g = (rgb >> 8) & 0xff;  // extract green\n        var b = (rgb >> 0) & 0xff;  // extract blue\n\n        var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709\n\n        if (luma > 140) {\n          return \"#aaaaaa\"\n        } else {\n          return color\n        }\n\n\n      },\n      getSubtitle() {\n        if (this.kind == 'card') {\n          try {\n            if (typeof this.item.attributes.artistNames != \"undefined\") {\n              return this.item.attributes.artistNames\n            } else if (typeof this.item.attributes.editorialNotes != \"undefined\") {\n              return this.item.attributes.editorialNotes.short\n            } else if (typeof this.item.attributes.artistName != \"undefined\") {\n              return this.item.attributes.artistName\n            } else {\n              return ''\n            }\n          } catch (e) {\n            return ''\n          }\n        } else {\n          if (typeof this.item.attributes.artistName != \"undefined\") {\n            return this.item.attributes.artistName\n          } else {\n            return ''\n          }\n        }\n      },\n      getSubtitleNavigation() {\n        if (this.kind == 'card') {\n          try {\n            if (typeof this.item.attributes.artistNames != \"undefined\") {\n              return app.routeView(this.item)\n            } else if (typeof this.item.attributes.editorialNotes != \"undefined\") {\n              return app.routeView(this.item)\n            } else if (typeof this.item.attributes.artistName != \"undefined\") {\n              return app.searchAndNavigate(this.item, 'artist')\n            } else {\n              return app.routeView(this.item)\n            }\n          } catch (e) {\n            return app.routeView(this.item)\n          }\n        } else {\n          if (typeof this.item.attributes.artistName != \"undefined\") {\n            return app.searchAndNavigate(this.item, 'artist')\n          } else {\n            return app.routeView(this.item)\n          }\n        }\n      },\n      async getBadges() {\n        const self = this\n        const id = (this.item.attributes.playParams ? this.item.attributes.playParams.id : null) || this.item.id\n        if (id && this.badges[id]) {\n          let friends = this.badges[id]\n          if (friends) {\n            friends.forEach(function(friend) {\n              self.app.mk.api.v3.music(`/v1/social/${app.mk.storefrontId}/social-profiles/${friend}`).then(data => {\n                self.itemBadges.push(data.data.data[0])\n              })\n            })\n          }\n        }\n      },\n      revisedRandId() {\n        return Math.random().toString(36).replace(/[^a-z]+/g, '').slice(2, 10);\n      },\n      async isInLibrary() {\n        if (this.item.type && !this.item.type.includes(\"library\")) {\n          var params = {\n            \"fields[playlists]\": \"inLibrary\",\n            \"fields[albums]\": \"inLibrary\",\n            \"relate\": \"library\",\n            \"extend\": this.revisedRandId()\n          }\n          var res = await app.mkapi(this.item.attributes.playParams.kind ?? this.item.type, this.item.attributes.playParams.isLibrary ?? false, this.item.attributes.playParams.id ?? this.item.id, params);\n          res = res.data.data[0]\n          this.addedToLibrary = (res && res.attributes && res.attributes.inLibrary) ? res.attributes.inLibrary : false\n        } else {\n          this.addedToLibrary = true\n        }\n      },\n      async removeFromLibrary(id) {\n        var params = {\n          \"fields[playlists]\": \"inLibrary\",\n          \"fields[songs]\": \"inLibrary\",\n          \"fields[albums]\": \"inLibrary\",\n          \"relate\": \"library\",\n          \"extend\": this.revisedRandId()\n        }\n        var id = this.item.id ?? this.item.attributes.playParams.id\n        var res = await app.mkapi(this.item.attributes.playParams.kind ?? this.item.type, this.item.attributes.playParams.isLibrary ?? false, this.item.attributes.playParams.id ?? this.item.id, params);\n        res = res.data.data[0]\n        if (res && res.relationships && res.relationships.library && res.relationships.library.data && res.relationships.library.data.length > 0) {\n          id = res.relationships.library.data[0].id\n        }\n        let kind = this.item.attributes.playParams.kind ?? this.item.type ?? '';\n        var truekind = (!kind.endsWith(\"s\")) ? (kind + \"s\") : kind;\n        app.mk.api.v3.music(`v1/me/library/${truekind}/${id.toString()}`, {},\n          {\n            fetchOptions: {\n              method: \"DELETE\"\n            }\n          })\n        this.addedToLibrary = true\n      },\n      uuidv4() {\n        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>\n          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n        );\n      },\n      getArtworkUrl(size = -1, includeUrl = false) {\n        let artwork = this.item.attributes.artwork ? this.item.attributes.artwork.url : ''\n        if (size != -1) {\n          artwork = artwork.replace('{w}', size).replace('{h}', size).replace('{f}', \"webp\").replace('{c}', ((size === 900) ? \"sr\" : \"cc\"))\n        }\n        switch (this.kind) {\n          case \"385\":\n            artwork = this.item.attributes?.editorialArtwork?.subscriptionHero?.url\n            break;\n        }\n        if (!includeUrl) {\n          return artwork\n        } else {\n          return `url(\"${artwork}\")`\n        }\n      },\n      getClasses() {\n        let type = this.item.type\n        if (this.kind != \"\") {\n          type = this.kind\n        }\n        switch (type) {\n          default:\n            return []\n            break;\n          case \"card\":\n            return [\"mediaitem-card\"]\n            break;\n          case \"385\": // editorial\n            return [\"mediaitem-brick\"]\n            break;\n          case \"small\":\n            return [\"mediaitem-small\"]\n            break;\n          case \"music-videos\":\n          case \"uploadedVideo\":\n          case \"uploaded-videos\":\n            return \"mediaitem-video\";\n            break;\n        }\n      },\n      visibilityChanged: function(isVisible, entry) {\n        this.isVisible = isVisible\n      },\n      async contextMenu(event) {\n        if (this.nomenu.includes(this.item.type)) {\n          return\n        }\n        if (!event) {\n          event = this.$refs.main\n        } else {\n          console.log(event)\n        }\n        let self = this\n        let useMenu = \"normal\"\n        if (app.selectedMediaItems.length <= 1) {\n          app.selectedMediaItems = []\n          app.select_selectMediaItem(this.item.attributes.playParams.id ?? this.item.id, this.item.attributes.playParams.kind ?? this.item.type, this.index, this.guid, this.item.attributes.playParams.isLibrary ?? false)\n        } else {\n          useMenu = \"multiple\"\n        }\n        let menus = {\n          multiple: {\n            items: [\n              {\n                name: `Play ${app.selectedMediaItems.length} tracks next`,\n                \"icon\": \"./assets/arrow-bend-up.svg\",\n                action: () => {\n                  let itemsToPlay = {}\n                  app.selectedMediaItems.forEach(item => {\n                    if (!itemsToPlay[item.kind]) {\n                      itemsToPlay[item.kind] = []\n                    }\n                    itemsToPlay[item.kind].push(item.id)\n                  })\n                  // loop through itemsToPlay\n                  for (let kind in itemsToPlay) {\n                    let ids = itemsToPlay[kind]\n                    if (ids.length > 0) {\n                      app.mk.playNext({ [kind + \"s\"]: itemsToPlay[kind] })\n                    }\n                  }\n                  console.log(itemsToPlay)\n                  app.selectedMediaItems = []\n                }\n              },\n              {\n                name: `Play ${app.selectedMediaItems.length} tracks later`,\n                \"icon\": \"./assets/arrow-bend-down.svg\",\n                action: () => {\n                  let itemsToPlay = {}\n                  app.selectedMediaItems.forEach(item => {\n                    if (!itemsToPlay[item.kind]) {\n                      itemsToPlay[item.kind] = []\n                    }\n                    itemsToPlay[item.kind].push(item.id)\n                  })\n                  // loop through itemsToPlay\n                  for (let kind in itemsToPlay) {\n                    let ids = itemsToPlay[kind]\n                    if (ids.length > 0) {\n                      app.mk.playLater({ [kind + \"s\"]: itemsToPlay[kind] })\n                    }\n                  }\n                  app.selectedMediaItems = []\n                }\n              },\n            ]\n          },\n          normal: {\n            headerItems: [\n              {\n                \"icon\": \"./assets/feather/heart.svg\",\n                \"id\": \"love\",\n                \"name\": app.getLz(\"action.love\"),\n                \"hidden\": false,\n                \"disabled\": true,\n                \"action\": function() {\n                  app.love(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/heart.svg\",\n                \"id\": \"unlove\",\n                \"active\": true,\n                \"name\": app.getLz(\"action.unlove\"),\n                \"hidden\": true,\n                \"action\": function() {\n                  app.unlove(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/thumbs-down.svg\",\n                \"id\": \"dislike\",\n                \"name\": app.getLz(\"action.dislike\"),\n                \"hidden\": false,\n                \"disabled\": true,\n                \"action\": function() {\n                  app.dislike(self.item)\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/thumbs-down.svg\",\n                \"id\": \"undo_dislike\",\n                \"name\": app.getLz(\"action.undoDislike\"),\n                \"active\": true,\n                \"hidden\": true,\n                \"action\": function() {\n                  app.unlove(self.item)\n                }\n              },\n            ],\n            items: [\n              {\n                \"icon\": \"./assets/feather/list.svg\",\n                \"id\": \"addToPlaylist\",\n                \"name\": app.getLz(\"action.addToPlaylist\") + \" ...\",\n                \"action\": function() {\n                  app.promptAddToPlaylist()\n                }\n              },\n              {\n                \"id\": \"addToLibrary\",\n                \"icon\": \"./assets/feather/plus.svg\",\n                \"name\": app.getLz(\"action.addToLibrary\") + \" ...\",\n                \"hidden\": false,\n                \"disabled\": true,\n                \"action\": function() {\n                  let item_id = self.item.attributes.playParams.id ?? self.item.id;\n                  let data_type = self.item.attributes.playParams.kind ?? self.item.type;\n                  app.addToLibrary(item_id);\n                  self.addedToLibrary = true;\n                }\n              },\n              {\n                \"id\": \"removeFromLibrary\",\n                \"icon\": \"./assets/feather/x-circle.svg\",\n                \"name\": app.getLz(\"action.removeFromLibrary\"),\n                \"hidden\": true,\n                \"action\": async function() {\n                  console.log(\"remove\");\n                  let item_id = self.item.attributes.playParams.id ?? self.item.id;\n                  let data_type = self.item.attributes.playParams.kind ?? self.item.type;\n                  await self.removeFromLibrary(item_id);\n                  self.addedToLibrary = false\n                }\n              },\n              {\n                \"name\": app.getLz(\"action.playNext\"),\n                \"icon\": \"./assets/arrow-bend-up.svg\",\n                \"action\": function() {\n                  app.mk.playNext({ [self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id })\n                  app.mk.queue._reindex()\n                  app.selectedMediaItems = []\n                }\n              },\n              {\n                \"name\": app.getLz(\"action.playLater\"),\n                \"icon\": \"./assets/arrow-bend-down.svg\",\n                \"action\": function() {\n                  app.mk.playLater({ [self.item.attributes.playParams.kind ?? self.item.type]: self.item.attributes.playParams.id ?? self.item.id })\n                  app.mk.queue._reindex()\n                  app.selectedMediaItems = []\n                }\n              },\n              {\n                \"icon\": \"./assets/feather/share.svg\",\n                \"name\": app.getLz(\"action.share\"),\n                \"action\": function() {\n                  self.app.copyToClipboard(self.item.attributes.url)\n                }\n              }\n            ]\n          }\n        }\n        if ((self.item.attributes.playParams.kind ?? self.item.type).includes(\"playlist\")) {\n          // remove the add to playlist option by id \"addToPlaylist\" using the .filter() method\n          menus.normal.items = menus.normal.items.filter(function(item) {\n            return item.id != \"addToPlaylist\"\n          })\n        }\n        app.showMenuPanel(menus[useMenu], event)\n\n        try {\n          await this.isInLibrary().then((_) => {\n            if (self.addedToLibrary) {\n              menus.normal.items.find(x => x.id == 'addToLibrary').hidden = true\n              menus.normal.items.find(x => x.id == 'removeFromLibrary').hidden = false\n            } else {\n              menus.normal.items.find(x => x.id == 'addToLibrary').disabled = false\n            }\n          })\n\n        } catch (e) {\n\n        }\n        try {\n          let rating = await app.getRating(self.item)\n          if (rating == 0) {\n            menus.normal.headerItems.find(x => x.id == 'love').disabled = false\n            menus.normal.headerItems.find(x => x.id == 'dislike').disabled = false\n          } else if (rating == 1) {\n            menus.normal.headerItems.find(x => x.id == 'unlove').hidden = false\n            menus.normal.headerItems.find(x => x.id == 'love').hidden = true\n          } else if (rating == -1) {\n            menus.normal.headerItems.find(x => x.id == 'undo_dislike').hidden = false\n            menus.normal.headerItems.find(x => x.id == 'dislike').hidden = true\n          }\n        } catch (err) {\n\n        }\n\n        if (this.contextExt) {\n          if (this.contextExt.normal) {\n            menus.normal.items = menus.normal.items.concat(this.contextExt.normal)\n          }\n          if (this.contextExt.multiple) {\n            menus.multiple.items = menus.multiple.items.concat(this.contextExt.multiple)\n          }\n        }\n      },\n    },\n    beforeDestroy: function() {\n      // this.item = null;\n      // this.kind = null;\n      // this.size = null;\n    }\n  });\n</script>\n"
  },
  {
    "path": "src/web-remote/views/index.ejs",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <meta charset=\"UTF-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover\">\n    <title>Web Remote</title>\n    <link rel=\"stylesheet\" href=\"style.css?v=2\">\n    <script src=\"vue.js\"></script>\n    <script src=\"sortable.min.js\"></script>\n    <script src=\"vuedraggable.umd.min.js\"></script>\n    <link rel=\"manifest\" href=\"./manifest.json?v=2\">\n</head>\n\n<body oncontextmenu=\"return false;\">\n<div id=\"app\" :style=\"{'--artwork': getAlbumArtUrl()}\">\n    <!-- App view when connected -->\n    <template v-if=\"connectedState == 1\">\n        <!-- Streamer Overlay -->\n        <template></template>\n        <!-- Mini Player -->\n        <template v-if=\"screen == 'miniplayer'\">\n            <div class=\"miniplayer-main\">\n                <div class=\"media-artwork--miniplayer\" :class=\"artworkPlaying()\"\n                     :style=\"{'--artwork': getAlbumArtUrl()}\">\n                </div>\n                <div class=\"miniplayer-draggable\">\n\n                </div>\n                <div class=\"miniplayer-controls\">\n                    <button class=\"md-btn playback-button--small shuffle\" @click=\"shuffle()\"\n                            v-if=\"player.currentMediaItem.shuffleMode == 0\"></button>\n                    <button class=\"md-btn playback-button--small shuffle active\" @click=\"shuffle()\" v-else></button>\n                    <button class=\"md-btn playback-button previous\" @click=\"previous()\"></button>\n                    <button class=\"md-btn playback-button pause\" @click=\"pause()\"\n                            v-if=\"player.currentMediaItem.status\"></button>\n                    <button class=\"md-btn playback-button play\" @click=\"play()\" v-else></button>\n                    <button class=\"md-btn playback-button next\" @click=\"next()\"></button>\n                    <button class=\"md-btn playback-button--small repeat\" @click=\"repeat()\"\n                            v-if=\"player.currentMediaItem.repeatMode == 0\"></button>\n                    <button class=\"md-btn playback-button--small repeat repeatOne\" @click=\"repeat()\"\n                            v-else-if=\"player.currentMediaItem.repeatMode == 1\"></button>\n                    <button class=\"md-btn playback-button--small repeat active\" @click=\"repeat()\"\n                            v-else-if=\"player.currentMediaItem.repeatMode == 2\"></button>\n                </div>\n            </div>\n        </template>\n        <!-- Player -->\n        <transition name=\"wpfade\">\n            <div id=\"popup-confirm\" v-if=\"screen == 'popup-confirm'\">\n                <div class=\"overlay\" @click=\"screen = 'player'\"></div>\n                <div class=\"popup\">\n                    <h3>Quit Cider</h3>\n                    <p>Are you sure you want to quit Cider?</p>\n                    <div class=\"button-holder two-button\">\n                        <a href=\"#\" @click=\"quit()\"> Yes</a>\n                        <a href=\"#\" @click=\"screen = 'player'\">Naah</a>\n                        <div style=\"clear: both\"></div>\n                    </div>\n                </div>\n            </div>\n            <div class=\"md-container md-container_panel player-panel\" v-if=\"screen == 'player'\">\n                <div class=\"player_top\">\n                    <div class=\"quit-button-container\">\n                        <button class=\"md-btn playback-button quit\" @click=\"screen = 'popup-confirm'\"></button>\n                    </div>\n                    <div class=\"md-body player-artwork-container\">\n                        <div class=\"media-artwork\" :class=\"artworkPlaying()\"\n                             :style=\"{'--artwork': getAlbumArtUrl()}\">\n\n                        </div>\n                    </div>\n                </div>\n                <div class=\"player_bottom\" v-if=\"player.lowerPanelState == 'lyrics'\">\n                    <div class=\"md-header\" style=\"width:100%;\">\n                        <div class=\"list-entry\" v-if=\"false\">\n                            <div class=\"row\">\n                                <div class=\"col-auto flex-center\">\n                                    <div class=\"list-entry-image\" :style=\"{'--artwork': getAlbumArtUrl()}\">\n                                    </div>\n                                </div>\n                                <div class=\"col flex-center\">\n                                    <div class=\"list-entry-name\">\n                                        {{ player.currentMediaItem.name }}\n                                    </div>\n                                    <div class=\"list-entry-artist\">\n                                        {{ player.currentMediaItem.artistName }}\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                    <div class=\"md-body lyric-body\" style=\"width:100%;\" @scroll.passive=\"blockLyricsScrolling()\">\n                        <template v-if=\"player.lyrics\">\n                            <template v-for=\"lyric in player.lyrics\" v-if=\"lyric.line != 'lrcInstrumental'\">\n                                <h3 class=\"lyric-line\" @click=\"seekTo(lyric.startTime, false)\"\n                                    :class=\"getLyricClass(lyric.startTime, lyric.endTime)\">\n                                    {{ lyric.line }}\n                                </h3>\n                            </template>\n                            <template v-else>\n                                <h3 class=\"lyric-line\" @click=\"seekTo(lyric.startTime, false)\"\n                                    :class=\"getLyricClass(lyric.startTime, lyric.endTime)\">\n                                    <div class=\"lyricWaiting\">\n                                        <div></div>\n                                        <div></div>\n                                        <div></div>\n                                    </div>\n                                </h3>\n                            </template>\n                        </template>\n                        <template v-else>\n                            No Lyrics Available\n                        </template>\n                    </div>\n                    <div class=\"md-footer\">\n                        <button class=\"md-btn playback-button--small lyrics active\"\n                                @click=\"player.lowerPanelState = 'controls'\"></button>\n                    </div>\n                </div>\n                <div class=\"player_bottom\" v-if=\"player.lowerPanelState == 'controls'\">\n                    <div class=\"md-footer\">\n                        <div class=\"row player-track-info\">\n                            <div class=\"col nopadding text-overflow-elipsis\">\n                                <div class=\"player-song-title text-overflow-elipsis\">\n                                    {{ player.currentMediaItem.name }}\n                                </div>\n                                <div class=\"player-song-artist text-overflow-elipsis\" @click=\"searchArtist()\">\n                                    {{ player.currentMediaItem.artistName }}\n                                </div>\n                            </div>\n                            <div class=\"col-auto nopadding player-more-container\" style=\"\">\n                                <button @click=\"openSongMenu()\" class=\"player-more-button\">...</button>\n                            </div>\n                        </div>\n                    </div>\n                    <div class=\"md-footer\">\n                        <input type=\"range\" min=\"0\"\n                               :value=\"player.currentMediaItem.durationInMillis - player.currentMediaItem.remainingTime\"\n                               :max=\"player.currentMediaItem.durationInMillis\" class=\"web-slider playback-slider\"\n                               @input=\"seekTo($event.target.value)\">\n                        <div class=\"row nopadding player-duration-container\" style=\"width: 90%;margin: 0 auto;\">\n                            <div class=\"col nopadding player-duration-time\" style=\"text-align:left\">\n                                {{ parseTime(player.currentMediaItem.durationInMillis -\n                                player.currentMediaItem.remainingTime) }}\n                            </div>\n                            <div class=\"col nopadding player-duration-time\" style=\"text-align:right\">\n                                -{{ parseTime(player.currentMediaItem.remainingTime) }}\n                            </div>\n                        </div>\n                    </div>\n                    <div class=\"md-footer playback-buttons\">\n                        <button class=\"md-btn playback-button--small shuffle\" @click=\"shuffle()\"\n                                v-if=\"player.currentMediaItem.shuffleMode == 0\"></button>\n                        <button class=\"md-btn playback-button--small shuffle active\" @click=\"shuffle()\" v-else></button>\n                        <button class=\"md-btn playback-button previous\" @click=\"previous()\"></button>\n                        <button class=\"md-btn playback-button pause\" @click=\"pause()\"\n                                v-if=\"player.currentMediaItem.status\"></button>\n                        <button class=\"md-btn playback-button play\" @click=\"play()\" v-else></button>\n                        <button class=\"md-btn playback-button next\" @click=\"next()\"></button>\n                        <button class=\"md-btn playback-button--small repeat\" @click=\"repeat()\"\n                                v-if=\"player.currentMediaItem.repeatMode == 0\"></button>\n                        <button class=\"md-btn playback-button--small repeat repeatOne\" @click=\"repeat()\"\n                                v-else-if=\"player.currentMediaItem.repeatMode == 1\"></button>\n                        <button class=\"md-btn playback-button--small repeat active\" @click=\"repeat()\"\n                                v-else-if=\"player.currentMediaItem.repeatMode == 2\"></button>\n                    </div>\n                    <div class=\"md-footer\">\n                        <div class=\"row volume-slider-container\">\n                            <div class=\"col-auto\">\n                                <div class=\"player-volume-glyph decrease\"></div>\n                            </div>\n                            <div class=\"col\">\n                                <input type=\"range\" class=\"web-slider volume-slider\" :max=\"player.maxVolume\" min=\"0\"\n                                       step=\"0.01\" :pseudo-value=\"getVolumeMax()\"\n                                       @input=\"setVolume($event.target.value)\" :value=\"player.currentMediaItem.volume\">\n                            </div>\n                            <div class=\"col-auto\">\n                                <div class=\"player-volume-glyph increase\"></div>\n\n                            </div>\n                        </div>\n\n                    </div>\n                    <div class=\"md-footer\">\n                        <button class=\"md-btn playback-button--small lyrics\" v-if=\"checkOrientation() == 'portrait'\"\n                                @click=\"showLyrics()\"></button>\n                        <button class=\"md-btn playback-button--small lyrics\"\n                                v-if=\"checkOrientation() == 'landscape'\" @click=\"showLyricsInline()\"></button>\n                        <button class=\"md-btn playback-button--small queue\" @click=\"showQueue()\"></button>\n                        <button class=\"md-btn playback-button--small search\" @click=\"showSearch()\"></button>\n                    </div>\n                </div>\n            </div>\n        </transition>\n        <!-- Search -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel search-panel\" v-if=\"screen == 'search'\">\n                <div class=\"search-header\">\n                    <div class=\"md-header\">\n                        <div class=\"row\">\n                            <div class=\"col-auto\">\n                                <button class=\"back-button\" @click=\"screen = 'player'\"></button>\n                            </div>\n                            <div class=\"col\" style=\"display: flex;align-items: center;\">\n                                <div class=\"col\">\n                                    <input type=\"text\" placeholder=\"Artists, Songs, Lyrics, and More\"\n                                           spellcheck=\"false\" v-model=\"search.query\" @change=\"searchQuery()\"\n                                           v-on:keyup.enter=\"searchQuery()\" class=\"search-input\">\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                    <div class=\"md-header search-type-container\">\n                        <button class=\"search-type-button\" @click=\"search.searchType = 'applemusic';searchQuery()\"\n                                :class=\"searchTypeClass('applemusic')\" style=\"width:100%;\">Apple Music\n                        </button>\n                        <button class=\"search-type-button\" @click=\"search.searchType = 'library';searchQuery()\"\n                                :class=\"searchTypeClass('library')\" style=\"width:100%;\">Library\n                        </button>\n                    </div>\n                    <div class=\"md-header search-tab-container\" v-if=\"search.state == 2\">\n                        <button class=\"search-tab\" @click=\"search.tab = 'all'\" :class=\"searchTabClass('all')\">All\n                            Results\n                        </button>\n                        <button class=\"search-tab\" @click=\"search.tab = 'songs'\"\n                                :class=\"searchTabClass('songs')\">Songs\n                        </button>\n                        <button class=\"search-tab\" @click=\"search.tab = 'albums'\"\n                                :class=\"searchTabClass('albums')\">Albums\n                        </button>\n                        <button class=\"search-tab\" @click=\"search.tab = 'artists'\"\n                                :class=\"searchTabClass('artists')\">Artists\n                        </button>\n                        <button class=\"search-tab\" @click=\"search.tab = 'playlists'\"\n                                :class=\"searchTabClass('playlists')\">Playlists\n                        </button>\n                    </div>\n                </div>\n                <div class=\"search-body-container\">\n                    <transition name=\"wpfade\">\n                        <div class=\"md-body search-body\" v-if=\"search.state == 0\">\n                            <div\n                                    style=\"font-size: 17px;display:flex;flex-direction: column;justify-content: center;align-items: center;\">\n                                <img src=\"./assets/search.svg\" style=\"width: 40px;margin: 32px;opacity: 0.85\">\n                                Search by song, album, artist, or lyrics.\n                            </div>\n                        </div>\n                    </transition>\n                    <transition name=\"wpfade\">\n                        <div class=\"md-body search-body\" v-if=\"search.state == 1\">\n                            <!-- loading state -->\n                        </div>\n                    </transition>\n                    <transition name=\"wpfade\">\n                        <div class=\"md-body search-body\" ref=\"searchBody\" @scroll=\"searchScroll\"\n                             style=\"overflow-y:auto;\" v-if=\"search.state == 2\">\n                            <template v-if=\"canShowSearchTab('songs')\">\n                                <div class=\"list-entry-header\">Songs</div>\n                                <template v-if=\"search.results.songs != null\">\n                                    <div class=\"list-entry\" v-for=\"song in search.results.songs.data\"\n                                         @click=\"trackSelect(song)\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(song.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ song.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ song.attributes.artistName }}\n                                                    <!-- <span class=\"lossless-badge\" v-if=\"song.audioTraits.includes('lossless')\">Lossless</span> -->\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                                <template v-if=\"search.results['library-songs'] != null\">\n                                    <div class=\"list-entry\" v-for=\"song in search.results['library-songs'].data\"\n                                         @click=\"trackSelect(song)\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(song.attributes.artwork?.url ?? './assets/MissingArtwork.svg' )}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ song.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ song.attributes.artistName }}\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                            </template>\n                            <template v-if=\"canShowSearchTab('albums')\">\n                                <div class=\"list-entry-header\">Albums</div>\n                                <template v-if=\"search.results.albums != null\">\n                                    <div class=\"list-entry\" v-for=\"album in search.results.albums.data\"\n                                         @click=\"showAlbum(album.id)\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(album.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ album.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ album.attributes.artistName }}\n                                                    <!-- <span class=\"lossless-badge\" v-if=\"album.audioTraits.includes('lossless')\">Lossless</span> -->\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                                <template v-if=\"search.results['library-albums'] != null\">\n                                    <div class=\"list-entry\" v-for=\"album in search.results['library-albums'].data\"\n                                         @click=\"showAlbum(album.id, true)\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(album.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ album.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ album.attributes.artistName }}\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                            </template>\n                            <template v-if=\"canShowSearchTab('artists')\">\n                                <div class=\"list-entry-header\">Artists</div>\n                                <template v-if=\"search.results.artists != null\">\n                                    <div class=\"list-entry\" @click=\"showArtist(artist.id)\"\n                                         v-for=\"artist in search.results.artists.data\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image artist\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(artist?.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ artist.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                                <template v-if=\"search.results['library-artists'] != null\">\n                                    <div class=\"list-entry\"\n                                         v-for=\"artist in search.results['library-artists'].data\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image artist\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(artist.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ artist.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                            </template>\n                            <template v-if=\"canShowSearchTab('playlists')\">\n                                <div class=\"list-entry-header\">Playlists</div>\n                                <template v-if=\"search.results.playlists != null\">\n                                    <div class=\"list-entry\" v-for=\"playlist in search.results.playlists.data\"\n                                         @click=\"showPlaylist(playlist.attributes.playParams.id)\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(playlist.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ playlist.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ playlist.attributes.artistName }}\n                                                    <!-- <span class=\"lossless-badge\" v-if=\"album.audioTraits.includes('lossless')\">Lossless</span> -->\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                                <template v-if=\"search.results['library-playlists'] != null\">\n                                    <div class=\"list-entry\" v-for=\"playlist in search.results['library-playlists'].data\"\n                                         @click=\"showPlaylist(playlist.attributes.playParams.id, true)\"\n                                    >\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\"\n                                                     :style=\"{'--artwork': getAlbumArtUrlList(playlist.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ playlist.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ playlist.attributes.artistName }}\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </div>\n                                </template>\n                            </template>\n\n                        </div>\n                    </transition>\n                </div>\n                <footer-player></footer-player>\n            </div>\n        </transition>\n        <!-- Track Select Actions -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel context-menu\" style=\"overflow-y:auto;\"\n                 v-if=\"search.trackSelect\">\n                <div class=\"md-body context-menu-body\">\n                    <button class=\"context-menu-item context-menu-item--left\"\n                            @click=\"playMediaItemById(search.selected.attributes.playParams?.id ?? search.selected.id );clearSelectedTrack()\">\n                        <div class=\"row\">\n                            <div class=\"col-auto flex-center\" v-if=\"search.selected.attributes.artwork\"\n                                 style=\"display:flex;align-items: center;\">\n                                <div class=\"list-entry-image\"\n                                     :style=\"{'--artwork': getAlbumArtUrlList(search.selected.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                </div>\n                            </div>\n                            <div class=\"col flex-center\" style=\"display:flex;align-items: center;\">\n                                <div style=\"width:100%;font-size: 18px;\">\n                                    {{ search.selected.attributes.name }}\n                                </div>\n                                <div style=\"width:100%;font-size: 16px;\">\n                                    {{ search.selected.attributes.artistName }}\n                                </div>\n                                <div style=\"width:100%;font-size: 14px;\">\n                                    {{ parseTime(search.selected.attributes.durationInMillis) }}\n                                </div>\n                            </div>\n                        </div>\n                    </button>\n                </div>\n                <div class=\"md-body context-menu-body\" style=\"height: auto;\">\n                    <button class=\"context-menu-item context-menu-item--left\"\n                            @click=\"playMediaItemById(search.selected.attributes.playParams?.id ?? search.selected.id );clearSelectedTrack()\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Play\n                            </div>\n                            <div class=\"col-auto\">\n                                ▶️\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\"\n                            @click=\"playNext('song',search.selected.attributes.playParams?.id ?? search.selected.id );clearSelectedTrack()\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Play Next\n                            </div>\n                            <div class=\"col-auto\">\n                                ⏭️\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\"\n                            @click=\"playLater('song', search.selected.attributes.playParams?.id ?? search.selected.id );clearSelectedTrack()\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Play Later\n                            </div>\n                            <div class=\"col-auto\">\n                                ⌛\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\" v-if=\"false\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Open in {{ musicAppVariant() }}\n                            </div>\n                            <div class=\"col-auto\">\n                                🎵\n                            </div>\n                        </div>\n                    </button>\n                </div>\n                <div class=\"md-footer\">\n                    <button class=\"context-menu-item\" @click=\"clearSelectedTrack()\">Cancel</button>\n                </div>\n            </div>\n        </transition>\n        <!-- Song Actions -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel context-menu\" v-if=\"player.songActions\">\n                <div class=\"md-header\">\n\n                </div>\n                <div class=\"md-body context-menu-body\">\n                    <button class=\"context-menu-item context-menu-item--left\" v-if=\"!player.status.inLibrary\"\n                            @click=\"toLibrary(true)\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Add To Library\n                            </div>\n                            <div class=\"col-auto\">\n                                ➕\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\" v-if=\"player.status.inLibrary\"\n                            @click=\"toLibrary(false)\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Remove From Library\n                            </div>\n                            <div class=\"col-auto\">\n                                ➖\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\" :disabled=\"player.status.rating === 1\"\n                            @click=\"rate(1)\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Love\n                            </div>\n                            <div class=\"col-auto\">\n                                ❤️\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\" :disabled=\"player.status.rating === 0\"\n                            @click=\"rate(0)\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Remove Rating\n                            </div>\n                            <div class=\"col-auto\">\n                                ❌\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\"\n                            :disabled=\"player.status.rating === -1\" @click=\"rate(-1)\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Dislike\n                            </div>\n                            <div class=\"col-auto\">\n                                👎\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\" v-if=\"false\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Share\n                            </div>\n                            <div class=\"col-auto\">\n                                🌐\n                            </div>\n                        </div>\n                    </button>\n                    <button class=\"context-menu-item context-menu-item--left\" v-if=\"false\">\n                        <div class=\"row\">\n                            <div class=\"col\">\n                                Open in {{ musicAppVariant() }}\n                            </div>\n                            <div class=\"col-auto\">\n                                🎵\n                            </div>\n                        </div>\n                    </button>\n                </div>\n                <div class=\"md-footer\">\n                    <button class=\"context-menu-item\" @click=\"player.songActions = false\">Cancel</button>\n                </div>\n            </div>\n        </transition>\n        <!-- Artist Page -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel\" v-if=\"screen == 'artist-page'\"\n                 v-if=\"artistPage.data.attributes['name']\">\n                <div class=\"md-header\">\n                    <div class=\"row\">\n                        <div class=\"col-auto\">\n                            <button class=\"back-button\" @click=\"showSearch(true)\"></button>\n                        </div>\n                        <div class=\"col flex-center\">\n                            {{ artistPage.data.attributes[\"name\"] }}\n                        </div>\n                    </div>\n                </div>\n                <div class=\"album-body-container\" :style=\"getMediaPalette(artistPage.data.attributes)\">\n                    <div class=\"artist-header\" v-if=\"artistPage.data.attributes['artwork']\"\n                         :style=\"getMediaPalette(artistPage.data.attributes)\">\n                        <div class=\"artist-header-portrait\"\n                             :style=\"{'--artwork': getAlbumArtUrlList(artistPage.data.attributes['artwork']['url'] ?? './assets/MissingArtwork.svg', 600)}\">\n                        </div>\n                        <h2>{{ artistPage.data.attributes[\"name\"] }}</h2>\n                    </div>\n                    <div class=\"md-body artist-body\">\n                        <h2>Songs</h2>\n                        <div class=\"song-scroller-horizontal\">\n                            <div class=\"list-entry artist-song\" v-for=\"song in artistPage.data.relationships['songs'].data\"\n                                         @click=\"trackSelect(song)\">\n                                        <div class=\"row\">\n                                            <div class=\"col-auto flex-center\">\n                                                <div class=\"list-entry-image\" \n                                                     :style=\"{'--artwork': getAlbumArtUrlList(song.attributes?.artwork?.url ?? './assets/MissingArtwork.svg', 45)}\">\n                                                </div>\n                                            </div>\n                                            <div class=\"col flex-center\">\n                                                <div class=\"list-entry-name\">\n                                                    {{ song.attributes.name }}\n                                                </div>\n                                                <div class=\"list-entry-artist\">\n                                                    {{ song.attributes.artistName }}\n                                                </div>\n                                            </div>\n                                        </div>\n                            </div>           \n                            <!-- <button v-for=\"song in artistPage.data.relationships['songs'].data\"\n                                    class=\"song-placeholder\" @click=\"trackSelect(song)\">\n                                {{ song.attributes.name }}\n                            </button> -->\n                        </div>\n                        <h2>Albums</h2>\n                        <div class=\"mediaitem-scroller-horizontal\">\n                            <div v-for=\"album in artistPage.data.relationships['albums'].data\"\n                                 @click=\"showAlbum(album.attributes.playParams.id)\">\n                                <template v-if=\"album.attributes.artwork\">\n                                    <mediaitem-artwork :url=\"album.attributes.artwork.url\"\n                                                       :size=\"200\"></mediaitem-artwork>\n                                </template>\n                                <div class=\"text-overflow-elipsis\" style=\"width: 213px\">\n                                    {{ album.attributes[\"name\"] }}\n                                </div>\n                                <div class=\"text-overflow-elipsis\" style=\"width: 213px\">\n                                    {{ album.attributes[\"artistName\"] }}\n                                </div>\n                            </div>\n                        </div>\n                        <h2>Playlists</h2>\n                        <div class=\"mediaitem-scroller-horizontal\">\n                            <div v-for=\"playlist in artistPage.data.relationships['playlists'].data\"\n                                 @click=\"showPlaylist(playlist.attributes.playParams.id)\">\n                                <template v-if=\"playlist.attributes.artwork\">\n                                    <mediaitem-artwork :url=\"playlist.attributes.artwork.url\"\n                                                       :size=\"200\"></mediaitem-artwork>\n                                </template>\n                                <div class=\"text-overflow-elipsis\" style=\"width: 213px\">\n                                    {{ playlist.attributes[\"name\"] }}\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <footer-player></footer-player>\n            </div>\n        </transition>\n        <!-- Queue -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel\" v-if=\"screen == 'queue'\">\n                <div class=\"md-header\">\n                    <div class=\"list-entry\" @click=\"screen = 'player'\">\n                        <div class=\"row\">\n                            <div class=\"col-auto flex-center\">\n                                <div class=\"list-entry-image\" :style=\"{'--artwork': getAlbumArtUrl()}\">\n                                </div>\n                            </div>\n                            <div class=\"col flex-center\">\n                                <div class=\"list-entry-name\">\n                                    {{ player.currentMediaItem.name }}\n                                </div>\n                                <div class=\"list-entry-artist\">\n                                    {{ player.currentMediaItem.artistName }}\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <div class=\"md-header\" style=\"text-align: right;padding: 5px 16px;\">\n                    <button class=\"md-btn playback-button--small autoplay\"\n                            v-if=\"!player.currentMediaItem.autoplayEnabled\" @click=\"setAutoplay(true)\"></button>\n                    <button class=\"md-btn playback-button--small autoplay activeColor\" v-else\n                            @click=\"setAutoplay(false)\"></button>\n                </div>\n                <div class=\"md-body queue-body\" v-if=\"!player.queue['_queueItems']\">\n                    Empty\n                </div>\n                <div class=\"md-body queue-body\" style=\"overflow-y:auto;\" id=\"list-queue\" v-else>\n                    <draggable v-model=\"queue.temp\" handle=\".handle\" filter=\".passed\" @change=\"queueMove\">\n                        <template v-for=\"(song, position) in queue.temp\"\n                                  v-if=\"position > player.queue['_position']\">\n                            <div class=\"list-entry\" :class=\"getQueuePositionClass(position)\">\n                                <div class=\"row\" style=\"width:100%;\">\n                                    <div class=\"col-auto\">\n                                        <div class=\"handle\">\n                                        </div>\n                                    </div>\n                                    <div class=\"col-auto flex-center\">\n                                        <div class=\"list-entry-image\" \n                                             :style=\"{'--artwork': getAlbumArtUrlList(song.item.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                        </div>\n                                    </div>\n                                    <div class=\"col flex-center\">\n                                        <div class=\"list-entry-name\">\n                                            {{ song.item.attributes.name }}\n                                        </div>\n                                        <div class=\"list-entry-artist\">\n                                            {{ song.item.attributes.artistName }}\n                                        </div>\n                                    </div>\n                                    <div class=\"col-auto flex-center\" style=\"text-align:right;\">\n                                        <div v-if=\"position == player.queue['_position']\">▶️</div>\n                                    </div>\n                                </div>\n                            </div>\n                        </template>\n                    </draggable>\n                </div>\n                <div class=\"md-footer\">\n                    <button class=\"md-btn playback-button--small lyrics\" v-if=\"checkOrientation() == 'portrait'\"\n                            @click=\"showLyrics()\"></button>\n                    <button class=\"md-btn playback-button--small lyrics\" v-if=\"checkOrientation() == 'landscape'\"\n                            @click=\"screen = 'player';showLyricsInline()\"></button>\n                    <button class=\"md-btn playback-button--small queue active\" @click=\"screen = 'player'\"></button>\n                    <button class=\"md-btn playback-button--small search\" @click=\"showSearch()\"></button>\n                </div>\n            </div>\n        </transition>\n        <!-- Lyrics -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel\" v-if=\"screen == 'lyrics'\">\n                <div class=\"md-header\">\n                    <div class=\"list-entry\" @click=\"screen = 'player'\">\n                        <div class=\"row\">\n                            <div class=\"col-auto flex-center\">\n                                <div class=\"list-entry-image\" :style=\"{'--artwork': getAlbumArtUrl()}\">\n                                </div>\n                            </div>\n                            <div class=\"col flex-center\">\n                                <div class=\"list-entry-name\">\n                                    {{ player.currentMediaItem.name }}\n                                </div>\n                                <div class=\"list-entry-artist\">\n                                    {{ player.currentMediaItem.artistName }}\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <div class=\"md-body lyric-body\" @scroll.passive=\"blockLyricsScrolling()\">\n                    <template v-if=\"player.lyrics\">\n                        <template v-for=\"lyric in player.lyrics\" v-if=\"lyric.line != 'lrcInstrumental'\">\n                            <h3 class=\"lyric-line\" @click=\"seekTo(lyric.startTime, false)\"\n                                :class=\"getLyricClass(lyric.startTime, lyric.endTime)\">\n                                {{ lyric.line }}\n                            </h3>\n                        </template>\n                        <template v-else>\n                            <h3 class=\"lyric-line\" @click=\"seekTo(lyric.startTime, false)\"\n                                :class=\"getLyricClass(lyric.startTime, lyric.endTime)\">\n                                <div class=\"lyricWaiting\">\n                                    <div></div>\n                                    <div></div>\n                                    <div></div>\n                                </div>\n                            </h3>\n                        </template>\n                    </template>\n                    <template v-else>\n                        No Lyrics Available\n                    </template>\n                </div>\n                <div class=\"md-footer\">\n                    <button class=\"md-btn playback-button--small lyrics active\" @click=\"screen = 'player'\"></button>\n                    <button class=\"md-btn playback-button--small queue\" @click=\"showQueue()\"></button>\n                    <button class=\"md-btn playback-button--small search\" @click=\"showSearch()\"></button>\n                </div>\n            </div>\n        </transition>\n        <!-- Album Page -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel md-container_album\"\n                 v-if=\"screen == 'album-page' && albumPage.data.attributes['name']\">\n                <div class=\"md-header\">\n                    <div class=\"row\">\n                        <div class=\"col-auto\">\n                            <button class=\"back-button\" @click=\"showSearch(true)\"></button>\n                        </div>\n                    </div>\n                </div>\n                <div class=\"album-body-container\">\n                    <div class=\"md-header\">\n                        <div class=\"albumpage-artwork\"\n                             :style=\"{'--artwork': getAlbumArtUrlList(albumPage.data.attributes['artwork'] ? albumPage.data.attributes['artwork']['url'] : './assets/MissingArtwork.svg', 300)}\">\n                        </div>\n                        <div class=\"albumpage-album-name\">\n                            {{ albumPage.data.attributes[\"name\"] }}\n                        </div>\n                        <template v-if=\"albumPage.data.attributes['artists']\">\n                            <div class=\"albumpage-artist-name\"\n                                 @click=\"showArtist(albumPage.data.attributes['artists'][0]['id'])\">\n                                {{ albumPage.data.attributes[\"artistName\"] }}\n                            </div>\n                        </template>\n                        <template>\n                            <div class=\"albumpage-misc-info\">\n                                {{ albumPage.data.attributes.genreNames ? albumPage.data.attributes.genreNames[0] :\n                                '' }} ∙ {{\n                                albumPage.data.attributes.releaseDate ? new\n                                Date(albumPage.data.attributes.releaseDate).getFullYear() : '' }}\n                            </div>\n                        </template>\n                        <div class=\"row\" style=\"margin-top: 20px;\">\n                            <div class=\"col\">\n                                <button class=\"wr-btn\"\n                                        @click=\"playCustom(albumPage.data.attributes.playParams.id, albumPage.data.attributes.playParams.kind, false)\"\n                                        style=\"width:100%;\">Play\n                                </button>\n                            </div>\n                            <div class=\"col\">\n                                <button class=\"wr-btn\" style=\"width:100%;\"\n                                        @click=\"playCustom(albumPage.data.attributes.playParams.id, albumPage.data.attributes.playParams.kind, true)\">\n                                    Shuffle\n                                </button>\n                            </div>\n                        </div>\n                        <div class=\"albumpage-album-notes\" v-if=\"albumPage.data.attributes['editorialNotes']\">\n                            <div class=\"notes-preview\"\n                                 v-html=\"albumPage.data.attributes['editorialNotes']['standard']\">\n                            </div>\n                            <button @click=\"albumPage.editorsNotes = true\" class=\"notes-more\">More</button>\n                        </div>\n                    </div>\n                    <div class=\"md-body artist-body\">\n                        <div class=\"list-entry-header\">Tracks</div>\n                        <div class=\"list-entry\" v-for=\"song in albumPage.data.relationships['tracks'].data\"\n                             @click=\"trackSelect(song)\">\n                            <div class=\"row\">\n                                <div class=\"col-auto flex-center\">\n                                    <div class=\"list-entry-image\"\n                                         :style=\"{'--artwork': getAlbumArtUrlList(song.attributes?.artwork?.url ?? './assets/MissingArtwork.svg')}\">\n                                    </div>\n                                </div>\n                                <div class=\"col flex-center\">\n                                    <div class=\"list-entry-name\">\n                                        {{ song.attributes.name }}\n                                    </div>\n                                    <div class=\"list-entry-artist\">\n                                        {{ song.attributes.artistName }}\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                        <div class=\"md-footer\">\n                            <div>{{ albumPage.data.relationships['tracks'].data.length }} Tracks</div>\n                            <div>\n                                {{ albumPage.data.attributes['copyright'] }}\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                <footer-player></footer-player>\n            </div>\n        </transition>\n        <!-- Album Page - Editorial Notes -->\n        <transition name=\"wpfade\">\n            <div class=\"md-container md-container_panel context-menu\" v-if=\"albumPage.editorsNotes\"\n                 style=\"padding-top: 42px;\">\n                <div class=\"md-header\" :style=\"getMediaPalette(albumPage.data)\"\n                     style=\"font-size: 18px;background:var(--bgColor);color:var(--textColor1);text-align: center;border-radius: 10px 10px 0 0;border-top: 1px solid #ffffff1f;\">\n                    {{ albumPage.data.attributes[\"name\"] }}\n                </div>\n                <div class=\"md-body album-page-fullnotes-body\" :style=\"getMediaPalette(albumPage.data.attributes)\"\n                     style=\"background:var(--bgColor);color:var(--textColor1);\"\n                     v-html=\"albumPage.data.attributes['editorialNotes']['standard']\">\n                </div>\n                <div class=\"md-footer\" :style=\"getMediaPalette(albumPage.data.attributes)\"\n                     style=\"background:var(--bgColor);color:var(--textColor1);\">\n                    <button class=\"context-menu-item\" @click=\"albumPage.editorsNotes = false\">Close</button>\n                </div>\n            </div>\n        </transition>\n    </template>\n    <!-- Loading -->\n    <transition name=\"wpfade\">\n        <div class=\"md-container md-container_panel connection-error-panel\" v-if=\"connectedState != 1\">\n            <div class=\"md-header\">\n\n            </div>\n            <div class=\"md-body\" style=\"display:flex;justify-content: center;align-items: center;\">\n                <div v-if=\"connectedState == 0\">\n                    Loading...\n                </div>\n                <div v-else>\n                    <h3 style=\"text-align:center;\">Connection Interrupted</h3>\n                    <!--<button class=\"md-btn md-btn-primary\" style=\"font-weight:500;width: 120px;border-radius: 50px;display:block;margin: 0 auto;\" @click=\"connect()\">Retry-->\n                    <button class=\"md-btn md-btn-primary\"\n                            style=\"font-weight:500;width: 120px;border-radius: 50px;display:block;margin: 0 auto;\"\n                            onclick=\"document.location = document.location\">Retry\n                    </button>\n                </div>\n            </div>\n            <div class=\"md-footer\">\n\n            </div>\n        </div>\n    </transition>\n    <!-- Template -->\n    <transition name=\"wpfade\">\n        <div class=\"md-container md-container_panel\" v-if=\"false\">\n            <div class=\"md-header\">\n\n            </div>\n            <div class=\"md-body\">\n\n            </div>\n            <div class=\"md-footer\">\n\n            </div>\n        </div>\n    </transition>\n</div>\n\n<script type=\"text/x-template\" id=\"footer-player\">\n    <div class=\"footer-player\" v-show=\"$parent.player.currentMediaItem['name']\">\n        <div class=\"row\" style=\"width:100%;margin:0px;\">\n            <div class=\"col-auto flex-center\" style=\"padding:0 6px;\" @click=\"$parent.screen = 'player'\">\n                <div class=\"list-entry-image\" :style=\"{'--artwork': $parent.getAlbumArtUrl()}\">\n                </div>\n            </div>\n            <div class=\"col flex-center text-overflow-elipsis\" @click=\"$parent.screen = 'player'\">\n                <div class=\"list-entry-name text-overflow-elipsis\">\n                    {{ $parent.player.currentMediaItem.name }}\n                </div>\n                <div class=\"list-entry-artist text-overflow-elipsis\">\n                    {{ $parent.player.currentMediaItem.artistName }}\n                </div>\n            </div>\n            <div class=\"col-auto\">\n                <button class=\"md-btn playback-button pause\" @click=\"$parent.pause()\"\n                        v-if=\"$parent.player.currentMediaItem.status\"></button>\n                <button class=\"md-btn playback-button play\" @click=\"$parent.play()\" v-else></button>\n            </div>\n        </div>\n    </div>\n</script>\n\n<script src=\"./index.js?v=1\"></script>\n\n</body>\n<!-- Horizontal MediaItem Scroller (MV) -->\n\n<%- include('components/mediaitem-artwork')\n%>\n\n</html>\n"
  },
  {
    "path": "src/web-remote/vue.js",
    "content": "/*!\n * Vue.js v2.6.14\n * (c) 2014-2021 Evan You\n * Released under the MIT License.\n */\n!(function (e, t) {\n  \"object\" == typeof exports && \"undefined\" != typeof module ? (module.exports = t()) : \"function\" == typeof define && define.amd ? define(t) : ((e = e || self).Vue = t());\n})(this, function () {\n  \"use strict\";\n  var e = Object.freeze({});\n  function t(e) {\n    return null == e;\n  }\n  function n(e) {\n    return null != e;\n  }\n  function r(e) {\n    return !0 === e;\n  }\n  function i(e) {\n    return \"string\" == typeof e || \"number\" == typeof e || \"symbol\" == typeof e || \"boolean\" == typeof e;\n  }\n  function o(e) {\n    return null !== e && \"object\" == typeof e;\n  }\n  var a = Object.prototype.toString;\n  function s(e) {\n    return \"[object Object]\" === a.call(e);\n  }\n  function c(e) {\n    var t = parseFloat(String(e));\n    return t >= 0 && Math.floor(t) === t && isFinite(e);\n  }\n  function u(e) {\n    return n(e) && \"function\" == typeof e.then && \"function\" == typeof e.catch;\n  }\n  function l(e) {\n    return null == e ? \"\" : Array.isArray(e) || (s(e) && e.toString === a) ? JSON.stringify(e, null, 2) : String(e);\n  }\n  function f(e) {\n    var t = parseFloat(e);\n    return isNaN(t) ? e : t;\n  }\n  function p(e, t) {\n    for (var n = Object.create(null), r = e.split(\",\"), i = 0; i < r.length; i++) n[r[i]] = !0;\n    return t\n      ? function (e) {\n          return n[e.toLowerCase()];\n        }\n      : function (e) {\n          return n[e];\n        };\n  }\n  var d = p(\"slot,component\", !0),\n    v = p(\"key,ref,slot,slot-scope,is\");\n  function h(e, t) {\n    if (e.length) {\n      var n = e.indexOf(t);\n      if (n > -1) return e.splice(n, 1);\n    }\n  }\n  var m = Object.prototype.hasOwnProperty;\n  function y(e, t) {\n    return m.call(e, t);\n  }\n  function g(e) {\n    var t = Object.create(null);\n    return function (n) {\n      return t[n] || (t[n] = e(n));\n    };\n  }\n  var _ = /-(\\w)/g,\n    b = g(function (e) {\n      return e.replace(_, function (e, t) {\n        return t ? t.toUpperCase() : \"\";\n      });\n    }),\n    $ = g(function (e) {\n      return e.charAt(0).toUpperCase() + e.slice(1);\n    }),\n    w = /\\B([A-Z])/g,\n    C = g(function (e) {\n      return e.replace(w, \"-$1\").toLowerCase();\n    });\n  var x = Function.prototype.bind\n    ? function (e, t) {\n        return e.bind(t);\n      }\n    : function (e, t) {\n        function n(n) {\n          var r = arguments.length;\n          return r ? (r > 1 ? e.apply(t, arguments) : e.call(t, n)) : e.call(t);\n        }\n        return (n._length = e.length), n;\n      };\n  function k(e, t) {\n    t = t || 0;\n    for (var n = e.length - t, r = new Array(n); n--; ) r[n] = e[n + t];\n    return r;\n  }\n  function A(e, t) {\n    for (var n in t) e[n] = t[n];\n    return e;\n  }\n  function O(e) {\n    for (var t = {}, n = 0; n < e.length; n++) e[n] && A(t, e[n]);\n    return t;\n  }\n  function S(e, t, n) {}\n  var T = function (e, t, n) {\n      return !1;\n    },\n    N = function (e) {\n      return e;\n    };\n  function E(e, t) {\n    if (e === t) return !0;\n    var n = o(e),\n      r = o(t);\n    if (!n || !r) return !n && !r && String(e) === String(t);\n    try {\n      var i = Array.isArray(e),\n        a = Array.isArray(t);\n      if (i && a)\n        return (\n          e.length === t.length &&\n          e.every(function (e, n) {\n            return E(e, t[n]);\n          })\n        );\n      if (e instanceof Date && t instanceof Date) return e.getTime() === t.getTime();\n      if (i || a) return !1;\n      var s = Object.keys(e),\n        c = Object.keys(t);\n      return (\n        s.length === c.length &&\n        s.every(function (n) {\n          return E(e[n], t[n]);\n        })\n      );\n    } catch (e) {\n      return !1;\n    }\n  }\n  function j(e, t) {\n    for (var n = 0; n < e.length; n++) if (E(e[n], t)) return n;\n    return -1;\n  }\n  function D(e) {\n    var t = !1;\n    return function () {\n      t || ((t = !0), e.apply(this, arguments));\n    };\n  }\n  var L = \"data-server-rendered\",\n    I = [\"component\", \"directive\", \"filter\"],\n    M = [\"beforeCreate\", \"created\", \"beforeMount\", \"mounted\", \"beforeUpdate\", \"updated\", \"beforeDestroy\", \"destroyed\", \"activated\", \"deactivated\", \"errorCaptured\", \"serverPrefetch\"],\n    F = {\n      optionMergeStrategies: Object.create(null),\n      silent: !1,\n      productionTip: !1,\n      devtools: !1,\n      performance: !1,\n      errorHandler: null,\n      warnHandler: null,\n      ignoredElements: [],\n      keyCodes: Object.create(null),\n      isReservedTag: T,\n      isReservedAttr: T,\n      isUnknownElement: T,\n      getTagNamespace: S,\n      parsePlatformTagName: N,\n      mustUseProp: T,\n      async: !0,\n      _lifecycleHooks: M,\n    },\n    P = /a-zA-Z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD/;\n  function R(e, t, n, r) {\n    Object.defineProperty(e, t, {\n      value: n,\n      enumerable: !!r,\n      writable: !0,\n      configurable: !0,\n    });\n  }\n  var H = new RegExp(\"[^\" + P.source + \".$_\\\\d]\");\n  var B,\n    U = \"__proto__\" in {},\n    V = \"undefined\" != typeof window,\n    z = \"undefined\" != typeof WXEnvironment && !!WXEnvironment.platform,\n    K = z && WXEnvironment.platform.toLowerCase(),\n    J = V && window.navigator.userAgent.toLowerCase(),\n    q = J && /msie|trident/.test(J),\n    W = J && J.indexOf(\"msie 9.0\") > 0,\n    Z = J && J.indexOf(\"edge/\") > 0,\n    G = (J && J.indexOf(\"android\"), (J && /iphone|ipad|ipod|ios/.test(J)) || \"ios\" === K),\n    X = (J && /chrome\\/\\d+/.test(J), J && /phantomjs/.test(J), J && J.match(/firefox\\/(\\d+)/)),\n    Y = {}.watch,\n    Q = !1;\n  if (V)\n    try {\n      var ee = {};\n      Object.defineProperty(ee, \"passive\", {\n        get: function () {\n          Q = !0;\n        },\n      }),\n        window.addEventListener(\"test-passive\", null, ee);\n    } catch (e) {}\n  var te = function () {\n      return void 0 === B && (B = !V && !z && \"undefined\" != typeof global && global.process && \"server\" === global.process.env.VUE_ENV), B;\n    },\n    ne = V && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;\n  function re(e) {\n    return \"function\" == typeof e && /native code/.test(e.toString());\n  }\n  var ie,\n    oe = \"undefined\" != typeof Symbol && re(Symbol) && \"undefined\" != typeof Reflect && re(Reflect.ownKeys);\n  ie =\n    \"undefined\" != typeof Set && re(Set)\n      ? Set\n      : (function () {\n          function e() {\n            this.set = Object.create(null);\n          }\n          return (\n            (e.prototype.has = function (e) {\n              return !0 === this.set[e];\n            }),\n            (e.prototype.add = function (e) {\n              this.set[e] = !0;\n            }),\n            (e.prototype.clear = function () {\n              this.set = Object.create(null);\n            }),\n            e\n          );\n        })();\n  var ae = S,\n    se = 0,\n    ce = function () {\n      (this.id = se++), (this.subs = []);\n    };\n  (ce.prototype.addSub = function (e) {\n    this.subs.push(e);\n  }),\n    (ce.prototype.removeSub = function (e) {\n      h(this.subs, e);\n    }),\n    (ce.prototype.depend = function () {\n      ce.target && ce.target.addDep(this);\n    }),\n    (ce.prototype.notify = function () {\n      for (var e = this.subs.slice(), t = 0, n = e.length; t < n; t++) e[t].update();\n    }),\n    (ce.target = null);\n  var ue = [];\n  function le(e) {\n    ue.push(e), (ce.target = e);\n  }\n  function fe() {\n    ue.pop(), (ce.target = ue[ue.length - 1]);\n  }\n  var pe = function (e, t, n, r, i, o, a, s) {\n      (this.tag = e), (this.data = t), (this.children = n), (this.text = r), (this.elm = i), (this.ns = void 0), (this.context = o), (this.fnContext = void 0), (this.fnOptions = void 0), (this.fnScopeId = void 0), (this.key = t && t.key), (this.componentOptions = a), (this.componentInstance = void 0), (this.parent = void 0), (this.raw = !1), (this.isStatic = !1), (this.isRootInsert = !0), (this.isComment = !1), (this.isCloned = !1), (this.isOnce = !1), (this.asyncFactory = s), (this.asyncMeta = void 0), (this.isAsyncPlaceholder = !1);\n    },\n    de = { child: { configurable: !0 } };\n  (de.child.get = function () {\n    return this.componentInstance;\n  }),\n    Object.defineProperties(pe.prototype, de);\n  var ve = function (e) {\n    void 0 === e && (e = \"\");\n    var t = new pe();\n    return (t.text = e), (t.isComment = !0), t;\n  };\n  function he(e) {\n    return new pe(void 0, void 0, void 0, String(e));\n  }\n  function me(e) {\n    var t = new pe(e.tag, e.data, e.children && e.children.slice(), e.text, e.elm, e.context, e.componentOptions, e.asyncFactory);\n    return (t.ns = e.ns), (t.isStatic = e.isStatic), (t.key = e.key), (t.isComment = e.isComment), (t.fnContext = e.fnContext), (t.fnOptions = e.fnOptions), (t.fnScopeId = e.fnScopeId), (t.asyncMeta = e.asyncMeta), (t.isCloned = !0), t;\n  }\n  var ye = Array.prototype,\n    ge = Object.create(ye);\n  [\"push\", \"pop\", \"shift\", \"unshift\", \"splice\", \"sort\", \"reverse\"].forEach(function (e) {\n    var t = ye[e];\n    R(ge, e, function () {\n      for (var n = [], r = arguments.length; r--; ) n[r] = arguments[r];\n      var i,\n        o = t.apply(this, n),\n        a = this.__ob__;\n      switch (e) {\n        case \"push\":\n        case \"unshift\":\n          i = n;\n          break;\n        case \"splice\":\n          i = n.slice(2);\n      }\n      return i && a.observeArray(i), a.dep.notify(), o;\n    });\n  });\n  var _e = Object.getOwnPropertyNames(ge),\n    be = !0;\n  function $e(e) {\n    be = e;\n  }\n  var we = function (e) {\n    var t;\n    (this.value = e),\n      (this.dep = new ce()),\n      (this.vmCount = 0),\n      R(e, \"__ob__\", this),\n      Array.isArray(e)\n        ? (U\n            ? ((t = ge), (e.__proto__ = t))\n            : (function (e, t, n) {\n                for (var r = 0, i = n.length; r < i; r++) {\n                  var o = n[r];\n                  R(e, o, t[o]);\n                }\n              })(e, ge, _e),\n          this.observeArray(e))\n        : this.walk(e);\n  };\n  function Ce(e, t) {\n    var n;\n    if (o(e) && !(e instanceof pe)) return y(e, \"__ob__\") && e.__ob__ instanceof we ? (n = e.__ob__) : be && !te() && (Array.isArray(e) || s(e)) && Object.isExtensible(e) && !e._isVue && (n = new we(e)), t && n && n.vmCount++, n;\n  }\n  function xe(e, t, n, r, i) {\n    var o = new ce(),\n      a = Object.getOwnPropertyDescriptor(e, t);\n    if (!a || !1 !== a.configurable) {\n      var s = a && a.get,\n        c = a && a.set;\n      (s && !c) || 2 !== arguments.length || (n = e[t]);\n      var u = !i && Ce(n);\n      Object.defineProperty(e, t, {\n        enumerable: !0,\n        configurable: !0,\n        get: function () {\n          var t = s ? s.call(e) : n;\n          return (\n            ce.target &&\n              (o.depend(),\n              u &&\n                (u.dep.depend(),\n                Array.isArray(t) &&\n                  (function e(t) {\n                    for (var n = void 0, r = 0, i = t.length; r < i; r++) (n = t[r]) && n.__ob__ && n.__ob__.dep.depend(), Array.isArray(n) && e(n);\n                  })(t))),\n            t\n          );\n        },\n        set: function (t) {\n          var r = s ? s.call(e) : n;\n          t === r || (t != t && r != r) || (s && !c) || (c ? c.call(e, t) : (n = t), (u = !i && Ce(t)), o.notify());\n        },\n      });\n    }\n  }\n  function ke(e, t, n) {\n    if (Array.isArray(e) && c(t)) return (e.length = Math.max(e.length, t)), e.splice(t, 1, n), n;\n    if (t in e && !(t in Object.prototype)) return (e[t] = n), n;\n    var r = e.__ob__;\n    return e._isVue || (r && r.vmCount) ? n : r ? (xe(r.value, t, n), r.dep.notify(), n) : ((e[t] = n), n);\n  }\n  function Ae(e, t) {\n    if (Array.isArray(e) && c(t)) e.splice(t, 1);\n    else {\n      var n = e.__ob__;\n      e._isVue || (n && n.vmCount) || (y(e, t) && (delete e[t], n && n.dep.notify()));\n    }\n  }\n  (we.prototype.walk = function (e) {\n    for (var t = Object.keys(e), n = 0; n < t.length; n++) xe(e, t[n]);\n  }),\n    (we.prototype.observeArray = function (e) {\n      for (var t = 0, n = e.length; t < n; t++) Ce(e[t]);\n    });\n  var Oe = F.optionMergeStrategies;\n  function Se(e, t) {\n    if (!t) return e;\n    for (var n, r, i, o = oe ? Reflect.ownKeys(t) : Object.keys(t), a = 0; a < o.length; a++) \"__ob__\" !== (n = o[a]) && ((r = e[n]), (i = t[n]), y(e, n) ? r !== i && s(r) && s(i) && Se(r, i) : ke(e, n, i));\n    return e;\n  }\n  function Te(e, t, n) {\n    return n\n      ? function () {\n          var r = \"function\" == typeof t ? t.call(n, n) : t,\n            i = \"function\" == typeof e ? e.call(n, n) : e;\n          return r ? Se(r, i) : i;\n        }\n      : t\n        ? e\n          ? function () {\n              return Se(\"function\" == typeof t ? t.call(this, this) : t, \"function\" == typeof e ? e.call(this, this) : e);\n            }\n          : t\n        : e;\n  }\n  function Ne(e, t) {\n    var n = t ? (e ? e.concat(t) : Array.isArray(t) ? t : [t]) : e;\n    return n\n      ? (function (e) {\n          for (var t = [], n = 0; n < e.length; n++) -1 === t.indexOf(e[n]) && t.push(e[n]);\n          return t;\n        })(n)\n      : n;\n  }\n  function Ee(e, t, n, r) {\n    var i = Object.create(e || null);\n    return t ? A(i, t) : i;\n  }\n  (Oe.data = function (e, t, n) {\n    return n ? Te(e, t, n) : t && \"function\" != typeof t ? e : Te(e, t);\n  }),\n    M.forEach(function (e) {\n      Oe[e] = Ne;\n    }),\n    I.forEach(function (e) {\n      Oe[e + \"s\"] = Ee;\n    }),\n    (Oe.watch = function (e, t, n, r) {\n      if ((e === Y && (e = void 0), t === Y && (t = void 0), !t)) return Object.create(e || null);\n      if (!e) return t;\n      var i = {};\n      for (var o in (A(i, e), t)) {\n        var a = i[o],\n          s = t[o];\n        a && !Array.isArray(a) && (a = [a]), (i[o] = a ? a.concat(s) : Array.isArray(s) ? s : [s]);\n      }\n      return i;\n    }),\n    (Oe.props =\n      Oe.methods =\n      Oe.inject =\n      Oe.computed =\n        function (e, t, n, r) {\n          if (!e) return t;\n          var i = Object.create(null);\n          return A(i, e), t && A(i, t), i;\n        }),\n    (Oe.provide = Te);\n  var je = function (e, t) {\n    return void 0 === t ? e : t;\n  };\n  function De(e, t, n) {\n    if (\n      (\"function\" == typeof t && (t = t.options),\n      (function (e, t) {\n        var n = e.props;\n        if (n) {\n          var r,\n            i,\n            o = {};\n          if (Array.isArray(n)) for (r = n.length; r--; ) \"string\" == typeof (i = n[r]) && (o[b(i)] = { type: null });\n          else if (s(n)) for (var a in n) (i = n[a]), (o[b(a)] = s(i) ? i : { type: i });\n          e.props = o;\n        }\n      })(t),\n      (function (e, t) {\n        var n = e.inject;\n        if (n) {\n          var r = (e.inject = {});\n          if (Array.isArray(n)) for (var i = 0; i < n.length; i++) r[n[i]] = { from: n[i] };\n          else if (s(n))\n            for (var o in n) {\n              var a = n[o];\n              r[o] = s(a) ? A({ from: o }, a) : { from: a };\n            }\n        }\n      })(t),\n      (function (e) {\n        var t = e.directives;\n        if (t)\n          for (var n in t) {\n            var r = t[n];\n            \"function\" == typeof r && (t[n] = { bind: r, update: r });\n          }\n      })(t),\n      !t._base && (t.extends && (e = De(e, t.extends, n)), t.mixins))\n    )\n      for (var r = 0, i = t.mixins.length; r < i; r++) e = De(e, t.mixins[r], n);\n    var o,\n      a = {};\n    for (o in e) c(o);\n    for (o in t) y(e, o) || c(o);\n    function c(r) {\n      var i = Oe[r] || je;\n      a[r] = i(e[r], t[r], n, r);\n    }\n    return a;\n  }\n  function Le(e, t, n, r) {\n    if (\"string\" == typeof n) {\n      var i = e[t];\n      if (y(i, n)) return i[n];\n      var o = b(n);\n      if (y(i, o)) return i[o];\n      var a = $(o);\n      return y(i, a) ? i[a] : i[n] || i[o] || i[a];\n    }\n  }\n  function Ie(e, t, n, r) {\n    var i = t[e],\n      o = !y(n, e),\n      a = n[e],\n      s = Re(Boolean, i.type);\n    if (s > -1)\n      if (o && !y(i, \"default\")) a = !1;\n      else if (\"\" === a || a === C(e)) {\n        var c = Re(String, i.type);\n        (c < 0 || s < c) && (a = !0);\n      }\n    if (void 0 === a) {\n      a = (function (e, t, n) {\n        if (!y(t, \"default\")) return;\n        var r = t.default;\n        if (e && e.$options.propsData && void 0 === e.$options.propsData[n] && void 0 !== e._props[n]) return e._props[n];\n        return \"function\" == typeof r && \"Function\" !== Fe(t.type) ? r.call(e) : r;\n      })(r, i, e);\n      var u = be;\n      $e(!0), Ce(a), $e(u);\n    }\n    return a;\n  }\n  var Me = /^\\s*function (\\w+)/;\n  function Fe(e) {\n    var t = e && e.toString().match(Me);\n    return t ? t[1] : \"\";\n  }\n  function Pe(e, t) {\n    return Fe(e) === Fe(t);\n  }\n  function Re(e, t) {\n    if (!Array.isArray(t)) return Pe(t, e) ? 0 : -1;\n    for (var n = 0, r = t.length; n < r; n++) if (Pe(t[n], e)) return n;\n    return -1;\n  }\n  function He(e, t, n) {\n    le();\n    try {\n      if (t)\n        for (var r = t; (r = r.$parent); ) {\n          var i = r.$options.errorCaptured;\n          if (i)\n            for (var o = 0; o < i.length; o++)\n              try {\n                if (!1 === i[o].call(r, e, t, n)) return;\n              } catch (e) {\n                Ue(e, r, \"errorCaptured hook\");\n              }\n        }\n      Ue(e, t, n);\n    } finally {\n      fe();\n    }\n  }\n  function Be(e, t, n, r, i) {\n    var o;\n    try {\n      (o = n ? e.apply(t, n) : e.call(t)) &&\n        !o._isVue &&\n        u(o) &&\n        !o._handled &&\n        (o.catch(function (e) {\n          return He(e, r, i + \" (Promise/async)\");\n        }),\n        (o._handled = !0));\n    } catch (e) {\n      He(e, r, i);\n    }\n    return o;\n  }\n  function Ue(e, t, n) {\n    if (F.errorHandler)\n      try {\n        return F.errorHandler.call(null, e, t, n);\n      } catch (t) {\n        t !== e && Ve(t, null, \"config.errorHandler\");\n      }\n    Ve(e, t, n);\n  }\n  function Ve(e, t, n) {\n    if ((!V && !z) || \"undefined\" == typeof console) throw e;\n    console.error(e);\n  }\n  var ze,\n    Ke = !1,\n    Je = [],\n    qe = !1;\n  function We() {\n    qe = !1;\n    var e = Je.slice(0);\n    Je.length = 0;\n    for (var t = 0; t < e.length; t++) e[t]();\n  }\n  if (\"undefined\" != typeof Promise && re(Promise)) {\n    var Ze = Promise.resolve();\n    (ze = function () {\n      Ze.then(We), G && setTimeout(S);\n    }),\n      (Ke = !0);\n  } else if (q || \"undefined\" == typeof MutationObserver || (!re(MutationObserver) && \"[object MutationObserverConstructor]\" !== MutationObserver.toString()))\n    ze =\n      \"undefined\" != typeof setImmediate && re(setImmediate)\n        ? function () {\n            setImmediate(We);\n          }\n        : function () {\n            setTimeout(We, 0);\n          };\n  else {\n    var Ge = 1,\n      Xe = new MutationObserver(We),\n      Ye = document.createTextNode(String(Ge));\n    Xe.observe(Ye, { characterData: !0 }),\n      (ze = function () {\n        (Ge = (Ge + 1) % 2), (Ye.data = String(Ge));\n      }),\n      (Ke = !0);\n  }\n  function Qe(e, t) {\n    var n;\n    if (\n      (Je.push(function () {\n        if (e)\n          try {\n            e.call(t);\n          } catch (e) {\n            He(e, t, \"nextTick\");\n          }\n        else n && n(t);\n      }),\n      qe || ((qe = !0), ze()),\n      !e && \"undefined\" != typeof Promise)\n    )\n      return new Promise(function (e) {\n        n = e;\n      });\n  }\n  var et = new ie();\n  function tt(e) {\n    !(function e(t, n) {\n      var r, i;\n      var a = Array.isArray(t);\n      if ((!a && !o(t)) || Object.isFrozen(t) || t instanceof pe) return;\n      if (t.__ob__) {\n        var s = t.__ob__.dep.id;\n        if (n.has(s)) return;\n        n.add(s);\n      }\n      if (a) for (r = t.length; r--; ) e(t[r], n);\n      else for (i = Object.keys(t), r = i.length; r--; ) e(t[i[r]], n);\n    })(e, et),\n      et.clear();\n  }\n  var nt = g(function (e) {\n    var t = \"&\" === e.charAt(0),\n      n = \"~\" === (e = t ? e.slice(1) : e).charAt(0),\n      r = \"!\" === (e = n ? e.slice(1) : e).charAt(0);\n    return { name: (e = r ? e.slice(1) : e), once: n, capture: r, passive: t };\n  });\n  function rt(e, t) {\n    function n() {\n      var e = arguments,\n        r = n.fns;\n      if (!Array.isArray(r)) return Be(r, null, arguments, t, \"v-on handler\");\n      for (var i = r.slice(), o = 0; o < i.length; o++) Be(i[o], null, e, t, \"v-on handler\");\n    }\n    return (n.fns = e), n;\n  }\n  function it(e, n, i, o, a, s) {\n    var c, u, l, f;\n    for (c in e) (u = e[c]), (l = n[c]), (f = nt(c)), t(u) || (t(l) ? (t(u.fns) && (u = e[c] = rt(u, s)), r(f.once) && (u = e[c] = a(f.name, u, f.capture)), i(f.name, u, f.capture, f.passive, f.params)) : u !== l && ((l.fns = u), (e[c] = l)));\n    for (c in n) t(e[c]) && o((f = nt(c)).name, n[c], f.capture);\n  }\n  function ot(e, i, o) {\n    var a;\n    e instanceof pe && (e = e.data.hook || (e.data.hook = {}));\n    var s = e[i];\n    function c() {\n      o.apply(this, arguments), h(a.fns, c);\n    }\n    t(s) ? (a = rt([c])) : n(s.fns) && r(s.merged) ? (a = s).fns.push(c) : (a = rt([s, c])), (a.merged = !0), (e[i] = a);\n  }\n  function at(e, t, r, i, o) {\n    if (n(t)) {\n      if (y(t, r)) return (e[r] = t[r]), o || delete t[r], !0;\n      if (y(t, i)) return (e[r] = t[i]), o || delete t[i], !0;\n    }\n    return !1;\n  }\n  function st(e) {\n    return i(e)\n      ? [he(e)]\n      : Array.isArray(e)\n        ? (function e(o, a) {\n            var s = [];\n            var c, u, l, f;\n            for (c = 0; c < o.length; c++) t((u = o[c])) || \"boolean\" == typeof u || ((l = s.length - 1), (f = s[l]), Array.isArray(u) ? u.length > 0 && (ct((u = e(u, (a || \"\") + \"_\" + c))[0]) && ct(f) && ((s[l] = he(f.text + u[0].text)), u.shift()), s.push.apply(s, u)) : i(u) ? (ct(f) ? (s[l] = he(f.text + u)) : \"\" !== u && s.push(he(u))) : ct(u) && ct(f) ? (s[l] = he(f.text + u.text)) : (r(o._isVList) && n(u.tag) && t(u.key) && n(a) && (u.key = \"__vlist\" + a + \"_\" + c + \"__\"), s.push(u)));\n            return s;\n          })(e)\n        : void 0;\n  }\n  function ct(e) {\n    return n(e) && n(e.text) && !1 === e.isComment;\n  }\n  function ut(e, t) {\n    if (e) {\n      for (var n = Object.create(null), r = oe ? Reflect.ownKeys(e) : Object.keys(e), i = 0; i < r.length; i++) {\n        var o = r[i];\n        if (\"__ob__\" !== o) {\n          for (var a = e[o].from, s = t; s; ) {\n            if (s._provided && y(s._provided, a)) {\n              n[o] = s._provided[a];\n              break;\n            }\n            s = s.$parent;\n          }\n          if (!s && \"default\" in e[o]) {\n            var c = e[o].default;\n            n[o] = \"function\" == typeof c ? c.call(t) : c;\n          }\n        }\n      }\n      return n;\n    }\n  }\n  function lt(e, t) {\n    if (!e || !e.length) return {};\n    for (var n = {}, r = 0, i = e.length; r < i; r++) {\n      var o = e[r],\n        a = o.data;\n      if ((a && a.attrs && a.attrs.slot && delete a.attrs.slot, (o.context !== t && o.fnContext !== t) || !a || null == a.slot)) (n.default || (n.default = [])).push(o);\n      else {\n        var s = a.slot,\n          c = n[s] || (n[s] = []);\n        \"template\" === o.tag ? c.push.apply(c, o.children || []) : c.push(o);\n      }\n    }\n    for (var u in n) n[u].every(ft) && delete n[u];\n    return n;\n  }\n  function ft(e) {\n    return (e.isComment && !e.asyncFactory) || \" \" === e.text;\n  }\n  function pt(e) {\n    return e.isComment && e.asyncFactory;\n  }\n  function dt(t, n, r) {\n    var i,\n      o = Object.keys(n).length > 0,\n      a = t ? !!t.$stable : !o,\n      s = t && t.$key;\n    if (t) {\n      if (t._normalized) return t._normalized;\n      if (a && r && r !== e && s === r.$key && !o && !r.$hasNormal) return r;\n      for (var c in ((i = {}), t)) t[c] && \"$\" !== c[0] && (i[c] = vt(n, c, t[c]));\n    } else i = {};\n    for (var u in n) u in i || (i[u] = ht(n, u));\n    return t && Object.isExtensible(t) && (t._normalized = i), R(i, \"$stable\", a), R(i, \"$key\", s), R(i, \"$hasNormal\", o), i;\n  }\n  function vt(e, t, n) {\n    var r = function () {\n      var e = arguments.length ? n.apply(null, arguments) : n({}),\n        t = (e = e && \"object\" == typeof e && !Array.isArray(e) ? [e] : st(e)) && e[0];\n      return e && (!t || (1 === e.length && t.isComment && !pt(t))) ? void 0 : e;\n    };\n    return (\n      n.proxy &&\n        Object.defineProperty(e, t, {\n          get: r,\n          enumerable: !0,\n          configurable: !0,\n        }),\n      r\n    );\n  }\n  function ht(e, t) {\n    return function () {\n      return e[t];\n    };\n  }\n  function mt(e, t) {\n    var r, i, a, s, c;\n    if (Array.isArray(e) || \"string\" == typeof e) for (r = new Array(e.length), i = 0, a = e.length; i < a; i++) r[i] = t(e[i], i);\n    else if (\"number\" == typeof e) for (r = new Array(e), i = 0; i < e; i++) r[i] = t(i + 1, i);\n    else if (o(e))\n      if (oe && e[Symbol.iterator]) {\n        r = [];\n        for (var u = e[Symbol.iterator](), l = u.next(); !l.done; ) r.push(t(l.value, r.length)), (l = u.next());\n      } else for (s = Object.keys(e), r = new Array(s.length), i = 0, a = s.length; i < a; i++) (c = s[i]), (r[i] = t(e[c], c, i));\n    return n(r) || (r = []), (r._isVList = !0), r;\n  }\n  function yt(e, t, n, r) {\n    var i,\n      o = this.$scopedSlots[e];\n    o ? ((n = n || {}), r && (n = A(A({}, r), n)), (i = o(n) || (\"function\" == typeof t ? t() : t))) : (i = this.$slots[e] || (\"function\" == typeof t ? t() : t));\n    var a = n && n.slot;\n    return a ? this.$createElement(\"template\", { slot: a }, i) : i;\n  }\n  function gt(e) {\n    return Le(this.$options, \"filters\", e) || N;\n  }\n  function _t(e, t) {\n    return Array.isArray(e) ? -1 === e.indexOf(t) : e !== t;\n  }\n  function bt(e, t, n, r, i) {\n    var o = F.keyCodes[t] || n;\n    return i && r && !F.keyCodes[t] ? _t(i, r) : o ? _t(o, e) : r ? C(r) !== t : void 0 === e;\n  }\n  function $t(e, t, n, r, i) {\n    if (n)\n      if (o(n)) {\n        var a;\n        Array.isArray(n) && (n = O(n));\n        var s = function (o) {\n          if (\"class\" === o || \"style\" === o || v(o)) a = e;\n          else {\n            var s = e.attrs && e.attrs.type;\n            a = r || F.mustUseProp(t, s, o) ? e.domProps || (e.domProps = {}) : e.attrs || (e.attrs = {});\n          }\n          var c = b(o),\n            u = C(o);\n          c in a ||\n            u in a ||\n            ((a[o] = n[o]),\n            i &&\n              ((e.on || (e.on = {}))[\"update:\" + o] = function (e) {\n                n[o] = e;\n              }));\n        };\n        for (var c in n) s(c);\n      } else;\n    return e;\n  }\n  function wt(e, t) {\n    var n = this._staticTrees || (this._staticTrees = []),\n      r = n[e];\n    return r && !t ? r : (xt((r = n[e] = this.$options.staticRenderFns[e].call(this._renderProxy, null, this)), \"__static__\" + e, !1), r);\n  }\n  function Ct(e, t, n) {\n    return xt(e, \"__once__\" + t + (n ? \"_\" + n : \"\"), !0), e;\n  }\n  function xt(e, t, n) {\n    if (Array.isArray(e)) for (var r = 0; r < e.length; r++) e[r] && \"string\" != typeof e[r] && kt(e[r], t + \"_\" + r, n);\n    else kt(e, t, n);\n  }\n  function kt(e, t, n) {\n    (e.isStatic = !0), (e.key = t), (e.isOnce = n);\n  }\n  function At(e, t) {\n    if (t)\n      if (s(t)) {\n        var n = (e.on = e.on ? A({}, e.on) : {});\n        for (var r in t) {\n          var i = n[r],\n            o = t[r];\n          n[r] = i ? [].concat(i, o) : o;\n        }\n      } else;\n    return e;\n  }\n  function Ot(e, t, n, r) {\n    t = t || { $stable: !n };\n    for (var i = 0; i < e.length; i++) {\n      var o = e[i];\n      Array.isArray(o) ? Ot(o, t, n) : o && (o.proxy && (o.fn.proxy = !0), (t[o.key] = o.fn));\n    }\n    return r && (t.$key = r), t;\n  }\n  function St(e, t) {\n    for (var n = 0; n < t.length; n += 2) {\n      var r = t[n];\n      \"string\" == typeof r && r && (e[t[n]] = t[n + 1]);\n    }\n    return e;\n  }\n  function Tt(e, t) {\n    return \"string\" == typeof e ? t + e : e;\n  }\n  function Nt(e) {\n    (e._o = Ct), (e._n = f), (e._s = l), (e._l = mt), (e._t = yt), (e._q = E), (e._i = j), (e._m = wt), (e._f = gt), (e._k = bt), (e._b = $t), (e._v = he), (e._e = ve), (e._u = Ot), (e._g = At), (e._d = St), (e._p = Tt);\n  }\n  function Et(t, n, i, o, a) {\n    var s,\n      c = this,\n      u = a.options;\n    y(o, \"_uid\") ? ((s = Object.create(o))._original = o) : ((s = o), (o = o._original));\n    var l = r(u._compiled),\n      f = !l;\n    (this.data = t),\n      (this.props = n),\n      (this.children = i),\n      (this.parent = o),\n      (this.listeners = t.on || e),\n      (this.injections = ut(u.inject, o)),\n      (this.slots = function () {\n        return c.$slots || dt(t.scopedSlots, (c.$slots = lt(i, o))), c.$slots;\n      }),\n      Object.defineProperty(this, \"scopedSlots\", {\n        enumerable: !0,\n        get: function () {\n          return dt(t.scopedSlots, this.slots());\n        },\n      }),\n      l && ((this.$options = u), (this.$slots = this.slots()), (this.$scopedSlots = dt(t.scopedSlots, this.$slots))),\n      u._scopeId\n        ? (this._c = function (e, t, n, r) {\n            var i = Ht(s, e, t, n, r, f);\n            return i && !Array.isArray(i) && ((i.fnScopeId = u._scopeId), (i.fnContext = o)), i;\n          })\n        : (this._c = function (e, t, n, r) {\n            return Ht(s, e, t, n, r, f);\n          });\n  }\n  function jt(e, t, n, r, i) {\n    var o = me(e);\n    return (o.fnContext = n), (o.fnOptions = r), t.slot && ((o.data || (o.data = {})).slot = t.slot), o;\n  }\n  function Dt(e, t) {\n    for (var n in t) e[b(n)] = t[n];\n  }\n  Nt(Et.prototype);\n  var Lt = {\n      init: function (e, t) {\n        if (e.componentInstance && !e.componentInstance._isDestroyed && e.data.keepAlive) {\n          var r = e;\n          Lt.prepatch(r, r);\n        } else {\n          (e.componentInstance = (function (e, t) {\n            var r = { _isComponent: !0, _parentVnode: e, parent: t },\n              i = e.data.inlineTemplate;\n            n(i) && ((r.render = i.render), (r.staticRenderFns = i.staticRenderFns));\n            return new e.componentOptions.Ctor(r);\n          })(e, Zt)).$mount(t ? e.elm : void 0, t);\n        }\n      },\n      prepatch: function (t, n) {\n        var r = n.componentOptions;\n        !(function (t, n, r, i, o) {\n          var a = i.data.scopedSlots,\n            s = t.$scopedSlots,\n            c = !!((a && !a.$stable) || (s !== e && !s.$stable) || (a && t.$scopedSlots.$key !== a.$key) || (!a && t.$scopedSlots.$key)),\n            u = !!(o || t.$options._renderChildren || c);\n          (t.$options._parentVnode = i), (t.$vnode = i), t._vnode && (t._vnode.parent = i);\n          if (((t.$options._renderChildren = o), (t.$attrs = i.data.attrs || e), (t.$listeners = r || e), n && t.$options.props)) {\n            $e(!1);\n            for (var l = t._props, f = t.$options._propKeys || [], p = 0; p < f.length; p++) {\n              var d = f[p],\n                v = t.$options.props;\n              l[d] = Ie(d, v, n, t);\n            }\n            $e(!0), (t.$options.propsData = n);\n          }\n          r = r || e;\n          var h = t.$options._parentListeners;\n          (t.$options._parentListeners = r), Wt(t, r, h), u && ((t.$slots = lt(o, i.context)), t.$forceUpdate());\n        })((n.componentInstance = t.componentInstance), r.propsData, r.listeners, n, r.children);\n      },\n      insert: function (e) {\n        var t,\n          n = e.context,\n          r = e.componentInstance;\n        r._isMounted || ((r._isMounted = !0), Qt(r, \"mounted\")), e.data.keepAlive && (n._isMounted ? (((t = r)._inactive = !1), tn.push(t)) : Yt(r, !0));\n      },\n      destroy: function (e) {\n        var t = e.componentInstance;\n        t._isDestroyed ||\n          (e.data.keepAlive\n            ? (function e(t, n) {\n                if (n && ((t._directInactive = !0), Xt(t))) return;\n                if (!t._inactive) {\n                  t._inactive = !0;\n                  for (var r = 0; r < t.$children.length; r++) e(t.$children[r]);\n                  Qt(t, \"deactivated\");\n                }\n              })(t, !0)\n            : t.$destroy());\n      },\n    },\n    It = Object.keys(Lt);\n  function Mt(i, a, s, c, l) {\n    if (!t(i)) {\n      var f = s.$options._base;\n      if ((o(i) && (i = f.extend(i)), \"function\" == typeof i)) {\n        var p;\n        if (\n          t(i.cid) &&\n          void 0 ===\n            (i = (function (e, i) {\n              if (r(e.error) && n(e.errorComp)) return e.errorComp;\n              if (n(e.resolved)) return e.resolved;\n              var a = Ut;\n              a && n(e.owners) && -1 === e.owners.indexOf(a) && e.owners.push(a);\n              if (r(e.loading) && n(e.loadingComp)) return e.loadingComp;\n              if (a && !n(e.owners)) {\n                var s = (e.owners = [a]),\n                  c = !0,\n                  l = null,\n                  f = null;\n                a.$on(\"hook:destroyed\", function () {\n                  return h(s, a);\n                });\n                var p = function (e) {\n                    for (var t = 0, n = s.length; t < n; t++) s[t].$forceUpdate();\n                    e && ((s.length = 0), null !== l && (clearTimeout(l), (l = null)), null !== f && (clearTimeout(f), (f = null)));\n                  },\n                  d = D(function (t) {\n                    (e.resolved = Vt(t, i)), c ? (s.length = 0) : p(!0);\n                  }),\n                  v = D(function (t) {\n                    n(e.errorComp) && ((e.error = !0), p(!0));\n                  }),\n                  m = e(d, v);\n                return (\n                  o(m) &&\n                    (u(m)\n                      ? t(e.resolved) && m.then(d, v)\n                      : u(m.component) &&\n                        (m.component.then(d, v),\n                        n(m.error) && (e.errorComp = Vt(m.error, i)),\n                        n(m.loading) &&\n                          ((e.loadingComp = Vt(m.loading, i)),\n                          0 === m.delay\n                            ? (e.loading = !0)\n                            : (l = setTimeout(function () {\n                                (l = null), t(e.resolved) && t(e.error) && ((e.loading = !0), p(!1));\n                              }, m.delay || 200))),\n                        n(m.timeout) &&\n                          (f = setTimeout(function () {\n                            (f = null), t(e.resolved) && v(null);\n                          }, m.timeout)))),\n                  (c = !1),\n                  e.loading ? e.loadingComp : e.resolved\n                );\n              }\n            })((p = i), f))\n        )\n          return (function (e, t, n, r, i) {\n            var o = ve();\n            return (o.asyncFactory = e), (o.asyncMeta = { data: t, context: n, children: r, tag: i }), o;\n          })(p, a, s, c, l);\n        (a = a || {}),\n          wn(i),\n          n(a.model) &&\n            (function (e, t) {\n              var r = (e.model && e.model.prop) || \"value\",\n                i = (e.model && e.model.event) || \"input\";\n              (t.attrs || (t.attrs = {}))[r] = t.model.value;\n              var o = t.on || (t.on = {}),\n                a = o[i],\n                s = t.model.callback;\n              n(a) ? (Array.isArray(a) ? -1 === a.indexOf(s) : a !== s) && (o[i] = [s].concat(a)) : (o[i] = s);\n            })(i.options, a);\n        var d = (function (e, r, i) {\n          var o = r.options.props;\n          if (!t(o)) {\n            var a = {},\n              s = e.attrs,\n              c = e.props;\n            if (n(s) || n(c))\n              for (var u in o) {\n                var l = C(u);\n                at(a, c, u, l, !0) || at(a, s, u, l, !1);\n              }\n            return a;\n          }\n        })(a, i);\n        if (r(i.options.functional))\n          return (function (t, r, i, o, a) {\n            var s = t.options,\n              c = {},\n              u = s.props;\n            if (n(u)) for (var l in u) c[l] = Ie(l, u, r || e);\n            else n(i.attrs) && Dt(c, i.attrs), n(i.props) && Dt(c, i.props);\n            var f = new Et(i, c, a, o, t),\n              p = s.render.call(null, f._c, f);\n            if (p instanceof pe) return jt(p, i, f.parent, s);\n            if (Array.isArray(p)) {\n              for (var d = st(p) || [], v = new Array(d.length), h = 0; h < d.length; h++) v[h] = jt(d[h], i, f.parent, s);\n              return v;\n            }\n          })(i, d, a, s, c);\n        var v = a.on;\n        if (((a.on = a.nativeOn), r(i.options.abstract))) {\n          var m = a.slot;\n          (a = {}), m && (a.slot = m);\n        }\n        !(function (e) {\n          for (var t = e.hook || (e.hook = {}), n = 0; n < It.length; n++) {\n            var r = It[n],\n              i = t[r],\n              o = Lt[r];\n            i === o || (i && i._merged) || (t[r] = i ? Ft(o, i) : o);\n          }\n        })(a);\n        var y = i.options.name || l;\n        return new pe(\"vue-component-\" + i.cid + (y ? \"-\" + y : \"\"), a, void 0, void 0, void 0, s, { Ctor: i, propsData: d, listeners: v, tag: l, children: c }, p);\n      }\n    }\n  }\n  function Ft(e, t) {\n    var n = function (n, r) {\n      e(n, r), t(n, r);\n    };\n    return (n._merged = !0), n;\n  }\n  var Pt = 1,\n    Rt = 2;\n  function Ht(e, a, s, c, u, l) {\n    return (\n      (Array.isArray(s) || i(s)) && ((u = c), (c = s), (s = void 0)),\n      r(l) && (u = Rt),\n      (function (e, i, a, s, c) {\n        if (n(a) && n(a.__ob__)) return ve();\n        n(a) && n(a.is) && (i = a.is);\n        if (!i) return ve();\n        Array.isArray(s) && \"function\" == typeof s[0] && (((a = a || {}).scopedSlots = { default: s[0] }), (s.length = 0));\n        c === Rt\n          ? (s = st(s))\n          : c === Pt &&\n            (s = (function (e) {\n              for (var t = 0; t < e.length; t++) if (Array.isArray(e[t])) return Array.prototype.concat.apply([], e);\n              return e;\n            })(s));\n        var u, l;\n        if (\"string\" == typeof i) {\n          var f;\n          (l = (e.$vnode && e.$vnode.ns) || F.getTagNamespace(i)), (u = F.isReservedTag(i) ? new pe(F.parsePlatformTagName(i), a, s, void 0, void 0, e) : (a && a.pre) || !n((f = Le(e.$options, \"components\", i))) ? new pe(i, a, s, void 0, void 0, e) : Mt(f, a, e, s, i));\n        } else u = Mt(i, a, e, s);\n        return Array.isArray(u)\n          ? u\n          : n(u)\n            ? (n(l) &&\n                (function e(i, o, a) {\n                  i.ns = o;\n                  \"foreignObject\" === i.tag && ((o = void 0), (a = !0));\n                  if (n(i.children))\n                    for (var s = 0, c = i.children.length; s < c; s++) {\n                      var u = i.children[s];\n                      n(u.tag) && (t(u.ns) || (r(a) && \"svg\" !== u.tag)) && e(u, o, a);\n                    }\n                })(u, l),\n              n(a) &&\n                (function (e) {\n                  o(e.style) && tt(e.style);\n                  o(e.class) && tt(e.class);\n                })(a),\n              u)\n            : ve();\n      })(e, a, s, c, u)\n    );\n  }\n  var Bt,\n    Ut = null;\n  function Vt(e, t) {\n    return (e.__esModule || (oe && \"Module\" === e[Symbol.toStringTag])) && (e = e.default), o(e) ? t.extend(e) : e;\n  }\n  function zt(e) {\n    if (Array.isArray(e))\n      for (var t = 0; t < e.length; t++) {\n        var r = e[t];\n        if (n(r) && (n(r.componentOptions) || pt(r))) return r;\n      }\n  }\n  function Kt(e, t) {\n    Bt.$on(e, t);\n  }\n  function Jt(e, t) {\n    Bt.$off(e, t);\n  }\n  function qt(e, t) {\n    var n = Bt;\n    return function r() {\n      null !== t.apply(null, arguments) && n.$off(e, r);\n    };\n  }\n  function Wt(e, t, n) {\n    (Bt = e), it(t, n || {}, Kt, Jt, qt, e), (Bt = void 0);\n  }\n  var Zt = null;\n  function Gt(e) {\n    var t = Zt;\n    return (\n      (Zt = e),\n      function () {\n        Zt = t;\n      }\n    );\n  }\n  function Xt(e) {\n    for (; e && (e = e.$parent); ) if (e._inactive) return !0;\n    return !1;\n  }\n  function Yt(e, t) {\n    if (t) {\n      if (((e._directInactive = !1), Xt(e))) return;\n    } else if (e._directInactive) return;\n    if (e._inactive || null === e._inactive) {\n      e._inactive = !1;\n      for (var n = 0; n < e.$children.length; n++) Yt(e.$children[n]);\n      Qt(e, \"activated\");\n    }\n  }\n  function Qt(e, t) {\n    le();\n    var n = e.$options[t],\n      r = t + \" hook\";\n    if (n) for (var i = 0, o = n.length; i < o; i++) Be(n[i], e, null, e, r);\n    e._hasHookEvent && e.$emit(\"hook:\" + t), fe();\n  }\n  var en = [],\n    tn = [],\n    nn = {},\n    rn = !1,\n    on = !1,\n    an = 0;\n  var sn = 0,\n    cn = Date.now;\n  if (V && !q) {\n    var un = window.performance;\n    un &&\n      \"function\" == typeof un.now &&\n      cn() > document.createEvent(\"Event\").timeStamp &&\n      (cn = function () {\n        return un.now();\n      });\n  }\n  function ln() {\n    var e, t;\n    for (\n      sn = cn(),\n        on = !0,\n        en.sort(function (e, t) {\n          return e.id - t.id;\n        }),\n        an = 0;\n      an < en.length;\n      an++\n    )\n      (e = en[an]).before && e.before(), (t = e.id), (nn[t] = null), e.run();\n    var n = tn.slice(),\n      r = en.slice();\n    (an = en.length = tn.length = 0),\n      (nn = {}),\n      (rn = on = !1),\n      (function (e) {\n        for (var t = 0; t < e.length; t++) (e[t]._inactive = !0), Yt(e[t], !0);\n      })(n),\n      (function (e) {\n        var t = e.length;\n        for (; t--; ) {\n          var n = e[t],\n            r = n.vm;\n          r._watcher === n && r._isMounted && !r._isDestroyed && Qt(r, \"updated\");\n        }\n      })(r),\n      ne && F.devtools && ne.emit(\"flush\");\n  }\n  var fn = 0,\n    pn = function (e, t, n, r, i) {\n      (this.vm = e),\n        i && (e._watcher = this),\n        e._watchers.push(this),\n        r ? ((this.deep = !!r.deep), (this.user = !!r.user), (this.lazy = !!r.lazy), (this.sync = !!r.sync), (this.before = r.before)) : (this.deep = this.user = this.lazy = this.sync = !1),\n        (this.cb = n),\n        (this.id = ++fn),\n        (this.active = !0),\n        (this.dirty = this.lazy),\n        (this.deps = []),\n        (this.newDeps = []),\n        (this.depIds = new ie()),\n        (this.newDepIds = new ie()),\n        (this.expression = \"\"),\n        \"function\" == typeof t\n          ? (this.getter = t)\n          : ((this.getter = (function (e) {\n              if (!H.test(e)) {\n                var t = e.split(\".\");\n                return function (e) {\n                  for (var n = 0; n < t.length; n++) {\n                    if (!e) return;\n                    e = e[t[n]];\n                  }\n                  return e;\n                };\n              }\n            })(t)),\n            this.getter || (this.getter = S)),\n        (this.value = this.lazy ? void 0 : this.get());\n    };\n  (pn.prototype.get = function () {\n    var e;\n    le(this);\n    var t = this.vm;\n    try {\n      e = this.getter.call(t, t);\n    } catch (e) {\n      if (!this.user) throw e;\n      He(e, t, 'getter for watcher \"' + this.expression + '\"');\n    } finally {\n      this.deep && tt(e), fe(), this.cleanupDeps();\n    }\n    return e;\n  }),\n    (pn.prototype.addDep = function (e) {\n      var t = e.id;\n      this.newDepIds.has(t) || (this.newDepIds.add(t), this.newDeps.push(e), this.depIds.has(t) || e.addSub(this));\n    }),\n    (pn.prototype.cleanupDeps = function () {\n      for (var e = this.deps.length; e--; ) {\n        var t = this.deps[e];\n        this.newDepIds.has(t.id) || t.removeSub(this);\n      }\n      var n = this.depIds;\n      (this.depIds = this.newDepIds), (this.newDepIds = n), this.newDepIds.clear(), (n = this.deps), (this.deps = this.newDeps), (this.newDeps = n), (this.newDeps.length = 0);\n    }),\n    (pn.prototype.update = function () {\n      this.lazy\n        ? (this.dirty = !0)\n        : this.sync\n          ? this.run()\n          : (function (e) {\n              var t = e.id;\n              if (null == nn[t]) {\n                if (((nn[t] = !0), on)) {\n                  for (var n = en.length - 1; n > an && en[n].id > e.id; ) n--;\n                  en.splice(n + 1, 0, e);\n                } else en.push(e);\n                rn || ((rn = !0), Qe(ln));\n              }\n            })(this);\n    }),\n    (pn.prototype.run = function () {\n      if (this.active) {\n        var e = this.get();\n        if (e !== this.value || o(e) || this.deep) {\n          var t = this.value;\n          if (((this.value = e), this.user)) {\n            var n = 'callback for watcher \"' + this.expression + '\"';\n            Be(this.cb, this.vm, [e, t], this.vm, n);\n          } else this.cb.call(this.vm, e, t);\n        }\n      }\n    }),\n    (pn.prototype.evaluate = function () {\n      (this.value = this.get()), (this.dirty = !1);\n    }),\n    (pn.prototype.depend = function () {\n      for (var e = this.deps.length; e--; ) this.deps[e].depend();\n    }),\n    (pn.prototype.teardown = function () {\n      if (this.active) {\n        this.vm._isBeingDestroyed || h(this.vm._watchers, this);\n        for (var e = this.deps.length; e--; ) this.deps[e].removeSub(this);\n        this.active = !1;\n      }\n    });\n  var dn = { enumerable: !0, configurable: !0, get: S, set: S };\n  function vn(e, t, n) {\n    (dn.get = function () {\n      return this[t][n];\n    }),\n      (dn.set = function (e) {\n        this[t][n] = e;\n      }),\n      Object.defineProperty(e, n, dn);\n  }\n  function hn(e) {\n    e._watchers = [];\n    var t = e.$options;\n    t.props &&\n      (function (e, t) {\n        var n = e.$options.propsData || {},\n          r = (e._props = {}),\n          i = (e.$options._propKeys = []);\n        e.$parent && $e(!1);\n        var o = function (o) {\n          i.push(o);\n          var a = Ie(o, t, n, e);\n          xe(r, o, a), o in e || vn(e, \"_props\", o);\n        };\n        for (var a in t) o(a);\n        $e(!0);\n      })(e, t.props),\n      t.methods &&\n        (function (e, t) {\n          e.$options.props;\n          for (var n in t) e[n] = \"function\" != typeof t[n] ? S : x(t[n], e);\n        })(e, t.methods),\n      t.data\n        ? (function (e) {\n            var t = e.$options.data;\n            s(\n              (t = e._data =\n                \"function\" == typeof t\n                  ? (function (e, t) {\n                      le();\n                      try {\n                        return e.call(t, t);\n                      } catch (e) {\n                        return He(e, t, \"data()\"), {};\n                      } finally {\n                        fe();\n                      }\n                    })(t, e)\n                  : t || {}),\n            ) || (t = {});\n            var n = Object.keys(t),\n              r = e.$options.props,\n              i = (e.$options.methods, n.length);\n            for (; i--; ) {\n              var o = n[i];\n              (r && y(r, o)) || ((a = void 0), 36 !== (a = (o + \"\").charCodeAt(0)) && 95 !== a && vn(e, \"_data\", o));\n            }\n            var a;\n            Ce(t, !0);\n          })(e)\n        : Ce((e._data = {}), !0),\n      t.computed &&\n        (function (e, t) {\n          var n = (e._computedWatchers = Object.create(null)),\n            r = te();\n          for (var i in t) {\n            var o = t[i],\n              a = \"function\" == typeof o ? o : o.get;\n            r || (n[i] = new pn(e, a || S, S, mn)), i in e || yn(e, i, o);\n          }\n        })(e, t.computed),\n      t.watch &&\n        t.watch !== Y &&\n        (function (e, t) {\n          for (var n in t) {\n            var r = t[n];\n            if (Array.isArray(r)) for (var i = 0; i < r.length; i++) bn(e, n, r[i]);\n            else bn(e, n, r);\n          }\n        })(e, t.watch);\n  }\n  var mn = { lazy: !0 };\n  function yn(e, t, n) {\n    var r = !te();\n    \"function\" == typeof n ? ((dn.get = r ? gn(t) : _n(n)), (dn.set = S)) : ((dn.get = n.get ? (r && !1 !== n.cache ? gn(t) : _n(n.get)) : S), (dn.set = n.set || S)), Object.defineProperty(e, t, dn);\n  }\n  function gn(e) {\n    return function () {\n      var t = this._computedWatchers && this._computedWatchers[e];\n      if (t) return t.dirty && t.evaluate(), ce.target && t.depend(), t.value;\n    };\n  }\n  function _n(e) {\n    return function () {\n      return e.call(this, this);\n    };\n  }\n  function bn(e, t, n, r) {\n    return s(n) && ((r = n), (n = n.handler)), \"string\" == typeof n && (n = e[n]), e.$watch(t, n, r);\n  }\n  var $n = 0;\n  function wn(e) {\n    var t = e.options;\n    if (e.super) {\n      var n = wn(e.super);\n      if (n !== e.superOptions) {\n        e.superOptions = n;\n        var r = (function (e) {\n          var t,\n            n = e.options,\n            r = e.sealedOptions;\n          for (var i in n) n[i] !== r[i] && (t || (t = {}), (t[i] = n[i]));\n          return t;\n        })(e);\n        r && A(e.extendOptions, r), (t = e.options = De(n, e.extendOptions)).name && (t.components[t.name] = e);\n      }\n    }\n    return t;\n  }\n  function Cn(e) {\n    this._init(e);\n  }\n  function xn(e) {\n    e.cid = 0;\n    var t = 1;\n    e.extend = function (e) {\n      e = e || {};\n      var n = this,\n        r = n.cid,\n        i = e._Ctor || (e._Ctor = {});\n      if (i[r]) return i[r];\n      var o = e.name || n.options.name,\n        a = function (e) {\n          this._init(e);\n        };\n      return (\n        ((a.prototype = Object.create(n.prototype)).constructor = a),\n        (a.cid = t++),\n        (a.options = De(n.options, e)),\n        (a.super = n),\n        a.options.props &&\n          (function (e) {\n            var t = e.options.props;\n            for (var n in t) vn(e.prototype, \"_props\", n);\n          })(a),\n        a.options.computed &&\n          (function (e) {\n            var t = e.options.computed;\n            for (var n in t) yn(e.prototype, n, t[n]);\n          })(a),\n        (a.extend = n.extend),\n        (a.mixin = n.mixin),\n        (a.use = n.use),\n        I.forEach(function (e) {\n          a[e] = n[e];\n        }),\n        o && (a.options.components[o] = a),\n        (a.superOptions = n.options),\n        (a.extendOptions = e),\n        (a.sealedOptions = A({}, a.options)),\n        (i[r] = a),\n        a\n      );\n    };\n  }\n  function kn(e) {\n    return e && (e.Ctor.options.name || e.tag);\n  }\n  function An(e, t) {\n    return Array.isArray(e) ? e.indexOf(t) > -1 : \"string\" == typeof e ? e.split(\",\").indexOf(t) > -1 : ((n = e), \"[object RegExp]\" === a.call(n) && e.test(t));\n    var n;\n  }\n  function On(e, t) {\n    var n = e.cache,\n      r = e.keys,\n      i = e._vnode;\n    for (var o in n) {\n      var a = n[o];\n      if (a) {\n        var s = a.name;\n        s && !t(s) && Sn(n, o, r, i);\n      }\n    }\n  }\n  function Sn(e, t, n, r) {\n    var i = e[t];\n    !i || (r && i.tag === r.tag) || i.componentInstance.$destroy(), (e[t] = null), h(n, t);\n  }\n  !(function (t) {\n    t.prototype._init = function (t) {\n      var n = this;\n      (n._uid = $n++),\n        (n._isVue = !0),\n        t && t._isComponent\n          ? (function (e, t) {\n              var n = (e.$options = Object.create(e.constructor.options)),\n                r = t._parentVnode;\n              (n.parent = t.parent), (n._parentVnode = r);\n              var i = r.componentOptions;\n              (n.propsData = i.propsData), (n._parentListeners = i.listeners), (n._renderChildren = i.children), (n._componentTag = i.tag), t.render && ((n.render = t.render), (n.staticRenderFns = t.staticRenderFns));\n            })(n, t)\n          : (n.$options = De(wn(n.constructor), t || {}, n)),\n        (n._renderProxy = n),\n        (n._self = n),\n        (function (e) {\n          var t = e.$options,\n            n = t.parent;\n          if (n && !t.abstract) {\n            for (; n.$options.abstract && n.$parent; ) n = n.$parent;\n            n.$children.push(e);\n          }\n          (e.$parent = n), (e.$root = n ? n.$root : e), (e.$children = []), (e.$refs = {}), (e._watcher = null), (e._inactive = null), (e._directInactive = !1), (e._isMounted = !1), (e._isDestroyed = !1), (e._isBeingDestroyed = !1);\n        })(n),\n        (function (e) {\n          (e._events = Object.create(null)), (e._hasHookEvent = !1);\n          var t = e.$options._parentListeners;\n          t && Wt(e, t);\n        })(n),\n        (function (t) {\n          (t._vnode = null), (t._staticTrees = null);\n          var n = t.$options,\n            r = (t.$vnode = n._parentVnode),\n            i = r && r.context;\n          (t.$slots = lt(n._renderChildren, i)),\n            (t.$scopedSlots = e),\n            (t._c = function (e, n, r, i) {\n              return Ht(t, e, n, r, i, !1);\n            }),\n            (t.$createElement = function (e, n, r, i) {\n              return Ht(t, e, n, r, i, !0);\n            });\n          var o = r && r.data;\n          xe(t, \"$attrs\", (o && o.attrs) || e, null, !0), xe(t, \"$listeners\", n._parentListeners || e, null, !0);\n        })(n),\n        Qt(n, \"beforeCreate\"),\n        (function (e) {\n          var t = ut(e.$options.inject, e);\n          t &&\n            ($e(!1),\n            Object.keys(t).forEach(function (n) {\n              xe(e, n, t[n]);\n            }),\n            $e(!0));\n        })(n),\n        hn(n),\n        (function (e) {\n          var t = e.$options.provide;\n          t && (e._provided = \"function\" == typeof t ? t.call(e) : t);\n        })(n),\n        Qt(n, \"created\"),\n        n.$options.el && n.$mount(n.$options.el);\n    };\n  })(Cn),\n    (function (e) {\n      var t = {\n          get: function () {\n            return this._data;\n          },\n        },\n        n = {\n          get: function () {\n            return this._props;\n          },\n        };\n      Object.defineProperty(e.prototype, \"$data\", t),\n        Object.defineProperty(e.prototype, \"$props\", n),\n        (e.prototype.$set = ke),\n        (e.prototype.$delete = Ae),\n        (e.prototype.$watch = function (e, t, n) {\n          if (s(t)) return bn(this, e, t, n);\n          (n = n || {}).user = !0;\n          var r = new pn(this, e, t, n);\n          if (n.immediate) {\n            var i = 'callback for immediate watcher \"' + r.expression + '\"';\n            le(), Be(t, this, [r.value], this, i), fe();\n          }\n          return function () {\n            r.teardown();\n          };\n        });\n    })(Cn),\n    (function (e) {\n      var t = /^hook:/;\n      (e.prototype.$on = function (e, n) {\n        var r = this;\n        if (Array.isArray(e)) for (var i = 0, o = e.length; i < o; i++) r.$on(e[i], n);\n        else (r._events[e] || (r._events[e] = [])).push(n), t.test(e) && (r._hasHookEvent = !0);\n        return r;\n      }),\n        (e.prototype.$once = function (e, t) {\n          var n = this;\n          function r() {\n            n.$off(e, r), t.apply(n, arguments);\n          }\n          return (r.fn = t), n.$on(e, r), n;\n        }),\n        (e.prototype.$off = function (e, t) {\n          var n = this;\n          if (!arguments.length) return (n._events = Object.create(null)), n;\n          if (Array.isArray(e)) {\n            for (var r = 0, i = e.length; r < i; r++) n.$off(e[r], t);\n            return n;\n          }\n          var o,\n            a = n._events[e];\n          if (!a) return n;\n          if (!t) return (n._events[e] = null), n;\n          for (var s = a.length; s--; )\n            if ((o = a[s]) === t || o.fn === t) {\n              a.splice(s, 1);\n              break;\n            }\n          return n;\n        }),\n        (e.prototype.$emit = function (e) {\n          var t = this._events[e];\n          if (t) {\n            t = t.length > 1 ? k(t) : t;\n            for (var n = k(arguments, 1), r = 'event handler for \"' + e + '\"', i = 0, o = t.length; i < o; i++) Be(t[i], this, n, this, r);\n          }\n          return this;\n        });\n    })(Cn),\n    (function (e) {\n      (e.prototype._update = function (e, t) {\n        var n = this,\n          r = n.$el,\n          i = n._vnode,\n          o = Gt(n);\n        (n._vnode = e), (n.$el = i ? n.__patch__(i, e) : n.__patch__(n.$el, e, t, !1)), o(), r && (r.__vue__ = null), n.$el && (n.$el.__vue__ = n), n.$vnode && n.$parent && n.$vnode === n.$parent._vnode && (n.$parent.$el = n.$el);\n      }),\n        (e.prototype.$forceUpdate = function () {\n          this._watcher && this._watcher.update();\n        }),\n        (e.prototype.$destroy = function () {\n          var e = this;\n          if (!e._isBeingDestroyed) {\n            Qt(e, \"beforeDestroy\"), (e._isBeingDestroyed = !0);\n            var t = e.$parent;\n            !t || t._isBeingDestroyed || e.$options.abstract || h(t.$children, e), e._watcher && e._watcher.teardown();\n            for (var n = e._watchers.length; n--; ) e._watchers[n].teardown();\n            e._data.__ob__ && e._data.__ob__.vmCount--, (e._isDestroyed = !0), e.__patch__(e._vnode, null), Qt(e, \"destroyed\"), e.$off(), e.$el && (e.$el.__vue__ = null), e.$vnode && (e.$vnode.parent = null);\n          }\n        });\n    })(Cn),\n    (function (e) {\n      Nt(e.prototype),\n        (e.prototype.$nextTick = function (e) {\n          return Qe(e, this);\n        }),\n        (e.prototype._render = function () {\n          var e,\n            t = this,\n            n = t.$options,\n            r = n.render,\n            i = n._parentVnode;\n          i && (t.$scopedSlots = dt(i.data.scopedSlots, t.$slots, t.$scopedSlots)), (t.$vnode = i);\n          try {\n            (Ut = t), (e = r.call(t._renderProxy, t.$createElement));\n          } catch (n) {\n            He(n, t, \"render\"), (e = t._vnode);\n          } finally {\n            Ut = null;\n          }\n          return Array.isArray(e) && 1 === e.length && (e = e[0]), e instanceof pe || (e = ve()), (e.parent = i), e;\n        });\n    })(Cn);\n  var Tn = [String, RegExp, Array],\n    Nn = {\n      KeepAlive: {\n        name: \"keep-alive\",\n        abstract: !0,\n        props: { include: Tn, exclude: Tn, max: [String, Number] },\n        methods: {\n          cacheVNode: function () {\n            var e = this.cache,\n              t = this.keys,\n              n = this.vnodeToCache,\n              r = this.keyToCache;\n            if (n) {\n              var i = n.tag,\n                o = n.componentInstance,\n                a = n.componentOptions;\n              (e[r] = { name: kn(a), tag: i, componentInstance: o }), t.push(r), this.max && t.length > parseInt(this.max) && Sn(e, t[0], t, this._vnode), (this.vnodeToCache = null);\n            }\n          },\n        },\n        created: function () {\n          (this.cache = Object.create(null)), (this.keys = []);\n        },\n        destroyed: function () {\n          for (var e in this.cache) Sn(this.cache, e, this.keys);\n        },\n        mounted: function () {\n          var e = this;\n          this.cacheVNode(),\n            this.$watch(\"include\", function (t) {\n              On(e, function (e) {\n                return An(t, e);\n              });\n            }),\n            this.$watch(\"exclude\", function (t) {\n              On(e, function (e) {\n                return !An(t, e);\n              });\n            });\n        },\n        updated: function () {\n          this.cacheVNode();\n        },\n        render: function () {\n          var e = this.$slots.default,\n            t = zt(e),\n            n = t && t.componentOptions;\n          if (n) {\n            var r = kn(n),\n              i = this.include,\n              o = this.exclude;\n            if ((i && (!r || !An(i, r))) || (o && r && An(o, r))) return t;\n            var a = this.cache,\n              s = this.keys,\n              c = null == t.key ? n.Ctor.cid + (n.tag ? \"::\" + n.tag : \"\") : t.key;\n            a[c] ? ((t.componentInstance = a[c].componentInstance), h(s, c), s.push(c)) : ((this.vnodeToCache = t), (this.keyToCache = c)), (t.data.keepAlive = !0);\n          }\n          return t || (e && e[0]);\n        },\n      },\n    };\n  !(function (e) {\n    var t = {\n      get: function () {\n        return F;\n      },\n    };\n    Object.defineProperty(e, \"config\", t),\n      (e.util = { warn: ae, extend: A, mergeOptions: De, defineReactive: xe }),\n      (e.set = ke),\n      (e.delete = Ae),\n      (e.nextTick = Qe),\n      (e.observable = function (e) {\n        return Ce(e), e;\n      }),\n      (e.options = Object.create(null)),\n      I.forEach(function (t) {\n        e.options[t + \"s\"] = Object.create(null);\n      }),\n      (e.options._base = e),\n      A(e.options.components, Nn),\n      (function (e) {\n        e.use = function (e) {\n          var t = this._installedPlugins || (this._installedPlugins = []);\n          if (t.indexOf(e) > -1) return this;\n          var n = k(arguments, 1);\n          return n.unshift(this), \"function\" == typeof e.install ? e.install.apply(e, n) : \"function\" == typeof e && e.apply(null, n), t.push(e), this;\n        };\n      })(e),\n      (function (e) {\n        e.mixin = function (e) {\n          return (this.options = De(this.options, e)), this;\n        };\n      })(e),\n      xn(e),\n      (function (e) {\n        I.forEach(function (t) {\n          e[t] = function (e, n) {\n            return n ? (\"component\" === t && s(n) && ((n.name = n.name || e), (n = this.options._base.extend(n))), \"directive\" === t && \"function\" == typeof n && (n = { bind: n, update: n }), (this.options[t + \"s\"][e] = n), n) : this.options[t + \"s\"][e];\n          };\n        });\n      })(e);\n  })(Cn),\n    Object.defineProperty(Cn.prototype, \"$isServer\", { get: te }),\n    Object.defineProperty(Cn.prototype, \"$ssrContext\", {\n      get: function () {\n        return this.$vnode && this.$vnode.ssrContext;\n      },\n    }),\n    Object.defineProperty(Cn, \"FunctionalRenderContext\", { value: Et }),\n    (Cn.version = \"2.6.14\");\n  var En = p(\"style,class\"),\n    jn = p(\"input,textarea,option,select,progress\"),\n    Dn = function (e, t, n) {\n      return (\"value\" === n && jn(e) && \"button\" !== t) || (\"selected\" === n && \"option\" === e) || (\"checked\" === n && \"input\" === e) || (\"muted\" === n && \"video\" === e);\n    },\n    Ln = p(\"contenteditable,draggable,spellcheck\"),\n    In = p(\"events,caret,typing,plaintext-only\"),\n    Mn = function (e, t) {\n      return Bn(t) || \"false\" === t ? \"false\" : \"contenteditable\" === e && In(t) ? t : \"true\";\n    },\n    Fn = p(\"allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible\"),\n    Pn = \"http://www.w3.org/1999/xlink\",\n    Rn = function (e) {\n      return \":\" === e.charAt(5) && \"xlink\" === e.slice(0, 5);\n    },\n    Hn = function (e) {\n      return Rn(e) ? e.slice(6, e.length) : \"\";\n    },\n    Bn = function (e) {\n      return null == e || !1 === e;\n    };\n  function Un(e) {\n    for (var t = e.data, r = e, i = e; n(i.componentInstance); ) (i = i.componentInstance._vnode) && i.data && (t = Vn(i.data, t));\n    for (; n((r = r.parent)); ) r && r.data && (t = Vn(t, r.data));\n    return (function (e, t) {\n      if (n(e) || n(t)) return zn(e, Kn(t));\n      return \"\";\n    })(t.staticClass, t.class);\n  }\n  function Vn(e, t) {\n    return {\n      staticClass: zn(e.staticClass, t.staticClass),\n      class: n(e.class) ? [e.class, t.class] : t.class,\n    };\n  }\n  function zn(e, t) {\n    return e ? (t ? e + \" \" + t : e) : t || \"\";\n  }\n  function Kn(e) {\n    return Array.isArray(e)\n      ? (function (e) {\n          for (var t, r = \"\", i = 0, o = e.length; i < o; i++) n((t = Kn(e[i]))) && \"\" !== t && (r && (r += \" \"), (r += t));\n          return r;\n        })(e)\n      : o(e)\n        ? (function (e) {\n            var t = \"\";\n            for (var n in e) e[n] && (t && (t += \" \"), (t += n));\n            return t;\n          })(e)\n        : \"string\" == typeof e\n          ? e\n          : \"\";\n  }\n  var Jn = {\n      svg: \"http://www.w3.org/2000/svg\",\n      math: \"http://www.w3.org/1998/Math/MathML\",\n    },\n    qn = p(\n      \"html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template,blockquote,iframe,tfoot\",\n    ),\n    Wn = p(\"svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,foreignobject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view\", !0),\n    Zn = function (e) {\n      return qn(e) || Wn(e);\n    };\n  function Gn(e) {\n    return Wn(e) ? \"svg\" : \"math\" === e ? \"math\" : void 0;\n  }\n  var Xn = Object.create(null);\n  var Yn = p(\"text,number,password,search,email,tel,url\");\n  function Qn(e) {\n    if (\"string\" == typeof e) {\n      var t = document.querySelector(e);\n      return t || document.createElement(\"div\");\n    }\n    return e;\n  }\n  var er = Object.freeze({\n      createElement: function (e, t) {\n        var n = document.createElement(e);\n        return \"select\" !== e ? n : (t.data && t.data.attrs && void 0 !== t.data.attrs.multiple && n.setAttribute(\"multiple\", \"multiple\"), n);\n      },\n      createElementNS: function (e, t) {\n        return document.createElementNS(Jn[e], t);\n      },\n      createTextNode: function (e) {\n        return document.createTextNode(e);\n      },\n      createComment: function (e) {\n        return document.createComment(e);\n      },\n      insertBefore: function (e, t, n) {\n        e.insertBefore(t, n);\n      },\n      removeChild: function (e, t) {\n        e.removeChild(t);\n      },\n      appendChild: function (e, t) {\n        e.appendChild(t);\n      },\n      parentNode: function (e) {\n        return e.parentNode;\n      },\n      nextSibling: function (e) {\n        return e.nextSibling;\n      },\n      tagName: function (e) {\n        return e.tagName;\n      },\n      setTextContent: function (e, t) {\n        e.textContent = t;\n      },\n      setStyleScope: function (e, t) {\n        e.setAttribute(t, \"\");\n      },\n    }),\n    tr = {\n      create: function (e, t) {\n        nr(t);\n      },\n      update: function (e, t) {\n        e.data.ref !== t.data.ref && (nr(e, !0), nr(t));\n      },\n      destroy: function (e) {\n        nr(e, !0);\n      },\n    };\n  function nr(e, t) {\n    var r = e.data.ref;\n    if (n(r)) {\n      var i = e.context,\n        o = e.componentInstance || e.elm,\n        a = i.$refs;\n      t ? (Array.isArray(a[r]) ? h(a[r], o) : a[r] === o && (a[r] = void 0)) : e.data.refInFor ? (Array.isArray(a[r]) ? a[r].indexOf(o) < 0 && a[r].push(o) : (a[r] = [o])) : (a[r] = o);\n    }\n  }\n  var rr = new pe(\"\", {}, []),\n    ir = [\"create\", \"activate\", \"update\", \"remove\", \"destroy\"];\n  function or(e, i) {\n    return (\n      e.key === i.key &&\n      e.asyncFactory === i.asyncFactory &&\n      ((e.tag === i.tag &&\n        e.isComment === i.isComment &&\n        n(e.data) === n(i.data) &&\n        (function (e, t) {\n          if (\"input\" !== e.tag) return !0;\n          var r,\n            i = n((r = e.data)) && n((r = r.attrs)) && r.type,\n            o = n((r = t.data)) && n((r = r.attrs)) && r.type;\n          return i === o || (Yn(i) && Yn(o));\n        })(e, i)) ||\n        (r(e.isAsyncPlaceholder) && t(i.asyncFactory.error)))\n    );\n  }\n  function ar(e, t, r) {\n    var i,\n      o,\n      a = {};\n    for (i = t; i <= r; ++i) n((o = e[i].key)) && (a[o] = i);\n    return a;\n  }\n  var sr = {\n    create: cr,\n    update: cr,\n    destroy: function (e) {\n      cr(e, rr);\n    },\n  };\n  function cr(e, t) {\n    (e.data.directives || t.data.directives) &&\n      (function (e, t) {\n        var n,\n          r,\n          i,\n          o = e === rr,\n          a = t === rr,\n          s = lr(e.data.directives, e.context),\n          c = lr(t.data.directives, t.context),\n          u = [],\n          l = [];\n        for (n in c) (r = s[n]), (i = c[n]), r ? ((i.oldValue = r.value), (i.oldArg = r.arg), pr(i, \"update\", t, e), i.def && i.def.componentUpdated && l.push(i)) : (pr(i, \"bind\", t, e), i.def && i.def.inserted && u.push(i));\n        if (u.length) {\n          var f = function () {\n            for (var n = 0; n < u.length; n++) pr(u[n], \"inserted\", t, e);\n          };\n          o ? ot(t, \"insert\", f) : f();\n        }\n        l.length &&\n          ot(t, \"postpatch\", function () {\n            for (var n = 0; n < l.length; n++) pr(l[n], \"componentUpdated\", t, e);\n          });\n        if (!o) for (n in s) c[n] || pr(s[n], \"unbind\", e, e, a);\n      })(e, t);\n  }\n  var ur = Object.create(null);\n  function lr(e, t) {\n    var n,\n      r,\n      i = Object.create(null);\n    if (!e) return i;\n    for (n = 0; n < e.length; n++) (r = e[n]).modifiers || (r.modifiers = ur), (i[fr(r)] = r), (r.def = Le(t.$options, \"directives\", r.name));\n    return i;\n  }\n  function fr(e) {\n    return e.rawName || e.name + \".\" + Object.keys(e.modifiers || {}).join(\".\");\n  }\n  function pr(e, t, n, r, i) {\n    var o = e.def && e.def[t];\n    if (o)\n      try {\n        o(n.elm, e, n, r, i);\n      } catch (r) {\n        He(r, n.context, \"directive \" + e.name + \" \" + t + \" hook\");\n      }\n  }\n  var dr = [tr, sr];\n  function vr(e, r) {\n    var i = r.componentOptions;\n    if (!((n(i) && !1 === i.Ctor.options.inheritAttrs) || (t(e.data.attrs) && t(r.data.attrs)))) {\n      var o,\n        a,\n        s = r.elm,\n        c = e.data.attrs || {},\n        u = r.data.attrs || {};\n      for (o in (n(u.__ob__) && (u = r.data.attrs = A({}, u)), u)) (a = u[o]), c[o] !== a && hr(s, o, a, r.data.pre);\n      for (o in ((q || Z) && u.value !== c.value && hr(s, \"value\", u.value), c)) t(u[o]) && (Rn(o) ? s.removeAttributeNS(Pn, Hn(o)) : Ln(o) || s.removeAttribute(o));\n    }\n  }\n  function hr(e, t, n, r) {\n    r || e.tagName.indexOf(\"-\") > -1 ? mr(e, t, n) : Fn(t) ? (Bn(n) ? e.removeAttribute(t) : ((n = \"allowfullscreen\" === t && \"EMBED\" === e.tagName ? \"true\" : t), e.setAttribute(t, n))) : Ln(t) ? e.setAttribute(t, Mn(t, n)) : Rn(t) ? (Bn(n) ? e.removeAttributeNS(Pn, Hn(t)) : e.setAttributeNS(Pn, t, n)) : mr(e, t, n);\n  }\n  function mr(e, t, n) {\n    if (Bn(n)) e.removeAttribute(t);\n    else {\n      if (q && !W && \"TEXTAREA\" === e.tagName && \"placeholder\" === t && \"\" !== n && !e.__ieph) {\n        var r = function (t) {\n          t.stopImmediatePropagation(), e.removeEventListener(\"input\", r);\n        };\n        e.addEventListener(\"input\", r), (e.__ieph = !0);\n      }\n      e.setAttribute(t, n);\n    }\n  }\n  var yr = { create: vr, update: vr };\n  function gr(e, r) {\n    var i = r.elm,\n      o = r.data,\n      a = e.data;\n    if (!(t(o.staticClass) && t(o.class) && (t(a) || (t(a.staticClass) && t(a.class))))) {\n      var s = Un(r),\n        c = i._transitionClasses;\n      n(c) && (s = zn(s, Kn(c))), s !== i._prevClass && (i.setAttribute(\"class\", s), (i._prevClass = s));\n    }\n  }\n  var _r,\n    br,\n    $r,\n    wr,\n    Cr,\n    xr,\n    kr = { create: gr, update: gr },\n    Ar = /[\\w).+\\-_$\\]]/;\n  function Or(e) {\n    var t,\n      n,\n      r,\n      i,\n      o,\n      a = !1,\n      s = !1,\n      c = !1,\n      u = !1,\n      l = 0,\n      f = 0,\n      p = 0,\n      d = 0;\n    for (r = 0; r < e.length; r++)\n      if (((n = t), (t = e.charCodeAt(r)), a)) 39 === t && 92 !== n && (a = !1);\n      else if (s) 34 === t && 92 !== n && (s = !1);\n      else if (c) 96 === t && 92 !== n && (c = !1);\n      else if (u) 47 === t && 92 !== n && (u = !1);\n      else if (124 !== t || 124 === e.charCodeAt(r + 1) || 124 === e.charCodeAt(r - 1) || l || f || p) {\n        switch (t) {\n          case 34:\n            s = !0;\n            break;\n          case 39:\n            a = !0;\n            break;\n          case 96:\n            c = !0;\n            break;\n          case 40:\n            p++;\n            break;\n          case 41:\n            p--;\n            break;\n          case 91:\n            f++;\n            break;\n          case 93:\n            f--;\n            break;\n          case 123:\n            l++;\n            break;\n          case 125:\n            l--;\n        }\n        if (47 === t) {\n          for (var v = r - 1, h = void 0; v >= 0 && \" \" === (h = e.charAt(v)); v--);\n          (h && Ar.test(h)) || (u = !0);\n        }\n      } else void 0 === i ? ((d = r + 1), (i = e.slice(0, r).trim())) : m();\n    function m() {\n      (o || (o = [])).push(e.slice(d, r).trim()), (d = r + 1);\n    }\n    if ((void 0 === i ? (i = e.slice(0, r).trim()) : 0 !== d && m(), o)) for (r = 0; r < o.length; r++) i = Sr(i, o[r]);\n    return i;\n  }\n  function Sr(e, t) {\n    var n = t.indexOf(\"(\");\n    if (n < 0) return '_f(\"' + t + '\")(' + e + \")\";\n    var r = t.slice(0, n),\n      i = t.slice(n + 1);\n    return '_f(\"' + r + '\")(' + e + (\")\" !== i ? \",\" + i : i);\n  }\n  function Tr(e, t) {\n    console.error(\"[Vue compiler]: \" + e);\n  }\n  function Nr(e, t) {\n    return e\n      ? e\n          .map(function (e) {\n            return e[t];\n          })\n          .filter(function (e) {\n            return e;\n          })\n      : [];\n  }\n  function Er(e, t, n, r, i) {\n    (e.props || (e.props = [])).push(Hr({ name: t, value: n, dynamic: i }, r)), (e.plain = !1);\n  }\n  function jr(e, t, n, r, i) {\n    (i ? e.dynamicAttrs || (e.dynamicAttrs = []) : e.attrs || (e.attrs = [])).push(Hr({ name: t, value: n, dynamic: i }, r)), (e.plain = !1);\n  }\n  function Dr(e, t, n, r) {\n    (e.attrsMap[t] = n), e.attrsList.push(Hr({ name: t, value: n }, r));\n  }\n  function Lr(e, t, n, r, i, o, a, s) {\n    (e.directives || (e.directives = [])).push(\n      Hr(\n        {\n          name: t,\n          rawName: n,\n          value: r,\n          arg: i,\n          isDynamicArg: o,\n          modifiers: a,\n        },\n        s,\n      ),\n    ),\n      (e.plain = !1);\n  }\n  function Ir(e, t, n) {\n    return n ? \"_p(\" + t + ',\"' + e + '\")' : e + t;\n  }\n  function Mr(t, n, r, i, o, a, s, c) {\n    var u;\n    (i = i || e).right ? (c ? (n = \"(\" + n + \")==='click'?'contextmenu':(\" + n + \")\") : \"click\" === n && ((n = \"contextmenu\"), delete i.right)) : i.middle && (c ? (n = \"(\" + n + \")==='click'?'mouseup':(\" + n + \")\") : \"click\" === n && (n = \"mouseup\")), i.capture && (delete i.capture, (n = Ir(\"!\", n, c))), i.once && (delete i.once, (n = Ir(\"~\", n, c))), i.passive && (delete i.passive, (n = Ir(\"&\", n, c))), i.native ? (delete i.native, (u = t.nativeEvents || (t.nativeEvents = {}))) : (u = t.events || (t.events = {}));\n    var l = Hr({ value: r.trim(), dynamic: c }, s);\n    i !== e && (l.modifiers = i);\n    var f = u[n];\n    Array.isArray(f) ? (o ? f.unshift(l) : f.push(l)) : (u[n] = f ? (o ? [l, f] : [f, l]) : l), (t.plain = !1);\n  }\n  function Fr(e, t, n) {\n    var r = Pr(e, \":\" + t) || Pr(e, \"v-bind:\" + t);\n    if (null != r) return Or(r);\n    if (!1 !== n) {\n      var i = Pr(e, t);\n      if (null != i) return JSON.stringify(i);\n    }\n  }\n  function Pr(e, t, n) {\n    var r;\n    if (null != (r = e.attrsMap[t]))\n      for (var i = e.attrsList, o = 0, a = i.length; o < a; o++)\n        if (i[o].name === t) {\n          i.splice(o, 1);\n          break;\n        }\n    return n && delete e.attrsMap[t], r;\n  }\n  function Rr(e, t) {\n    for (var n = e.attrsList, r = 0, i = n.length; r < i; r++) {\n      var o = n[r];\n      if (t.test(o.name)) return n.splice(r, 1), o;\n    }\n  }\n  function Hr(e, t) {\n    return t && (null != t.start && (e.start = t.start), null != t.end && (e.end = t.end)), e;\n  }\n  function Br(e, t, n) {\n    var r = n || {},\n      i = r.number,\n      o = \"$$v\";\n    r.trim && (o = \"(typeof $$v === 'string'? $$v.trim(): $$v)\"), i && (o = \"_n(\" + o + \")\");\n    var a = Ur(t, o);\n    e.model = {\n      value: \"(\" + t + \")\",\n      expression: JSON.stringify(t),\n      callback: \"function ($$v) {\" + a + \"}\",\n    };\n  }\n  function Ur(e, t) {\n    var n = (function (e) {\n      if (((e = e.trim()), (_r = e.length), e.indexOf(\"[\") < 0 || e.lastIndexOf(\"]\") < _r - 1)) return (wr = e.lastIndexOf(\".\")) > -1 ? { exp: e.slice(0, wr), key: '\"' + e.slice(wr + 1) + '\"' } : { exp: e, key: null };\n      (br = e), (wr = Cr = xr = 0);\n      for (; !zr(); ) Kr(($r = Vr())) ? qr($r) : 91 === $r && Jr($r);\n      return { exp: e.slice(0, Cr), key: e.slice(Cr + 1, xr) };\n    })(e);\n    return null === n.key ? e + \"=\" + t : \"$set(\" + n.exp + \", \" + n.key + \", \" + t + \")\";\n  }\n  function Vr() {\n    return br.charCodeAt(++wr);\n  }\n  function zr() {\n    return wr >= _r;\n  }\n  function Kr(e) {\n    return 34 === e || 39 === e;\n  }\n  function Jr(e) {\n    var t = 1;\n    for (Cr = wr; !zr(); )\n      if (Kr((e = Vr()))) qr(e);\n      else if ((91 === e && t++, 93 === e && t--, 0 === t)) {\n        xr = wr;\n        break;\n      }\n  }\n  function qr(e) {\n    for (var t = e; !zr() && (e = Vr()) !== t; );\n  }\n  var Wr,\n    Zr = \"__r\",\n    Gr = \"__c\";\n  function Xr(e, t, n) {\n    var r = Wr;\n    return function i() {\n      null !== t.apply(null, arguments) && ei(e, i, n, r);\n    };\n  }\n  var Yr = Ke && !(X && Number(X[1]) <= 53);\n  function Qr(e, t, n, r) {\n    if (Yr) {\n      var i = sn,\n        o = t;\n      t = o._wrapper = function (e) {\n        if (e.target === e.currentTarget || e.timeStamp >= i || e.timeStamp <= 0 || e.target.ownerDocument !== document) return o.apply(this, arguments);\n      };\n    }\n    Wr.addEventListener(e, t, Q ? { capture: n, passive: r } : n);\n  }\n  function ei(e, t, n, r) {\n    (r || Wr).removeEventListener(e, t._wrapper || t, n);\n  }\n  function ti(e, r) {\n    if (!t(e.data.on) || !t(r.data.on)) {\n      var i = r.data.on || {},\n        o = e.data.on || {};\n      (Wr = r.elm),\n        (function (e) {\n          if (n(e[Zr])) {\n            var t = q ? \"change\" : \"input\";\n            (e[t] = [].concat(e[Zr], e[t] || [])), delete e[Zr];\n          }\n          n(e[Gr]) && ((e.change = [].concat(e[Gr], e.change || [])), delete e[Gr]);\n        })(i),\n        it(i, o, Qr, ei, Xr, r.context),\n        (Wr = void 0);\n    }\n  }\n  var ni,\n    ri = { create: ti, update: ti };\n  function ii(e, r) {\n    if (!t(e.data.domProps) || !t(r.data.domProps)) {\n      var i,\n        o,\n        a = r.elm,\n        s = e.data.domProps || {},\n        c = r.data.domProps || {};\n      for (i in (n(c.__ob__) && (c = r.data.domProps = A({}, c)), s)) i in c || (a[i] = \"\");\n      for (i in c) {\n        if (((o = c[i]), \"textContent\" === i || \"innerHTML\" === i)) {\n          if ((r.children && (r.children.length = 0), o === s[i])) continue;\n          1 === a.childNodes.length && a.removeChild(a.childNodes[0]);\n        }\n        if (\"value\" === i && \"PROGRESS\" !== a.tagName) {\n          a._value = o;\n          var u = t(o) ? \"\" : String(o);\n          oi(a, u) && (a.value = u);\n        } else if (\"innerHTML\" === i && Wn(a.tagName) && t(a.innerHTML)) {\n          (ni = ni || document.createElement(\"div\")).innerHTML = \"<svg>\" + o + \"</svg>\";\n          for (var l = ni.firstChild; a.firstChild; ) a.removeChild(a.firstChild);\n          for (; l.firstChild; ) a.appendChild(l.firstChild);\n        } else if (o !== s[i])\n          try {\n            a[i] = o;\n          } catch (e) {}\n      }\n    }\n  }\n  function oi(e, t) {\n    return (\n      !e.composing &&\n      (\"OPTION\" === e.tagName ||\n        (function (e, t) {\n          var n = !0;\n          try {\n            n = document.activeElement !== e;\n          } catch (e) {}\n          return n && e.value !== t;\n        })(e, t) ||\n        (function (e, t) {\n          var r = e.value,\n            i = e._vModifiers;\n          if (n(i)) {\n            if (i.number) return f(r) !== f(t);\n            if (i.trim) return r.trim() !== t.trim();\n          }\n          return r !== t;\n        })(e, t))\n    );\n  }\n  var ai = { create: ii, update: ii },\n    si = g(function (e) {\n      var t = {},\n        n = /:(.+)/;\n      return (\n        e.split(/;(?![^(]*\\))/g).forEach(function (e) {\n          if (e) {\n            var r = e.split(n);\n            r.length > 1 && (t[r[0].trim()] = r[1].trim());\n          }\n        }),\n        t\n      );\n    });\n  function ci(e) {\n    var t = ui(e.style);\n    return e.staticStyle ? A(e.staticStyle, t) : t;\n  }\n  function ui(e) {\n    return Array.isArray(e) ? O(e) : \"string\" == typeof e ? si(e) : e;\n  }\n  var li,\n    fi = /^--/,\n    pi = /\\s*!important$/,\n    di = function (e, t, n) {\n      if (fi.test(t)) e.style.setProperty(t, n);\n      else if (pi.test(n)) e.style.setProperty(C(t), n.replace(pi, \"\"), \"important\");\n      else {\n        var r = hi(t);\n        if (Array.isArray(n)) for (var i = 0, o = n.length; i < o; i++) e.style[r] = n[i];\n        else e.style[r] = n;\n      }\n    },\n    vi = [\"Webkit\", \"Moz\", \"ms\"],\n    hi = g(function (e) {\n      if (((li = li || document.createElement(\"div\").style), \"filter\" !== (e = b(e)) && e in li)) return e;\n      for (var t = e.charAt(0).toUpperCase() + e.slice(1), n = 0; n < vi.length; n++) {\n        var r = vi[n] + t;\n        if (r in li) return r;\n      }\n    });\n  function mi(e, r) {\n    var i = r.data,\n      o = e.data;\n    if (!(t(i.staticStyle) && t(i.style) && t(o.staticStyle) && t(o.style))) {\n      var a,\n        s,\n        c = r.elm,\n        u = o.staticStyle,\n        l = o.normalizedStyle || o.style || {},\n        f = u || l,\n        p = ui(r.data.style) || {};\n      r.data.normalizedStyle = n(p.__ob__) ? A({}, p) : p;\n      var d = (function (e, t) {\n        var n,\n          r = {};\n        if (t) for (var i = e; i.componentInstance; ) (i = i.componentInstance._vnode) && i.data && (n = ci(i.data)) && A(r, n);\n        (n = ci(e.data)) && A(r, n);\n        for (var o = e; (o = o.parent); ) o.data && (n = ci(o.data)) && A(r, n);\n        return r;\n      })(r, !0);\n      for (s in f) t(d[s]) && di(c, s, \"\");\n      for (s in d) (a = d[s]) !== f[s] && di(c, s, null == a ? \"\" : a);\n    }\n  }\n  var yi = { create: mi, update: mi },\n    gi = /\\s+/;\n  function _i(e, t) {\n    if (t && (t = t.trim()))\n      if (e.classList)\n        t.indexOf(\" \") > -1\n          ? t.split(gi).forEach(function (t) {\n              return e.classList.add(t);\n            })\n          : e.classList.add(t);\n      else {\n        var n = \" \" + (e.getAttribute(\"class\") || \"\") + \" \";\n        n.indexOf(\" \" + t + \" \") < 0 && e.setAttribute(\"class\", (n + t).trim());\n      }\n  }\n  function bi(e, t) {\n    if (t && (t = t.trim()))\n      if (e.classList)\n        t.indexOf(\" \") > -1\n          ? t.split(gi).forEach(function (t) {\n              return e.classList.remove(t);\n            })\n          : e.classList.remove(t),\n          e.classList.length || e.removeAttribute(\"class\");\n      else {\n        for (var n = \" \" + (e.getAttribute(\"class\") || \"\") + \" \", r = \" \" + t + \" \"; n.indexOf(r) >= 0; ) n = n.replace(r, \" \");\n        (n = n.trim()) ? e.setAttribute(\"class\", n) : e.removeAttribute(\"class\");\n      }\n  }\n  function $i(e) {\n    if (e) {\n      if (\"object\" == typeof e) {\n        var t = {};\n        return !1 !== e.css && A(t, wi(e.name || \"v\")), A(t, e), t;\n      }\n      return \"string\" == typeof e ? wi(e) : void 0;\n    }\n  }\n  var wi = g(function (e) {\n      return {\n        enterClass: e + \"-enter\",\n        enterToClass: e + \"-enter-to\",\n        enterActiveClass: e + \"-enter-active\",\n        leaveClass: e + \"-leave\",\n        leaveToClass: e + \"-leave-to\",\n        leaveActiveClass: e + \"-leave-active\",\n      };\n    }),\n    Ci = V && !W,\n    xi = \"transition\",\n    ki = \"animation\",\n    Ai = \"transition\",\n    Oi = \"transitionend\",\n    Si = \"animation\",\n    Ti = \"animationend\";\n  Ci && (void 0 === window.ontransitionend && void 0 !== window.onwebkittransitionend && ((Ai = \"WebkitTransition\"), (Oi = \"webkitTransitionEnd\")), void 0 === window.onanimationend && void 0 !== window.onwebkitanimationend && ((Si = \"WebkitAnimation\"), (Ti = \"webkitAnimationEnd\")));\n  var Ni = V\n    ? window.requestAnimationFrame\n      ? window.requestAnimationFrame.bind(window)\n      : setTimeout\n    : function (e) {\n        return e();\n      };\n  function Ei(e) {\n    Ni(function () {\n      Ni(e);\n    });\n  }\n  function ji(e, t) {\n    var n = e._transitionClasses || (e._transitionClasses = []);\n    n.indexOf(t) < 0 && (n.push(t), _i(e, t));\n  }\n  function Di(e, t) {\n    e._transitionClasses && h(e._transitionClasses, t), bi(e, t);\n  }\n  function Li(e, t, n) {\n    var r = Mi(e, t),\n      i = r.type,\n      o = r.timeout,\n      a = r.propCount;\n    if (!i) return n();\n    var s = i === xi ? Oi : Ti,\n      c = 0,\n      u = function () {\n        e.removeEventListener(s, l), n();\n      },\n      l = function (t) {\n        t.target === e && ++c >= a && u();\n      };\n    setTimeout(function () {\n      c < a && u();\n    }, o + 1),\n      e.addEventListener(s, l);\n  }\n  var Ii = /\\b(transform|all)(,|$)/;\n  function Mi(e, t) {\n    var n,\n      r = window.getComputedStyle(e),\n      i = (r[Ai + \"Delay\"] || \"\").split(\", \"),\n      o = (r[Ai + \"Duration\"] || \"\").split(\", \"),\n      a = Fi(i, o),\n      s = (r[Si + \"Delay\"] || \"\").split(\", \"),\n      c = (r[Si + \"Duration\"] || \"\").split(\", \"),\n      u = Fi(s, c),\n      l = 0,\n      f = 0;\n    return (\n      t === xi ? a > 0 && ((n = xi), (l = a), (f = o.length)) : t === ki ? u > 0 && ((n = ki), (l = u), (f = c.length)) : (f = (n = (l = Math.max(a, u)) > 0 ? (a > u ? xi : ki) : null) ? (n === xi ? o.length : c.length) : 0),\n      {\n        type: n,\n        timeout: l,\n        propCount: f,\n        hasTransform: n === xi && Ii.test(r[Ai + \"Property\"]),\n      }\n    );\n  }\n  function Fi(e, t) {\n    for (; e.length < t.length; ) e = e.concat(e);\n    return Math.max.apply(\n      null,\n      t.map(function (t, n) {\n        return Pi(t) + Pi(e[n]);\n      }),\n    );\n  }\n  function Pi(e) {\n    return 1e3 * Number(e.slice(0, -1).replace(\",\", \".\"));\n  }\n  function Ri(e, r) {\n    var i = e.elm;\n    n(i._leaveCb) && ((i._leaveCb.cancelled = !0), i._leaveCb());\n    var a = $i(e.data.transition);\n    if (!t(a) && !n(i._enterCb) && 1 === i.nodeType) {\n      for (var s = a.css, c = a.type, u = a.enterClass, l = a.enterToClass, p = a.enterActiveClass, d = a.appearClass, v = a.appearToClass, h = a.appearActiveClass, m = a.beforeEnter, y = a.enter, g = a.afterEnter, _ = a.enterCancelled, b = a.beforeAppear, $ = a.appear, w = a.afterAppear, C = a.appearCancelled, x = a.duration, k = Zt, A = Zt.$vnode; A && A.parent; ) (k = A.context), (A = A.parent);\n      var O = !k._isMounted || !e.isRootInsert;\n      if (!O || $ || \"\" === $) {\n        var S = O && d ? d : u,\n          T = O && h ? h : p,\n          N = O && v ? v : l,\n          E = (O && b) || m,\n          j = O && \"function\" == typeof $ ? $ : y,\n          L = (O && w) || g,\n          I = (O && C) || _,\n          M = f(o(x) ? x.enter : x),\n          F = !1 !== s && !W,\n          P = Ui(j),\n          R = (i._enterCb = D(function () {\n            F && (Di(i, N), Di(i, T)), R.cancelled ? (F && Di(i, S), I && I(i)) : L && L(i), (i._enterCb = null);\n          }));\n        e.data.show ||\n          ot(e, \"insert\", function () {\n            var t = i.parentNode,\n              n = t && t._pending && t._pending[e.key];\n            n && n.tag === e.tag && n.elm._leaveCb && n.elm._leaveCb(), j && j(i, R);\n          }),\n          E && E(i),\n          F &&\n            (ji(i, S),\n            ji(i, T),\n            Ei(function () {\n              Di(i, S), R.cancelled || (ji(i, N), P || (Bi(M) ? setTimeout(R, M) : Li(i, c, R)));\n            })),\n          e.data.show && (r && r(), j && j(i, R)),\n          F || P || R();\n      }\n    }\n  }\n  function Hi(e, r) {\n    var i = e.elm;\n    n(i._enterCb) && ((i._enterCb.cancelled = !0), i._enterCb());\n    var a = $i(e.data.transition);\n    if (t(a) || 1 !== i.nodeType) return r();\n    if (!n(i._leaveCb)) {\n      var s = a.css,\n        c = a.type,\n        u = a.leaveClass,\n        l = a.leaveToClass,\n        p = a.leaveActiveClass,\n        d = a.beforeLeave,\n        v = a.leave,\n        h = a.afterLeave,\n        m = a.leaveCancelled,\n        y = a.delayLeave,\n        g = a.duration,\n        _ = !1 !== s && !W,\n        b = Ui(v),\n        $ = f(o(g) ? g.leave : g),\n        w = (i._leaveCb = D(function () {\n          i.parentNode && i.parentNode._pending && (i.parentNode._pending[e.key] = null), _ && (Di(i, l), Di(i, p)), w.cancelled ? (_ && Di(i, u), m && m(i)) : (r(), h && h(i)), (i._leaveCb = null);\n        }));\n      y ? y(C) : C();\n    }\n    function C() {\n      w.cancelled ||\n        (!e.data.show && i.parentNode && ((i.parentNode._pending || (i.parentNode._pending = {}))[e.key] = e),\n        d && d(i),\n        _ &&\n          (ji(i, u),\n          ji(i, p),\n          Ei(function () {\n            Di(i, u), w.cancelled || (ji(i, l), b || (Bi($) ? setTimeout(w, $) : Li(i, c, w)));\n          })),\n        v && v(i, w),\n        _ || b || w());\n    }\n  }\n  function Bi(e) {\n    return \"number\" == typeof e && !isNaN(e);\n  }\n  function Ui(e) {\n    if (t(e)) return !1;\n    var r = e.fns;\n    return n(r) ? Ui(Array.isArray(r) ? r[0] : r) : (e._length || e.length) > 1;\n  }\n  function Vi(e, t) {\n    !0 !== t.data.show && Ri(t);\n  }\n  var zi = (function (e) {\n    var o,\n      a,\n      s = {},\n      c = e.modules,\n      u = e.nodeOps;\n    for (o = 0; o < ir.length; ++o) for (s[ir[o]] = [], a = 0; a < c.length; ++a) n(c[a][ir[o]]) && s[ir[o]].push(c[a][ir[o]]);\n    function l(e) {\n      var t = u.parentNode(e);\n      n(t) && u.removeChild(t, e);\n    }\n    function f(e, t, i, o, a, c, l) {\n      if (\n        (n(e.elm) && n(c) && (e = c[l] = me(e)),\n        (e.isRootInsert = !a),\n        !(function (e, t, i, o) {\n          var a = e.data;\n          if (n(a)) {\n            var c = n(e.componentInstance) && a.keepAlive;\n            if ((n((a = a.hook)) && n((a = a.init)) && a(e, !1), n(e.componentInstance)))\n              return (\n                d(e, t),\n                v(i, e.elm, o),\n                r(c) &&\n                  (function (e, t, r, i) {\n                    for (var o, a = e; a.componentInstance; )\n                      if (((a = a.componentInstance._vnode), n((o = a.data)) && n((o = o.transition)))) {\n                        for (o = 0; o < s.activate.length; ++o) s.activate[o](rr, a);\n                        t.push(a);\n                        break;\n                      }\n                    v(r, e.elm, i);\n                  })(e, t, i, o),\n                !0\n              );\n          }\n        })(e, t, i, o))\n      ) {\n        var f = e.data,\n          p = e.children,\n          m = e.tag;\n        n(m) ? ((e.elm = e.ns ? u.createElementNS(e.ns, m) : u.createElement(m, e)), g(e), h(e, p, t), n(f) && y(e, t), v(i, e.elm, o)) : r(e.isComment) ? ((e.elm = u.createComment(e.text)), v(i, e.elm, o)) : ((e.elm = u.createTextNode(e.text)), v(i, e.elm, o));\n      }\n    }\n    function d(e, t) {\n      n(e.data.pendingInsert) && (t.push.apply(t, e.data.pendingInsert), (e.data.pendingInsert = null)), (e.elm = e.componentInstance.$el), m(e) ? (y(e, t), g(e)) : (nr(e), t.push(e));\n    }\n    function v(e, t, r) {\n      n(e) && (n(r) ? u.parentNode(r) === e && u.insertBefore(e, t, r) : u.appendChild(e, t));\n    }\n    function h(e, t, n) {\n      if (Array.isArray(t)) for (var r = 0; r < t.length; ++r) f(t[r], n, e.elm, null, !0, t, r);\n      else i(e.text) && u.appendChild(e.elm, u.createTextNode(String(e.text)));\n    }\n    function m(e) {\n      for (; e.componentInstance; ) e = e.componentInstance._vnode;\n      return n(e.tag);\n    }\n    function y(e, t) {\n      for (var r = 0; r < s.create.length; ++r) s.create[r](rr, e);\n      n((o = e.data.hook)) && (n(o.create) && o.create(rr, e), n(o.insert) && t.push(e));\n    }\n    function g(e) {\n      var t;\n      if (n((t = e.fnScopeId))) u.setStyleScope(e.elm, t);\n      else for (var r = e; r; ) n((t = r.context)) && n((t = t.$options._scopeId)) && u.setStyleScope(e.elm, t), (r = r.parent);\n      n((t = Zt)) && t !== e.context && t !== e.fnContext && n((t = t.$options._scopeId)) && u.setStyleScope(e.elm, t);\n    }\n    function _(e, t, n, r, i, o) {\n      for (; r <= i; ++r) f(n[r], o, e, t, !1, n, r);\n    }\n    function b(e) {\n      var t,\n        r,\n        i = e.data;\n      if (n(i)) for (n((t = i.hook)) && n((t = t.destroy)) && t(e), t = 0; t < s.destroy.length; ++t) s.destroy[t](e);\n      if (n((t = e.children))) for (r = 0; r < e.children.length; ++r) b(e.children[r]);\n    }\n    function $(e, t, r) {\n      for (; t <= r; ++t) {\n        var i = e[t];\n        n(i) && (n(i.tag) ? (w(i), b(i)) : l(i.elm));\n      }\n    }\n    function w(e, t) {\n      if (n(t) || n(e.data)) {\n        var r,\n          i = s.remove.length + 1;\n        for (\n          n(t)\n            ? (t.listeners += i)\n            : (t = (function (e, t) {\n                function n() {\n                  0 == --n.listeners && l(e);\n                }\n                return (n.listeners = t), n;\n              })(e.elm, i)),\n            n((r = e.componentInstance)) && n((r = r._vnode)) && n(r.data) && w(r, t),\n            r = 0;\n          r < s.remove.length;\n          ++r\n        )\n          s.remove[r](e, t);\n        n((r = e.data.hook)) && n((r = r.remove)) ? r(e, t) : t();\n      } else l(e.elm);\n    }\n    function C(e, t, r, i) {\n      for (var o = r; o < i; o++) {\n        var a = t[o];\n        if (n(a) && or(e, a)) return o;\n      }\n    }\n    function x(e, i, o, a, c, l) {\n      if (e !== i) {\n        n(i.elm) && n(a) && (i = a[c] = me(i));\n        var p = (i.elm = e.elm);\n        if (r(e.isAsyncPlaceholder)) n(i.asyncFactory.resolved) ? O(e.elm, i, o) : (i.isAsyncPlaceholder = !0);\n        else if (r(i.isStatic) && r(e.isStatic) && i.key === e.key && (r(i.isCloned) || r(i.isOnce))) i.componentInstance = e.componentInstance;\n        else {\n          var d,\n            v = i.data;\n          n(v) && n((d = v.hook)) && n((d = d.prepatch)) && d(e, i);\n          var h = e.children,\n            y = i.children;\n          if (n(v) && m(i)) {\n            for (d = 0; d < s.update.length; ++d) s.update[d](e, i);\n            n((d = v.hook)) && n((d = d.update)) && d(e, i);\n          }\n          t(i.text)\n            ? n(h) && n(y)\n              ? h !== y &&\n                (function (e, r, i, o, a) {\n                  for (var s, c, l, p = 0, d = 0, v = r.length - 1, h = r[0], m = r[v], y = i.length - 1, g = i[0], b = i[y], w = !a; p <= v && d <= y; )\n                    t(h)\n                      ? (h = r[++p])\n                      : t(m)\n                        ? (m = r[--v])\n                        : or(h, g)\n                          ? (x(h, g, o, i, d), (h = r[++p]), (g = i[++d]))\n                          : or(m, b)\n                            ? (x(m, b, o, i, y), (m = r[--v]), (b = i[--y]))\n                            : or(h, b)\n                              ? (x(h, b, o, i, y), w && u.insertBefore(e, h.elm, u.nextSibling(m.elm)), (h = r[++p]), (b = i[--y]))\n                              : or(m, g)\n                                ? (x(m, g, o, i, d), w && u.insertBefore(e, m.elm, h.elm), (m = r[--v]), (g = i[++d]))\n                                : (t(s) && (s = ar(r, p, v)), t((c = n(g.key) ? s[g.key] : C(g, r, p, v))) ? f(g, o, e, h.elm, !1, i, d) : or((l = r[c]), g) ? (x(l, g, o, i, d), (r[c] = void 0), w && u.insertBefore(e, l.elm, h.elm)) : f(g, o, e, h.elm, !1, i, d), (g = i[++d]));\n                  p > v ? _(e, t(i[y + 1]) ? null : i[y + 1].elm, i, d, y, o) : d > y && $(r, p, v);\n                })(p, h, y, o, l)\n              : n(y)\n                ? (n(e.text) && u.setTextContent(p, \"\"), _(p, null, y, 0, y.length - 1, o))\n                : n(h)\n                  ? $(h, 0, h.length - 1)\n                  : n(e.text) && u.setTextContent(p, \"\")\n            : e.text !== i.text && u.setTextContent(p, i.text),\n            n(v) && n((d = v.hook)) && n((d = d.postpatch)) && d(e, i);\n        }\n      }\n    }\n    function k(e, t, i) {\n      if (r(i) && n(e.parent)) e.parent.data.pendingInsert = t;\n      else for (var o = 0; o < t.length; ++o) t[o].data.hook.insert(t[o]);\n    }\n    var A = p(\"attrs,class,staticClass,staticStyle,key\");\n    function O(e, t, i, o) {\n      var a,\n        s = t.tag,\n        c = t.data,\n        u = t.children;\n      if (((o = o || (c && c.pre)), (t.elm = e), r(t.isComment) && n(t.asyncFactory))) return (t.isAsyncPlaceholder = !0), !0;\n      if (n(c) && (n((a = c.hook)) && n((a = a.init)) && a(t, !0), n((a = t.componentInstance)))) return d(t, i), !0;\n      if (n(s)) {\n        if (n(u))\n          if (e.hasChildNodes())\n            if (n((a = c)) && n((a = a.domProps)) && n((a = a.innerHTML))) {\n              if (a !== e.innerHTML) return !1;\n            } else {\n              for (var l = !0, f = e.firstChild, p = 0; p < u.length; p++) {\n                if (!f || !O(f, u[p], i, o)) {\n                  l = !1;\n                  break;\n                }\n                f = f.nextSibling;\n              }\n              if (!l || f) return !1;\n            }\n          else h(t, u, i);\n        if (n(c)) {\n          var v = !1;\n          for (var m in c)\n            if (!A(m)) {\n              (v = !0), y(t, i);\n              break;\n            }\n          !v && c.class && tt(c.class);\n        }\n      } else e.data !== t.text && (e.data = t.text);\n      return !0;\n    }\n    return function (e, i, o, a) {\n      if (!t(i)) {\n        var c,\n          l = !1,\n          p = [];\n        if (t(e)) (l = !0), f(i, p);\n        else {\n          var d = n(e.nodeType);\n          if (!d && or(e, i)) x(e, i, p, null, null, a);\n          else {\n            if (d) {\n              if ((1 === e.nodeType && e.hasAttribute(L) && (e.removeAttribute(L), (o = !0)), r(o) && O(e, i, p))) return k(i, p, !0), e;\n              (c = e), (e = new pe(u.tagName(c).toLowerCase(), {}, [], void 0, c));\n            }\n            var v = e.elm,\n              h = u.parentNode(v);\n            if ((f(i, p, v._leaveCb ? null : h, u.nextSibling(v)), n(i.parent)))\n              for (var y = i.parent, g = m(i); y; ) {\n                for (var _ = 0; _ < s.destroy.length; ++_) s.destroy[_](y);\n                if (((y.elm = i.elm), g)) {\n                  for (var w = 0; w < s.create.length; ++w) s.create[w](rr, y);\n                  var C = y.data.hook.insert;\n                  if (C.merged) for (var A = 1; A < C.fns.length; A++) C.fns[A]();\n                } else nr(y);\n                y = y.parent;\n              }\n            n(h) ? $([e], 0, 0) : n(e.tag) && b(e);\n          }\n        }\n        return k(i, p, l), i.elm;\n      }\n      n(e) && b(e);\n    };\n  })({\n    nodeOps: er,\n    modules: [\n      yr,\n      kr,\n      ri,\n      ai,\n      yi,\n      V\n        ? {\n            create: Vi,\n            activate: Vi,\n            remove: function (e, t) {\n              !0 !== e.data.show ? Hi(e, t) : t();\n            },\n          }\n        : {},\n    ].concat(dr),\n  });\n  W &&\n    document.addEventListener(\"selectionchange\", function () {\n      var e = document.activeElement;\n      e && e.vmodel && Yi(e, \"input\");\n    });\n  var Ki = {\n    inserted: function (e, t, n, r) {\n      \"select\" === n.tag\n        ? (r.elm && !r.elm._vOptions\n            ? ot(n, \"postpatch\", function () {\n                Ki.componentUpdated(e, t, n);\n              })\n            : Ji(e, t, n.context),\n          (e._vOptions = [].map.call(e.options, Zi)))\n        : (\"textarea\" === n.tag || Yn(e.type)) && ((e._vModifiers = t.modifiers), t.modifiers.lazy || (e.addEventListener(\"compositionstart\", Gi), e.addEventListener(\"compositionend\", Xi), e.addEventListener(\"change\", Xi), W && (e.vmodel = !0)));\n    },\n    componentUpdated: function (e, t, n) {\n      if (\"select\" === n.tag) {\n        Ji(e, t, n.context);\n        var r = e._vOptions,\n          i = (e._vOptions = [].map.call(e.options, Zi));\n        if (\n          i.some(function (e, t) {\n            return !E(e, r[t]);\n          })\n        )\n          (e.multiple\n            ? t.value.some(function (e) {\n                return Wi(e, i);\n              })\n            : t.value !== t.oldValue && Wi(t.value, i)) && Yi(e, \"change\");\n      }\n    },\n  };\n  function Ji(e, t, n) {\n    qi(e, t, n),\n      (q || Z) &&\n        setTimeout(function () {\n          qi(e, t, n);\n        }, 0);\n  }\n  function qi(e, t, n) {\n    var r = t.value,\n      i = e.multiple;\n    if (!i || Array.isArray(r)) {\n      for (var o, a, s = 0, c = e.options.length; s < c; s++)\n        if (((a = e.options[s]), i)) (o = j(r, Zi(a)) > -1), a.selected !== o && (a.selected = o);\n        else if (E(Zi(a), r)) return void (e.selectedIndex !== s && (e.selectedIndex = s));\n      i || (e.selectedIndex = -1);\n    }\n  }\n  function Wi(e, t) {\n    return t.every(function (t) {\n      return !E(t, e);\n    });\n  }\n  function Zi(e) {\n    return \"_value\" in e ? e._value : e.value;\n  }\n  function Gi(e) {\n    e.target.composing = !0;\n  }\n  function Xi(e) {\n    e.target.composing && ((e.target.composing = !1), Yi(e.target, \"input\"));\n  }\n  function Yi(e, t) {\n    var n = document.createEvent(\"HTMLEvents\");\n    n.initEvent(t, !0, !0), e.dispatchEvent(n);\n  }\n  function Qi(e) {\n    return !e.componentInstance || (e.data && e.data.transition) ? e : Qi(e.componentInstance._vnode);\n  }\n  var eo = {\n      model: Ki,\n      show: {\n        bind: function (e, t, n) {\n          var r = t.value,\n            i = (n = Qi(n)).data && n.data.transition,\n            o = (e.__vOriginalDisplay = \"none\" === e.style.display ? \"\" : e.style.display);\n          r && i\n            ? ((n.data.show = !0),\n              Ri(n, function () {\n                e.style.display = o;\n              }))\n            : (e.style.display = r ? o : \"none\");\n        },\n        update: function (e, t, n) {\n          var r = t.value;\n          !r != !t.oldValue &&\n            ((n = Qi(n)).data && n.data.transition\n              ? ((n.data.show = !0),\n                r\n                  ? Ri(n, function () {\n                      e.style.display = e.__vOriginalDisplay;\n                    })\n                  : Hi(n, function () {\n                      e.style.display = \"none\";\n                    }))\n              : (e.style.display = r ? e.__vOriginalDisplay : \"none\"));\n        },\n        unbind: function (e, t, n, r, i) {\n          i || (e.style.display = e.__vOriginalDisplay);\n        },\n      },\n    },\n    to = {\n      name: String,\n      appear: Boolean,\n      css: Boolean,\n      mode: String,\n      type: String,\n      enterClass: String,\n      leaveClass: String,\n      enterToClass: String,\n      leaveToClass: String,\n      enterActiveClass: String,\n      leaveActiveClass: String,\n      appearClass: String,\n      appearActiveClass: String,\n      appearToClass: String,\n      duration: [Number, String, Object],\n    };\n  function no(e) {\n    var t = e && e.componentOptions;\n    return t && t.Ctor.options.abstract ? no(zt(t.children)) : e;\n  }\n  function ro(e) {\n    var t = {},\n      n = e.$options;\n    for (var r in n.propsData) t[r] = e[r];\n    var i = n._parentListeners;\n    for (var o in i) t[b(o)] = i[o];\n    return t;\n  }\n  function io(e, t) {\n    if (/\\d-keep-alive$/.test(t.tag)) return e(\"keep-alive\", { props: t.componentOptions.propsData });\n  }\n  var oo = function (e) {\n      return e.tag || pt(e);\n    },\n    ao = function (e) {\n      return \"show\" === e.name;\n    },\n    so = {\n      name: \"transition\",\n      props: to,\n      abstract: !0,\n      render: function (e) {\n        var t = this,\n          n = this.$slots.default;\n        if (n && (n = n.filter(oo)).length) {\n          var r = this.mode,\n            o = n[0];\n          if (\n            (function (e) {\n              for (; (e = e.parent); ) if (e.data.transition) return !0;\n            })(this.$vnode)\n          )\n            return o;\n          var a = no(o);\n          if (!a) return o;\n          if (this._leaving) return io(e, o);\n          var s = \"__transition-\" + this._uid + \"-\";\n          a.key = null == a.key ? (a.isComment ? s + \"comment\" : s + a.tag) : i(a.key) ? (0 === String(a.key).indexOf(s) ? a.key : s + a.key) : a.key;\n          var c = ((a.data || (a.data = {})).transition = ro(this)),\n            u = this._vnode,\n            l = no(u);\n          if (\n            (a.data.directives && a.data.directives.some(ao) && (a.data.show = !0),\n            l &&\n              l.data &&\n              !(function (e, t) {\n                return t.key === e.key && t.tag === e.tag;\n              })(a, l) &&\n              !pt(l) &&\n              (!l.componentInstance || !l.componentInstance._vnode.isComment))\n          ) {\n            var f = (l.data.transition = A({}, c));\n            if (\"out-in\" === r)\n              return (\n                (this._leaving = !0),\n                ot(f, \"afterLeave\", function () {\n                  (t._leaving = !1), t.$forceUpdate();\n                }),\n                io(e, o)\n              );\n            if (\"in-out\" === r) {\n              if (pt(a)) return u;\n              var p,\n                d = function () {\n                  p();\n                };\n              ot(c, \"afterEnter\", d),\n                ot(c, \"enterCancelled\", d),\n                ot(f, \"delayLeave\", function (e) {\n                  p = e;\n                });\n            }\n          }\n          return o;\n        }\n      },\n    },\n    co = A({ tag: String, moveClass: String }, to);\n  function uo(e) {\n    e.elm._moveCb && e.elm._moveCb(), e.elm._enterCb && e.elm._enterCb();\n  }\n  function lo(e) {\n    e.data.newPos = e.elm.getBoundingClientRect();\n  }\n  function fo(e) {\n    var t = e.data.pos,\n      n = e.data.newPos,\n      r = t.left - n.left,\n      i = t.top - n.top;\n    if (r || i) {\n      e.data.moved = !0;\n      var o = e.elm.style;\n      (o.transform = o.WebkitTransform = \"translate(\" + r + \"px,\" + i + \"px)\"), (o.transitionDuration = \"0s\");\n    }\n  }\n  delete co.mode;\n  var po = {\n    Transition: so,\n    TransitionGroup: {\n      props: co,\n      beforeMount: function () {\n        var e = this,\n          t = this._update;\n        this._update = function (n, r) {\n          var i = Gt(e);\n          e.__patch__(e._vnode, e.kept, !1, !0), (e._vnode = e.kept), i(), t.call(e, n, r);\n        };\n      },\n      render: function (e) {\n        for (var t = this.tag || this.$vnode.data.tag || \"span\", n = Object.create(null), r = (this.prevChildren = this.children), i = this.$slots.default || [], o = (this.children = []), a = ro(this), s = 0; s < i.length; s++) {\n          var c = i[s];\n          c.tag && null != c.key && 0 !== String(c.key).indexOf(\"__vlist\") && (o.push(c), (n[c.key] = c), ((c.data || (c.data = {})).transition = a));\n        }\n        if (r) {\n          for (var u = [], l = [], f = 0; f < r.length; f++) {\n            var p = r[f];\n            (p.data.transition = a), (p.data.pos = p.elm.getBoundingClientRect()), n[p.key] ? u.push(p) : l.push(p);\n          }\n          (this.kept = e(t, null, u)), (this.removed = l);\n        }\n        return e(t, null, o);\n      },\n      updated: function () {\n        var e = this.prevChildren,\n          t = this.moveClass || (this.name || \"v\") + \"-move\";\n        e.length &&\n          this.hasMove(e[0].elm, t) &&\n          (e.forEach(uo),\n          e.forEach(lo),\n          e.forEach(fo),\n          (this._reflow = document.body.offsetHeight),\n          e.forEach(function (e) {\n            if (e.data.moved) {\n              var n = e.elm,\n                r = n.style;\n              ji(n, t),\n                (r.transform = r.WebkitTransform = r.transitionDuration = \"\"),\n                n.addEventListener(\n                  Oi,\n                  (n._moveCb = function e(r) {\n                    (r && r.target !== n) || (r && !/transform$/.test(r.propertyName)) || (n.removeEventListener(Oi, e), (n._moveCb = null), Di(n, t));\n                  }),\n                );\n            }\n          }));\n      },\n      methods: {\n        hasMove: function (e, t) {\n          if (!Ci) return !1;\n          if (this._hasMove) return this._hasMove;\n          var n = e.cloneNode();\n          e._transitionClasses &&\n            e._transitionClasses.forEach(function (e) {\n              bi(n, e);\n            }),\n            _i(n, t),\n            (n.style.display = \"none\"),\n            this.$el.appendChild(n);\n          var r = Mi(n);\n          return this.$el.removeChild(n), (this._hasMove = r.hasTransform);\n        },\n      },\n    },\n  };\n  (Cn.config.mustUseProp = Dn),\n    (Cn.config.isReservedTag = Zn),\n    (Cn.config.isReservedAttr = En),\n    (Cn.config.getTagNamespace = Gn),\n    (Cn.config.isUnknownElement = function (e) {\n      if (!V) return !0;\n      if (Zn(e)) return !1;\n      if (((e = e.toLowerCase()), null != Xn[e])) return Xn[e];\n      var t = document.createElement(e);\n      return e.indexOf(\"-\") > -1 ? (Xn[e] = t.constructor === window.HTMLUnknownElement || t.constructor === window.HTMLElement) : (Xn[e] = /HTMLUnknownElement/.test(t.toString()));\n    }),\n    A(Cn.options.directives, eo),\n    A(Cn.options.components, po),\n    (Cn.prototype.__patch__ = V ? zi : S),\n    (Cn.prototype.$mount = function (e, t) {\n      return (function (e, t, n) {\n        var r;\n        return (\n          (e.$el = t),\n          e.$options.render || (e.$options.render = ve),\n          Qt(e, \"beforeMount\"),\n          (r = function () {\n            e._update(e._render(), n);\n          }),\n          new pn(\n            e,\n            r,\n            S,\n            {\n              before: function () {\n                e._isMounted && !e._isDestroyed && Qt(e, \"beforeUpdate\");\n              },\n            },\n            !0,\n          ),\n          (n = !1),\n          null == e.$vnode && ((e._isMounted = !0), Qt(e, \"mounted\")),\n          e\n        );\n      })(this, (e = e && V ? Qn(e) : void 0), t);\n    }),\n    V &&\n      setTimeout(function () {\n        F.devtools && ne && ne.emit(\"init\", Cn);\n      }, 0);\n  var vo = /\\{\\{((?:.|\\r?\\n)+?)\\}\\}/g,\n    ho = /[-.*+?^${}()|[\\]\\/\\\\]/g,\n    mo = g(function (e) {\n      var t = e[0].replace(ho, \"\\\\$&\"),\n        n = e[1].replace(ho, \"\\\\$&\");\n      return new RegExp(t + \"((?:.|\\\\n)+?)\" + n, \"g\");\n    });\n  var yo = {\n    staticKeys: [\"staticClass\"],\n    transformNode: function (e, t) {\n      t.warn;\n      var n = Pr(e, \"class\");\n      n && (e.staticClass = JSON.stringify(n));\n      var r = Fr(e, \"class\", !1);\n      r && (e.classBinding = r);\n    },\n    genData: function (e) {\n      var t = \"\";\n      return e.staticClass && (t += \"staticClass:\" + e.staticClass + \",\"), e.classBinding && (t += \"class:\" + e.classBinding + \",\"), t;\n    },\n  };\n  var go,\n    _o = {\n      staticKeys: [\"staticStyle\"],\n      transformNode: function (e, t) {\n        t.warn;\n        var n = Pr(e, \"style\");\n        n && (e.staticStyle = JSON.stringify(si(n)));\n        var r = Fr(e, \"style\", !1);\n        r && (e.styleBinding = r);\n      },\n      genData: function (e) {\n        var t = \"\";\n        return e.staticStyle && (t += \"staticStyle:\" + e.staticStyle + \",\"), e.styleBinding && (t += \"style:(\" + e.styleBinding + \"),\"), t;\n      },\n    },\n    bo = function (e) {\n      return ((go = go || document.createElement(\"div\")).innerHTML = e), go.textContent;\n    },\n    $o = p(\"area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr\"),\n    wo = p(\"colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source\"),\n    Co = p(\"address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track\"),\n    xo = /^\\s*([^\\s\"'<>\\/=]+)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/,\n    ko = /^\\s*((?:v-[\\w-]+:|@|:|#)\\[[^=]+?\\][^\\s\"'<>\\/=]*)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/,\n    Ao = \"[a-zA-Z_][\\\\-\\\\.0-9_a-zA-Z\" + P.source + \"]*\",\n    Oo = \"((?:\" + Ao + \"\\\\:)?\" + Ao + \")\",\n    So = new RegExp(\"^<\" + Oo),\n    To = /^\\s*(\\/?)>/,\n    No = new RegExp(\"^<\\\\/\" + Oo + \"[^>]*>\"),\n    Eo = /^<!DOCTYPE [^>]+>/i,\n    jo = /^<!\\--/,\n    Do = /^<!\\[/,\n    Lo = p(\"script,style,textarea\", !0),\n    Io = {},\n    Mo = {\n      \"&lt;\": \"<\",\n      \"&gt;\": \">\",\n      \"&quot;\": '\"',\n      \"&amp;\": \"&\",\n      \"&#10;\": \"\\n\",\n      \"&#9;\": \"\\t\",\n      \"&#39;\": \"'\",\n    },\n    Fo = /&(?:lt|gt|quot|amp|#39);/g,\n    Po = /&(?:lt|gt|quot|amp|#39|#10|#9);/g,\n    Ro = p(\"pre,textarea\", !0),\n    Ho = function (e, t) {\n      return e && Ro(e) && \"\\n\" === t[0];\n    };\n  function Bo(e, t) {\n    var n = t ? Po : Fo;\n    return e.replace(n, function (e) {\n      return Mo[e];\n    });\n  }\n  var Uo,\n    Vo,\n    zo,\n    Ko,\n    Jo,\n    qo,\n    Wo,\n    Zo,\n    Go = /^@|^v-on:/,\n    Xo = /^v-|^@|^:|^#/,\n    Yo = /([\\s\\S]*?)\\s+(?:in|of)\\s+([\\s\\S]*)/,\n    Qo = /,([^,\\}\\]]*)(?:,([^,\\}\\]]*))?$/,\n    ea = /^\\(|\\)$/g,\n    ta = /^\\[.*\\]$/,\n    na = /:(.*)$/,\n    ra = /^:|^\\.|^v-bind:/,\n    ia = /\\.[^.\\]]+(?=[^\\]]*$)/g,\n    oa = /^v-slot(:|$)|^#/,\n    aa = /[\\r\\n]/,\n    sa = /[ \\f\\t\\r\\n]+/g,\n    ca = g(bo),\n    ua = \"_empty_\";\n  function la(e, t, n) {\n    return {\n      type: 1,\n      tag: e,\n      attrsList: t,\n      attrsMap: ya(t),\n      rawAttrsMap: {},\n      parent: n,\n      children: [],\n    };\n  }\n  function fa(e, t) {\n    (Uo = t.warn || Tr), (qo = t.isPreTag || T), (Wo = t.mustUseProp || T), (Zo = t.getTagNamespace || T);\n    t.isReservedTag;\n    (zo = Nr(t.modules, \"transformNode\")), (Ko = Nr(t.modules, \"preTransformNode\")), (Jo = Nr(t.modules, \"postTransformNode\")), (Vo = t.delimiters);\n    var n,\n      r,\n      i = [],\n      o = !1 !== t.preserveWhitespace,\n      a = t.whitespace,\n      s = !1,\n      c = !1;\n    function u(e) {\n      if ((l(e), s || e.processed || (e = pa(e, t)), i.length || e === n || (n.if && (e.elseif || e.else) && va(n, { exp: e.elseif, block: e })), r && !e.forbidden))\n        if (e.elseif || e.else)\n          (a = e),\n            (u = (function (e) {\n              var t = e.length;\n              for (; t--; ) {\n                if (1 === e[t].type) return e[t];\n                e.pop();\n              }\n            })(r.children)) &&\n              u.if &&\n              va(u, { exp: a.elseif, block: a });\n        else {\n          if (e.slotScope) {\n            var o = e.slotTarget || '\"default\"';\n            (r.scopedSlots || (r.scopedSlots = {}))[o] = e;\n          }\n          r.children.push(e), (e.parent = r);\n        }\n      var a, u;\n      (e.children = e.children.filter(function (e) {\n        return !e.slotScope;\n      })),\n        l(e),\n        e.pre && (s = !1),\n        qo(e.tag) && (c = !1);\n      for (var f = 0; f < Jo.length; f++) Jo[f](e, t);\n    }\n    function l(e) {\n      if (!c) for (var t; (t = e.children[e.children.length - 1]) && 3 === t.type && \" \" === t.text; ) e.children.pop();\n    }\n    return (\n      (function (e, t) {\n        for (var n, r, i = [], o = t.expectHTML, a = t.isUnaryTag || T, s = t.canBeLeftOpenTag || T, c = 0; e; ) {\n          if (((n = e), r && Lo(r))) {\n            var u = 0,\n              l = r.toLowerCase(),\n              f = Io[l] || (Io[l] = new RegExp(\"([\\\\s\\\\S]*?)(</\" + l + \"[^>]*>)\", \"i\")),\n              p = e.replace(f, function (e, n, r) {\n                return (u = r.length), Lo(l) || \"noscript\" === l || (n = n.replace(/<!\\--([\\s\\S]*?)-->/g, \"$1\").replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g, \"$1\")), Ho(l, n) && (n = n.slice(1)), t.chars && t.chars(n), \"\";\n              });\n            (c += e.length - p.length), (e = p), A(l, c - u, c);\n          } else {\n            var d = e.indexOf(\"<\");\n            if (0 === d) {\n              if (jo.test(e)) {\n                var v = e.indexOf(\"--\\x3e\");\n                if (v >= 0) {\n                  t.shouldKeepComment && t.comment(e.substring(4, v), c, c + v + 3), C(v + 3);\n                  continue;\n                }\n              }\n              if (Do.test(e)) {\n                var h = e.indexOf(\"]>\");\n                if (h >= 0) {\n                  C(h + 2);\n                  continue;\n                }\n              }\n              var m = e.match(Eo);\n              if (m) {\n                C(m[0].length);\n                continue;\n              }\n              var y = e.match(No);\n              if (y) {\n                var g = c;\n                C(y[0].length), A(y[1], g, c);\n                continue;\n              }\n              var _ = x();\n              if (_) {\n                k(_), Ho(_.tagName, e) && C(1);\n                continue;\n              }\n            }\n            var b = void 0,\n              $ = void 0,\n              w = void 0;\n            if (d >= 0) {\n              for ($ = e.slice(d); !(No.test($) || So.test($) || jo.test($) || Do.test($) || (w = $.indexOf(\"<\", 1)) < 0); ) (d += w), ($ = e.slice(d));\n              b = e.substring(0, d);\n            }\n            d < 0 && (b = e), b && C(b.length), t.chars && b && t.chars(b, c - b.length, c);\n          }\n          if (e === n) {\n            t.chars && t.chars(e);\n            break;\n          }\n        }\n        function C(t) {\n          (c += t), (e = e.substring(t));\n        }\n        function x() {\n          var t = e.match(So);\n          if (t) {\n            var n,\n              r,\n              i = { tagName: t[1], attrs: [], start: c };\n            for (C(t[0].length); !(n = e.match(To)) && (r = e.match(ko) || e.match(xo)); ) (r.start = c), C(r[0].length), (r.end = c), i.attrs.push(r);\n            if (n) return (i.unarySlash = n[1]), C(n[0].length), (i.end = c), i;\n          }\n        }\n        function k(e) {\n          var n = e.tagName,\n            c = e.unarySlash;\n          o && (\"p\" === r && Co(n) && A(r), s(n) && r === n && A(n));\n          for (var u = a(n) || !!c, l = e.attrs.length, f = new Array(l), p = 0; p < l; p++) {\n            var d = e.attrs[p],\n              v = d[3] || d[4] || d[5] || \"\",\n              h = \"a\" === n && \"href\" === d[1] ? t.shouldDecodeNewlinesForHref : t.shouldDecodeNewlines;\n            f[p] = { name: d[1], value: Bo(v, h) };\n          }\n          u ||\n            (i.push({\n              tag: n,\n              lowerCasedTag: n.toLowerCase(),\n              attrs: f,\n              start: e.start,\n              end: e.end,\n            }),\n            (r = n)),\n            t.start && t.start(n, f, u, e.start, e.end);\n        }\n        function A(e, n, o) {\n          var a, s;\n          if ((null == n && (n = c), null == o && (o = c), e)) for (s = e.toLowerCase(), a = i.length - 1; a >= 0 && i[a].lowerCasedTag !== s; a--);\n          else a = 0;\n          if (a >= 0) {\n            for (var u = i.length - 1; u >= a; u--) t.end && t.end(i[u].tag, n, o);\n            (i.length = a), (r = a && i[a - 1].tag);\n          } else \"br\" === s ? t.start && t.start(e, [], !0, n, o) : \"p\" === s && (t.start && t.start(e, [], !1, n, o), t.end && t.end(e, n, o));\n        }\n        A();\n      })(e, {\n        warn: Uo,\n        expectHTML: t.expectHTML,\n        isUnaryTag: t.isUnaryTag,\n        canBeLeftOpenTag: t.canBeLeftOpenTag,\n        shouldDecodeNewlines: t.shouldDecodeNewlines,\n        shouldDecodeNewlinesForHref: t.shouldDecodeNewlinesForHref,\n        shouldKeepComment: t.comments,\n        outputSourceRange: t.outputSourceRange,\n        start: function (e, o, a, l, f) {\n          var p = (r && r.ns) || Zo(e);\n          q &&\n            \"svg\" === p &&\n            (o = (function (e) {\n              for (var t = [], n = 0; n < e.length; n++) {\n                var r = e[n];\n                ga.test(r.name) || ((r.name = r.name.replace(_a, \"\")), t.push(r));\n              }\n              return t;\n            })(o));\n          var d,\n            v = la(e, o, r);\n          p && (v.ns = p), (\"style\" !== (d = v).tag && (\"script\" !== d.tag || (d.attrsMap.type && \"text/javascript\" !== d.attrsMap.type))) || te() || (v.forbidden = !0);\n          for (var h = 0; h < Ko.length; h++) v = Ko[h](v, t) || v;\n          s ||\n            (!(function (e) {\n              null != Pr(e, \"v-pre\") && (e.pre = !0);\n            })(v),\n            v.pre && (s = !0)),\n            qo(v.tag) && (c = !0),\n            s\n              ? (function (e) {\n                  var t = e.attrsList,\n                    n = t.length;\n                  if (n)\n                    for (var r = (e.attrs = new Array(n)), i = 0; i < n; i++)\n                      (r[i] = {\n                        name: t[i].name,\n                        value: JSON.stringify(t[i].value),\n                      }),\n                        null != t[i].start && ((r[i].start = t[i].start), (r[i].end = t[i].end));\n                  else e.pre || (e.plain = !0);\n                })(v)\n              : v.processed ||\n                (da(v),\n                (function (e) {\n                  var t = Pr(e, \"v-if\");\n                  if (t) (e.if = t), va(e, { exp: t, block: e });\n                  else {\n                    null != Pr(e, \"v-else\") && (e.else = !0);\n                    var n = Pr(e, \"v-else-if\");\n                    n && (e.elseif = n);\n                  }\n                })(v),\n                (function (e) {\n                  null != Pr(e, \"v-once\") && (e.once = !0);\n                })(v)),\n            n || (n = v),\n            a ? u(v) : ((r = v), i.push(v));\n        },\n        end: function (e, t, n) {\n          var o = i[i.length - 1];\n          (i.length -= 1), (r = i[i.length - 1]), u(o);\n        },\n        chars: function (e, t, n) {\n          if (r && (!q || \"textarea\" !== r.tag || r.attrsMap.placeholder !== e)) {\n            var i,\n              u,\n              l,\n              f = r.children;\n            if ((e = c || e.trim() ? (\"script\" === (i = r).tag || \"style\" === i.tag ? e : ca(e)) : f.length ? (a ? (\"condense\" === a && aa.test(e) ? \"\" : \" \") : o ? \" \" : \"\") : \"\"))\n              c || \"condense\" !== a || (e = e.replace(sa, \" \")),\n                !s &&\n                \" \" !== e &&\n                (u = (function (e, t) {\n                  var n = t ? mo(t) : vo;\n                  if (n.test(e)) {\n                    for (var r, i, o, a = [], s = [], c = (n.lastIndex = 0); (r = n.exec(e)); ) {\n                      (i = r.index) > c && (s.push((o = e.slice(c, i))), a.push(JSON.stringify(o)));\n                      var u = Or(r[1].trim());\n                      a.push(\"_s(\" + u + \")\"), s.push({ \"@binding\": u }), (c = i + r[0].length);\n                    }\n                    return c < e.length && (s.push((o = e.slice(c))), a.push(JSON.stringify(o))), { expression: a.join(\"+\"), tokens: s };\n                  }\n                })(e, Vo))\n                  ? (l = {\n                      type: 2,\n                      expression: u.expression,\n                      tokens: u.tokens,\n                      text: e,\n                    })\n                  : (\" \" === e && f.length && \" \" === f[f.length - 1].text) || (l = { type: 3, text: e }),\n                l && f.push(l);\n          }\n        },\n        comment: function (e, t, n) {\n          if (r) {\n            var i = { type: 3, text: e, isComment: !0 };\n            r.children.push(i);\n          }\n        },\n      }),\n      n\n    );\n  }\n  function pa(e, t) {\n    var n, r;\n    (r = Fr((n = e), \"key\")) && (n.key = r),\n      (e.plain = !e.key && !e.scopedSlots && !e.attrsList.length),\n      (function (e) {\n        var t = Fr(e, \"ref\");\n        t &&\n          ((e.ref = t),\n          (e.refInFor = (function (e) {\n            var t = e;\n            for (; t; ) {\n              if (void 0 !== t.for) return !0;\n              t = t.parent;\n            }\n            return !1;\n          })(e)));\n      })(e),\n      (function (e) {\n        var t;\n        \"template\" === e.tag ? ((t = Pr(e, \"scope\")), (e.slotScope = t || Pr(e, \"slot-scope\"))) : (t = Pr(e, \"slot-scope\")) && (e.slotScope = t);\n        var n = Fr(e, \"slot\");\n        n &&\n          ((e.slotTarget = '\"\"' === n ? '\"default\"' : n),\n          (e.slotTargetDynamic = !(!e.attrsMap[\":slot\"] && !e.attrsMap[\"v-bind:slot\"])),\n          \"template\" === e.tag ||\n            e.slotScope ||\n            jr(\n              e,\n              \"slot\",\n              n,\n              (function (e, t) {\n                return e.rawAttrsMap[\":\" + t] || e.rawAttrsMap[\"v-bind:\" + t] || e.rawAttrsMap[t];\n              })(e, \"slot\"),\n            ));\n        if (\"template\" === e.tag) {\n          var r = Rr(e, oa);\n          if (r) {\n            var i = ha(r),\n              o = i.name,\n              a = i.dynamic;\n            (e.slotTarget = o), (e.slotTargetDynamic = a), (e.slotScope = r.value || ua);\n          }\n        } else {\n          var s = Rr(e, oa);\n          if (s) {\n            var c = e.scopedSlots || (e.scopedSlots = {}),\n              u = ha(s),\n              l = u.name,\n              f = u.dynamic,\n              p = (c[l] = la(\"template\", [], e));\n            (p.slotTarget = l),\n              (p.slotTargetDynamic = f),\n              (p.children = e.children.filter(function (e) {\n                if (!e.slotScope) return (e.parent = p), !0;\n              })),\n              (p.slotScope = s.value || ua),\n              (e.children = []),\n              (e.plain = !1);\n          }\n        }\n      })(e),\n      (function (e) {\n        \"slot\" === e.tag && (e.slotName = Fr(e, \"name\"));\n      })(e),\n      (function (e) {\n        var t;\n        (t = Fr(e, \"is\")) && (e.component = t);\n        null != Pr(e, \"inline-template\") && (e.inlineTemplate = !0);\n      })(e);\n    for (var i = 0; i < zo.length; i++) e = zo[i](e, t) || e;\n    return (\n      (function (e) {\n        var t,\n          n,\n          r,\n          i,\n          o,\n          a,\n          s,\n          c,\n          u = e.attrsList;\n        for (t = 0, n = u.length; t < n; t++)\n          if (((r = i = u[t].name), (o = u[t].value), Xo.test(r)))\n            if (((e.hasBindings = !0), (a = ma(r.replace(Xo, \"\"))) && (r = r.replace(ia, \"\")), ra.test(r)))\n              (r = r.replace(ra, \"\")), (o = Or(o)), (c = ta.test(r)) && (r = r.slice(1, -1)), a && (a.prop && !c && \"innerHtml\" === (r = b(r)) && (r = \"innerHTML\"), a.camel && !c && (r = b(r)), a.sync && ((s = Ur(o, \"$event\")), c ? Mr(e, '\"update:\"+(' + r + \")\", s, null, !1, 0, u[t], !0) : (Mr(e, \"update:\" + b(r), s, null, !1, 0, u[t]), C(r) !== b(r) && Mr(e, \"update:\" + C(r), s, null, !1, 0, u[t])))), (a && a.prop) || (!e.component && Wo(e.tag, e.attrsMap.type, r)) ? Er(e, r, o, u[t], c) : jr(e, r, o, u[t], c);\n            else if (Go.test(r)) (r = r.replace(Go, \"\")), (c = ta.test(r)) && (r = r.slice(1, -1)), Mr(e, r, o, a, !1, 0, u[t], c);\n            else {\n              var l = (r = r.replace(Xo, \"\")).match(na),\n                f = l && l[1];\n              (c = !1), f && ((r = r.slice(0, -(f.length + 1))), ta.test(f) && ((f = f.slice(1, -1)), (c = !0))), Lr(e, r, i, o, f, c, a, u[t]);\n            }\n          else jr(e, r, JSON.stringify(o), u[t]), !e.component && \"muted\" === r && Wo(e.tag, e.attrsMap.type, r) && Er(e, r, \"true\", u[t]);\n      })(e),\n      e\n    );\n  }\n  function da(e) {\n    var t;\n    if ((t = Pr(e, \"v-for\"))) {\n      var n = (function (e) {\n        var t = e.match(Yo);\n        if (!t) return;\n        var n = {};\n        n.for = t[2].trim();\n        var r = t[1].trim().replace(ea, \"\"),\n          i = r.match(Qo);\n        i ? ((n.alias = r.replace(Qo, \"\").trim()), (n.iterator1 = i[1].trim()), i[2] && (n.iterator2 = i[2].trim())) : (n.alias = r);\n        return n;\n      })(t);\n      n && A(e, n);\n    }\n  }\n  function va(e, t) {\n    e.ifConditions || (e.ifConditions = []), e.ifConditions.push(t);\n  }\n  function ha(e) {\n    var t = e.name.replace(oa, \"\");\n    return t || (\"#\" !== e.name[0] && (t = \"default\")), ta.test(t) ? { name: t.slice(1, -1), dynamic: !0 } : { name: '\"' + t + '\"', dynamic: !1 };\n  }\n  function ma(e) {\n    var t = e.match(ia);\n    if (t) {\n      var n = {};\n      return (\n        t.forEach(function (e) {\n          n[e.slice(1)] = !0;\n        }),\n        n\n      );\n    }\n  }\n  function ya(e) {\n    for (var t = {}, n = 0, r = e.length; n < r; n++) t[e[n].name] = e[n].value;\n    return t;\n  }\n  var ga = /^xmlns:NS\\d+/,\n    _a = /^NS\\d+:/;\n  function ba(e) {\n    return la(e.tag, e.attrsList.slice(), e.parent);\n  }\n  var $a = [\n    yo,\n    _o,\n    {\n      preTransformNode: function (e, t) {\n        if (\"input\" === e.tag) {\n          var n,\n            r = e.attrsMap;\n          if (!r[\"v-model\"]) return;\n          if (((r[\":type\"] || r[\"v-bind:type\"]) && (n = Fr(e, \"type\")), r.type || n || !r[\"v-bind\"] || (n = \"(\" + r[\"v-bind\"] + \").type\"), n)) {\n            var i = Pr(e, \"v-if\", !0),\n              o = i ? \"&&(\" + i + \")\" : \"\",\n              a = null != Pr(e, \"v-else\", !0),\n              s = Pr(e, \"v-else-if\", !0),\n              c = ba(e);\n            da(c), Dr(c, \"type\", \"checkbox\"), pa(c, t), (c.processed = !0), (c.if = \"(\" + n + \")==='checkbox'\" + o), va(c, { exp: c.if, block: c });\n            var u = ba(e);\n            Pr(u, \"v-for\", !0), Dr(u, \"type\", \"radio\"), pa(u, t), va(c, { exp: \"(\" + n + \")==='radio'\" + o, block: u });\n            var l = ba(e);\n            return Pr(l, \"v-for\", !0), Dr(l, \":type\", n), pa(l, t), va(c, { exp: i, block: l }), a ? (c.else = !0) : s && (c.elseif = s), c;\n          }\n        }\n      },\n    },\n  ];\n  var wa,\n    Ca,\n    xa = {\n      expectHTML: !0,\n      modules: $a,\n      directives: {\n        model: function (e, t, n) {\n          var r = t.value,\n            i = t.modifiers,\n            o = e.tag,\n            a = e.attrsMap.type;\n          if (e.component) return Br(e, r, i), !1;\n          if (\"select\" === o)\n            !(function (e, t, n) {\n              var r = 'var $$selectedVal = Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = \"_value\" in o ? o._value : o.value;return ' + (n && n.number ? \"_n(val)\" : \"val\") + \"});\";\n              (r = r + \" \" + Ur(t, \"$event.target.multiple ? $$selectedVal : $$selectedVal[0]\")), Mr(e, \"change\", r, null, !0);\n            })(e, r, i);\n          else if (\"input\" === o && \"checkbox\" === a)\n            !(function (e, t, n) {\n              var r = n && n.number,\n                i = Fr(e, \"value\") || \"null\",\n                o = Fr(e, \"true-value\") || \"true\",\n                a = Fr(e, \"false-value\") || \"false\";\n              Er(e, \"checked\", \"Array.isArray(\" + t + \")?_i(\" + t + \",\" + i + \")>-1\" + (\"true\" === o ? \":(\" + t + \")\" : \":_q(\" + t + \",\" + o + \")\")), Mr(e, \"change\", \"var $$a=\" + t + \",$$el=$event.target,$$c=$$el.checked?(\" + o + \"):(\" + a + \");if(Array.isArray($$a)){var $$v=\" + (r ? \"_n(\" + i + \")\" : i) + \",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&(\" + Ur(t, \"$$a.concat([$$v])\") + \")}else{$$i>-1&&(\" + Ur(t, \"$$a.slice(0,$$i).concat($$a.slice($$i+1))\") + \")}}else{\" + Ur(t, \"$$c\") + \"}\", null, !0);\n            })(e, r, i);\n          else if (\"input\" === o && \"radio\" === a)\n            !(function (e, t, n) {\n              var r = n && n.number,\n                i = Fr(e, \"value\") || \"null\";\n              Er(e, \"checked\", \"_q(\" + t + \",\" + (i = r ? \"_n(\" + i + \")\" : i) + \")\"), Mr(e, \"change\", Ur(t, i), null, !0);\n            })(e, r, i);\n          else if (\"input\" === o || \"textarea\" === o)\n            !(function (e, t, n) {\n              var r = e.attrsMap.type,\n                i = n || {},\n                o = i.lazy,\n                a = i.number,\n                s = i.trim,\n                c = !o && \"range\" !== r,\n                u = o ? \"change\" : \"range\" === r ? Zr : \"input\",\n                l = \"$event.target.value\";\n              s && (l = \"$event.target.value.trim()\"), a && (l = \"_n(\" + l + \")\");\n              var f = Ur(t, l);\n              c && (f = \"if($event.target.composing)return;\" + f), Er(e, \"value\", \"(\" + t + \")\"), Mr(e, u, f, null, !0), (s || a) && Mr(e, \"blur\", \"$forceUpdate()\");\n            })(e, r, i);\n          else if (!F.isReservedTag(o)) return Br(e, r, i), !1;\n          return !0;\n        },\n        text: function (e, t) {\n          t.value && Er(e, \"textContent\", \"_s(\" + t.value + \")\", t);\n        },\n        html: function (e, t) {\n          t.value && Er(e, \"innerHTML\", \"_s(\" + t.value + \")\", t);\n        },\n      },\n      isPreTag: function (e) {\n        return \"pre\" === e;\n      },\n      isUnaryTag: $o,\n      mustUseProp: Dn,\n      canBeLeftOpenTag: wo,\n      isReservedTag: Zn,\n      getTagNamespace: Gn,\n      staticKeys: (function (e) {\n        return e\n          .reduce(function (e, t) {\n            return e.concat(t.staticKeys || []);\n          }, [])\n          .join(\",\");\n      })($a),\n    },\n    ka = g(function (e) {\n      return p(\"type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap\" + (e ? \",\" + e : \"\"));\n    });\n  function Aa(e, t) {\n    e &&\n      ((wa = ka(t.staticKeys || \"\")),\n      (Ca = t.isReservedTag || T),\n      (function e(t) {\n        t.static = (function (e) {\n          if (2 === e.type) return !1;\n          if (3 === e.type) return !0;\n          return !(\n            !e.pre &&\n            (e.hasBindings ||\n              e.if ||\n              e.for ||\n              d(e.tag) ||\n              !Ca(e.tag) ||\n              (function (e) {\n                for (; e.parent; ) {\n                  if (\"template\" !== (e = e.parent).tag) return !1;\n                  if (e.for) return !0;\n                }\n                return !1;\n              })(e) ||\n              !Object.keys(e).every(wa))\n          );\n        })(t);\n        if (1 === t.type) {\n          if (!Ca(t.tag) && \"slot\" !== t.tag && null == t.attrsMap[\"inline-template\"]) return;\n          for (var n = 0, r = t.children.length; n < r; n++) {\n            var i = t.children[n];\n            e(i), i.static || (t.static = !1);\n          }\n          if (t.ifConditions)\n            for (var o = 1, a = t.ifConditions.length; o < a; o++) {\n              var s = t.ifConditions[o].block;\n              e(s), s.static || (t.static = !1);\n            }\n        }\n      })(e),\n      (function e(t, n) {\n        if (1 === t.type) {\n          if (((t.static || t.once) && (t.staticInFor = n), t.static && t.children.length && (1 !== t.children.length || 3 !== t.children[0].type))) return void (t.staticRoot = !0);\n          if (((t.staticRoot = !1), t.children)) for (var r = 0, i = t.children.length; r < i; r++) e(t.children[r], n || !!t.for);\n          if (t.ifConditions) for (var o = 1, a = t.ifConditions.length; o < a; o++) e(t.ifConditions[o].block, n);\n        }\n      })(e, !1));\n  }\n  var Oa = /^([\\w$_]+|\\([^)]*?\\))\\s*=>|^function(?:\\s+[\\w$]+)?\\s*\\(/,\n    Sa = /\\([^)]*?\\);*$/,\n    Ta = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*|\\['[^']*?']|\\[\"[^\"]*?\"]|\\[\\d+]|\\[[A-Za-z_$][\\w$]*])*$/,\n    Na = {\n      esc: 27,\n      tab: 9,\n      enter: 13,\n      space: 32,\n      up: 38,\n      left: 37,\n      right: 39,\n      down: 40,\n      delete: [8, 46],\n    },\n    Ea = {\n      esc: [\"Esc\", \"Escape\"],\n      tab: \"Tab\",\n      enter: \"Enter\",\n      space: [\" \", \"Spacebar\"],\n      up: [\"Up\", \"ArrowUp\"],\n      left: [\"Left\", \"ArrowLeft\"],\n      right: [\"Right\", \"ArrowRight\"],\n      down: [\"Down\", \"ArrowDown\"],\n      delete: [\"Backspace\", \"Delete\", \"Del\"],\n    },\n    ja = function (e) {\n      return \"if(\" + e + \")return null;\";\n    },\n    Da = {\n      stop: \"$event.stopPropagation();\",\n      prevent: \"$event.preventDefault();\",\n      self: ja(\"$event.target !== $event.currentTarget\"),\n      ctrl: ja(\"!$event.ctrlKey\"),\n      shift: ja(\"!$event.shiftKey\"),\n      alt: ja(\"!$event.altKey\"),\n      meta: ja(\"!$event.metaKey\"),\n      left: ja(\"'button' in $event && $event.button !== 0\"),\n      middle: ja(\"'button' in $event && $event.button !== 1\"),\n      right: ja(\"'button' in $event && $event.button !== 2\"),\n    };\n  function La(e, t) {\n    var n = t ? \"nativeOn:\" : \"on:\",\n      r = \"\",\n      i = \"\";\n    for (var o in e) {\n      var a = Ia(e[o]);\n      e[o] && e[o].dynamic ? (i += o + \",\" + a + \",\") : (r += '\"' + o + '\":' + a + \",\");\n    }\n    return (r = \"{\" + r.slice(0, -1) + \"}\"), i ? n + \"_d(\" + r + \",[\" + i.slice(0, -1) + \"])\" : n + r;\n  }\n  function Ia(e) {\n    if (!e) return \"function(){}\";\n    if (Array.isArray(e))\n      return (\n        \"[\" +\n        e\n          .map(function (e) {\n            return Ia(e);\n          })\n          .join(\",\") +\n        \"]\"\n      );\n    var t = Ta.test(e.value),\n      n = Oa.test(e.value),\n      r = Ta.test(e.value.replace(Sa, \"\"));\n    if (e.modifiers) {\n      var i = \"\",\n        o = \"\",\n        a = [];\n      for (var s in e.modifiers)\n        if (Da[s]) (o += Da[s]), Na[s] && a.push(s);\n        else if (\"exact\" === s) {\n          var c = e.modifiers;\n          o += ja(\n            [\"ctrl\", \"shift\", \"alt\", \"meta\"]\n              .filter(function (e) {\n                return !c[e];\n              })\n              .map(function (e) {\n                return \"$event.\" + e + \"Key\";\n              })\n              .join(\"||\"),\n          );\n        } else a.push(s);\n      return (\n        a.length &&\n          (i += (function (e) {\n            return \"if(!$event.type.indexOf('key')&&\" + e.map(Ma).join(\"&&\") + \")return null;\";\n          })(a)),\n        o && (i += o),\n        \"function($event){\" + i + (t ? \"return \" + e.value + \".apply(null, arguments)\" : n ? \"return (\" + e.value + \").apply(null, arguments)\" : r ? \"return \" + e.value : e.value) + \"}\"\n      );\n    }\n    return t || n ? e.value : \"function($event){\" + (r ? \"return \" + e.value : e.value) + \"}\";\n  }\n  function Ma(e) {\n    var t = parseInt(e, 10);\n    if (t) return \"$event.keyCode!==\" + t;\n    var n = Na[e],\n      r = Ea[e];\n    return \"_k($event.keyCode,\" + JSON.stringify(e) + \",\" + JSON.stringify(n) + \",$event.key,\" + JSON.stringify(r) + \")\";\n  }\n  var Fa = {\n      on: function (e, t) {\n        e.wrapListeners = function (e) {\n          return \"_g(\" + e + \",\" + t.value + \")\";\n        };\n      },\n      bind: function (e, t) {\n        e.wrapData = function (n) {\n          return \"_b(\" + n + \",'\" + e.tag + \"',\" + t.value + \",\" + (t.modifiers && t.modifiers.prop ? \"true\" : \"false\") + (t.modifiers && t.modifiers.sync ? \",true\" : \"\") + \")\";\n        };\n      },\n      cloak: S,\n    },\n    Pa = function (e) {\n      (this.options = e), (this.warn = e.warn || Tr), (this.transforms = Nr(e.modules, \"transformCode\")), (this.dataGenFns = Nr(e.modules, \"genData\")), (this.directives = A(A({}, Fa), e.directives));\n      var t = e.isReservedTag || T;\n      (this.maybeComponent = function (e) {\n        return !!e.component || !t(e.tag);\n      }),\n        (this.onceId = 0),\n        (this.staticRenderFns = []),\n        (this.pre = !1);\n    };\n  function Ra(e, t) {\n    var n = new Pa(t);\n    return {\n      render: \"with(this){return \" + (e ? (\"script\" === e.tag ? \"null\" : Ha(e, n)) : '_c(\"div\")') + \"}\",\n      staticRenderFns: n.staticRenderFns,\n    };\n  }\n  function Ha(e, t) {\n    if ((e.parent && (e.pre = e.pre || e.parent.pre), e.staticRoot && !e.staticProcessed)) return Ba(e, t);\n    if (e.once && !e.onceProcessed) return Ua(e, t);\n    if (e.for && !e.forProcessed) return za(e, t);\n    if (e.if && !e.ifProcessed) return Va(e, t);\n    if (\"template\" !== e.tag || e.slotTarget || t.pre) {\n      if (\"slot\" === e.tag)\n        return (function (e, t) {\n          var n = e.slotName || '\"default\"',\n            r = Wa(e, t),\n            i = \"_t(\" + n + (r ? \",function(){return \" + r + \"}\" : \"\"),\n            o =\n              e.attrs || e.dynamicAttrs\n                ? Xa(\n                    (e.attrs || []).concat(e.dynamicAttrs || []).map(function (e) {\n                      return {\n                        name: b(e.name),\n                        value: e.value,\n                        dynamic: e.dynamic,\n                      };\n                    }),\n                  )\n                : null,\n            a = e.attrsMap[\"v-bind\"];\n          (!o && !a) || r || (i += \",null\");\n          o && (i += \",\" + o);\n          a && (i += (o ? \"\" : \",null\") + \",\" + a);\n          return i + \")\";\n        })(e, t);\n      var n;\n      if (e.component)\n        n = (function (e, t, n) {\n          var r = t.inlineTemplate ? null : Wa(t, n, !0);\n          return \"_c(\" + e + \",\" + Ka(t, n) + (r ? \",\" + r : \"\") + \")\";\n        })(e.component, e, t);\n      else {\n        var r;\n        (!e.plain || (e.pre && t.maybeComponent(e))) && (r = Ka(e, t));\n        var i = e.inlineTemplate ? null : Wa(e, t, !0);\n        n = \"_c('\" + e.tag + \"'\" + (r ? \",\" + r : \"\") + (i ? \",\" + i : \"\") + \")\";\n      }\n      for (var o = 0; o < t.transforms.length; o++) n = t.transforms[o](e, n);\n      return n;\n    }\n    return Wa(e, t) || \"void 0\";\n  }\n  function Ba(e, t) {\n    e.staticProcessed = !0;\n    var n = t.pre;\n    return e.pre && (t.pre = e.pre), t.staticRenderFns.push(\"with(this){return \" + Ha(e, t) + \"}\"), (t.pre = n), \"_m(\" + (t.staticRenderFns.length - 1) + (e.staticInFor ? \",true\" : \"\") + \")\";\n  }\n  function Ua(e, t) {\n    if (((e.onceProcessed = !0), e.if && !e.ifProcessed)) return Va(e, t);\n    if (e.staticInFor) {\n      for (var n = \"\", r = e.parent; r; ) {\n        if (r.for) {\n          n = r.key;\n          break;\n        }\n        r = r.parent;\n      }\n      return n ? \"_o(\" + Ha(e, t) + \",\" + t.onceId++ + \",\" + n + \")\" : Ha(e, t);\n    }\n    return Ba(e, t);\n  }\n  function Va(e, t, n, r) {\n    return (\n      (e.ifProcessed = !0),\n      (function e(t, n, r, i) {\n        if (!t.length) return i || \"_e()\";\n        var o = t.shift();\n        return o.exp ? \"(\" + o.exp + \")?\" + a(o.block) + \":\" + e(t, n, r, i) : \"\" + a(o.block);\n        function a(e) {\n          return r ? r(e, n) : e.once ? Ua(e, n) : Ha(e, n);\n        }\n      })(e.ifConditions.slice(), t, n, r)\n    );\n  }\n  function za(e, t, n, r) {\n    var i = e.for,\n      o = e.alias,\n      a = e.iterator1 ? \",\" + e.iterator1 : \"\",\n      s = e.iterator2 ? \",\" + e.iterator2 : \"\";\n    return (e.forProcessed = !0), (r || \"_l\") + \"((\" + i + \"),function(\" + o + a + s + \"){return \" + (n || Ha)(e, t) + \"})\";\n  }\n  function Ka(e, t) {\n    var n = \"{\",\n      r = (function (e, t) {\n        var n = e.directives;\n        if (!n) return;\n        var r,\n          i,\n          o,\n          a,\n          s = \"directives:[\",\n          c = !1;\n        for (r = 0, i = n.length; r < i; r++) {\n          (o = n[r]), (a = !0);\n          var u = t.directives[o.name];\n          u && (a = !!u(e, o, t.warn)), a && ((c = !0), (s += '{name:\"' + o.name + '\",rawName:\"' + o.rawName + '\"' + (o.value ? \",value:(\" + o.value + \"),expression:\" + JSON.stringify(o.value) : \"\") + (o.arg ? \",arg:\" + (o.isDynamicArg ? o.arg : '\"' + o.arg + '\"') : \"\") + (o.modifiers ? \",modifiers:\" + JSON.stringify(o.modifiers) : \"\") + \"},\"));\n        }\n        if (c) return s.slice(0, -1) + \"]\";\n      })(e, t);\n    r && (n += r + \",\"), e.key && (n += \"key:\" + e.key + \",\"), e.ref && (n += \"ref:\" + e.ref + \",\"), e.refInFor && (n += \"refInFor:true,\"), e.pre && (n += \"pre:true,\"), e.component && (n += 'tag:\"' + e.tag + '\",');\n    for (var i = 0; i < t.dataGenFns.length; i++) n += t.dataGenFns[i](e);\n    if (\n      (e.attrs && (n += \"attrs:\" + Xa(e.attrs) + \",\"),\n      e.props && (n += \"domProps:\" + Xa(e.props) + \",\"),\n      e.events && (n += La(e.events, !1) + \",\"),\n      e.nativeEvents && (n += La(e.nativeEvents, !0) + \",\"),\n      e.slotTarget && !e.slotScope && (n += \"slot:\" + e.slotTarget + \",\"),\n      e.scopedSlots &&\n        (n +=\n          (function (e, t, n) {\n            var r =\n                e.for ||\n                Object.keys(t).some(function (e) {\n                  var n = t[e];\n                  return n.slotTargetDynamic || n.if || n.for || Ja(n);\n                }),\n              i = !!e.if;\n            if (!r)\n              for (var o = e.parent; o; ) {\n                if ((o.slotScope && o.slotScope !== ua) || o.for) {\n                  r = !0;\n                  break;\n                }\n                o.if && (i = !0), (o = o.parent);\n              }\n            var a = Object.keys(t)\n              .map(function (e) {\n                return qa(t[e], n);\n              })\n              .join(\",\");\n            return (\n              \"scopedSlots:_u([\" +\n              a +\n              \"]\" +\n              (r ? \",null,true\" : \"\") +\n              (!r && i\n                ? \",null,false,\" +\n                  (function (e) {\n                    var t = 5381,\n                      n = e.length;\n                    for (; n; ) t = (33 * t) ^ e.charCodeAt(--n);\n                    return t >>> 0;\n                  })(a)\n                : \"\") +\n              \")\"\n            );\n          })(e, e.scopedSlots, t) + \",\"),\n      e.model && (n += \"model:{value:\" + e.model.value + \",callback:\" + e.model.callback + \",expression:\" + e.model.expression + \"},\"),\n      e.inlineTemplate)\n    ) {\n      var o = (function (e, t) {\n        var n = e.children[0];\n        if (n && 1 === n.type) {\n          var r = Ra(n, t.options);\n          return (\n            \"inlineTemplate:{render:function(){\" +\n            r.render +\n            \"},staticRenderFns:[\" +\n            r.staticRenderFns\n              .map(function (e) {\n                return \"function(){\" + e + \"}\";\n              })\n              .join(\",\") +\n            \"]}\"\n          );\n        }\n      })(e, t);\n      o && (n += o + \",\");\n    }\n    return (n = n.replace(/,$/, \"\") + \"}\"), e.dynamicAttrs && (n = \"_b(\" + n + ',\"' + e.tag + '\",' + Xa(e.dynamicAttrs) + \")\"), e.wrapData && (n = e.wrapData(n)), e.wrapListeners && (n = e.wrapListeners(n)), n;\n  }\n  function Ja(e) {\n    return 1 === e.type && (\"slot\" === e.tag || e.children.some(Ja));\n  }\n  function qa(e, t) {\n    var n = e.attrsMap[\"slot-scope\"];\n    if (e.if && !e.ifProcessed && !n) return Va(e, t, qa, \"null\");\n    if (e.for && !e.forProcessed) return za(e, t, qa);\n    var r = e.slotScope === ua ? \"\" : String(e.slotScope),\n      i = \"function(\" + r + \"){return \" + (\"template\" === e.tag ? (e.if && n ? \"(\" + e.if + \")?\" + (Wa(e, t) || \"undefined\") + \":undefined\" : Wa(e, t) || \"undefined\") : Ha(e, t)) + \"}\",\n      o = r ? \"\" : \",proxy:true\";\n    return \"{key:\" + (e.slotTarget || '\"default\"') + \",fn:\" + i + o + \"}\";\n  }\n  function Wa(e, t, n, r, i) {\n    var o = e.children;\n    if (o.length) {\n      var a = o[0];\n      if (1 === o.length && a.for && \"template\" !== a.tag && \"slot\" !== a.tag) {\n        var s = n ? (t.maybeComponent(a) ? \",1\" : \",0\") : \"\";\n        return \"\" + (r || Ha)(a, t) + s;\n      }\n      var c = n\n          ? (function (e, t) {\n              for (var n = 0, r = 0; r < e.length; r++) {\n                var i = e[r];\n                if (1 === i.type) {\n                  if (\n                    Za(i) ||\n                    (i.ifConditions &&\n                      i.ifConditions.some(function (e) {\n                        return Za(e.block);\n                      }))\n                  ) {\n                    n = 2;\n                    break;\n                  }\n                  (t(i) ||\n                    (i.ifConditions &&\n                      i.ifConditions.some(function (e) {\n                        return t(e.block);\n                      }))) &&\n                    (n = 1);\n                }\n              }\n              return n;\n            })(o, t.maybeComponent)\n          : 0,\n        u = i || Ga;\n      return (\n        \"[\" +\n        o\n          .map(function (e) {\n            return u(e, t);\n          })\n          .join(\",\") +\n        \"]\" +\n        (c ? \",\" + c : \"\")\n      );\n    }\n  }\n  function Za(e) {\n    return void 0 !== e.for || \"template\" === e.tag || \"slot\" === e.tag;\n  }\n  function Ga(e, t) {\n    return 1 === e.type ? Ha(e, t) : 3 === e.type && e.isComment ? ((r = e), \"_e(\" + JSON.stringify(r.text) + \")\") : \"_v(\" + (2 === (n = e).type ? n.expression : Ya(JSON.stringify(n.text))) + \")\";\n    var n, r;\n  }\n  function Xa(e) {\n    for (var t = \"\", n = \"\", r = 0; r < e.length; r++) {\n      var i = e[r],\n        o = Ya(i.value);\n      i.dynamic ? (n += i.name + \",\" + o + \",\") : (t += '\"' + i.name + '\":' + o + \",\");\n    }\n    return (t = \"{\" + t.slice(0, -1) + \"}\"), n ? \"_d(\" + t + \",[\" + n.slice(0, -1) + \"])\" : t;\n  }\n  function Ya(e) {\n    return e.replace(/\\u2028/g, \"\\\\u2028\").replace(/\\u2029/g, \"\\\\u2029\");\n  }\n  new RegExp(\"\\\\b\" + \"do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments\".split(\",\").join(\"\\\\b|\\\\b\") + \"\\\\b\");\n  function Qa(e, t) {\n    try {\n      return new Function(e);\n    } catch (n) {\n      return t.push({ err: n, code: e }), S;\n    }\n  }\n  function es(e) {\n    var t = Object.create(null);\n    return function (n, r, i) {\n      (r = A({}, r)).warn;\n      delete r.warn;\n      var o = r.delimiters ? String(r.delimiters) + n : n;\n      if (t[o]) return t[o];\n      var a = e(n, r),\n        s = {},\n        c = [];\n      return (\n        (s.render = Qa(a.render, c)),\n        (s.staticRenderFns = a.staticRenderFns.map(function (e) {\n          return Qa(e, c);\n        })),\n        (t[o] = s)\n      );\n    };\n  }\n  var ts,\n    ns,\n    rs = ((ts = function (e, t) {\n      var n = fa(e.trim(), t);\n      !1 !== t.optimize && Aa(n, t);\n      var r = Ra(n, t);\n      return { ast: n, render: r.render, staticRenderFns: r.staticRenderFns };\n    }),\n    function (e) {\n      function t(t, n) {\n        var r = Object.create(e),\n          i = [],\n          o = [];\n        if (n) for (var a in (n.modules && (r.modules = (e.modules || []).concat(n.modules)), n.directives && (r.directives = A(Object.create(e.directives || null), n.directives)), n)) \"modules\" !== a && \"directives\" !== a && (r[a] = n[a]);\n        r.warn = function (e, t, n) {\n          (n ? o : i).push(e);\n        };\n        var s = ts(t.trim(), r);\n        return (s.errors = i), (s.tips = o), s;\n      }\n      return { compile: t, compileToFunctions: es(t) };\n    })(xa),\n    is = (rs.compile, rs.compileToFunctions);\n  function os(e) {\n    return ((ns = ns || document.createElement(\"div\")).innerHTML = e ? '<a href=\"\\n\"/>' : '<div a=\"\\n\"/>'), ns.innerHTML.indexOf(\"&#10;\") > 0;\n  }\n  var as = !!V && os(!1),\n    ss = !!V && os(!0),\n    cs = g(function (e) {\n      var t = Qn(e);\n      return t && t.innerHTML;\n    }),\n    us = Cn.prototype.$mount;\n  return (\n    (Cn.prototype.$mount = function (e, t) {\n      if ((e = e && Qn(e)) === document.body || e === document.documentElement) return this;\n      var n = this.$options;\n      if (!n.render) {\n        var r = n.template;\n        if (r)\n          if (\"string\" == typeof r) \"#\" === r.charAt(0) && (r = cs(r));\n          else {\n            if (!r.nodeType) return this;\n            r = r.innerHTML;\n          }\n        else\n          e &&\n            (r = (function (e) {\n              if (e.outerHTML) return e.outerHTML;\n              var t = document.createElement(\"div\");\n              return t.appendChild(e.cloneNode(!0)), t.innerHTML;\n            })(e));\n        if (r) {\n          var i = is(\n              r,\n              {\n                outputSourceRange: !1,\n                shouldDecodeNewlines: as,\n                shouldDecodeNewlinesForHref: ss,\n                delimiters: n.delimiters,\n                comments: n.comments,\n              },\n              this,\n            ),\n            o = i.render,\n            a = i.staticRenderFns;\n          (n.render = o), (n.staticRenderFns = a);\n        }\n      }\n      return us.call(this, e, t);\n    }),\n    (Cn.compile = is),\n    Cn\n  );\n});\n"
  },
  {
    "path": "steam-deck.json",
    "content": "{\n  \"electronVersion\": \"18.3.12\",\n  \"electronDownload\": {\n    \"version\": \"18.3.12+wvcus\",\n    \"mirror\": \"https://github.com/castlabs/electron-releases/releases/download/v\"\n  },\n  \"appId\": \"cider\",\n  \"protocols\": [\n    {\n      \"name\": \"Cider\",\n      \"schemes\": [\"ame\", \"cider\", \"itms\", \"itmss\", \"musics\", \"music\"]\n    }\n  ],\n  \"extends\": null,\n  \"files\": [\"**/*\", \"./src/**/*\", \"./resources/icons/icon.*\"],\n  \"linux\": {\n    \"target\": [\"AppImage\", \"flatpak\", \"pacman\"],\n    \"synopsis\": \"A new look into listening and enjoying music in style and performance. \",\n    \"category\": \"AudioVideo\",\n    \"icon\": \"cider\",\n    \"executableName\": \"cider\"\n  },\n  \"appx\": {\n    \"applicationId\": \"CiderAlpha\",\n    \"publisher\": \"CN=CiderCollective, OID.2.25.311729368913984317654407730594956997722=1\",\n    \"displayName\": \"Cider\",\n    \"identityName\": \"CiderCollective.CiderAlpha\",\n    \"backgroundColor\": \"transparent\",\n    \"setBuildNumber\": true\n  },\n  \"win\": {\n    \"target\": [\"appx\"],\n    \"icon\": \"resources/icons/icon.ico\"\n  },\n  \"directories\": {\n    \"buildResources\": \".\",\n    \"output\": \"dist\"\n  },\n  \"mac\": {\n    \"icon\": \"./resources/icons/icon.icns\",\n    \"category\": \"public.app-category.music\",\n    \"entitlements\": \"resources/entitlements.mac.plist\",\n    \"darkModeSupport\": true\n  }\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"outDir\": \"build\",\n    \"inlineSources\": true,\n    \"allowJs\": true,\n    \"esModuleInterop\": true,\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    // Needed to address https://github.com/quasarframework/app-extension-typescript/issues/36\n    \"noEmit\": false,\n    \"resolveJsonModule\": true,\n    // Avoid cross-os errors due to inconsistent file casing\n    \"forceConsistentCasingInFileNames\": true,\n    \"sourceMap\": true,\n    \"strict\": true,\n    \"target\": \"esnext\",\n    \"isolatedModules\": true,\n    \"useDefineForClassFields\": true,\n    // Fix Volar issue https://github.com/johnsoncodehk/volar/issues/1153\n    \"jsx\": \"preserve\",\n    \"lib\": [\"esnext\", \"dom\"],\n    \"experimentalDecorators\": true,\n    \"baseUrl\": \"./\",\n    \"allowSyntheticDefaultImports\": true,\n    \"noImplicitThis\": true,\n    \"skipLibCheck\": true /* Skip type checking of declaration files. */,\n    \"typeRoots\": [\"node_modules/musickit-typescript\", \"node_modules/@types\"],\n  },\n  \"include\": [\"src/**/*.ts\"],\n}\n"
  },
  {
    "path": "winget.json",
    "content": "{\n  \"electronVersion\": \"24.3.0\",\n  \"electronDownload\": {\n    \"version\": \"24.3.0+wvcus\",\n    \"mirror\": \"https://github.com/castlabs/electron-releases/releases/download/v\"\n  },\n  \"appId\": \"cider\",\n  \"afterPack\": \"./resources/afterPack.cjs\",\n  \"afterSign\": \"./resources/notarize.cjs\",\n  \"protocols\": [\n    {\n      \"name\": \"Cider\",\n      \"schemes\": [\"ame\", \"cider\", \"itms\", \"itmss\", \"musics\", \"music\"]\n    }\n  ],\n  \"extends\": null,\n  \"files\": [\"./build/**/*\", \"./src/**/*\", \"./resources/icons/**/*\"],\n  \"nsis\": {\n    \"oneClick\": true,\n    \"perMachine\": false,\n    \"deleteAppDataOnUninstall\": true,\n    \"artifactName\": \"${productName}-Setup-winget-${version}.${ext}\"\n  },\n  \"win\": {\n    \"target\": [\"nsis\"],\n    \"icon\": \"resources/icons/icon.ico\"\n  }\n}\n"
  },
  {
    "path": "workbox-config.js",
    "content": "module.exports = {\n  globDirectory: \"src/renderer/\",\n  swDest: \"src/renderer/sw.js\",\n  // Define runtime caching rules.\n  runtimeCaching: [\n    {\n      // Match any request that ends with .png, .jpg, .jpeg or .svg.\n      urlPattern: /\\.(?:png|jpg|jpeg|svg|webp)$/,\n\n      // Apply a cache-first strategy.\n      handler: \"CacheFirst\",\n\n      options: {\n        // Use a custom cache name.\n        cacheName: \"imageinternet\",\n        // Only cache 10 images.\n      },\n    },\n    {\n      urlPattern: /https:\\/\\/is[0-9]-ssl\\.mzstatic\\.com\\/image+/,\n      handler: \"CacheFirst\",\n    },\n    {\n      urlPattern: /^https:\\/\\/store-\\d{3}\\.blobstore\\.apple\\.com\\/.{65}\\/image+/,\n      handler: \"CacheFirst\",\n    },\n  ],\n  ignoreURLParametersMatching: [/^utm_/, /^fbclid$/, /^X-Amz-Algorithm/, /^X-Amz-Date/, /^X-Amz-SignedHeaders/, /^X-Amz-Expires/, /^X-Amz-Credential/, /^X-Amz-Signature/],\n};\n"
  }
]